BPF List
 help / color / mirror / Atom feed
* [PATCH bpf-next v1 00/73] Cancellations
@ 2026-12-01  4:38 Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 01/73] bpf: Refuse a program that is too large for bpf_prog->pages Kumar Kartikeya Dwivedi
                   ` (72 more replies)
  0 siblings, 73 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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/20240201042109.1150490-1-memxor@gmail.com
  [1]: https://lore.kernel.org/bpf/cover.1794399387.git.memxor@gmail.com
  [2]: https://lore.kernel.org/bpf/20250907230415.289327-1-sidchintamaneni@gmail.com

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
-- 
2.53.1-Meta


^ permalink raw reply	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 01/73] bpf: Refuse a program that is too large for bpf_prog->pages
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 02/73] bpf: Require CAP_PERFMON for unwind_exit and unwind_goto Kumar Kartikeya Dwivedi
                   ` (71 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/filter.h |  4 ++++
 kernel/bpf/core.c      | 14 +++++++++++++-
 kernel/bpf/fixups.c    |  3 +++
 3 files changed, 20 insertions(+), 1 deletion(-)

diff --git a/include/linux/filter.h b/include/linux/filter.h
index 06f128632d5c..5f038006ecbc 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -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);
 
 /*
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index facb0d6d2e8d..b1c8c246dc25 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -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);
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index a7116e2cb7d6..ad0ea7803332 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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;
 
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 02/73] bpf: Require CAP_PERFMON for unwind_exit and unwind_goto
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 01/73] bpf: Refuse a program that is too large for bpf_prog->pages Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 03/73] bpf: Reject bpf_percpu_obj_drop() of a type with special fields Kumar Kartikeya Dwivedi
                   ` (70 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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".

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 50b3f8ab9720..c48584a960e9 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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 */
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 18c59ae784eb..c725fd09490c 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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;
diff --git a/tools/testing/selftests/bpf/progs/verifier_unwind.c b/tools/testing/selftests/bpf/progs/verifier_unwind.c
index 596e5e0301e5..be3992ed8eed 100644
--- a/tools/testing/selftests/bpf/progs/verifier_unwind.c
+++ b/tools/testing/selftests/bpf/progs/verifier_unwind.c
@@ -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 (
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 03/73] bpf: Reject bpf_percpu_obj_drop() of a type with special fields
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 01/73] bpf: Refuse a program that is too large for bpf_prog->pages Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 02/73] bpf: Require CAP_PERFMON for unwind_exit and unwind_goto Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 04/73] bpf: Drop the edge after bpf_throw() from the control flow graph Kumar Kartikeya Dwivedi
                   ` (69 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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")
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 kernel/bpf/verifier.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index c725fd09490c..89fd40ce1bca 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 04/73] bpf: Drop the edge after bpf_throw() from the control flow graph
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (2 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 03/73] bpf: Reject bpf_percpu_obj_drop() of a type with special fields Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 05/73] bpf: Let a helper call its callback with an unwind label Kumar Kartikeya Dwivedi
                   ` (68 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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")
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index c48584a960e9..b8617d364f9c 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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 */
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index 23a66b22393d..2c93798e1f15 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -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 &&
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 89fd40ce1bca..f10f3660208f 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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)) {
diff --git a/tools/testing/selftests/bpf/progs/verifier_cfg.c b/tools/testing/selftests/bpf/progs/verifier_cfg.c
index e97e89ba3d68..719d35d0dfab 100644
--- a/tools/testing/selftests/bpf/progs/verifier_cfg.c
+++ b/tools/testing/selftests/bpf/progs/verifier_cfg.c
@@ -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
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 05/73] bpf: Let a helper call its callback with an unwind label
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (3 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 04/73] bpf: Drop the edge after bpf_throw() from the control flow graph Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 06/73] bpf, x86, arm64: Add landings that redo what follows a helper call Kumar Kartikeya Dwivedi
                   ` (67 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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

diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index 85008d55233e..0108b66b5619 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -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;
 }
 
 /*
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 2b2a81e02cfc..5558dbc80669 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -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;
 }
 
 /*
diff --git a/include/linux/bpf_unwind.h b/include/linux/bpf_unwind.h
new file mode 100644
index 000000000000..097e540b1844
--- /dev/null
+++ b/include/linux/bpf_unwind.h
@@ -0,0 +1,289 @@
+/* SPDX-License-Identifier: GPL-2.0 */
+#ifndef _LINUX_BPF_UNWIND_H
+#define _LINUX_BPF_UNWIND_H
+
+/*
+ * The unwind label of a helper, which the identifiers call a pad.
+ *
+ * A helper that calls a callback is a C frame between the callback and the BPF code that called
+ * the helper. For the callback to leave with unwind_exit, the helper calls it with bpf_call_cb()
+ * and names a label, at which it continues when the callback does not return:
+ *
+ *		bpf_call_cb(cb, a1, a2, a3, a4, a5, r0, unwound);
+ *		...
+ *	unwound:
+ *		rcu_read_unlock();		<- the helper releases what it holds
+ *		bpf_unwind_leave();		<- and returns to the unwind_goto after its own
+ *		return r0;			   call, with R0 of the callback alone
+ *
+ * The return address of the callback has an exception table entry, EX_TYPE_BPF, for the label.
+ * unwind_exit of the callback finds the entry with bpf_unwind_target() and returns there.
+ *
+ * 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 BPF code called, or in one that such a function
+ *    called with bpf_call_cb(). A body that two kfuncs share is inlined into both. noinline also
+ *    keeps gcc from splitting the label out of the function (ipa-split).
+ *  - 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.
+ *
+ * The key of the entry is the return address itself, not ret_addr - 1 as in the JITs, because
+ * objtool wants the key to be an insn. fixup_exception() searches the same table, so that insn,
+ * which follows bpf_call_cb(), must not fault or have a fixup of its own.
+ *
+ * Without asm goto outputs, and on other architectures, bpf_call_cb() is a plain call and
+ * BPF_HAS_CB_PADS is 0: the verifier rejects a callback that can unwind.
+ */
+
+#include <linux/bug.h>
+#include <linux/compiler.h>
+#include <linux/kprobes.h>
+#include <linux/types.h>
+#include <linux/filter.h>
+#include <linux/stringify.h>
+
+/* UML on x86-64 has no JIT, and the x86 headers below are not for it */
+#if defined(CONFIG_X86_64) && !defined(CONFIG_UML) && defined(CONFIG_CC_HAS_ASM_GOTO_OUTPUT)
+
+#include <asm/asm.h>
+#include <asm/extable_fixup_types.h>
+#include <asm/nospec-branch.h>
+
+#define BPF_HAS_CB_PADS 1
+
+#ifdef CONFIG_CFI
+/*
+ * The kCFI check as the compiler emits it, byte for byte, so that apply_fineibt() and
+ * handle_cfi_failure() take it for one of the compiler: the hash where the compiler and the JIT
+ * put it, the trap in .kcfi_traps, the target in r11 for FineIBT. The type id is the symbol that
+ * clang emits for a declaration of the type whose address is taken, see BPF_CB_PAD_TYPE(). The
+ * symbol is absolute, so the assembler can negate it.
+ */
+#define BPF_CB_PAD_TYPE(name, type)						\
+	extern type name;							\
+	__ADDRESSABLE(name)
+
+#ifdef CONFIG_CALL_PADDING
+#define BPF_KCFI_HASH_OFF	(4 + CONFIG_FUNCTION_PADDING_CFI)
+#else
+#define BPF_KCFI_HASH_OFF	4
+#endif
+
+#define BPF_KCFI_CHECK(type)							\
+	"	movl $-__kcfi_typeid_" #type ", %%r10d\n"			\
+	"	addl -" __stringify(BPF_KCFI_HASH_OFF) "(%%r11), %%r10d\n"	\
+	"	je 2f\n"							\
+	"3:	ud2\n"								\
+	"	.pushsection .kcfi_traps, \"ao\", @progbits, .text\n"		\
+	"	.long 3b - .\n"							\
+	"	.popsection\n"							\
+	"2:\n"
+#else
+#define BPF_CB_PAD_TYPE(name, type)
+#define BPF_KCFI_CHECK(type)
+#endif
+
+/*
+ * The registers that the call clobbers are outputs, so that the compiler uses none of them for
+ * another operand. r0 is rax after the call and at the label: the outputs of an asm goto are
+ * valid on both edges, see CC_HAS_ASM_GOTO_OUTPUT. apply_retpolines() and apply_fineibt() pad
+ * before the call, never after it, so the return address stays the byte after the call. The
+ * arguments are evaluated before the register variables are set, because a call among them,
+ * instrumentation included, would clobber the variables.
+ */
+#define __bpf_call_cb(type, fn, a1, a2, a3, a4, a5, r0, unwound)		\
+do {										\
+	u64 __f = (u64)(long)(fn), __1 = (u64)(long)(a1), __2 = (u64)(long)(a2),	\
+	    __3 = (u64)(long)(a3), __4 = (u64)(long)(a4), __5 = (u64)(long)(a5);	\
+	register u64 __fn asm("r11") = __f;					\
+	register u64 __a5 asm("r8") = __5;					\
+	register u64 __c5 asm("r8");						\
+	register u64 __c11 asm("r11");						\
+	u64 __c1, __c2, __c3, __c4;						\
+										\
+	asm_goto_output(BPF_KCFI_CHECK(type)					\
+		 "	" CALL_NOSPEC "\n"					\
+		 "1:\n"								\
+		 _ASM_EXTABLE_TYPE(1b, %l[unwound], EX_TYPE_BPF)		\
+		 : "=a"(r0), "=D"(__c1), "=S"(__c2), "=d"(__c3), "=c"(__c4),	\
+		   "=r"(__c5), "=r"(__c11)					\
+		 : [thunk_target] "r"(__fn), "D"(__1), "S"(__2), "d"(__3),	\
+		   "c"(__4), "r"(__a5)						\
+		 : "r9", "r10", "memory", "cc"					\
+		 : unwound);							\
+} while (0)
+
+/*
+ * Make the function that this is inlined into return to the target of the unwind_goto after its
+ * call. The return address is the word below the canonical frame address. Nothing checks that a
+ * target was found: after 'unwind_goto +0' the target is the return address itself, because the
+ * JIT emits no code for unwind_goto.
+ * The store is the last thing before the return, into the frame of the function itself, so a
+ * compiler may take it for a dead store. Hence WRITE_ONCE().
+ */
+static __always_inline void bpf_unwind_leave(void)
+{
+	unsigned long *slot = (unsigned long *)__builtin_dwarf_cfa() - 1;
+
+	WRITE_ONCE(*slot, bpf_unwind_target(*slot));
+}
+
+#elif defined(CONFIG_ARM64) && defined(CONFIG_CC_HAS_ASM_GOTO_OUTPUT)
+
+#include <linux/scs.h>
+#include <asm/asm-extable.h>
+#include <asm/brk-imm.h>
+#include <asm/compiler.h>
+
+#define BPF_HAS_CB_PADS 1
+
+#ifdef CONFIG_CFI
+/*
+ * The kCFI check as the compiler emits it: the type id is in w17 and the target in x15, and the
+ * brk says so. The hash of the callee is the word before its first insn.
+ */
+#define BPF_CB_PAD_TYPE(name, type)						\
+	extern type name;							\
+	__ADDRESSABLE(name)
+
+#define BPF_KCFI_CHECK(type)							\
+	"	ldur w16, [x15, #-4]\n"						\
+	"	movz w17, #:abs_g0_nc:__kcfi_typeid_" #type "\n"		\
+	"	movk w17, #:abs_g1_nc:__kcfi_typeid_" #type "\n"		\
+	"	cmp w16, w17\n"							\
+	"	b.eq 2f\n"							\
+	"	brk #" __stringify((CFI_BRK_IMM_BASE | (17 << 5) | 15)) "\n"	\
+	"2:\n"
+#else
+#define BPF_CB_PAD_TYPE(name, type)
+#define BPF_KCFI_CHECK(type)
+#endif
+
+/* x18 is a temporary, unless it holds the shadow call stack: then the callee keeps it */
+#ifdef CONFIG_SHADOW_CALL_STACK
+#define BPF_CB_CLOBBER_X18
+#else
+#define BPF_CB_CLOBBER_X18	"x18",
+#endif
+
+/*
+ * r0 is x0, which only a register variable can name, and gcc does not keep such a variable across
+ * a call. KCOV puts a call at the head of each block, and an asm goto ends its block, so C code
+ * after it would read x0 too late on either edge. So the assembly moves x0 to r0 itself, after
+ * the call and where unwind_exit returns to, out of line. For the same reason the arguments are
+ * evaluated before the register variables are set.
+ */
+#define __bpf_call_cb(type, fn, a1, a2, a3, a4, a5, r0, unwound)		\
+do {										\
+	u64 __f = (u64)(long)(fn), __1 = (u64)(long)(a1), __2 = (u64)(long)(a2),	\
+	    __3 = (u64)(long)(a3), __4 = (u64)(long)(a4), __5 = (u64)(long)(a5);	\
+	register u64 __fn asm("x15") = __f;					\
+	register u64 __a0 asm("x0") = __1;					\
+	register u64 __a1 asm("x1") = __2;					\
+	register u64 __a2 asm("x2") = __3;					\
+	register u64 __a3 asm("x3") = __4;					\
+	register u64 __a4 asm("x4") = __5;					\
+	register u64 __c0 asm("x0");						\
+	register u64 __c1 asm("x1");						\
+	register u64 __c2 asm("x2");						\
+	register u64 __c3 asm("x3");						\
+	register u64 __c4 asm("x4");						\
+	register u64 __c15 asm("x15");						\
+										\
+	asm_goto_output(BPF_KCFI_CHECK(type)					\
+		 "	blr x15\n"						\
+		 "1:	mov %[ret], x0\n"					\
+		 "	.subsection 1\n"					\
+		 "3:	mov %[ret], x0\n"					\
+		 "	b %l[" __stringify(unwound) "]\n"			\
+		 "	.previous\n"						\
+		 __ASM_EXTABLE_RAW("1b", "3b", __stringify(EX_TYPE_BPF), "0")	\
+		 : [ret] "=r"(r0), "=r"(__c0), "=r"(__c1), "=r"(__c2),		\
+		   "=r"(__c3), "=r"(__c4), "=r"(__c15)				\
+		 : "r"(__fn), "r"(__a0), "r"(__a1), "r"(__a2), "r"(__a3),	\
+		   "r"(__a4)							\
+		 : "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13",	\
+		   "x14", "x16", "x17", BPF_CB_CLOBBER_X18 "x30", "memory", "cc"	\
+		 : unwound);							\
+} while (0)
+
+/*
+ * 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.
+ *
+ * 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,
+ * like paciasp. On arm64 clang gives the frame pointer for __builtin_dwarf_cfa() and the stack
+ * pointer at entry for __builtin_sponentry().
+ *
+ * A shadow call stack holds a copy of the return address, which the epilogue prefers. A dynamic
+ * one is off where there is pointer authentication. A static one holds what the compiler pushed:
+ * gcc and clang from 21 on sign first, so the copy is the word of the frame record. clang up to
+ * 20 pushes first, so the copy is plain. The copy is read and written in assembly, because KASAN
+ * poisons the shadow call stack.
+ */
+static __always_inline void bpf_unwind_leave(void)
+{
+	unsigned long *slot = (unsigned long *)__builtin_frame_address(0) + 1;
+	unsigned long old = *slot;
+	unsigned long from = ptrauth_strip_kernel_insn_pac(old);
+	unsigned long to = bpf_unwind_target(from), sig = to;
+
+	WARN_ON_ONCE(to == from);
+#ifdef CONFIG_ARM64_PTR_AUTH_KERNEL
+	{
+		register unsigned long x17 asm("x17") = to;
+#ifdef __clang__
+		register unsigned long x16 asm("x16") = (unsigned long)__builtin_sponentry();
+#else
+		register unsigned long x16 asm("x16") = (unsigned long)__builtin_dwarf_cfa();
+#endif
+
+		asm("pacia1716" : "+r"(x17) : "r"(x16));
+		sig = x17;
+	}
+#endif
+	/* the store is the last before the return, see x86-64 above */
+	WRITE_ONCE(*slot, sig);
+#ifdef CONFIG_SHADOW_CALL_STACK
+	if (scs_is_enabled()) {
+		unsigned long copy;
+
+		asm volatile("ldur %0, [x18, #-8]" : "=r"(copy));
+		asm volatile("stur %0, [x18, #-8]"
+			     : : "r"(copy == old ? sig : to) : "memory");
+	}
+#endif
+}
+
+#else
+
+#define BPF_HAS_CB_PADS 0
+
+#define BPF_CB_PAD_TYPE(name, type)
+
+#define __bpf_call_cb(type, fn, a1, a2, a3, a4, a5, r0, unwound)		\
+do {										\
+	(r0) = ((bpf_callback_t)(void *)(fn))((u64)(long)(a1), (u64)(long)(a2),	\
+					      (u64)(long)(a3), (u64)(long)(a4),	\
+					      (u64)(long)(a5));			\
+	if (0)									\
+		goto unwound;							\
+} while (0)
+
+static __always_inline void bpf_unwind_leave(void)
+{
+}
+
+#endif
+
+/*
+ * bpf_call_cb() checks the call against the type of a callback, bpf_callback_t. A function of
+ * another type is called with __bpf_call_cb() and a name that BPF_CB_PAD_TYPE() declares for it.
+ */
+BPF_CB_PAD_TYPE(__bpf_callback_fn, typeof(*(bpf_callback_t)0));
+
+#define bpf_call_cb(fn, a1, a2, a3, a4, a5, r0, unwound)			\
+	__bpf_call_cb(__bpf_callback_fn, fn, a1, a2, a3, a4, a5, r0, unwound)
+
+#endif /* _LINUX_BPF_UNWIND_H */
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 5f038006ecbc..4aad10c3c8e9 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -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);
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index b1c8c246dc25..2b1d655aa070 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -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
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 06/73] bpf, x86, arm64: Add landings that redo what follows a helper call
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (4 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 05/73] bpf: Let a helper call its callback with an unwind label Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 07/73] bpf: Let a callback unwind out of a helper that has an unwind label Kumar Kartikeya Dwivedi
                   ` (66 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index 0108b66b5619..fe41871e3d1c 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -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();
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 5558dbc80669..4a934bab9c79 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -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:
diff --git a/include/linux/bpf_unwind.h b/include/linux/bpf_unwind.h
index 097e540b1844..2a3bb47e2b10 100644
--- a/include/linux/bpf_unwind.h
+++ b/include/linux/bpf_unwind.h
@@ -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,
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 07/73] bpf: Let a callback unwind out of a helper that has an unwind label
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (5 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 06/73] bpf, x86, arm64: Add landings that redo what follows a helper call Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 08/73] bpf: Let the inlined bpf_loop pass on a callback that unwinds Kumar Kartikeya Dwivedi
                   ` (65 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index b8617d364f9c..117c3a3f7cbb 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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)
diff --git a/include/uapi/linux/bpf.h b/include/uapi/linux/bpf.h
index 28904c6f0787..95b41ae6584d 100644
--- a/include/uapi/linux/bpf.h
+++ b/include/uapi/linux/bpf.h
@@ -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,
diff --git a/kernel/bpf/const_fold.c b/kernel/bpf/const_fold.c
index 3310a55afa3b..1524166cf6db 100644
--- a/kernel/bpf/const_fold.c
+++ b/kernel/bpf/const_fold.c
@@ -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;
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index 2c93798e1f15..f6456e5be5fd 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -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;
diff --git a/kernel/bpf/precision.c b/kernel/bpf/precision.c
index 33b180b35c88..f2ef763684f4 100644
--- a/kernel/bpf/precision.c
+++ b/kernel/bpf/precision.c
@@ -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;
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index f10f3660208f..4b65f537668c 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -10,6 +10,7 @@
 #include <linux/types.h>
 #include <linux/slab.h>
 #include <linux/bpf.h>
+#include <linux/bpf_unwind.h>
 #include <linux/btf.h>
 #include <linux/bpf_verifier.h>
 #include <linux/filter.h>
@@ -3363,6 +3364,8 @@ static int record_callx_edge(struct bpf_verifier_env *env, int caller, int calle
  * 'call foo; unwind_goto pad' goes to the pad when foo left with unwind_exit.
  * JITs don't emit a branch for it. unwind_exit finds the pad by its return
  * address. So unwind_goto has to follow the call and nothing may jump to it.
+ * The call can be of a helper or a kfunc that calls a callback: it leaves the
+ * way the callback does, see check_cb_unwind().
  */
 static int check_unwind_insns(struct bpf_verifier_env *env)
 {
@@ -3388,8 +3391,10 @@ static int check_unwind_insns(struct bpf_verifier_env *env)
 		if (!bpf_is_unwind_goto(insn))
 			continue;
 		seen = true;
-		if (!i || !(bpf_pseudo_call(insn - 1) || bpf_is_callx(insn - 1))) {
-			verbose(env, "unwind_goto at insn %d doesn't follow a call of a subprog\n",
+		if (!i || !(bpf_pseudo_call(insn - 1) || bpf_is_callx(insn - 1) ||
+			    bpf_is_sync_callback_calling_insn(insn - 1))) {
+			verbose(env,
+				"unwind_goto at insn %d doesn't follow a call of a subprog or of a helper with a callback\n",
 				i);
 			return -EINVAL;
 		}
@@ -11448,6 +11453,66 @@ 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. */
+static bool helper_has_cb_pad(enum bpf_func_id func_id)
+{
+	return false;
+}
+
+/* The kfunc calls its callback with a pad. None yet. */
+static bool kfunc_has_cb_pad(u32 btf_id)
+{
+	return false;
+}
+
+static bool insn_has_cb_pad(struct bpf_insn *insn)
+{
+	return (bpf_helper_call(insn) && helper_has_cb_pad(insn->imm)) ||
+	       (bpf_pseudo_kfunc_call(insn) && kfunc_has_cb_pad(insn->imm));
+}
+
+/*
+ * A sync callback is called by a helper or a kfunc, a C frame between the
+ * callback and the BPF code that called it. unwind_exit of the callback returns
+ * to the pad of its caller when there is one, and a helper or a kfunc that
+ * calls a callback has one where BPF_HAS_CB_PADS and insn_has_cb_pad(): it
+ * calls the callback with bpf_call_cb(), drops what it holds when the callback
+ * unwinds and leaves to the pad of its own caller with the r0 of the callback.
+ * So a call with such a callback that can unwind is a call of something that
+ * can unwind, and unwind_goto has to follow it.
+ *
+ * A callback has no unwind_exit and unwinds all the same when it is recursive
+ * and unwind_goto follows every call of it that mark_recursive_subprogs() saw:
+ * its check of the recursion leaves with unwind_exit then, see
+ * check_recursion_guard(). The call of a helper that got the callback from a
+ * table of functions is not one of those calls. It is known here.
+ */
+static int check_cb_unwind(struct bpf_verifier_env *env, struct bpf_insn *insn,
+			   int insn_idx, int subprog)
+{
+	if (!bpf_subprog_unwinds(&env->subprog_info[subprog]))
+		return 0;
+	if (!bpf_is_unwind_goto(insn + 1)) {
+		if (bpf_helper_call(insn))
+			verbose(env, "no unwind_goto after the call of %s()\n",
+				func_id_name(insn->imm));
+		else
+			verbose(env, "no unwind_goto after the call of the kfunc at insn %d\n",
+				insn_idx);
+		return -EINVAL;
+	}
+	/* The helpers have unwind labels only with asm goto outputs, see bpf_call_cb(). */
+	if (!BPF_HAS_CB_PADS) {
+		verbose(env, "callback cannot unwind: the helpers have no pads\n");
+		return -ENOTSUPP;
+	}
+	if (!insn_has_cb_pad(insn)) {
+		verbose(env, "callback cannot unwind\n");
+		return -EINVAL;
+	}
+	return 0;
+}
+
 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 			      int insn_idx, int subprog,
 			      set_callee_state_fn set_callee_state_cb)
@@ -11457,6 +11522,11 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 	int err;
 
 	caller = state->frame[state->curframe];
+	/* The callback unwound. This second visit only applies the effects of the helper. */
+	if (state->unwound) {
+		leave_callback(caller);
+		return 0;
+	}
 	err = btf_check_subprog_call(env, subprog);
 	if (err == -EFAULT)
 		return err;
@@ -11527,6 +11597,10 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 	else
 		env->subprog_info[subprog].is_other_cb = true;
 
+	err = check_cb_unwind(env, insn, insn_idx, subprog);
+	if (err)
+		return err;
+
 	/* for callback functions enqueue entry to callback and
 	 * proceed with next instruction within current frame.
 	 */
@@ -11685,10 +11759,10 @@ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int i
  * A void function can leave a pointer to the stack in r0. The caller cannot read it. That holds
  * for the stack of a caller too: for stack liveness a call returns no pointer to the stack.
  */
-static void hide_returned_stack_ptrs(struct bpf_verifier_env *env, int subprog,
+static void hide_returned_stack_ptrs(struct bpf_verifier_env *env, u32 nregs,
 				     struct bpf_reg_state *regs)
 {
-	u32 i, nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1;
+	u32 i;
 
 	for (i = 0; i < nregs; i++) {
 		if (regs[ret_regs[i]].type != PTR_TO_STACK)
@@ -11706,7 +11780,8 @@ static int exit_func_on_its_own(struct bpf_verifier_env *env)
 	struct bpf_func_state *callee = state->frame[0];
 	int err;
 
-	hide_returned_stack_ptrs(env, callee->subprogno, callee->regs);
+	hide_returned_stack_ptrs(env, bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1,
+				 callee->regs);
 	state->unwound |= bpf_is_unwind_exit(&env->prog->insnsi[env->insn_idx]);
 
 	/* Invalidate callee-local dynptrs and their slices before the frame goes away. */
@@ -12463,20 +12538,30 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 	struct bpf_verifier_state *state = env->cur_state;
 	struct bpf_func_state *caller, *callee;
 	struct bpf_reg_state *r0;
+	bool unwinds;
 	u32 i, nregs;
 	int err;
 
 	callee = state->frame[state->curframe];
 	r0 = &callee->regs[BPF_REG_0];
-	nregs = bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1;
+	/*
+	 * A callback passes on R0 alone, whatever its prototype says, both when it returns to
+	 * the helper and when it unwinds through the unwind label of the helper. R2 stays the
+	 * caller's, because the second visit of the call reads the arguments.
+	 */
+	nregs = !callee->in_callback_fn && bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1;
 
 	caller = state->frame[state->curframe - 1];
-	if (bpf_is_unwind_exit(&env->prog->insnsi[*insn_idx]) || state->unwound) {
-		/* the helper or the kfunc that called it doesn't expect that */
-		if (callee->in_callback_fn) {
-			verbose(env, "callback cannot unwind\n");
-			return -EINVAL;
-		}
+	unwinds = bpf_is_unwind_exit(&env->prog->insnsi[*insn_idx]) || state->unwound;
+	if (unwinds) {
+		/*
+		 * A callback returns into the helper that called it, and to the
+		 * pad of the helper when the helper has one. check_cb_unwind()
+		 * has seen to that, and to the unwind_goto after the call of
+		 * the helper, where the helper leaves to right away, with the
+		 * r0 of the callback as it is: the pad gets its state, as the
+		 * pad after a subprog call does.
+		 */
 		if (!bpf_is_unwind_goto(&env->prog->insnsi[callee->callsite + 1])) {
 			verbose(env, "unwind_exit, but no unwind_goto after the call at insn %d\n",
 				callee->callsite);
@@ -12484,7 +12569,7 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 		}
 		state->unwound = true;
 	}
-	if (callee->in_callback_fn) {
+	if (callee->in_callback_fn && !unwinds) {
 		/* the helper continues after the barrier of its call */
 		if (state->speculative)
 			return -EACCES;
@@ -12527,7 +12612,7 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 			caller->regs[regno] = callee->regs[regno];
 			bpf_diag_mod_end(env);
 		}
-		hide_returned_stack_ptrs(env, callee->subprogno, caller->regs);
+		hide_returned_stack_ptrs(env, nregs, caller->regs);
 	}
 
 	/* Invalidate callee-local dynptrs and their slices before the frame goes away. */
@@ -12545,6 +12630,11 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 	/* for callbacks like bpf_loop or bpf_for_each_map_elem go back to callsite,
 	 * there function call logic would reschedule callback visit.
 	 */
+	/*
+	 * A callback that unwound goes back to the call too, because the helper has effects of
+	 * its own, such as releasing what it consumed. For a state that is marked unwound the
+	 * call starts no further iteration, and R0 stays what the callback unwound with.
+	 */
 	if (callee->in_callback_fn)
 		*insn_idx = callee->callsite;
 	else
@@ -13011,7 +13101,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 	const struct bpf_func_proto *fn = NULL;
 	enum bpf_return_type ret_type;
 	enum bpf_type_flag ret_flag;
-	struct bpf_reg_state *regs;
+	struct bpf_reg_state *regs, unwound_r0;
 	struct bpf_call_arg_meta meta;
 	const char *operation;
 	int insn_idx = *insn_idx_p;
@@ -13261,12 +13351,20 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 
 	/* reset caller saved regs */
 	bpf_diag_record_caller_saved(env, regs);
-	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
+	/* The callback unwound: the helper leaves with the R0 of the callback, so keep R0. */
+	if (env->cur_state->unwound)
+		unwound_r0 = regs[BPF_REG_0];
+	else
+		bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
 		bpf_mark_reg_not_init(env, &regs[caller_saved[i]]);
 		check_reg_arg(env, caller_saved[i], DST_OP_NO_MARK);
 	}
 	invalidate_outgoing_stack_args(env, cur_func(env));
+	if (env->cur_state->unwound) {
+		regs[BPF_REG_0] = unwound_r0;
+		goto unwound;
+	}
 
 	/* update return register (already marked as written above) */
 	ret_type = fn->ret_type;
@@ -13453,7 +13551,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 		return err;
 
 	bpf_diag_mod_end(env);
-
+unwound:
 	err = check_map_func_compatibility(env, meta.map.ptr, func_id);
 	if (err)
 		return err;
@@ -15827,7 +15925,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 {
 	bool sleepable, rcu_lock, rcu_unlock, preempt_disable, preempt_enable;
 	enum bpf_prog_type prog_type = resolve_prog_type(env->prog);
-	struct bpf_reg_state *regs = cur_regs(env);
+	struct bpf_reg_state *regs = cur_regs(env), unwound_r0;
 	const char *func_name, *ptr_type_name;
 	const struct btf_type *t, *ptr_type;
 	struct bpf_call_arg_meta meta;
@@ -16116,13 +16214,23 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	}
 
 	bpf_diag_record_caller_saved(env, regs);
-	bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
+	/* The callback unwound: keep its R0, see check_helper_call(). */
+	if (env->cur_state->unwound) {
+		unwound_r0 = regs[BPF_REG_0];
+		ret_nregs = 0;
+	} else {
+		bpf_diag_mod_begin(env, &regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
+	}
 	for (i = 0; i < CALLER_SAVED_REGS; i++) {
 		u32 regno = caller_saved[i];
 
 		bpf_mark_reg_not_init(env, &regs[regno]);
 	}
 	invalidate_outgoing_stack_args(env, cur_func(env));
+	if (env->cur_state->unwound) {
+		regs[BPF_REG_0] = unwound_r0;
+		goto unwound;
+	}
 
 	/* Check return type */
 	t = btf_type_skip_modifiers(desc_btf, meta.func_proto->type, NULL);
@@ -16316,6 +16424,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		}
 	}
 
+unwound:
 	if (is_kfunc_dynptr_write(&meta) ?
 	    dynptr_write_changes_pkt_data(meta.dynptr_write_type) :
 	    bpf_is_kfunc_pkt_changing(&meta))
diff --git a/tools/include/uapi/linux/bpf.h b/tools/include/uapi/linux/bpf.h
index 28904c6f0787..95b41ae6584d 100644
--- a/tools/include/uapi/linux/bpf.h
+++ b/tools/include/uapi/linux/bpf.h
@@ -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,
diff --git a/tools/testing/selftests/bpf/progs/verifier_unwind.c b/tools/testing/selftests/bpf/progs/verifier_unwind.c
index be3992ed8eed..6fd8e56485ed 100644
--- a/tools/testing/selftests/bpf/progs/verifier_unwind.c
+++ b/tools/testing/selftests/bpf/progs/verifier_unwind.c
@@ -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 (
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 08/73] bpf: Let the inlined bpf_loop pass on a callback that unwinds
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (6 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 07/73] bpf: Let a callback unwind out of a helper that has an unwind label Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 09/73] bpf: Give the helpers that call a callback an unwind label Kumar Kartikeya Dwivedi
                   ` (64 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  2 ++
 kernel/bpf/core.c            | 20 ++++++++++--
 kernel/bpf/fixups.c          | 59 +++++++++++++++++++++++++++++++-----
 3 files changed, 71 insertions(+), 10 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 117c3a3f7cbb..3f6de7caa0ad 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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 */
 };
 
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 2b1d655aa070..87262e4d4c0c 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -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;
 }
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index ad0ea7803332..f3faa7c300ec 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -3199,6 +3199,21 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 	return 0;
 }
 
+/*
+ * When the callback can unwind and unwind_goto follows the call of bpf_loop,
+ * unwind_goto follows the call of the callback, and the pad restores r6-r8 and
+ * jumps to the pad after the call of bpf_loop with the r0 of the callback, which
+ * the verifier has checked with the state of that r0. The callback may have no
+ * unwind_exit yet: bpf_insert_recursion_checks() adds the one of the check of a
+ * recursive callback when the loop is inlined already. That pad has to be one the
+ * verifier saw: a loop of no rounds never runs its callback, and an unwind_exit
+ * may sit on a path never taken, so the pad can be dead, and dead code is
+ * removed after the inlining, which sends a jump into it to whatever follows.
+ * The unwind_goto that followed the call of bpf_loop doesn't follow a call
+ * anymore and becomes a no-op jump either way. A loop of no rounds may have no
+ * unwind_goto at all, since the verifier asked for none, and then the insn after
+ * the call is some other insn.
+ */
 static int inline_bpf_loop(struct bpf_verifier_env *env, int position,
 			   s32 stack_base, u32 callback_subprogno)
 {
@@ -3208,10 +3223,15 @@ static int inline_bpf_loop(struct bpf_verifier_env *env, int position,
 	int reg_loop_max = BPF_REG_6;
 	int reg_loop_cnt = BPF_REG_7;
 	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);
+	bool pad = has_unwind_goto &&
+		   bpf_subprog_unwinds(&env->subprog_info[callback_subprogno]) &&
+		   env->insn_aux_data[position + 2 + unwind_goto->off].seen;
 
 	struct bpf_insn *insn_buf = env->insn_buf;
 	struct bpf_insn *last;
-	u32 cnt = 0;
+	u32 cnt = 0, call;
 
 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
 	 * be careful to modify this code in sync.
@@ -3220,9 +3240,20 @@ static int inline_bpf_loop(struct bpf_verifier_env *env, int position,
 	/* Return error and jump to the end of the patch if
 	 * expected number of iterations is too big.
 	 */
-	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2);
+	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, pad ? 6 : 2);
 	insn_buf[cnt++] = BPF_MOV64_IMM(BPF_REG_0, -E2BIG);
-	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16);
+	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, pad ? 21 : 16);
+	if (pad) {
+		/*
+		 * The pad: r0 is what the callback unwound with. Nothing falls through to this
+		 * place, so no jump around the pad is needed.
+		 */
+		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
+		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
+		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
+		/* to the pad of the caller, the target is set below */
+		insn_buf[cnt++] = BPF_JMP32_A(0);
+	}
 	/* spill R6, R7, R8 to use these as loop vars */
 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_6, r6_offset);
 	insn_buf[cnt++] = BPF_STX_MEM(BPF_DW, BPF_REG_10, BPF_REG_7, r7_offset);
@@ -3234,15 +3265,19 @@ static int inline_bpf_loop(struct bpf_verifier_env *env, int position,
 	/* loop header,
 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
 	 */
-	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5);
+	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, pad ? 6 : 5);
 	/* callback call, the offset is set below */
 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
+	call = cnt;
 	insn_buf[cnt++] = BPF_CALL_REL(0);
+	if (pad)
+		/* to the pad above when the callback left with unwind_exit */
+		insn_buf[cnt++] = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, BPF_UNWIND_GOTO, -15, 0);
 	/* increment loop counter */
 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
 	/* jump to loop header if callback returned 0 */
-	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6);
+	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, pad ? -7 : -6);
 	/* return value of bpf_loop,
 	 * set R0 to the number of iterations
 	 */
@@ -3255,9 +3290,19 @@ static int inline_bpf_loop(struct bpf_verifier_env *env, int position,
 	last = bpf_patch_list_add(env, position, insn_buf, cnt);
 	if (IS_ERR(last))
 		return PTR_ERR(last);
-	/* insn_buf[12] is the BPF_CALL_REL instruction */
-	bpf_patch_list_jump(&env->patch_list, last - (cnt - 1 - 12),
+	/* the BPF_CALL_REL instruction */
+	bpf_patch_list_jump(&env->patch_list, last - (cnt - 1 - call),
 			    env->subprog_info[callback_subprogno].start, 0);
+	/*
+	 * insn_buf[6] goes where the unwind_goto after the call of bpf_loop goes, whichever side
+	 * of the call that is. A long jump, since an unwind_goto may jump as far as a jump can.
+	 */
+	if (pad)
+		bpf_patch_list_jump(&env->patch_list, last - (cnt - 1 - 6),
+				    position + 2 + unwind_goto->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);
 	return 0;
 }
 
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 09/73] bpf: Give the helpers that call a callback an unwind label
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (7 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 08/73] bpf: Let the inlined bpf_loop pass on a callback that unwinds Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 10/73] bpf: Let the comparator of bpf_rbtree_add unwind Kumar Kartikeya Dwivedi
                   ` (63 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/kernel/bpf/arraymap.c b/kernel/bpf/arraymap.c
index 508706d0c360..15e9a18b4ec6 100644
--- a/kernel/bpf/arraymap.c
+++ b/kernel/bpf/arraymap.c
@@ -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)
 {
diff --git a/kernel/bpf/bpf_iter.c b/kernel/bpf/bpf_iter.c
index 2bb110e0867d..57e1800a5741 100644
--- a/kernel/bpf/bpf_iter.c
+++ b/kernel/bpf/bpf_iter.c
@@ -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,
diff --git a/kernel/bpf/hashtab.c b/kernel/bpf/hashtab.c
index b8491105430a..690f5ad80cc8 100644
--- a/kernel/bpf/hashtab.c
+++ b/kernel/bpf/hashtab.c
@@ -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)
 {
diff --git a/kernel/bpf/ringbuf.c b/kernel/bpf/ringbuf.c
index 447863ece26a..4aa7c78a6b6e 100644
--- a/kernel/bpf/ringbuf.c
+++ b/kernel/bpf/ringbuf.c
@@ -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,
diff --git a/kernel/bpf/task_iter.c b/kernel/bpf/task_iter.c
index 2ee7b3b3c10b..3480f6d9f648 100644
--- a/kernel/bpf/task_iter.c
+++ b/kernel/bpf/task_iter.c
@@ -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,
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 4b65f537668c..ca8e6fad617d 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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. */
diff --git a/tools/testing/selftests/bpf/progs/verifier_unwind.c b/tools/testing/selftests/bpf/progs/verifier_unwind.c
index 6fd8e56485ed..668e1d1b94b4 100644
--- a/tools/testing/selftests/bpf/progs/verifier_unwind.c
+++ b/tools/testing/selftests/bpf/progs/verifier_unwind.c
@@ -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
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 10/73] bpf: Let the comparator of bpf_rbtree_add unwind
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (8 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 09/73] bpf: Give the helpers that call a callback an unwind label Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 11/73] bpf: Let a state leave its frame at may_goto without an exit insn Kumar Kartikeya Dwivedi
                   ` (62 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 kernel/bpf/helpers.c  | 55 ++++++++++++++++++++++++----------
 kernel/bpf/verifier.c | 69 ++++++++++++++++++++++++++++++++++++++-----
 2 files changed, 100 insertions(+), 24 deletions(-)

diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index 7b3e10a4a97e..bc6f2a8da05e 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -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)
 {
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index ca8e6fad617d..35126b785f1f 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -11467,10 +11467,9 @@ static bool helper_has_cb_pad(enum bpf_func_id func_id)
 	}
 }
 
-/* The kfunc calls its callback with a pad. None yet. */
 static bool kfunc_has_cb_pad(u32 btf_id)
 {
-	return false;
+	return is_bpf_rbtree_add_kfunc(btf_id);
 }
 
 static bool insn_has_cb_pad(struct bpf_insn *insn)
@@ -15928,10 +15927,23 @@ static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg
 
 static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
 
+/*
+ * Does freeing an object of this type run code that a program may not call under a lock? The
+ * 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)
+{
+	const struct btf_struct_meta *meta = btf_find_struct_meta(btf, btf_id);
+
+	return meta && btf_record_has_field(meta->record,
+					    BPF_GRAPH_ROOT | BPF_KPTR_REF | BPF_KPTR_PERCPU);
+}
+
 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;
+	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;
@@ -16049,11 +16061,12 @@ 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);
 	if ((is_bpf_obj_drop_kfunc(meta.func_id) ||
-	     is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && (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))) {
+	     is_bpf_percpu_obj_drop_kfunc(meta.func_id)) && nmi_prog) {
 		struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
 		if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) {
 			verbose(env, "%s cannot be used in tracing programs on types with NMI unsafe fields\n",
@@ -16073,6 +16086,33 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	}
 
 	if (is_bpf_rbtree_add_kfunc(meta.func_id)) {
+		/*
+		 * The pad of the kfunc drops the node when the comparator
+		 * unwinds, the destructors of its fields included, which is a
+		 * bpf_obj_drop() under the rule above. The comparator unwinds
+		 * from the check of its recursion too, see check_cb_unwind().
+		 */
+		if (bpf_subprog_unwinds(&env->subprog_info[meta.subprogno]) && nmi_prog) {
+			struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
+			if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) {
+				verbose(env,
+					"%s with a comparator that unwinds cannot be used in tracing programs on types with NMI unsafe fields\n",
+					func_name);
+				return -EINVAL;
+			}
+		}
+		/*
+		 * The drop runs under the lock of the tree, where a program can call nothing that
+		 * releases an object, so no destructor of a field may run. A list head's would take
+		 * 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)) {
+			verbose(env,
+				"%s with a comparator that unwinds cannot be used on types that take a lock when freed\n",
+				func_name);
+			return -EINVAL;
+		}
 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
 					 set_rbtree_add_callback_state);
 		if (err) {
@@ -16179,11 +16219,24 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	}
 
 	if (is_bpf_list_push_kfunc(meta.func_id) || is_bpf_rbtree_add_kfunc(meta.func_id)) {
-		ref_convert_owning_non_owning(env, regs[BPF_REG_2].id);
+		id = regs[BPF_REG_2].id;
 		struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
 		err = record_call_fixup(env, regs[BPF_REG_2].var_off.value, struct_meta);
 		if (err)
 			return err;
+		/*
+		 * If the comparator unwound, the node is not in the tree and the kfunc has dropped
+		 * it. The comparator got the node as a non-owning reference and may have unwound
+		 * with it in R0, so all non-owning references are invalidated.
+		 */
+		if (env->cur_state->unwound) {
+			invalidate_non_owning_refs(env);
+			err = release_reference(env, id);
+			if (err)
+				return err;
+		} else {
+			ref_convert_owning_non_owning(env, id);
+		}
 	}
 
 	if ((is_kfunc_call(&meta, special_kfunc_list[KF_bpf_dynptr_slice]) ||
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 11/73] bpf: Let a state leave its frame at may_goto without an exit insn
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (9 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 10/73] bpf: Let the comparator of bpf_rbtree_add unwind Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` sashiko-bot
  2026-12-01  4:38 ` [PATCH bpf-next v1 12/73] bpf: Choose what a cancelled program returns by its type Kumar Kartikeya Dwivedi
                   ` (61 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 3f6de7caa0ad..2d214bc24db1 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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:
diff --git a/kernel/bpf/const_fold.c b/kernel/bpf/const_fold.c
index 1524166cf6db..1a7e521a4b92 100644
--- a/kernel/bpf/const_fold.c
+++ b/kernel/bpf/const_fold.c
@@ -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++)
diff --git a/kernel/bpf/failing_path.c b/kernel/bpf/failing_path.c
index 677ec4236226..26469e41f04a 100644
--- a/kernel/bpf/failing_path.c
+++ b/kernel/bpf/failing_path.c
@@ -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);
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index f6456e5be5fd..4d04d17603ae 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -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);
 
 	/*
diff --git a/kernel/bpf/precision.c b/kernel/bpf/precision.c
index f2ef763684f4..225dabbd4e70 100644
--- a/kernel/bpf/precision.c
+++ b/kernel/bpf/precision.c
@@ -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);
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 35126b785f1f..36024c4df4af 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -196,7 +196,7 @@ struct bpf_verifier_stack_elem {
 	 * and after processing instruction 'prev_insn_idx'
 	 */
 	struct bpf_verifier_state st;
-	int insn_idx;
+	int insn_idx; /* -1: the state leaves its frame at 'prev_insn_idx', see unwind_frame() */
 	int prev_insn_idx;
 	bool again;	/* see bpf_flow_deliver() */
 	struct bpf_verifier_stack_elem *next;
@@ -3373,17 +3373,12 @@ static int check_unwind_insns(struct bpf_verifier_env *env)
 	bool seen = false;
 	int i;
 
-	for (i = 0; i < env->subprog_cnt; i++)
-		env->subprog_info[i].bail_insn = -1;
-
 	for (i = 0; i < env->prog->len; i++, insn++) {
 		if (bpf_is_ldimm64(insn)) {
 			i++;
 			insn++;
 			continue;
 		}
-		if (insn->code == (BPF_JMP | BPF_EXIT))
-			bpf_find_containing_subprog(env, i)->bail_insn = i;
 		if (bpf_is_unwind_exit(insn)) {
 			bpf_find_containing_subprog(env, i)->can_unwind = true;
 			seen = true;
@@ -6078,7 +6073,7 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 				si[s].has_tail_call ? "tail calls" : "LD_ABS");
 			break;
 		}
-		if (si[s].bail_insn < 0) {
+		if (si[s].exit_idx == U32_MAX) {
 			verbose(env, "recursive %s() has no exit\n", bpf_subprog_name(env, s));
 			break;
 		}
@@ -11780,8 +11775,11 @@ static void hide_returned_stack_ptrs(struct bpf_verifier_env *env, u32 nregs,
 	}
 }
 
-/* The current state is at exit of a function that is verified on its own. */
-static int exit_func_on_its_own(struct bpf_verifier_env *env)
+/*
+ * The current state leaves a function that is verified separately.
+ * @exit_idx: the exit insn that the state is at, or else any exit of the function.
+ */
+static int exit_func_on_its_own(struct bpf_verifier_env *env, int exit_idx)
 {
 	struct bpf_verifier_state *state = env->cur_state;
 	struct bpf_func_state *callee = state->frame[0];
@@ -11801,7 +11799,7 @@ static int exit_func_on_its_own(struct bpf_verifier_env *env)
 		return err;
 
 	account_current_path(env);
-	err = bpf_flow_exit(env, state, env->insn_idx);
+	err = bpf_flow_exit(env, state, exit_idx);
 	return err ?: PROCESS_BPF_EXIT;
 }
 
@@ -20669,7 +20667,7 @@ static int process_bpf_exit_full(struct bpf_verifier_env *env,
 	struct bpf_func_state *cur_frame = cur_func(env);
 
 	if (!exception_exit && !env->cur_state->curframe && env->cur_state->instance_id)
-		return exit_func_on_its_own(env);
+		return exit_func_on_its_own(env, env->insn_idx);
 
 	/* We must do check_reference_leak here before
 	 * prepare_func_exit to handle the case when
@@ -21545,7 +21543,8 @@ static bool state_can_unwind(struct bpf_verifier_env *env, const struct bpf_veri
 	const struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
 	bool top;
 
-	if (sub->bail_insn < 0)
+	/* unwind_frame() needs an insn at which the state leaves the function. */
+	if (sub->exit_idx == U32_MAX)
 		return false;
 	if (st->acquired_refs != frame->entry_refs ||
 	    st->active_rcu_locks != frame->entry_rcu_locks ||
@@ -21576,8 +21575,7 @@ static bool guard_reads_unset_reg(struct bpf_verifier_env *env,
 
 /*
  * The current frame leaves with 0 in place of the result: with unwind_exit if the subprog
- * can do that, with exit otherwise. The insns are added when the main pass is over. Until
- * then an exit that the subprog has stands for them.
+ * can do that, with exit otherwise. The insns are added when the main pass is over.
  */
 static int push_unwind_exit(struct bpf_verifier_env *env)
 {
@@ -21587,7 +21585,7 @@ static int push_unwind_exit(struct bpf_verifier_env *env)
 
 	if (env->cur_state->speculative)
 		return 0;
-	branch = push_stack(env, sub->bail_insn, env->insn_idx, false);
+	branch = push_stack(env, -1, env->insn_idx, false);
 	if (IS_ERR(branch))
 		return PTR_ERR(branch);
 	branch->unwound = sub->bail_unwinds;
@@ -21680,6 +21678,54 @@ static int check_loop_guard(struct bpf_verifier_env *env)
 	return err;
 }
 
+/*
+ * The current frame of @st is left at @insn_idx, where the program has no exit: the verifier
+ * emits one after the main pass. @st->unwound tells which one. No insn stands for it in the
+ * main pass. What an exit does to a state is done to @st here, and what is left of @st goes
+ * where the frame returns to, through the worklist like every other state. @st is taken.
+ */
+static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int insn_idx)
+{
+	struct bpf_func_state *frame = st->frame[st->curframe];
+	struct bpf_verifier_state *cur = env->cur_state;
+	int cur_idx = env->insn_idx, err;
+	bool print_state;
+	u32 cnt;
+
+	if (env->log.level & BPF_LOG_LEVEL2)
+		verbose(env, "from %d to %s of func#%d\n", insn_idx,
+			st->unwound ? "unwind_exit" : "exit", frame->subprogno);
+	env->cur_state = st;
+	env->insn_idx = insn_idx;
+	if (!st->curframe && st->instance_id) {
+		/*
+		 * The states that leave the function are compared as if they were at one exit, so
+		 * leave the loops first. A recursion is not left, see loop_stack_pop().
+		 */
+		cnt = frame->loop_stack_cnt &&
+		      frame->loop_stack[0].loop->kind == BPF_LOOP_RECURSION;
+		if (frame->loop_stack_cnt != cnt) {
+			leave_loops(frame, cnt);
+			bpf_equations_clean(env, st);
+		}
+		err = exit_func_on_its_own(env, env->subprog_info[frame->subprogno].exit_idx);
+	} else {
+		err = process_bpf_exit_full(env, &print_state, false);
+	}
+	if (err == INSN_IDX_UPDATED)
+		err = bpf_flow_deliver(env, st, env->insn_idx, insn_idx, false);
+	else if (err == PROCESS_BPF_EXIT)
+		err = 0;
+	else if (err < 0 && st->frame[0])
+		/* the check of an exit failed for this state, see flow_apply_exit() */
+		err = min(bpf_flow_edge_unproven(env, st, insn_idx, err), 0);
+	env->cur_state = cur;
+	/* On an error env->insn_idx stays at the site, where the error is recorded. */
+	if (err >= 0)
+		env->insn_idx = cur_idx;
+	return err;
+}
+
 /* 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)
 {
@@ -21688,7 +21734,11 @@ static int flow_drain(struct bpf_verifier_env *env)
 
 	while ((elem = env->head)) {
 		env->head = elem->next;
-		if (!err)
+		if (err)
+			;
+		else if (elem->insn_idx < 0)
+			err = unwind_frame(env, &elem->st, elem->prev_insn_idx);
+		else
 			err = bpf_flow_deliver(env, &elem->st, elem->insn_idx,
 					       elem->prev_insn_idx, elem->again);
 		bpf_free_verifier_state(env, &elem->st, false);
diff --git a/tools/testing/selftests/bpf/progs/verifier_equations.c b/tools/testing/selftests/bpf/progs/verifier_equations.c
index e88d6ff0ca8e..66786aae3664 100644
--- a/tools/testing/selftests/bpf/progs/verifier_equations.c
+++ b/tools/testing/selftests/bpf/progs/verifier_equations.c
@@ -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"),
diff --git a/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c b/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c
index d030a8c52da5..8ec967ce8258 100644
--- a/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c
+++ b/tools/testing/selftests/bpf/progs/verifier_stack_ptr.c
@@ -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 ("					\
diff --git a/tools/testing/selftests/bpf/progs/verifier_trip_count.c b/tools/testing/selftests/bpf/progs/verifier_trip_count.c
index d298db135aad..70a2a549f115 100644
--- a/tools/testing/selftests/bpf/progs/verifier_trip_count.c
+++ b/tools/testing/selftests/bpf/progs/verifier_trip_count.c
@@ -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");
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 12/73] bpf: Choose what a cancelled program returns by its type
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (10 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 11/73] bpf: Let a state leave its frame at may_goto without an exit insn Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 13/73] bpf: Emit landing pads that leave RCU sections Kumar Kartikeya Dwivedi
                   ` (60 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 2d214bc24db1..bc5c9b13fc64 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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)
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 4aad10c3c8e9..5e30a4e70660 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -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)
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index f3faa7c300ec..54dcfb3faa42 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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();
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 36024c4df4af..72670bf3c129 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -3408,6 +3408,11 @@ static int check_unwind_insns(struct bpf_verifier_env *env)
 		verbose(env, "JIT does not support unwinding\n");
 		return -ENOTSUPP;
 	}
+	/* An extension must not unwind into the program that it extends. */
+	if (env->prog->type == BPF_PROG_TYPE_EXT && env->subprog_info[0].can_unwind) {
+		verbose(env, "unwind_exit in the main program of an extension\n");
+		return -EINVAL;
+	}
 	env->prog->jit_required = 1;
 	env->prog->aux->can_unwind = env->subprog_info[0].can_unwind;
 	return 0;
@@ -11722,7 +11727,6 @@ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int i
 	entry.speculative = state->speculative;
 	entry.in_sleepable = state->in_sleepable;
 	entry.suspect_loops = state->suspect_loops;
-	entry.callers_unknown = state->callers_unknown;
 	init_func_state(env, callee, BPF_MAIN_FUNC, 0, subprog);
 	/* the frame that says so is not there when the function is verified */
 	callee->in_rcu_callback_fn = in_rcu_callback(env);
@@ -12843,8 +12847,7 @@ static bool returns_to_kernel(const struct bpf_verifier_state *state)
 {
 	const struct bpf_func_state *frame = state->frame[0];
 
-	return !frame->in_async_callback_fn &&
-	       (!state->callers_unknown || frame->in_exception_callback_fn);
+	return !frame->subprogno || frame->in_exception_callback_fn;
 }
 
 static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
@@ -21508,14 +21511,60 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge
 	return enter_callback(env, false, NULL);
 }
 
-/* Can the main program return 0? */
-static bool zero_is_valid_retval(struct bpf_verifier_env *env)
+/*
+ * What @subprog returns when it is unwound, see push_unwind_exit(). No code of the program chooses
+ * that value, so for the main program it is the one that refuses, drops or changes nothing. That
+ * is 0, but:
+ *
+ *	tc					TC_ACT_SHOT, 0 is TC_ACT_OK
+ *	lwt, flow dissector			BPF_DROP, 0 is BPF_OK
+ *	syscall					-ECANCELED, 0 tells user space that all was done
+ *	lsm, the hook returns an errno		-EPERM, 0 lets the operation go on
+ *	the range is [1, 1]			1, hooks that cannot refuse
+ *
+ * Each is a value that check_return_code() lets the program return.
+ * Two 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.
+ * An extension returns into the program that it extends, with the value of that program.
+ * The exception callback returns in place of the main program.
+ */
+int bpf_cancelled_retval(struct bpf_verifier_env *env, int subprog)
 {
+	struct bpf_prog *prog = env->prog;
 	struct bpf_retval_range range;
 
-	if (program_returns_void(env) || !return_retval_range(env, &range))
-		return true;
-	return range.minval <= 0 && range.maxval >= 0;
+	if (subprog && subprog != env->exception_callback_subprog)
+		return 0;
+	switch (resolve_prog_type(prog)) {
+	case BPF_PROG_TYPE_SCHED_CLS:
+	case BPF_PROG_TYPE_SCHED_ACT:
+		return TC_ACT_SHOT;
+	case BPF_PROG_TYPE_LWT_IN:
+	case BPF_PROG_TYPE_LWT_OUT:
+	case BPF_PROG_TYPE_LWT_XMIT:
+	case BPF_PROG_TYPE_LWT_SEG6LOCAL:
+	case BPF_PROG_TYPE_FLOW_DISSECTOR:
+		return BPF_DROP;
+	case BPF_PROG_TYPE_SYSCALL:
+		return -ECANCELED;
+	case BPF_PROG_TYPE_XDP:
+		return XDP_ABORTED;
+	case BPF_PROG_TYPE_NETFILTER:
+		return NF_DROP;
+	case BPF_PROG_TYPE_SK_SKB:
+	case BPF_PROG_TYPE_SK_MSG:
+	case BPF_PROG_TYPE_SK_REUSEPORT:
+	case BPF_PROG_TYPE_SK_LOOKUP:
+		return SK_DROP;
+	default:
+		break;
+	}
+	if (get_func_retval_range(prog, &range) && range.minval < 0)
+		return -EPERM;
+	if (!program_returns_void(env) && return_retval_range(env, &range) && range.minval > 0)
+		return range.minval;
+	return 0;
 }
 
 /*
@@ -21541,7 +21590,6 @@ static bool state_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];
-	bool top;
 
 	/* unwind_frame() needs an insn at which the state leaves the function. */
 	if (sub->exit_idx == U32_MAX)
@@ -21550,14 +21598,13 @@ static bool state_can_unwind(struct bpf_verifier_env *env, const struct bpf_veri
 	    st->active_rcu_locks != frame->entry_rcu_locks ||
 	    st->active_preempt_locks != frame->entry_preempt_locks)
 		return false;
-	if (frame->in_callback_fn || frame->in_exception_callback_fn)
+	if (frame->in_callback_fn)
 		return false;
 	/* the kernel called it: either exit ends it */
-	top = !st->curframe && !st->callers_unknown &&
-	      (!frame->subprogno || frame->in_async_callback_fn);
-	if (top && !frame->subprogno && !zero_is_valid_retval(env))
-		return false;
-	return top || sub->bail_unwinds || or_exit;
+	if (!st->curframe && (!frame->subprogno || frame->in_async_callback_fn ||
+			      frame->in_exception_callback_fn))
+		return true;
+	return sub->bail_unwinds || or_exit;
 }
 
 /* May_goto at the head of a loop skips the body. Does it go to code that reads what is not set? */
@@ -21576,6 +21623,7 @@ static bool guard_reads_unset_reg(struct bpf_verifier_env *env,
 /*
  * The current frame leaves with 0 in place of the result: with unwind_exit if the subprog
  * can do that, with exit otherwise. The insns are added when the main pass is over.
+ * What the kernel called leaves with bpf_cancelled_retval().
  */
 static int push_unwind_exit(struct bpf_verifier_env *env)
 {
@@ -21590,7 +21638,8 @@ static int push_unwind_exit(struct bpf_verifier_env *env)
 		return PTR_ERR(branch);
 	branch->unwound = sub->bail_unwinds;
 	regs = branch->frame[branch->curframe]->regs;
-	__mark_reg_const_zero(&regs[BPF_REG_0]);
+	bpf_mark_reg_known_scalar(&regs[BPF_REG_0],
+				  bpf_cancelled_retval(env, cur_func(env)->subprogno));
 	if (bpf_ret_reg_pair(env, cur_func(env)->subprogno))
 		__mark_reg_const_zero(&regs[BPF_REG_2]);
 	bpf_equations_forget_xreg(env, branch, bpf_xreg(branch->curframe, BPF_REG_0));
@@ -23406,8 +23455,6 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog,
 	state->curframe = 0;
 	state->speculative = false;
 	state->in_sleepable = context == BPF_FUNC_CTX_SLEEPABLE;
-	/* nobody knows what the callers of a global function or of an extension hold */
-	state->callers_unknown = subprog || env->prog->type == BPF_PROG_TYPE_EXT;
 	env->no_rcu_read_lock = context == BPF_FUNC_CTX_NO_RCU_LOCK;
 	state->frame[0] = kzalloc_obj(struct bpf_func_state, BPF_VERIFIER_GFP);
 	if (!state->frame[0]) {
@@ -24689,10 +24736,8 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,
 				prog_extension ? "Extension" : "Tracing");
 			return -EINVAL;
 		}
-		/* unwind_exit of the main prog is exit, unless it's an extension */
-		tgt_can_unwind = (subprog || tgt_prog->type == BPF_PROG_TYPE_EXT) &&
-				 (aux->func ? aux->func[subprog]->aux->can_unwind
-					    : aux->can_unwind);
+		/* 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 &&
 		    prog->expected_attach_type != BPF_TRACE_FENTRY) {
@@ -24767,12 +24812,6 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,
 					"Extension program may sleep, while original does not\n");
 				return -EINVAL;
 			}
-			/* There is no unwind_goto after the calls of the original */
-			if (prog->aux->can_unwind && !tgt_can_unwind) {
-				bpf_log(log,
-					"Extension program can unwind, while original does not\n");
-				return -EINVAL;
-			}
 		}
 		if (!tgt_prog->jited) {
 			bpf_log(log, "Can attach to only JITed progs\n");
diff --git a/tools/testing/selftests/bpf/prog_tests/unwind_attach.c b/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
index 37e03b3e0ee8..674c5272cf75 100644
--- a/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
+++ b/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
@@ -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");
 
 	/*
diff --git a/tools/testing/selftests/bpf/progs/verifier_barrier.c b/tools/testing/selftests/bpf/progs/verifier_barrier.c
index bc12cc17f0f2..2cf55613406d 100644
--- a/tools/testing/selftests/bpf/progs/verifier_barrier.c
+++ b/tools/testing/selftests/bpf/progs/verifier_barrier.c
@@ -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)
diff --git a/tools/testing/selftests/bpf/progs/verifier_budget.c b/tools/testing/selftests/bpf/progs/verifier_budget.c
index 1bef19db503b..4f38518de92a 100644
--- a/tools/testing/selftests/bpf/progs/verifier_budget.c
+++ b/tools/testing/selftests/bpf/progs/verifier_budget.c
@@ -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 (
diff --git a/tools/testing/selftests/bpf/verifier/calls.c b/tools/testing/selftests/bpf/verifier/calls.c
index 6f621c69ff00..d1bf9922a306 100644
--- a/tools/testing/selftests/bpf/verifier/calls.c
+++ b/tools/testing/selftests/bpf/verifier/calls.c
@@ -599,6 +599,7 @@
 	},
 	.prog_type = BPF_PROG_TYPE_SCHED_CLS,
 	.result = ACCEPT,
+	.retval = 2, /* TC_ACT_SHOT */
 },
 {
 	"calls: using r0 returned by callee",
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 13/73] bpf: Emit landing pads that leave RCU sections
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (11 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 12/73] bpf: Choose what a cancelled program returns by its type Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 14/73] bpf: Release locks and irq flags in landing pads Kumar Kartikeya Dwivedi
                   ` (59 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Co-developed-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index bc5c9b13fc64..e9db40421411 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/Makefile b/kernel/bpf/Makefile
index 03f0539490c9..199c8635a71f 100644
--- a/kernel/bpf/Makefile
+++ b/kernel/bpf/Makefile
@@ -11,7 +11,7 @@ obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_
 obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list.o lpm_trie.o map_in_map.o bloom_filter.o
 obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o
-obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o 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
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 54dcfb3faa42..0df3b5630b0b 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -278,7 +278,7 @@ static void patch_list_adj_aux(struct bpf_prog *prog, struct bpf_insn_patch *p,
 		slot[i].seen = last->seen ?: i > p->self;
 		/* messages name the insn of the original program */
 		slot[i].orig_idx = last->orig_idx;
-		/* for may_goto in front of the insn, see bpf_insert_loop_guards() */
+		/* for may_goto before the insn, see bpf_insert_sites() */
 		slot[i].live_regs_before = last->live_regs_before;
 		slot[i].zext_dst = bpf_insn_def32(prog, &patch[i]) >= 0;
 		/*
@@ -569,10 +569,23 @@ int bpf_patch_list_commit(struct bpf_verifier_env *env)
 	return err;
 }
 
-/* How subprog @s leaves when it has to stop, see push_unwind_exit(). Returns the length. */
-static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn *buf)
+/* The insn that subprog @s leaves with when it has to stop: unwind_exit if it can do that */
+static struct bpf_insn unwind_exit_insn(struct bpf_verifier_env *env, int s)
 {
 	struct bpf_subprog_info *sub = &env->subprog_info[s];
+	struct bpf_insn insn = BPF_EXIT_INSN();
+
+	if (sub->bail_unwinds) {
+		insn.src_reg = BPF_UNWIND_EXIT;
+		sub->can_unwind = true;
+		env->prog->jit_required = 1;
+	}
+	return insn;
+}
+
+/* How subprog @s leaves when it has to stop, see unwind_frame(). Returns the length. */
+static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn *buf)
+{
 	int n = 0;
 
 	if (!env->bypass_spec_v1)
@@ -580,24 +593,82 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
 	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();
-	if (sub->bail_unwinds) {
-		buf[n].src_reg = BPF_UNWIND_EXIT;
-		sub->can_unwind = true;
-		env->prog->jit_required = 1;
+	buf[n++] = unwind_exit_insn(env, s);
+	return n;
+}
+
+/*
+ * The landing pad of a site in subprog @s. The only exit of a pad is its last insn. Nothing in a
+ * pad is hardened against a cpu that mispredicts: only a program that is loaded with CAP_PERFMON
+ * gets one, see state_can_unwind().
+ * Returns the number of insns, BPF_PAD_MAX_INSNS + 1 at most.
+ */
+static int emit_pad(struct bpf_verifier_env *env, int s, const struct bpf_pad_plan *plan,
+		    struct bpf_insn *buf)
+{
+	int n = 0;
+
+	n += bpf_pad_insns(env, plan, s, buf + n);
+	buf[n++] = unwind_exit_insn(env, s);
+	return n;
+}
+
+/*
+ * The landing pads of the sites of subprog @s go after its last insn. Sites whose pads have the
+ * same insns share one. @new has room for a pad. Returns the insns in @pads and their number.
+ */
+static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *new,
+			struct bpf_insn **pads)
+{
+	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;
+
+	for (i = env->subprog_info[s].start; i <= last; i++) {
+		if (!aux[i].loop_guard || !aux[i].guard_unwinds)
+			continue;
+		/* no state got there in the pass: the empty plan will do */
+		if (!bpf_pad_plan_get(env, i, BPF_SITE_GUARD))
+			return -ENOMEM;
+		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
+			/* bpf_insert_recursion_checks() emits the pad of the check */
+			if (plan->kind == BPF_SITE_RECURSION)
+				continue;
+			n = emit_pad(env, s, plan, new);
+			for (pad = 0; pad < cnt; pad += len) {
+				for (len = 1; buf[pad + len - 1].code != (BPF_JMP | BPF_EXIT);
+				     len++)
+					;
+				if (len == n && !memcmp(&buf[pad], new, n * sizeof(*buf)))
+					break;
+			}
+			plan->pad = pad;
+			if (pad < cnt)
+				continue;
+			insn = kvrealloc(buf, (cnt + n) * sizeof(*buf), BPF_VERIFIER_GFP);
+			if (!insn)
+				return -ENOMEM;
+			*pads = buf = insn;
+			memcpy(&buf[cnt], new, n * sizeof(*buf));
+			cnt += n;
+		}
 	}
-	return n + 1;
+	return cnt;
 }
 
 /*
- * Add may_goto in front of the insns that the main pass marked, see
- * check_loop_guard(). It verified the edge from the insn to where may_goto goes.
+ * Emit what the main pass decided about the sites: may_goto before the insns that it
+ * marked, see check_loop_guard(), and the landing pads. It verified the edge from the insn to
+ * where may_goto goes. What a pad does it did to the states that left the frame at the site, see
+ * unwind_frame().
  *
- *	may_goto to		or	may_goto leave		see push_unwind_exit()
+ *	may_goto to		or	may_goto pad
  *	insn				insn
  *					...
  *					last insn of the subprog
- *				leave:	r0 = 0
+ *				pad:	the releases
+ *					r0 = bpf_cancelled_retval()
  *					exit
  *
  * bpf_do_misc_fixups() keeps the address of the count of may_goto in a register that is
@@ -606,40 +677,59 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
  *  - The guard of a jump goes where the jump goes.
  *  - What is live where the guard at the head of a loop goes is live at the head,
  *    see bpf_head_guard_target().
- *  - On the way out of the subprog R0, and R2 of a pair, are set to 0.
+ *  - A landing pad reads no register.
  */
-int bpf_insert_loop_guards(struct bpf_verifier_env *env)
+int bpf_insert_sites(struct bpf_verifier_env *env)
 {
 	struct bpf_insn patch[2] = { BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0) };
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
-	struct bpf_insn leave[4], *insn;
+	struct bpf_insn *pads = NULL, *new, *insn;
+	const struct bpf_pad_plan *plan;
 	struct bpf_subprog_info *sub;
-	int i, s, n, err;
+	int i, s, cnt, err = 0;
 
-	for (s = 0; s < env->subprog_cnt; s++) {
+	new = kvzalloc_objs(*new, BPF_PAD_MAX_INSNS + 1, BPF_VERIFIER_GFP);
+	if (!new)
+		return -ENOMEM;
+	for (s = 0; s < env->subprog_cnt && !err; s++) {
 		sub = &env->subprog_info[s];
-		for (i = sub->start, n = 0; i < sub[1].start; i++) {
+		cnt = collect_pads(env, s, new, &pads);
+		if (cnt < 0) {
+			err = cnt;
+			break;
+		}
+		/* a pad has no nospec barrier, see emit_pad() */
+		if (verifier_bug_if(cnt && !bpf_may_unwind(env), env,
+				    "func#%d has landing pads without CAP_PERFMON", s)) {
+			err = -EFAULT;
+			break;
+		}
+		for (i = sub->start; i < sub[1].start; i++) {
 			if (!aux[i].loop_guard)
 				continue;
 			/* A jump to itself is a back edge. It goes through may_goto too. */
 			patch[1] = env->prog->insnsi[i];
 			insn = bpf_patch_list_add(env, i, patch, 2);
-			if (IS_ERR(insn))
-				return PTR_ERR(insn);
+			if (IS_ERR(insn)) {
+				err = PTR_ERR(insn);
+				goto out;
+			}
 			if (!aux[i].guard_unwinds) {
 				bpf_patch_list_jump(&env->patch_list, insn - 1, aux[i].guard_to, 0);
 				continue;
 			}
-			n = emit_unwind_exit(env, s, leave);
-			bpf_patch_list_jump(&env->patch_list, insn - 1, sub[1].start, n);
+			/* however far the pad is, see bpf_patch_list_jump() */
+			plan = bpf_pad_plan(&aux[i], BPF_SITE_GUARD);
+			bpf_patch_list_jump(&env->patch_list, insn - 1, sub[1].start,
+					    cnt - plan->pad);
 		}
-		if (!n)
-			continue;
-		err = bpf_patch_list_append(env, i - 1, leave, n);
-		if (err)
-			return err;
+		if (cnt)
+			err = bpf_patch_list_append(env, i - 1, pads, cnt);
 	}
-	return bpf_patch_list_commit(env);
+out:
+	kvfree(new);
+	kvfree(pads);
+	return err ?: bpf_patch_list_commit(env);
 }
 
 /*
@@ -781,6 +871,7 @@ 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]);
 	}
 }
 
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
new file mode 100644
index 000000000000..26bba616ee50
--- /dev/null
+++ b/kernel/bpf/pads.c
@@ -0,0 +1,319 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/*
+ * Landing pads that the verifier generates.
+ *
+ * The kernel can cancel a BPF program: it ends the program before the program's own code returns. A
+ * SITE is an insn at which that can happen:
+ *   - 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)
+ * 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
+ * time is up, and the program ends without reading '*p'. '+' marks what the verifier adds:
+ *
+ *	bpf_rcu_read_lock();				   call bpf_rcu_read_lock
+ *	do {						1: ...
+ *		p = bpf_map_lookup_elem(&map, &key);	   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
+ *
+ * The verifier does not verify a landing pad, and no insn stands for it in the main pass:
+ *   1. In the main pass, a state that reaches a site is cancelled there. bpf_pad_visit() adds what
+ *      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 leaves its frame as at an
+ *      exit insn.
+ *   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
+ *      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
+ *      their function, with the insns that bpf_pad_insns() makes from the record.
+ * A pad is a fixed list of calls, so it has to be right for every state at its site, also for a
+ * state that was pruned or joined on the way and never got there. It is, because a record uses only
+ * what the verifier compares before it lets one state stand for another: the numbers of sections,
+ * the references, and the registers and stack slots that are live at the site.
+ *
+ * A pad releases what its own frame holds and nothing of the callers. For RCU and preempt sections
+ * the record has a count. A frame that holds anything else is not cancelled.
+ */
+#include <linux/bpf.h>
+#include <linux/bpf_verifier.h>
+#include <linux/btf_ids.h>
+#include <linux/filter.h>
+
+#define verbose(env, fmt, args...) bpf_verifier_log_write(env, fmt, ##args)
+
+/* The kfuncs that release a resource, indexed by enum bpf_pad_class */
+BTF_ID_LIST(pad_kfuncs)
+BTF_ID(func, bpf_rcu_read_unlock)
+BTF_ID(func, bpf_preempt_enable)
+
+/* The insn of a pad that releases one resource of @class */
+static struct bpf_insn release_call(enum bpf_pad_class class)
+{
+	return BPF_CALL_KFUNC(0, pad_kfuncs[class]);
+}
+
+/*
+ * A pad is going to call what @insn calls, if the program can call that. The passes that follow the
+ * emission look for the descriptor of a kfunc, which the program gets here.
+ * Returns the reason of a conflict.
+ */
+static int get_release(struct bpf_verifier_env *env, const struct bpf_insn *insn)
+{
+	u32 log_level = env->log.level;
+	struct bpf_call_arg_meta meta;
+	int err;
+
+	env->log.level = 0;
+	err = bpf_add_kfunc_call(env, insn->imm, insn->off);
+	err = err ?: bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
+	env->log.level = log_level;
+	if (err == -ENOMEM)
+		return err;
+	return err ? BPF_CONFLICT_NO_RELEASE : 0;
+}
+
+struct bpf_pad_plan *bpf_pad_plan(const struct bpf_insn_aux_data *aux, enum bpf_site_kind kind)
+{
+	struct bpf_pad_plan *plan;
+
+	for (plan = aux->pad_plans; plan; plan = plan->next)
+		if (plan->kind == kind)
+			return plan;
+	return NULL;
+}
+
+/* Returns the record of the site, which is allocated empty if there is none, or NULL */
+struct bpf_pad_plan *bpf_pad_plan_get(struct bpf_verifier_env *env, int insn_idx,
+				      enum bpf_site_kind kind)
+{
+	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
+	struct bpf_pad_plan *plan = bpf_pad_plan(aux, kind);
+
+	if (plan)
+		return plan;
+	plan = kzalloc_obj(*plan, BPF_VERIFIER_GFP);
+	if (!plan)
+		return NULL;
+	plan->kind = kind;
+	plan->next = aux->pad_plans;
+	aux->pad_plans = plan;
+	return plan;
+}
+
+static void free_plans(struct bpf_pad_plan *plan)
+{
+	struct bpf_pad_plan *next;
+
+	for (; plan; plan = next) {
+		next = plan->next;
+		kfree(plan);
+	}
+}
+
+void bpf_pad_plans_free(struct bpf_insn_aux_data *aux)
+{
+	free_plans(aux->pad_plans);
+	aux->pad_plans = NULL;
+}
+
+/* A pass or a path-sensitive run begins */
+void bpf_pads_new_round(struct bpf_verifier_env *env)
+{
+	int i;
+
+	for (i = 0; i < env->prog->len; i++)
+		bpf_pad_plans_free(&env->insn_aux_data[i]);
+}
+
+/*
+ * The plans are what a pass found, like the fixups of the insns, and a pass that is kept can
+ * become the result when a later one has an error. So the plans move with the snapshot of the
+ * pass, see copy_snapshot(): to @plans, which has an entry per insn, if @save, else back from
+ * there. What was at the destination is freed, and the source has no plans after that.
+ */
+void bpf_pads_move(struct bpf_verifier_env *env, struct bpf_pad_plan **plans, bool save)
+{
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	int i;
+
+	for (i = 0; i < env->prog->len; i++, aux++) {
+		if (save) {
+			free_plans(plans[i]);
+			plans[i] = aux->pad_plans;
+			aux->pad_plans = NULL;
+		} else {
+			free_plans(aux->pad_plans);
+			aux->pad_plans = plans[i];
+			plans[i] = NULL;
+		}
+	}
+}
+
+/* The snapshot that has @plans of @cnt insns is freed */
+void bpf_pads_free_moved(struct bpf_pad_plan **plans, u32 cnt)
+{
+	u32 i;
+
+	for (i = 0; i < cnt; i++)
+		free_plans(plans[i]);
+}
+
+/* How many sections of @class the current frame of @st has entered and not left */
+static u32 frame_sections(const struct bpf_verifier_state *st, enum bpf_pad_class class)
+{
+	const struct bpf_func_state *frame = st->frame[st->curframe];
+
+	if (class == BPF_PAD_RCU)
+		return st->active_rcu_locks - frame->entry_rcu_locks;
+	return st->active_preempt_locks - frame->entry_preempt_locks;
+}
+
+/*
+ * The current frame of @st is about to be cancelled at the site of @kind at @insn_idx. Add what it
+ * holds to the record of the site, also if it holds nothing. Returns the record, whose 'conflict'
+ * says why the pad cannot be generated, or an ERR_PTR().
+ *
+ * Sections: the pad leaves as many as the frame has entered. That is a number of calls in the
+ * code of the pad, so it has to be the same on all visits.
+ *
+ * Returns the plan. It tells whether there is a conflict.
+ */
+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)
+{
+	struct bpf_pad_plan *plan;
+	u32 class, nr;
+
+	plan = bpf_pad_plan_get(env, insn_idx, kind);
+	if (!plan)
+		return ERR_PTR(-ENOMEM);
+	if (plan->conflict)
+		return plan;
+	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++) {
+		nr = frame_sections(st, class);
+		if (nr > BPF_PAD_MAX_SECTIONS)
+			plan->conflict = BPF_CONFLICT_TOO_MUCH;
+		else if (plan->visited && plan->sections[class] != nr)
+			plan->conflict = BPF_CONFLICT_SECTIONS_DIFFER;
+		plan->sections[class] = nr;
+	}
+	plan->visited = true;
+	return plan;
+}
+
+/*
+ * The insns of the landing pad of @plan, a site in @subprog, but for the last one, which leaves the
+ * frame. Returns their number, less than BPF_PAD_MAX_INSNS.
+ */
+int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan, int subprog,
+		  struct bpf_insn *buf)
+{
+	int class, i, n = 0;
+
+	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
+		for (i = 0; i < plan->sections[class]; i++)
+			buf[n++] = release_call(class);
+	buf[n++] = BPF_MOV64_IMM(BPF_REG_0, bpf_cancelled_retval(env, subprog));
+	if (bpf_ret_reg_pair(env, subprog))
+		buf[n++] = BPF_MOV64_IMM(BPF_REG_2, 0);
+	return n;
+}
+
+/* All states have reached the site of @plan. Returns 0 or why its pad cannot be generated. */
+static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
+{
+	struct bpf_insn release;
+	int class, err = plan->conflict;
+
+	for (class = 0; !err && class < BPF_PAD_NR_SECTIONS; class++) {
+		release = release_call(class);
+		if (plan->sections[class])
+			err = get_release(env, &release);
+	}
+	return err;
+}
+
+/* Print what the pad of the site at insn @i releases, or why it cannot be generated */
+static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
+{
+	static const char * const kind[] = {
+		[BPF_SITE_GUARD]		= "may_goto",
+		[BPF_SITE_RECURSION]		= "recursion check",
+	};
+	static const char * const why[] = {
+		[BPF_CONFLICT_SECTIONS_DIFFER]	= "the number of sections differs",
+		[BPF_CONFLICT_TOO_MUCH]		= "too much is held",
+		[BPF_CONFLICT_NO_RELEASE]	= "the program can call nothing that releases a resource",
+	};
+
+	verbose(env, "landing pad of %s at %d: ", kind[plan->kind], i);
+	if (plan->conflict)
+		verbose(env, "conflict: %s\n", why[plan->conflict]);
+	else
+		verbose(env, "rcu=%d preempt=%d\n", plan->sections[BPF_PAD_RCU],
+			plan->sections[BPF_PAD_PREEMPT]);
+}
+
+/* Log what the pad of the site of @plan at @insn_idx releases, or why it cannot be generated */
+void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan)
+{
+	print_plan(env, insn_idx, 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
+ * bpf_find_unproven_after_pass().
+ */
+int bpf_pads_settle(struct bpf_verifier_env *env)
+{
+	struct bpf_pad_plan *plan;
+	int i, err;
+
+	for (i = 0; i < env->prog->len; i++) {
+		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) {
+			err = settle_plan(env, plan);
+			if (err < 0)
+				return err;
+			plan->conflict = err;
+			if (plan->conflict) {
+				print_plan(env, i, plan);
+				return -EINVAL;
+			}
+		}
+	}
+	return 0;
+}
+
+/* A site at the insn has no landing pad that serves all states, see bpf_pads_settle() */
+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)
+			return true;
+	return false;
+}
+
+/* The plans of the program */
+void bpf_pads_log(struct bpf_verifier_env *env)
+{
+	const struct bpf_pad_plan *plan;
+	int i;
+
+	if (!(env->log.level & BPF_LOG_LEVEL2))
+		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);
+}
diff --git a/kernel/bpf/precision.c b/kernel/bpf/precision.c
index 225dabbd4e70..042ae3ddef92 100644
--- a/kernel/bpf/precision.c
+++ b/kernel/bpf/precision.c
@@ -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))) {
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 72670bf3c129..d8c2d239867a 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -198,6 +198,7 @@ struct bpf_verifier_stack_elem {
 	struct bpf_verifier_state st;
 	int insn_idx; /* -1: the state leaves its frame at 'prev_insn_idx', see unwind_frame() */
 	int prev_insn_idx;
+	enum bpf_site_kind site_kind; /* the kind of the site at 'prev_insn_idx' */
 	bool again;	/* see bpf_flow_deliver() */
 	struct bpf_verifier_stack_elem *next;
 };
@@ -21512,9 +21513,9 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge
 }
 
 /*
- * What @subprog returns when it is unwound, see push_unwind_exit(). No code of the program chooses
- * that value, so for the main program it is the one that refuses, drops or changes nothing. That
- * is 0, but:
+ * What @subprog returns when it is unwound, see unwind_frame(). No code of the program chooses that
+ * value, so for the main program it is the one that refuses, drops or changes nothing. That is 0,
+ * but:
  *
  *	tc					TC_ACT_SHOT, 0 is TC_ACT_OK
  *	lwt, flow dissector			BPF_DROP, 0 is BPF_OK
@@ -21567,6 +21568,30 @@ int bpf_cancelled_retval(struct bpf_verifier_env *env, int subprog)
 	return 0;
 }
 
+/*
+ * The kernel called the current frame of @st, or it is the main program of an extension or the
+ * exception callback. The program ends when this frame leaves.
+ */
+static bool frame_is_top(const struct bpf_verifier_state *st)
+{
+	const struct bpf_func_state *frame = st->frame[st->curframe];
+
+	if (st->curframe)
+		return false;
+	return !frame->subprogno || frame->in_async_callback_fn ||
+	       frame->in_exception_callback_fn;
+}
+
+/* The current frame of @st holds resources that it acquired since its entry */
+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;
+}
+
 /*
  * A loop or a recursion is out of budget in the current frame of @st. What the
  * program computed so far is not what it was meant to compute, so it's better
@@ -21575,7 +21600,8 @@ int bpf_cancelled_retval(struct bpf_verifier_env *env, int subprog)
  * hold, or the program is rejected.
  *
  * False when it cannot:
- * - There is no landing pad for what this frame took itself.
+ * - This frame acquired something itself, and there is no landing pad for that: the verifier
+ *   emits one for sections only.
  * - There is a call of the subprog that unwind_goto doesn't follow. That is every
  *   program that is compiled without unwinding.
  * - A helper that calls a callback doesn't expect it to unwind.
@@ -21594,17 +21620,14 @@ static bool state_can_unwind(struct bpf_verifier_env *env, const struct bpf_veri
 	/* unwind_frame() needs an insn at which the state leaves the function. */
 	if (sub->exit_idx == U32_MAX)
 		return false;
-	if (st->acquired_refs != frame->entry_refs ||
-	    st->active_rcu_locks != frame->entry_rcu_locks ||
-	    st->active_preempt_locks != frame->entry_preempt_locks)
+	/* A landing pad has no nospec barrier, so only a loader with CAP_PERFMON gets one. */
+	if (!bpf_may_unwind(env))
+		return false;
+	if (st->acquired_refs != frame->entry_refs)
 		return false;
 	if (frame->in_callback_fn)
 		return false;
-	/* the kernel called it: either exit ends it */
-	if (!st->curframe && (!frame->subprogno || frame->in_async_callback_fn ||
-			      frame->in_exception_callback_fn))
-		return true;
-	return sub->bail_unwinds || or_exit;
+	return frame_is_top(st) || sub->bail_unwinds || or_exit;
 }
 
 /* May_goto at the head of a loop skips the body. Does it go to code that reads what is not set? */
@@ -21620,30 +21643,17 @@ static bool guard_reads_unset_reg(struct bpf_verifier_env *env,
 	return false;
 }
 
-/*
- * The current frame leaves with 0 in place of the result: with unwind_exit if the subprog
- * can do that, with exit otherwise. The insns are added when the main pass is over.
- * What the kernel called leaves with bpf_cancelled_retval().
- */
-static int push_unwind_exit(struct bpf_verifier_env *env)
+/* This insn is a site of @kind. Push a copy of the current state that leaves its frame here. */
+static int push_unwind_edge(struct bpf_verifier_env *env, enum bpf_site_kind kind)
 {
-	struct bpf_subprog_info *sub = &env->subprog_info[cur_func(env)->subprogno];
 	struct bpf_verifier_state *branch;
-	struct bpf_reg_state *regs;
 
 	if (env->cur_state->speculative)
 		return 0;
 	branch = push_stack(env, -1, env->insn_idx, false);
 	if (IS_ERR(branch))
 		return PTR_ERR(branch);
-	branch->unwound = sub->bail_unwinds;
-	regs = branch->frame[branch->curframe]->regs;
-	bpf_mark_reg_known_scalar(&regs[BPF_REG_0],
-				  bpf_cancelled_retval(env, cur_func(env)->subprogno));
-	if (bpf_ret_reg_pair(env, cur_func(env)->subprogno))
-		__mark_reg_const_zero(&regs[BPF_REG_2]);
-	bpf_equations_forget_xreg(env, branch, bpf_xreg(branch->curframe, BPF_REG_0));
-	bpf_equations_forget_xreg(env, branch, bpf_xreg(branch->curframe, BPF_REG_2));
+	env->head->site_kind = kind;
 	return 0;
 }
 
@@ -21720,7 +21730,7 @@ static int check_loop_guard(struct bpf_verifier_env *env)
 	if (aux->guard_no_unwind)
 		err = PTR_ERR_OR_ZERO(push_stack(env, aux->guard_to, env->insn_idx, false));
 	else
-		err = push_unwind_exit(env);
+		err = push_unwind_edge(env, BPF_SITE_GUARD);
 	/* more peeled trips can show that the edge is dead */
 	if (!err && env->head)
 		env->head->st.suspect_loops |= loop->suspect_bit;
@@ -21728,24 +21738,73 @@ static int check_loop_guard(struct bpf_verifier_env *env)
 }
 
 /*
- * The current frame of @st is left at @insn_idx, where the program has no exit: the verifier
- * emits one after the main pass. @st->unwound tells which one. No insn stands for it in the
- * main pass. What an exit does to a state is done to @st here, and what is left of @st goes
- * where the frame returns to, through the worklist like every other state. @st is taken.
+ * The current frame is left at a site, and its landing pad releases what the frame acquired since
+ * 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. The callers may have pointers that are good as long as a
+ * lock or a section is held.
  */
-static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int insn_idx)
+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);
+
+	st->active_rcu_locks = frame->entry_rcu_locks;
+	st->active_preempt_locks = frame->entry_preempt_locks;
+	if (!in_rcu_cs(env))
+		invalidate_rcu_protected_refs(env);
+	return 0;
+}
+
+/*
+ * The current frame of @st is left at @insn_idx, a site of @kind. The program has no code for
+ * that: the verifier emits a landing pad after the main pass, see kernel/bpf/pads.c. No insn
+ * stands for it in the main pass. @st visits the plan of the site, which notes what the pad has to
+ * do. Then what the pad does to a state is done to @st: the releases, see
+ * release_frame_resources(), the value in place of the result, then unwind_exit if the subprog can
+ * do that, exit otherwise. What is left of @st goes where the frame returns to, through the
+ * worklist like every other state. @st is taken.
+ *
+ * With a conflict there is no pad: the site is an unproven insn in @st, which ends here. The pass
+ * goes on, and a pass that keeps more apart may have no such state.
+ */
+static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int insn_idx,
+			enum bpf_site_kind kind)
 {
 	struct bpf_func_state *frame = st->frame[st->curframe];
 	struct bpf_verifier_state *cur = env->cur_state;
 	int cur_idx = env->insn_idx, err;
+	struct bpf_pad_plan *plan;
 	bool print_state;
 	u32 cnt;
 
+	env->cur_state = st;
+	env->insn_idx = insn_idx;
+	/* its suspects are those of a conflict that only bpf_pads_settle() finds */
+	env->insn_aux_data[insn_idx].suspect_loops |= st->suspect_loops;
+	plan = bpf_pad_visit(env, st, insn_idx, kind);
+	err = PTR_ERR_OR_ZERO(plan);
+	if (err)
+		goto out;
+	if (plan->conflict) {
+		bpf_pad_log(env, insn_idx, plan);
+		err = -EINVAL;
+		goto unproven;
+	}
+
+	err = release_frame_resources(env);
+	if (err)
+		goto out;
+	bpf_mark_reg_known_scalar(&frame->regs[BPF_REG_0],
+				  bpf_cancelled_retval(env, frame->subprogno));
+	if (bpf_ret_reg_pair(env, frame->subprogno))
+		__mark_reg_const_zero(&frame->regs[BPF_REG_2]);
+	bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_0));
+	bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_2));
+
+	st->unwound = env->subprog_info[frame->subprogno].bail_unwinds;
 	if (env->log.level & BPF_LOG_LEVEL2)
 		verbose(env, "from %d to %s of func#%d\n", insn_idx,
 			st->unwound ? "unwind_exit" : "exit", frame->subprogno);
-	env->cur_state = st;
-	env->insn_idx = insn_idx;
 	if (!st->curframe && st->instance_id) {
 		/*
 		 * The states that leave the function are compared as if they were at one exit, so
@@ -21765,9 +21824,11 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		err = bpf_flow_deliver(env, st, env->insn_idx, insn_idx, false);
 	else if (err == PROCESS_BPF_EXIT)
 		err = 0;
-	else if (err < 0 && st->frame[0])
-		/* the check of an exit failed for this state, see flow_apply_exit() */
+unproven:
+	/* The site is an unproven insn for @st, also if a check of the exit failed. */
+	if (err < 0 && st->frame[0])
 		err = min(bpf_flow_edge_unproven(env, st, insn_idx, err), 0);
+out:
 	env->cur_state = cur;
 	/* On an error env->insn_idx stays at the site, where the error is recorded. */
 	if (err >= 0)
@@ -21786,7 +21847,7 @@ static int flow_drain(struct bpf_verifier_env *env)
 		if (err)
 			;
 		else if (elem->insn_idx < 0)
-			err = unwind_frame(env, &elem->st, elem->prev_insn_idx);
+			err = unwind_frame(env, &elem->st, elem->prev_insn_idx, elem->site_kind);
 		else
 			err = bpf_flow_deliver(env, &elem->st, elem->insn_idx,
 					       elem->prev_insn_idx, elem->again);
@@ -21808,7 +21869,10 @@ static int check_recursion_guard(struct bpf_verifier_env *env)
 
 	if (!sub->recursive || env->insn_idx != sub->start)
 		return 0;
-	return push_unwind_exit(env);
+	/* It got here by a jump, which goes past the check: at its entry a frame holds nothing. */
+	if (frame_holds_resources(env->cur_state))
+		return 0;
+	return push_unwind_edge(env, BPF_SITE_RECURSION);
 }
 
 static bool is_error_of_state(struct bpf_verifier_env *env, int err)
@@ -23704,6 +23768,7 @@ struct bpf_snapshot {
 	struct bpf_env_per_pass env;
 	struct bpf_prog_aux aux;
 	struct bpf_insn_fixups *insns;
+	struct bpf_pad_plan **plans;	/* per insn, see bpf_pads_move() */
 	struct bpf_subprog_info *subprogs;
 	struct bpf_func_info_aux *funcs;
 	struct bpf_prog prog;
@@ -23735,6 +23800,7 @@ static void copy_snapshot(struct bpf_verifier_env *env, struct bpf_snapshot *sna
 	COPY_AUX(kprobe_write_ctx);
 	for (i = 0; i < env->prog->len; i++)
 		COPY(snapshot->insns[i], env->insn_aux_data[i].fixups);
+	bpf_pads_move(env, snapshot->plans, save);
 	for (i = 0, sub = env->subprog_info; i < env->subprog_cnt; i++, sub++) {
 		/* the sum over all passes */
 		snapshot->subprogs[i].insns_total = sub->insns_total;
@@ -23752,23 +23818,35 @@ static struct bpf_snapshot *save_snapshot(struct bpf_verifier_env *env,
 					  struct bpf_snapshot *snapshot)
 {
 	size_t insns = array_size(env->prog->len, sizeof(*snapshot->insns));
+	size_t plans = array_size(env->prog->len, sizeof(*snapshot->plans));
 	size_t subprogs = env->subprog_cnt * sizeof(*snapshot->subprogs);
 
 	if (!snapshot) {
-		snapshot = kvmalloc(sizeof(*snapshot) + insns + subprogs +
-				    env->prog->aux->func_info_cnt * sizeof(*snapshot->funcs),
+		snapshot = kvmalloc(size_add(sizeof(*snapshot) + subprogs +
+					     env->prog->aux->func_info_cnt *
+					     sizeof(*snapshot->funcs), size_add(insns, plans)),
 				    BPF_VERIFIER_GFP);
 		if (!snapshot)
 			return NULL;
-		env->mem += insns + subprogs;
+		env->mem += insns + plans + subprogs;
 		snapshot->insns = (void *)(snapshot + 1);
-		snapshot->subprogs = (void *)snapshot->insns + insns;
+		snapshot->plans = (void *)snapshot->insns + insns;
+		memset(snapshot->plans, 0, plans);
+		snapshot->subprogs = (void *)snapshot->plans + plans;
 		snapshot->funcs = (void *)snapshot->subprogs + subprogs;
 	}
 	copy_snapshot(env, snapshot, true);
 	return snapshot;
 }
 
+static void free_snapshot(struct bpf_verifier_env *env, struct bpf_snapshot *snapshot)
+{
+	if (!snapshot)
+		return;
+	bpf_pads_free_moved(snapshot->plans, env->prog->len);
+	kvfree(snapshot);
+}
+
 static void restore_snapshot(struct bpf_verifier_env *env, struct bpf_snapshot *snapshot)
 {
 	copy_snapshot(env, snapshot, false);
@@ -23839,6 +23917,7 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
 	env->callx_edges = NULL;
 	env->callx_index = (struct bpf_index){};
 	bpf_flow_new_pass(env);
+	bpf_pads_new_round(env);
 	ret = do_check_main(env) ?: do_check_subprogs(env) ?: bpf_check_limits(env);
 	env->log.level = level;
 	env->pass_max_cost = U64_MAX;
@@ -23855,9 +23934,12 @@ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial
 	ret = check_funcs(env, initial);
 	if (ret || pass_needs_restart(env))
 		return ret;
-	ret = check_after_pass(env);
+	/* a state that never gets to a site makes no conflict there */
+	ret = check_after_pass(env) ?: bpf_pads_settle(env);
 	if (ret)
 		bpf_find_unproven_after_pass(env);
+	else
+		bpf_pads_log(env);
 	env->err = ret;
 	return ret;
 }
@@ -24018,7 +24100,7 @@ static int do_check_all(struct bpf_verifier_env *env)
 	initial = save_snapshot(env, NULL);
 	if (!initial || bpf_precision_init(env)) {
 		bpf_precision_free(env);
-		kvfree(initial);
+		free_snapshot(env, initial);
 		return -ENOMEM;
 	}
 	env->max_mem = min(env->max_mem, env->mem + BPF_PASS_MEM_BASE +
@@ -24068,7 +24150,7 @@ static int do_check_all(struct bpf_verifier_env *env)
 		}
 		if (!ret || good_pass) {
 			/* The driver sees a pass without errors. It can refuse an insn. */
-			kvfree(good_pass);
+			free_snapshot(env, good_pass);
 			good_pass = NULL;
 			env->max_cost = max_cost;
 			env->replay = replayed = true;
@@ -24132,8 +24214,8 @@ static int do_check_all(struct bpf_verifier_env *env)
 	if (!err && env->sleepable_async_cb)
 		mark_sleepable_async_cb(env);
 	bpf_precision_free(env);
-	kvfree(initial);
-	kvfree(good_pass);
+	free_snapshot(env, initial);
+	free_snapshot(env, good_pass);
 	return err;
 }
 
@@ -26236,14 +26318,14 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (ret == 0 && bpf_prog_is_offloaded(env->prog->aux))
 		ret = bpf_prog_offload_finalize(env);
 
-	if (ret == 0)
-		ret = bpf_insert_loop_guards(env);
-
 skip_full_check:
 	/* instruction rewrites happen after this point */
 	if (ret == 0)
 		ret = bpf_remove_fastcall_spills_fills(env);
 
+	if (ret == 0)
+		ret = bpf_insert_sites(env);
+
 	if (ret == 0)
 		ret = bpf_optimize_bpf_loop(env);
 
diff --git a/tools/testing/selftests/bpf/progs/verifier_barrier.c b/tools/testing/selftests/bpf/progs/verifier_barrier.c
index 2cf55613406d..aaef593976ec 100644
--- a/tools/testing/selftests/bpf/progs/verifier_barrier.c
+++ b/tools/testing/selftests/bpf/progs/verifier_barrier.c
@@ -132,13 +132,6 @@ __naked void exit_of_callback(void)
 SEC("tc")
 __description("barrier: on the way out of a loop that is out of budget")
 __success SPECULATES __success_unpriv
-#ifdef SPEC_V1
-__xlated_unpriv("r0 = 1")
-__xlated_unpriv("exit")
-__xlated_unpriv("nospec")
-__xlated_unpriv("r0 = 2")
-__xlated_unpriv("exit")
-#endif
 __naked void unwind_exit(void)
 {
 	ASM(START
@@ -168,25 +161,6 @@ __naked void in_front_of_guard(void)
 	"exit;");
 }
 
-/* The code after the loop needs the result of the jump: may_goto has to leave the program */
-SEC("tc")
-__description("barrier: a speculative state does not select the way of may_goto")
-__success SPECULATES __success_unpriv
-__naked void way_of_guard(void)
-{
-	ASM(START
-	"call bpf_rcu_read_lock;"
-	NEVER("1f")
-	"call bpf_rcu_read_unlock;"
-"1:	r1 = *(u64 *)(r6 + 8);"
-	"if r1 > 7 goto 1b;"
-	"r1 <<= 3;"
-	"r6 += r1;"
-	"r0 = *(u64 *)(r6 + 0);"
-	"r0 = 0;"
-	"exit;");
-}
-
 static __naked __noinline __used int recurse(void)
 {
 	ASM(START
@@ -815,24 +789,6 @@ __naked void far_fall(void)
 	"exit;");
 }
 
-SEC("tc")
-__description("barrier: on the far exit that is out of budget")
-__success __arch_x86_64 __caps_unpriv(CAP_BPF | CAP_NET_ADMIN) __success_unpriv
-#ifdef SPEC_V1
-__xlated_unpriv("16: gotol pc+32810")
-__xlated_unpriv("...")
-__xlated_unpriv("32827: nospec")
-#endif
-__naked void far_unwind_exit(void)
-{
-	ASM(START
-"1:	r1 = *(u64 *)(r6 + 8);"
-	"if r1 != 0 goto 1b;"
-	DIVS
-	"r0 = 1;"
-	"exit;");
-}
-
 /* the kfuncs have to be in BTF */
 void __kfunc_btf_root(void)
 {
diff --git a/tools/testing/selftests/bpf/progs/verifier_budget.c b/tools/testing/selftests/bpf/progs/verifier_budget.c
index 4f38518de92a..3b75af1d1fbd 100644
--- a/tools/testing/selftests/bpf/progs/verifier_budget.c
+++ b/tools/testing/selftests/bpf/progs/verifier_budget.c
@@ -7,9 +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, when unwind_goto follows every call of the subprog and the subprog
- *   holds nothing of its own. The pads of the callers are verified.
+ * - it unwinds, when unwind_goto follows every call of the subprog. The pads of the callers are
+ *   verified.
  * - the main prog and an async callback end
+ * - what the frame holds takes a landing pad, which the verifier emits
  * - otherwise it leaves the loop, or returns 0 from the subprog
  *
  * It takes unwinding, per-cpu insns and timed may_goto in JIT. Some of the progs never end
@@ -95,30 +96,6 @@ __naked void loop_in_main_dead_exit(void)
 	);
 }
 
-SEC("socket")
-__description("budget: a loop in the main prog that holds something is left")
-__arch_x86_64
-__arch_arm64
-__success __retval(1)
-__naked void loop_in_main_rcu(void)
-{
-	asm volatile (
-		"r6 = %[zero] ll;"
-		"call %[bpf_rcu_read_lock];"
-	"1:"
-		"r1 = *(u64 *)(r6 + 0);"
-		"if r1 != 0 goto 1b;"
-		"call %[bpf_rcu_read_unlock];"
-		"r0 = 1;"
-		"exit;"
-		:
-		: __imm_addr(zero),
-		  __imm(bpf_rcu_read_lock),
-		  __imm(bpf_rcu_read_unlock)
-		: __clobber_all
-	);
-}
-
 /* 0 is not what this prog may return */
 SEC("cgroup/recvmsg4")
 __description("budget: a loop in the main prog that can only return 1 ends it with 1")
@@ -146,15 +123,21 @@ __naked void loop_in_main_retval(void)
 }
 
 /*
- * do { p = lookup(); } while (!p); return *p;
- * may_goto must not go where the loop goes when it's over: p may be NULL. Something is held, so
- * it cannot end the prog either: there is no way out.
+ * rcu_read_lock(); do { p = lookup(); } while (!p); v = *p; rcu_read_unlock(); return v;
+ * may_goto must not go where the loop goes when it's over: p may be NULL. It ends the prog, by way
+ * of a landing pad that leaves the RCU section.
  */
 SEC("socket")
-__description("budget: something is held and the code behind the loop counts on its exit")
+__description("budget: an RCU section is held and the code behind the loop counts on its exit")
 __arch_x86_64
 __arch_arm64
-__failure __msg("R0 invalid mem access 'map_value_or_null'")
+__success __retval(0)
+__xlated("...")
+__xlated("r0 = r6")
+__xlated("exit")
+__xlated("call kernel-function")
+__xlated("r0 = 0")
+__xlated("exit")
 __naked void exit_of_loop_checks_null_rcu(void)
 {
 	asm volatile (
@@ -285,7 +268,7 @@ __naked void pad_forgets(void)
 	);
 }
 
-/* There is no pad for what the subprog took itself */
+/* The verifier emits the pad for what the subprog took itself. It goes on to the pad of the caller. */
 __naked __noinline __used
 static unsigned long spins_locked(void)
 {
@@ -306,10 +289,10 @@ static unsigned long spins_locked(void)
 }
 
 SEC("socket")
-__description("budget: a loop in a subprog that holds something is left")
+__description("budget: a loop in a subprog leaves the section and unwinds to the pad of the prog")
 __arch_x86_64
 __arch_arm64
-__success __retval(7)
+__success __retval(42)
 __naked void loop_in_subprog_locked(void)
 {
 	asm volatile (
@@ -1552,8 +1535,8 @@ __naked void two_callers_two_passes(void)
 
 /*
  * if (x) lock(); do { p = lookup(); } while (!p); if (x) { unlock(); return 0; } return *p;
- * looks(0) holds nothing: may_goto unwinds. looks(1) cannot, so may_goto leaves the loop, in
- * looks(0) too, and p is NULL.
+ * looks(0) holds nothing at may_goto, looks(1) is in a section: the program counter does not tell
+ * the landing pad what to do.
  */
 __naked __noinline __used
 static unsigned long looks(unsigned long x)
@@ -1587,10 +1570,10 @@ static unsigned long looks(unsigned long x)
 }
 
 SEC("socket")
-__description("budget: a subprog finds out late that something is held")
+__description("budget: a subprog is in a section on some paths")
 __arch_x86_64
 __arch_arm64
-__failure __msg("R0 invalid mem access 'map_value_or_null'")
+__failure __msg("landing pad of may_goto at {{[0-9]+}}: conflict: the number of sections differs")
 __naked void unwinds_then_cannot(void)
 {
 	asm volatile (
diff --git a/tools/testing/selftests/bpf/progs/verifier_loop_latch.c b/tools/testing/selftests/bpf/progs/verifier_loop_latch.c
index e1281d00b431..967ba9c2a295 100644
--- a/tools/testing/selftests/bpf/progs/verifier_loop_latch.c
+++ b/tools/testing/selftests/bpf/progs/verifier_loop_latch.c
@@ -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;")
diff --git a/tools/testing/selftests/bpf/progs/verifier_passes.c b/tools/testing/selftests/bpf/progs/verifier_passes.c
index 8d42c250d24e..8938135698b4 100644
--- a/tools/testing/selftests/bpf/progs/verifier_passes.c
+++ b/tools/testing/selftests/bpf/progs/verifier_passes.c
@@ -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);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 14/73] bpf: Release locks and irq flags in landing pads
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (12 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 13/73] bpf: Emit landing pads that leave RCU sections Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 15/73] bpf: Add unwind_goto after calls of subprogs Kumar Kartikeya Dwivedi
                   ` (58 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Co-developed-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index e9db40421411..d40bd855c539 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 0df3b5630b0b..154f9569b132 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -604,21 +604,29 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
  * Returns the number of insns, BPF_PAD_MAX_INSNS + 1 at most.
  */
 static int emit_pad(struct bpf_verifier_env *env, int s, const struct bpf_pad_plan *plan,
-		    struct bpf_insn *buf)
+		    struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
 {
 	int n = 0;
 
-	n += bpf_pad_insns(env, plan, s, buf + n);
+	n += bpf_pad_insns(env, plan, s, buf + n, aux + n);
 	buf[n++] = unwind_exit_insn(env, s);
 	return n;
 }
 
+/* Does the site of @plan at an insn with @aux get a landing pad after its subprog? */
+static bool plan_has_pad(const struct bpf_insn_aux_data *aux, const struct bpf_pad_plan *plan)
+{
+	/* bpf_insert_recursion_checks() emits the pad of the check */
+	return plan->kind != BPF_SITE_RECURSION && aux->loop_guard && aux->guard_unwinds;
+}
+
 /*
  * The landing pads of the sites of subprog @s go after its last insn. Sites whose pads have the
- * same insns share one. @new has room for a pad. Returns the insns in @pads and their number.
+ * same insns share one. @new and @new_aux have room for a pad. Returns the insns in @pads and
+ * their number.
  */
 static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *new,
-			struct bpf_insn **pads)
+			struct bpf_insn_aux_data *new_aux, struct bpf_insn **pads)
 {
 	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;
@@ -632,10 +640,9 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 		if (!bpf_pad_plan_get(env, i, BPF_SITE_GUARD))
 			return -ENOMEM;
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
-			/* bpf_insert_recursion_checks() emits the pad of the check */
-			if (plan->kind == BPF_SITE_RECURSION)
+			if (!plan_has_pad(&aux[i], plan))
 				continue;
-			n = emit_pad(env, s, plan, new);
+			n = emit_pad(env, s, plan, new, new_aux);
 			for (pad = 0; pad < cnt; pad += len) {
 				for (len = 1; buf[pad + len - 1].code != (BPF_JMP | BPF_EXIT);
 				     len++)
@@ -677,23 +684,29 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
  *  - The guard of a jump goes where the jump goes.
  *  - What is live where the guard at the head of a loop goes is live at the head,
  *    see bpf_head_guard_target().
- *  - A landing pad reads no register.
+ *  - A landing pad reads places, which are live before the insn.
  */
 int bpf_insert_sites(struct bpf_verifier_env *env)
 {
 	struct bpf_insn patch[2] = { BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0) };
-	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	struct bpf_insn_aux_data *aux = env->insn_aux_data, *pad_aux;
 	struct bpf_insn *pads = NULL, *new, *insn;
 	const struct bpf_pad_plan *plan;
 	struct bpf_subprog_info *sub;
 	int i, s, cnt, err = 0;
+	int *added;
 
+	/* how many insns the pads after the subprog have */
+	added = kvzalloc_objs(int, env->subprog_cnt, BPF_VERIFIER_GFP);
 	new = kvzalloc_objs(*new, BPF_PAD_MAX_INSNS + 1, BPF_VERIFIER_GFP);
-	if (!new)
-		return -ENOMEM;
+	pad_aux = kvzalloc_objs(*pad_aux, BPF_PAD_MAX_INSNS + 1, BPF_VERIFIER_GFP);
+	if (!added || !new || !pad_aux) {
+		err = -ENOMEM;
+		goto out;
+	}
 	for (s = 0; s < env->subprog_cnt && !err; s++) {
 		sub = &env->subprog_info[s];
-		cnt = collect_pads(env, s, new, &pads);
+		cnt = collect_pads(env, s, new, pad_aux, &pads);
 		if (cnt < 0) {
 			err = cnt;
 			break;
@@ -704,6 +717,7 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 			err = -EFAULT;
 			break;
 		}
+		added[s] = cnt;
 		for (i = sub->start; i < sub[1].start; i++) {
 			if (!aux[i].loop_guard)
 				continue;
@@ -726,10 +740,25 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 		if (cnt)
 			err = bpf_patch_list_append(env, i - 1, pads, cnt);
 	}
+	err = err ?: bpf_patch_list_commit(env);
+	if (err)
+		goto out;
+	/* the pads are in the program now, and their insns have aux data */
+	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(&aux[i], plan))
+					emit_pad(env, s, plan, new,
+						 &aux[sub[1].start - added[s] + plan->pad]);
+	}
 out:
+	kvfree(added);
 	kvfree(new);
+	kvfree(pad_aux);
 	kvfree(pads);
-	return err ?: bpf_patch_list_commit(env);
+	return err;
 }
 
 /*
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 26bba616ee50..1f6b084259fc 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -37,7 +37,16 @@
  * the references, and the registers and stack slots that are live at the site.
  *
  * A pad releases what its own frame holds and nothing of the callers. For RCU and preempt sections
- * the record has a count. A frame that holds anything else is not cancelled.
+ * the record has a count. Every other resource is one release of the record (struct bpf_pad_ent): a
+ * call, and for each argument a LOCATION (struct bpf_pad_place). A location is a register or a
+ * stack slot of the program that holds the pointer at the site, plus a constant offset. For a frame
+ * that holds a lock at R6 the pad is 'r1 = r6; call bpf_spin_unlock; r0 = 0; exit'. A pointer into
+ * a map value is a location for the lock in that value, and R10 is one for an object in the stack
+ * of the frame. A location has to be live at the site, because later passes reuse dead registers
+ * and remove dead stores, see find_cands().
+ *
+ * All states at a site have to share a location for each release, and the pad has to know whether
+ * the resource is held. Only the program counter tells the pad, so all states have to hold it.
  */
 #include <linux/bpf.h>
 #include <linux/bpf_verifier.h>
@@ -50,24 +59,36 @@
 BTF_ID_LIST(pad_kfuncs)
 BTF_ID(func, bpf_rcu_read_unlock)
 BTF_ID(func, bpf_preempt_enable)
+BTF_ID(func, bpf_local_irq_restore)
+BTF_ID(func, bpf_res_spin_unlock)
+BTF_ID(func, bpf_res_spin_unlock_irqrestore)
+
+static struct bpf_insn helper_call(enum bpf_func_id func_id)
+{
+	return BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, func_id);
+}
 
 /* The insn of a pad that releases one resource of @class */
 static struct bpf_insn release_call(enum bpf_pad_class class)
 {
+	if (class == BPF_PAD_SPIN_LOCK)
+		return helper_call(BPF_FUNC_spin_unlock);
 	return BPF_CALL_KFUNC(0, pad_kfuncs[class]);
 }
 
 /*
- * A pad is going to call what @insn calls, if the program can call that. The passes that follow the
- * emission look for the descriptor of a kfunc, which the program gets here.
- * Returns the reason of a conflict.
+ * Check that the program may call what @insn calls, and add the kfunc descriptor that the passes
+ * after the emission look up. Returns 0, BPF_CONFLICT_NO_RELEASE or -ENOMEM.
  */
 static int get_release(struct bpf_verifier_env *env, const struct bpf_insn *insn)
 {
+	const struct bpf_func_proto *fn;
 	u32 log_level = env->log.level;
 	struct bpf_call_arg_meta meta;
 	int err;
 
+	if (bpf_helper_call(insn))
+		return bpf_get_helper_proto(env, insn->imm, &fn) ? BPF_CONFLICT_NO_RELEASE : 0;
 	env->log.level = 0;
 	err = bpf_add_kfunc_call(env, insn->imm, insn->off);
 	err = err ?: bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta);
@@ -111,6 +132,7 @@ static void free_plans(struct bpf_pad_plan *plan)
 
 	for (; plan; plan = next) {
 		next = plan->next;
+		kfree(plan->ents);
 		kfree(plan);
 	}
 }
@@ -173,6 +195,341 @@ static u32 frame_sections(const struct bpf_verifier_state *st, enum bpf_pad_clas
 	return st->active_preempt_locks - frame->entry_preempt_locks;
 }
 
+static int ref_class(const struct bpf_reference_state *ref)
+{
+	switch (ref->type) {
+	case REF_TYPE_IRQ:
+		return BPF_PAD_IRQ;
+	case REF_TYPE_LOCK:
+		return BPF_PAD_SPIN_LOCK;
+	case REF_TYPE_RES_LOCK:
+		return BPF_PAD_RES_LOCK;
+	case REF_TYPE_RES_LOCK_IRQ:
+		return BPF_PAD_RES_LOCK_IRQ;
+	default:
+		return -ENOENT;
+	}
+}
+
+/* Returns the offset of the lock of @class in the type that @rec describes, or -ENOENT */
+static int lock_off(const struct btf_record *rec, enum bpf_pad_class class)
+{
+	if (class == BPF_PAD_SPIN_LOCK)
+		return btf_record_has_field(rec, BPF_SPIN_LOCK) ? rec->spin_lock_off : -ENOENT;
+	return btf_record_has_field(rec, BPF_RES_SPIN_LOCK) ? rec->res_spin_lock_off : -ENOENT;
+}
+
+/*
+ * Add (@loc, @at) to @cand if @reg, which is there, points at a constant offset into the map value
+ * or the object that the lock @ref is in, as process_spin_lock() asks of an unlock.
+ */
+static void add_lock_cand(struct bpf_pad_place *cand, int *nr, const struct bpf_reg_state *reg,
+			  const struct bpf_reference_state *ref, enum bpf_place_loc loc, int at)
+{
+	const struct btf_struct_meta *meta;
+	const struct btf_record *rec;
+	s64 delta;
+	int off;
+
+	if (*nr == BPF_PAD_MAX_CANDS || reg->id != ref->id || !tnum_is_const(reg->var_off))
+		return;
+	if (reg->type == PTR_TO_MAP_VALUE && reg->map_ptr == ref->ptr) {
+		rec = reg->map_ptr->record;
+	} else if (reg->type == (PTR_TO_BTF_ID | MEM_ALLOC) && reg->btf == ref->ptr) {
+		meta = btf_find_struct_meta(reg->btf, reg->btf_id);
+		rec = meta ? meta->record : NULL;
+	} else {
+		return;
+	}
+	off = lock_off(rec, ref_class(ref));
+	delta = (s64)reg->var_off.value - off;
+	if (off < 0 || delta < -S32_MAX || delta > S32_MAX)
+		return;
+	cand[(*nr)++] = (struct bpf_pad_place){ .loc = loc, .at = at, .delta = delta };
+}
+
+/* Add (@loc, @at) to @cand if @reg points to the stack of the frame of @obj at a constant offset */
+static void add_obj_cand(struct bpf_pad_place *cand, int *nr, const struct bpf_reg_state *reg,
+			 const struct bpf_reg_state *obj, enum bpf_place_loc loc, int at)
+{
+	s64 delta = reg->var_off.value - obj->var_off.value;
+
+	if (*nr == BPF_PAD_MAX_CANDS || reg->type != PTR_TO_STACK || reg->frameno != obj->frameno ||
+	    !tnum_is_const(reg->var_off) || delta < -S32_MAX || delta > S32_MAX)
+		return;
+	cand[(*nr)++] = (struct bpf_pad_place){ .loc = loc, .at = at, .delta = delta };
+}
+
+static void add_cand(struct bpf_pad_place *cand, int *nr, const struct bpf_reg_state *reg,
+		     const struct bpf_reference_state *ref, const struct bpf_reg_state *obj,
+		     enum bpf_place_loc loc, int at)
+{
+	if (obj)
+		add_obj_cand(cand, nr, reg, obj, loc, at);
+	else
+		add_lock_cand(cand, nr, reg, ref, loc, at);
+}
+
+/*
+ * The places of the current frame of @st that have the address of the lock @ref at @insn_idx: R6-R9
+ * and stack slots. If @ref is an object in the stack of a caller @obj is its address.
+ * A register or a stack slot that is not live there is no place: the passes that follow use
+ * such a register, remove the store to such a slot, and states that differ in it are the same to
+ * the main pass. Nor is a slot of the spills around bpf_fastcall calls: they are removed unless the
+ * main pass sees another access to the slot, and it does not see the pad.
+ */
+static int find_cands(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+		      int insn_idx, const struct bpf_reference_state *ref,
+		      const struct bpf_reg_state *obj, struct bpf_pad_place *cand)
+{
+	const struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
+	const struct bpf_func_state *frame = st->frame[st->curframe];
+	int fastcall_off = env->subprog_info[frame->subprogno].fastcall_stack_off;
+	const struct bpf_stack_state *slot;
+	int i, off, nr = 0;
+
+	for (i = BPF_REG_6; i < BPF_REG_FP; i++)
+		if (aux->live_regs_before & BIT(i))
+			add_cand(cand, &nr, &frame->regs[i], ref, obj, BPF_PLACE_REG, i);
+	for (i = 0; i < bpf_stack_nr_slots(frame); i++) {
+		slot = bpf_stack_slot(frame, i);
+		off = -(i + 1) * BPF_REG_SIZE;
+		if (test_bit(i, aux->live_stack_before) && bpf_spill_size(slot) == BPF_REG_SIZE &&
+		    off >= fastcall_off)
+			add_cand(cand, &nr, &slot->spilled_ptr, ref, obj, BPF_PLACE_SPILL, off);
+	}
+	return nr;
+}
+
+/* The candidates for the address of the lock @ref: a constant address, then find_cands() */
+static int find_lock_cands(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			   int insn_idx, const struct bpf_reference_state *ref,
+			   struct bpf_pad_place *cand)
+{
+	const struct bpf_map *map;
+	int i, off, nr = 0;
+	u64 addr;
+
+	/* a lock in a global variable has no id: the only value of an array, a constant address */
+	for (i = 0; !ref->id && i < env->used_map_cnt; i++) {
+		map = env->used_maps[i];
+		off = lock_off(map->record, ref_class(ref));
+		if (map != ref->ptr || map->map_type != BPF_MAP_TYPE_ARRAY || off < 0 ||
+		    map->ops->map_direct_value_addr(map, &addr, off))
+			continue;
+		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;
+}
+
+/* Is slot @spi of @frame the irq flags @ref? */
+static bool slot_is_obj(const struct bpf_func_state *frame, int spi,
+			const struct bpf_reference_state *ref)
+{
+	const struct bpf_reg_state *reg = &bpf_stack_slot(frame, spi)->spilled_ptr;
+
+	switch (bpf_stack_slot(frame, spi)->slot_type[BPF_REG_SIZE - 1]) {
+	case STACK_IRQ_FLAG:
+		return reg->id == ref->id;
+	}
+	return false;
+}
+
+/*
+ * If @ref is an object in the stack: the places that have its address at @insn_idx. R10 if the
+ * current frame of @st has the object. If a caller has it, what find_cands() finds: the function
+ * got a pointer and made the object there, like the constructor of a guard.
+ * *@obj: the first slot of the object.
+ */
+static int find_obj_cands(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			  int insn_idx, const struct bpf_reference_state *ref,
+			  struct bpf_pad_place *cand, const struct bpf_stack_state **obj)
+{
+	const struct bpf_func_state *frame;
+	struct bpf_reg_state addr;
+	int f, i, nr = 0;
+
+	for (f = st->curframe; f >= 0 && !nr; f--) {
+		frame = st->frame[f];
+		for (i = 0; i < bpf_stack_nr_slots(frame) && nr < BPF_PAD_MAX_CANDS; i++) {
+			if (!slot_is_obj(frame, i, ref))
+				continue;
+			*obj = nr ? *obj : bpf_stack_slot(frame, i);
+			if (f == st->curframe) {
+				cand[nr++] = (struct bpf_pad_place){ .loc = BPF_PLACE_REG,
+								     .at = BPF_REG_FP,
+								     .delta = (i + 1) * BPF_REG_SIZE };
+				continue;
+			}
+			addr = frame->regs[BPF_REG_FP];
+			addr.var_off = tnum_const(-(i + 1) * BPF_REG_SIZE);
+			return find_cands(env, st, insn_idx, ref, &addr, cand);
+		}
+	}
+	return nr;
+}
+
+/* Copy the candidates for argument @arg that @ent and @new share to @cand. Returns their number. */
+static int common_cands(const struct bpf_pad_ent *ent, const struct bpf_pad_ent *new, int arg,
+			struct bpf_pad_place *cand)
+{
+	const struct bpf_pad_place *old = ent->cand[arg], *place = new->cand[arg];
+	int i, j, n = 0;
+
+	for (i = 0; i < ent->nr_cands[arg]; i++) {
+		for (j = 0; j < new->nr_cands[arg]; j++) {
+			if (old[i].loc != place[j].loc || old[i].at != place[j].at ||
+			    old[i].delta != place[j].delta)
+				continue;
+			cand[n++] = old[i];
+			break;
+		}
+	}
+	return n;
+}
+
+/*
+ * Fill @ent with the release of @ref, one of refs[] of @st, for a pad at @insn_idx: the call that
+ * releases it, and the candidate locations of its arguments in the current frame. Returns 0, the
+ * enum bpf_pad_conflict that says why the pad cannot be generated, or a negative errno.
+ */
+static int ref_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
+		   const struct bpf_verifier_state *st, int insn_idx,
+		   const struct bpf_reference_state *ref)
+{
+	const struct bpf_stack_state *obj = NULL;
+	int class = ref_class(ref);
+
+	if (verifier_bug_if(class < 0, env, "no landing pad releases reference type %d", ref->type))
+		return -EFAULT;
+	memset(ent, 0, sizeof(*ent));
+	ent->origin = ref->origin;
+	ent->class = class;
+	ent->release = release_call(class);
+	if (class == BPF_PAD_IRQ)
+		ent->nr_cands[0] = find_obj_cands(env, st, insn_idx, ref, ent->cand[0], &obj);
+	else
+		ent->nr_cands[0] = find_lock_cands(env, st, insn_idx, ref, ent->cand[0]);
+	if (class == BPF_PAD_RES_LOCK_IRQ) {
+		/* the same insn saved irq flags, the next of refs[]: the second argument */
+		if (verifier_bug_if(ref + 1 == st->refs + st->acquired_refs ||
+				    ref[1].type != REF_TYPE_IRQ || ref[1].insn_idx != ref->insn_idx,
+				    env, "no irq flags after the lock of insn %d", ref->insn_idx))
+			return -EFAULT;
+		ent->nr_cands[1] = find_obj_cands(env, st, insn_idx, ref + 1, ent->cand[1], &obj);
+		if (!ent->nr_cands[1])
+			return BPF_CONFLICT_NO_PLACE;
+	}
+	return ent->nr_cands[0] ? 0 : BPF_CONFLICT_NO_PLACE;
+}
+
+/* Returns the release of @plan that refs[@ref] of the current state was matched with, or NULL */
+static struct bpf_pad_ent *held_ent(const struct bpf_pad_plan *plan, int ref)
+{
+	int i;
+
+	for (i = 0; i < plan->nr_ents; i++)
+		if (plan->ents[i].ref == ref)
+			return &plan->ents[i];
+	return NULL;
+}
+
+/*
+ * Returns a release of @plan that can stand for @new too, or NULL: no other reference of the
+ * current state is matched with it, the same call releases both, and they share a candidate for
+ * each argument. With @origin the same insn brought both to the frame.
+ */
+static struct bpf_pad_ent *match_ent(const struct bpf_pad_plan *plan, const struct bpf_pad_ent *new,
+				     bool origin)
+{
+	struct bpf_pad_place cand[BPF_PAD_MAX_CANDS];
+	struct bpf_pad_ent *ent;
+	int i, arg;
+
+	for (i = 0; i < plan->nr_ents; i++) {
+		ent = &plan->ents[i];
+		if (ent->ref >= 0 || (origin && ent->origin != new->origin) ||
+		    memcmp(&ent->release, &new->release, sizeof(ent->release)))
+			continue;
+		for (arg = 0; arg < BPF_PAD_MAX_ARGS; arg++)
+			if (new->nr_cands[arg] && !common_cands(ent, new, arg, cand))
+				break;
+		if (arg == BPF_PAD_MAX_ARGS)
+			return ent;
+	}
+	return NULL;
+}
+
+/* @new is one more entry of @plan. Returns it, or NULL if there is no memory. */
+static struct bpf_pad_ent *add_ent(struct bpf_pad_plan *plan, const struct bpf_pad_ent *new)
+{
+	if (!plan->ents)
+		plan->ents = kzalloc_objs(*plan->ents, BPF_PAD_MAX_ENTS, BPF_VERIFIER_GFP);
+	if (!plan->ents)
+		return NULL;
+	plan->ents[plan->nr_ents] = *new;
+	return &plan->ents[plan->nr_ents++];
+}
+
+/*
+ * The resources with a handle that the current frame of @st acquired: refs[] from
+ * entry_refs on, oldest first. Which entry is one of them? What a pad does with an entry is a call
+ * with what it finds at a place, so that is what an entry is, like a variable with a destructor. It
+ * does not matter which insn acquired what is there. Where that leaves a choice the origin decides.
+ * Every visit has to hold every entry.
+ * Locks and irq flags have to be in refs[] in the order of the plan.
+ * Returns the reason of a conflict.
+ */
+static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
+		      const struct bpf_verifier_state *st, int insn_idx)
+{
+	const struct bpf_reference_state *ref;
+	struct bpf_pad_ent new, *ent;
+	int i, arg, pass, pos, err;
+
+	for (i = 0; i < plan->nr_ents; i++)
+		plan->ents[i].ref = -1;
+	for (pass = 0; pass < 2; pass++) {
+		for (i = st->frame[st->curframe]->entry_refs; i < st->acquired_refs; i++) {
+			ref = &st->refs[i];
+			/* irq flags that a lock saved are an argument of its release */
+			if (i && ref[-1].type == REF_TYPE_RES_LOCK_IRQ)
+				continue;
+			if (held_ent(plan, i))
+				continue;
+			err = ref_ent(env, &new, st, insn_idx, ref);
+			if (err)
+				return err;
+			ent = match_ent(plan, &new, !pass);
+			if (!ent && !pass)
+				continue;
+			if (!ent && plan->visited)
+				return BPF_CONFLICT_NOT_ALWAYS_HELD;
+			if (!ent && plan->nr_ents == BPF_PAD_MAX_ENTS)
+				return BPF_CONFLICT_TOO_MUCH;
+			ent = ent ?: add_ent(plan, &new);
+			if (!ent)
+				return -ENOMEM;
+			ent->ref = i;
+			for (arg = 0; arg < BPF_PAD_MAX_ARGS; arg++)
+				ent->nr_cands[arg] = common_cands(ent, &new, arg, ent->cand[arg]);
+		}
+	}
+	for (i = st->frame[st->curframe]->entry_refs, pos = 0; i < st->acquired_refs; i++) {
+		ent = held_ent(plan, i);
+		if (!ent)
+			continue;
+		if (ent - plan->ents < pos)
+			return BPF_CONFLICT_ORDER_DIFFERS;
+		pos = ent - plan->ents;
+	}
+	for (i = 0; i < plan->nr_ents; i++)
+		if (plan->ents[i].ref < 0)
+			return BPF_CONFLICT_NOT_ALWAYS_HELD;
+	return 0;
+}
+
 /*
  * The current frame of @st is about to be cancelled at the site of @kind at @insn_idx. Add what it
  * holds to the record of the site, also if it holds nothing. Returns the record, whose 'conflict'
@@ -189,12 +546,17 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 {
 	struct bpf_pad_plan *plan;
 	u32 class, nr;
+	int err;
 
 	plan = bpf_pad_plan_get(env, insn_idx, kind);
 	if (!plan)
 		return ERR_PTR(-ENOMEM);
 	if (plan->conflict)
 		return plan;
+	err = visit_refs(env, plan, st, insn_idx);
+	if (err < 0)
+		return ERR_PTR(err);
+	plan->conflict = err;
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++) {
 		nr = frame_sections(st, class);
 		if (nr > BPF_PAD_MAX_SECTIONS)
@@ -208,14 +570,66 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 }
 
 /*
- * The insns of the landing pad of @plan, a site in @subprog, but for the last one, which leaves the
- * frame. Returns their number, less than BPF_PAD_MAX_INSNS.
+ * R@reg = the handle that is at @place. Returns the number of insns.
+ */
+static int load_handle(struct bpf_verifier_env *env, struct bpf_insn *buf,
+		       struct bpf_insn_aux_data *aux, int reg, const struct bpf_pad_place *place)
+{
+	const struct bpf_map *map;
+	u64 addr = 0;
+	int n = 0;
+
+	switch (place->loc) {
+	case BPF_PLACE_REG:
+		buf[n++] = BPF_MOV64_REG(reg, place->at);
+		break;
+	case BPF_PLACE_SPILL:
+		buf[n++] = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_FP, place->at);
+		break;
+	case BPF_PLACE_MAP_VALUE:
+		/* what check_and_resolve_insns() makes of such an insn */
+		map = env->used_maps[place->at];
+		map->ops->map_direct_value_addr(map, &addr, -place->delta);
+		addr -= place->delta;
+		aux[n].map_index = place->at;
+		aux[n].map_off = -place->delta;
+		buf[n++] = BPF_RAW_INSN(BPF_LD | BPF_DW | BPF_IMM, reg, BPF_PSEUDO_MAP_VALUE, 0,
+					(u32)addr);
+		buf[n++] = BPF_RAW_INSN(0, 0, 0, 0, addr >> 32);
+		return n;
+	}
+	if (place->delta)
+		buf[n++] = BPF_ALU64_IMM(BPF_ADD, reg, -place->delta);
+	return n;
+}
+
+/* The insns that release the entries of @plan, the youngest first */
+static int release_ents(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
+			struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
+{
+	const struct bpf_pad_ent *ent;
+	int i, arg, n = 0;
+
+	for (i = plan->nr_ents - 1; i >= 0; i--) {
+		ent = &plan->ents[i];
+		for (arg = 0; arg < BPF_PAD_MAX_ARGS && ent->nr_cands[arg]; arg++)
+			n += load_handle(env, &buf[n], &aux[n], BPF_REG_1 + arg, &ent->cand[arg][0]);
+		buf[n++] = ent->release;
+	}
+	return n;
+}
+
+/*
+ * Emit the insns of the pad of @plan, a site in @subprog, except the last one, which leaves the
+ * frame. The main pass does not see these insns, so the aux data that later passes look up for them
+ * goes to @aux, one element per insn. Returns the number of insns, at most BPF_PAD_MAX_INSNS.
  */
 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)
 {
-	int class, i, n = 0;
+	int class, i, n;
 
+	n = release_ents(env, plan, buf, aux);
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
 		for (i = 0; i < plan->sections[class]; i++)
 			buf[n++] = release_call(class);
@@ -229,8 +643,10 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 {
 	struct bpf_insn release;
-	int class, err = plan->conflict;
+	int i, class, err = plan->conflict;
 
+	for (i = 0; !err && i < plan->nr_ents; i++)
+		err = get_release(env, &plan->ents[i].release);
 	for (class = 0; !err && class < BPF_PAD_NR_SECTIONS; class++) {
 		release = release_call(class);
 		if (plan->sections[class])
@@ -239,6 +655,36 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 	return err;
 }
 
+/* 'spin_lock@5(r6-8)': what insn 5 brought to the frame, the arguments of its release */
+static void print_ent(struct bpf_verifier_env *env, const struct bpf_pad_ent *ent)
+{
+	static const char * const class[] = {
+		[BPF_PAD_IRQ]			= "irq",
+		[BPF_PAD_RES_LOCK]		= "res_lock",
+		[BPF_PAD_RES_LOCK_IRQ]		= "res_lock_irq",
+		[BPF_PAD_SPIN_LOCK]		= "spin_lock",
+	};
+	const struct bpf_pad_place *place;
+	int arg;
+
+	verbose(env, "%s@%d(", class[ent->class], ent->origin);
+	for (arg = 0; arg < BPF_PAD_MAX_ARGS && ent->nr_cands[arg]; arg++) {
+		place = &ent->cand[arg][0];
+		verbose(env, "%s", arg ? ", " : "");
+		if (place->loc == BPF_PLACE_SPILL)
+			verbose(env, "*fp%d", place->at);
+		else if (place->loc == BPF_PLACE_MAP_VALUE)
+			verbose(env, "map#%d", place->at);
+		else if (place->at == BPF_REG_FP)
+			verbose(env, "fp");
+		else
+			verbose(env, "r%d", place->at);
+		if (place->delta)
+			verbose(env, "%+d", -place->delta);
+	}
+	verbose(env, ") ");
+}
+
 /* Print what the pad of the site at insn @i releases, or why it cannot be generated */
 static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
 {
@@ -250,9 +696,15 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 		[BPF_CONFLICT_SECTIONS_DIFFER]	= "the number of sections differs",
 		[BPF_CONFLICT_TOO_MUCH]		= "too much is held",
 		[BPF_CONFLICT_NO_RELEASE]	= "the program can call nothing that releases a resource",
+		[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",
 	};
+	int j;
 
 	verbose(env, "landing pad of %s at %d: ", kind[plan->kind], i);
+	for (j = plan->nr_ents - 1; !plan->conflict && j >= 0; j--)
+		print_ent(env, &plan->ents[j]);
 	if (plan->conflict)
 		verbose(env, "conflict: %s\n", why[plan->conflict]);
 	else
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index d8c2d239867a..a1c4415266ed 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -1547,6 +1547,7 @@ static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_e
 	if (err)
 		return NULL;
 	state->refs[new_ofs].insn_idx = insn_idx;
+	state->refs[new_ofs].origin = insn_idx;
 
 	return &state->refs[new_ofs];
 }
@@ -11874,8 +11875,10 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 	err = resize_reference_state(caller, exit->acquired_refs);
 	if (err)
 		return err;
-	for (i = nheld; i < exit->acquired_refs; i++)
+	for (i = nheld; i < exit->acquired_refs; i++) {
 		caller->refs[i] = exit->refs[i];
+		caller->refs[i].origin = call_idx;
+	}
 	caller->held = exit->held;
 
 	nregs = bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1;
@@ -12623,6 +12626,9 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 			bpf_diag_mod_end(env);
 		}
 		hide_returned_stack_ptrs(env, nregs, caller->regs);
+		/* To the caller, the call acquired what the callee still holds. */
+		for (i = callee->entry_refs; i < state->acquired_refs; i++)
+			state->refs[i].origin = callee->callsite;
 	}
 
 	/* Invalidate callee-local dynptrs and their slices before the frame goes away. */
@@ -21601,7 +21607,7 @@ static bool frame_holds_resources(const struct bpf_verifier_state *st)
  *
  * False when it cannot:
  * - This frame acquired something itself, and there is no landing pad for that: the verifier
- *   emits one for sections only.
+ *   emits none for references.
  * - There is a call of the subprog that unwind_goto doesn't follow. That is every
  *   program that is compiled without unwinding.
  * - A helper that calls a callback doesn't expect it to unwind.
@@ -21616,6 +21622,7 @@ static bool state_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)
@@ -21623,8 +21630,9 @@ static bool state_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;
-	if (st->acquired_refs != frame->entry_refs)
-		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;
@@ -21737,17 +21745,49 @@ 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. */
+static void unmark_stack_obj(struct bpf_verifier_env *env, int id)
+{
+	u32 mask = 1 << STACK_IRQ_FLAG;
+	struct bpf_stack_state *slot;
+	struct bpf_func_state *frame;
+	struct bpf_reg_state *reg;
+
+	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);
+			memset(slot->slot_type, STACK_INVALID, sizeof(slot->slot_type));
+		}
+	}));
+}
+
 /*
  * The current frame is left at a site, and its landing pad releases what the frame acquired since
  * 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. The callers may have pointers that are good as long as a
- * lock or a section is held.
+ * 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.
  */
 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;
+	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)
+			err = release_irq_state(env, ref->id);
+		else
+			err = release_lock_state(env, ref->type, ref->id, ref->ptr);
+		if (verifier_bug_if(err, env, "the youngest of refs[] cannot be released"))
+			return -EFAULT;
+		unmark_stack_obj(env, id);
+	}
+	if (st->active_locks != locks)
+		invalidate_non_owning_refs(env);
 	st->active_rcu_locks = frame->entry_rcu_locks;
 	st->active_preempt_locks = frame->entry_preempt_locks;
 	if (!in_rcu_cs(env))
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 15/73] bpf: Add unwind_goto after calls of subprogs
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (13 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 14/73] bpf: Release locks and irq flags in landing pads Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 16/73] bpf: Let the kernel cancel a program in a global subprog Kumar Kartikeya Dwivedi
                   ` (57 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index d40bd855c539..893125e651d8 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 154f9569b132..0614a48b90e5 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -241,7 +241,10 @@ int bpf_patch_list_insert(struct bpf_verifier_env *env, u32 off,
 	return patch_list_insert(env, off, insns, cnt, false);
 }
 
-/* Queue insns to go behind insn 'off', which does not fall through. They are not dead code. */
+/*
+ * Queue insns to go after insn 'off'. They are not dead code, whatever the next insn is: 'off'
+ * falls through or returns to them, or a jump leads to them.
+ */
 int bpf_patch_list_append(struct bpf_verifier_env *env, u32 off,
 			  const struct bpf_insn *insns, u32 cnt)
 {
@@ -600,7 +603,7 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
 /*
  * The landing pad of a site in subprog @s. The only exit of a pad is its last insn. Nothing in a
  * pad is hardened against a cpu that mispredicts: only a program that is loaded with CAP_PERFMON
- * gets one, see state_can_unwind().
+ * gets one, see frame_can_unwind().
  * Returns the number of insns, BPF_PAD_MAX_INSNS + 1 at most.
  */
 static int emit_pad(struct bpf_verifier_env *env, int s, const struct bpf_pad_plan *plan,
@@ -613,11 +616,65 @@ static int emit_pad(struct bpf_verifier_env *env, int s, const struct bpf_pad_pl
 	return n;
 }
 
-/* Does the site of @plan at an insn with @aux get a landing pad after its subprog? */
-static bool plan_has_pad(const struct bpf_insn_aux_data *aux, const struct bpf_pad_plan *plan)
+static bool guard_leaves_subprog(const struct bpf_insn_aux_data *aux)
+{
+	return aux->loop_guard && aux->guard_unwinds;
+}
+
+/* Does the program leave the frame at the site of @plan, which is at insn @i? */
+static bool site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
+{
+	int s;
+
+	switch (plan->kind) {
+	case BPF_SITE_GUARD:
+		return guard_leaves_subprog(&env->insn_aux_data[i]);
+	case BPF_SITE_RECURSION:
+		return bpf_find_containing_subprog(env, i)->recursive;
+	case BPF_SITE_CALL:
+		if (!plan->visited || plan->conflict)
+			return false;
+		bpf_pad_for_each_callee(plan, s)
+			if (env->subprog_info[s].can_unwind)
+				return true;
+	}
+	return false;
+}
+
+/*
+ * 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.
+ */
+static void 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;
+	struct bpf_subprog_info *sub;
+	bool changed;
+	int i, s;
+
+	do {
+		changed = false;
+		for (s = 0; s < env->subprog_cnt; s++) {
+			sub = &env->subprog_info[s];
+			if (sub->can_unwind || !sub->bail_unwinds)
+				continue;
+			for (i = sub->start; i < sub[1].start && !sub->can_unwind; i++) {
+				sub->can_unwind = guard_leaves_subprog(&aux[i]);
+				for (plan = aux[i].pad_plans; plan; plan = plan->next)
+					sub->can_unwind |= site_is_used(env, i, plan);
+			}
+			changed |= sub->can_unwind;
+		}
+	} while (changed);
+}
+
+/* Does the site of @plan at insn @i get a landing pad after its subprog? */
+static bool plan_has_pad(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
 {
 	/* bpf_insert_recursion_checks() emits the pad of the check */
-	return plan->kind != BPF_SITE_RECURSION && aux->loop_guard && aux->guard_unwinds;
+	return plan->kind != BPF_SITE_RECURSION && site_is_used(env, i, plan);
 }
 
 /*
@@ -634,13 +691,11 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 	struct bpf_pad_plan *plan;
 
 	for (i = env->subprog_info[s].start; i <= last; i++) {
-		if (!aux[i].loop_guard || !aux[i].guard_unwinds)
-			continue;
 		/* no state got there in the pass: the empty plan will do */
-		if (!bpf_pad_plan_get(env, i, BPF_SITE_GUARD))
+		if (guard_leaves_subprog(&aux[i]) && !bpf_pad_plan_get(env, i, BPF_SITE_GUARD))
 			return -ENOMEM;
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
-			if (!plan_has_pad(&aux[i], plan))
+			if (!plan_has_pad(env, i, plan))
 				continue;
 			n = emit_pad(env, s, plan, new, new_aux);
 			for (pad = 0; pad < cnt; pad += len) {
@@ -664,11 +719,45 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 	return cnt;
 }
 
+/*
+ * Add unwind_goto after the calls that are sites, see check_unwound_arrival(). Nothing stands
+ * 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.
+ */
+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_aux_data *aux = env->insn_aux_data;
+	struct bpf_patch_list *pl = &env->patch_list;
+	const struct bpf_subprog_info *sub;
+	const struct bpf_pad_plan *plan;
+	const struct bpf_insn_patch *p;
+	int i, s, err;
+
+	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++) {
+			plan = bpf_pad_plan(&aux[i], BPF_SITE_CALL);
+			if (!plan || !site_is_used(env, i, plan))
+				continue;
+			/* the insn that follows the call may be dead code, what is appended is not */
+			err = bpf_patch_list_append(env, i, &unwind_goto, 1);
+			if (err)
+				return err;
+			p = &pl->patches[pl->cnt - 1];
+			bpf_patch_list_jump(pl, &pl->insns[p->start + p->len - 1],
+					    sub[1].start - added[s] + plan->pad, 0);
+		}
+	}
+	return bpf_patch_list_commit(env);
+}
+
 /*
  * Emit what the main pass decided about the sites: may_goto before the insns that it
- * marked, see check_loop_guard(), and the landing pads. It verified the edge from the insn to
- * where may_goto goes. What a pad does it did to the states that left the frame at the site, see
- * unwind_frame().
+ * marked, see check_loop_guard(), unwind_goto after calls, and the landing pads. It verified the
+ * edge from the insn to where may_goto goes. What a pad does it did to the states that left the
+ * frame at the site, see unwind_frame().
  *
  *	may_goto to		or	may_goto pad
  *	insn				insn
@@ -704,6 +793,7 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 		err = -ENOMEM;
 		goto out;
 	}
+	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);
@@ -749,10 +839,11 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 		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(&aux[i], plan))
+				if (plan_has_pad(env, i, plan))
 					emit_pad(env, s, plan, new,
 						 &aux[sub[1].start - added[s] + plan->pad]);
 	}
+	err = insert_unwind_gotos(env, added);
 out:
 	kvfree(added);
 	kvfree(new);
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 1f6b084259fc..1e97448f989f 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -6,6 +6,7 @@
  * SITE is an insn at which that can happen:
  *   - 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)
+ *   - 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
  * time is up, and the program ends without reading '*p'. '+' marks what the verifier adds:
@@ -23,8 +24,8 @@
  * The verifier does not verify a landing pad, and no insn stands for it in the main pass:
  *   1. In the main pass, a state that reaches a site is cancelled there. bpf_pad_visit() adds what
  *      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 leaves its frame as at an
- *      exit insn.
+ *      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
  *      the pass, like an insn that the pass could not prove: a later pass that keeps more states
@@ -47,6 +48,22 @@
  *
  * All states at a site have to share a location for each release, and the pad has to know whether
  * the resource is held. Only the program counter tells the pad, so all states have to hold it.
+ *
+ * The frames of a program are cancelled one at a time. The pad of a function that the program calls
+ * ends in unwind_exit. That returns to the unwind_goto after the call, which leads to the pad of
+ * the caller. The verifier adds the unwind_goto, which is an exception table entry and no code:
+ *
+ *       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
+ *
+ * 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.
  */
 #include <linux/bpf.h>
 #include <linux/bpf_verifier.h>
@@ -108,6 +125,35 @@ struct bpf_pad_plan *bpf_pad_plan(const struct bpf_insn_aux_data *aux, enum bpf_
 	return NULL;
 }
 
+/* @callee came back to the call of @plan: it takes its place in the list */
+static int plan_add_callee(struct bpf_verifier_env *env, struct bpf_pad_plan *plan, u32 callee)
+{
+	u32 n = plan->nr_callees, mid, lo = 0, hi = n, *list;
+
+	while (lo < hi) {
+		mid = (lo + hi) / 2;
+		if (plan->callee[mid] < callee)
+			lo = mid + 1;
+		else
+			hi = mid;
+	}
+	if (lo < n && plan->callee[lo] == callee)
+		return 0;
+	/* the list has room for the next power of two */
+	if (!(n & (n - 1))) {
+		list = krealloc_array(plan->callee, n ? 2 * n : 1, sizeof(*list), BPF_VERIFIER_GFP);
+		if (!list)
+			return -ENOMEM;
+		plan->callee = list;
+	}
+	/* callx can have many callees, and each new one moves those above it */
+	bpf_add_cost(env, (n - lo) * sizeof(*list) / 64, BPF_COST_SCAN);
+	memmove(&plan->callee[lo + 1], &plan->callee[lo], (n - lo) * sizeof(*list));
+	plan->callee[lo] = callee;
+	plan->nr_callees++;
+	return 0;
+}
+
 /* Returns the record of the site, which is allocated empty if there is none, or NULL */
 struct bpf_pad_plan *bpf_pad_plan_get(struct bpf_verifier_env *env, int insn_idx,
 				      enum bpf_site_kind kind)
@@ -126,6 +172,16 @@ struct bpf_pad_plan *bpf_pad_plan_get(struct bpf_verifier_env *env, int insn_idx
 	return plan;
 }
 
+/* @callee was left with unwind_exit and comes back to the call at @call_idx, which is a site */
+int bpf_pad_note_callee(struct bpf_verifier_env *env, int call_idx, int callee)
+{
+	struct bpf_pad_plan *plan = bpf_pad_plan_get(env, call_idx, BPF_SITE_CALL);
+
+	if (!plan)
+		return -ENOMEM;
+	return plan_add_callee(env, plan, callee);
+}
+
 static void free_plans(struct bpf_pad_plan *plan)
 {
 	struct bpf_pad_plan *next;
@@ -133,6 +189,7 @@ static void free_plans(struct bpf_pad_plan *plan)
 	for (; plan; plan = next) {
 		next = plan->next;
 		kfree(plan->ents);
+		kfree(plan->callee);
 		kfree(plan);
 	}
 }
@@ -488,6 +545,8 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 	struct bpf_pad_ent new, *ent;
 	int i, 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;
 	for (pass = 0; pass < 2; pass++) {
@@ -691,6 +750,7 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 	static const char * const kind[] = {
 		[BPF_SITE_GUARD]		= "may_goto",
 		[BPF_SITE_RECURSION]		= "recursion check",
+		[BPF_SITE_CALL]			= "call",
 	};
 	static const char * const why[] = {
 		[BPF_CONFLICT_SECTIONS_DIFFER]	= "the number of sections differs",
@@ -699,6 +759,7 @@ 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",
 	};
 	int j;
 
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index a1c4415266ed..81086ac450ed 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -3362,6 +3362,24 @@ static int record_callx_edge(struct bpf_verifier_env *env, int caller, int calle
 	return 0;
 }
 
+/*
+ * The helper or kfunc at this insn cannot pass on a callback that unwinds, so its callback @subprog
+ * must not leave with unwind_exit or cancel_exit. Mark @subprog 'stuck': its may_goto jumps and its
+ * accesses to arena are skipped. Fails if @subprog already left at a site without such a fallback.
+ */
+static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)
+{
+	struct bpf_subprog_info *sub = &env->subprog_info[subprog];
+
+	if (sub->did_unwind) {
+		verbose(env, "callback cannot unwind at insn %d: %s() does\n",
+			env->insn_idx, bpf_subprog_name(env, subprog));
+		return -EINVAL;
+	}
+	sub->bail_unwinds = false;
+	return 0;
+}
+
 /*
  * 'call foo; unwind_goto pad' goes to the pad when foo left with unwind_exit.
  * JITs don't emit a branch for it. unwind_exit finds the pad by its return
@@ -5986,17 +6004,15 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 	struct bpf_insn *insn = env->prog->insnsi;
 	int cnt = env->subprog_cnt, i, j, s, err;
 	struct bpf_call_graph cg;
-	bool plain_callx = false;
+	/* the program calls the subprog, or callx may | a helper may | such a subprog gets to it */
+	enum { CALLED = 1, CB = 2, BELOW_CB = 4 };
 
 	/* callx calls node 'cnt', which calls each subprog whose address is taken */
 	err = bpf_call_graph_init(&cg, cnt + 1);
 	for (s = 0; s < cnt; s++) {
 		for (i = si[s].start; i < si[s + 1].start && !err; i++) {
-			if (bpf_is_callx(&insn[i])) {
+			if (bpf_is_callx(&insn[i]))
 				err = bpf_call_graph_add(&cg, s, cnt);
-				if (!bpf_is_unwind_goto(&insn[i + 1]))
-					plain_callx = true;
-			}
 			if (bpf_pseudo_call(&insn[i]) || bpf_pseudo_func(&insn[i])) {
 				j = bpf_find_subprog(env, i + insn[i].imm + 1);
 				if (j < 0)
@@ -6010,16 +6026,15 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 					err = -EINVAL;
 					goto out;
 				}
-				/* the helper that calls a callback doesn't expect it to unwind */
-				if (bpf_pseudo_func(&insn[i]) || !bpf_is_unwind_goto(&insn[i + 1]))
-					si[j].plain_call = true;
 				/*
 				 * The helper that takes a callback calls it, or keeps it: the
 				 * callback that arms itself again doesn't call itself.
 				 */
 				if (bpf_pseudo_call(&insn[i]) ||
-				    !func_is_kept_for_later(env, i, si[s + 1].start))
+				    !func_is_kept_for_later(env, i, si[s + 1].start)) {
 					err = bpf_call_graph_add(&cg, s, j);
+					cg.marks[j] |= bpf_pseudo_call(&insn[i]) ? CALLED : CB;
+				}
 				if (bpf_pseudo_func(&insn[i]))
 					si[j].addr_taken = true;
 			}
@@ -6029,8 +6044,10 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 	}
 	for (i = 0; i < env->func_ptr_cnt; i++) {
 		j = bpf_find_subprog(env, env->func_ptrs[i].xlated_off);
-		if (j >= 0)
+		if (j >= 0) {
 			si[j].addr_taken = true;
+			cg.marks[j] |= CALLED;
+		}
 	}
 	for (s = 0; s < cnt && !err; s++)
 		if (si[s].addr_taken)
@@ -6038,21 +6055,27 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 	if (err)
 		goto out;
 
+	bpf_call_graph_sort(&cg, 0);
+
+	/* A helper doesn't expect its callback to unwind, so what the callback calls cannot either */
+	for (s = 0; s < cnt; s++)
+		if (cg.marks[s] & CB)
+			cg.marks[s] |= BELOW_CB;
+	bpf_call_graph_mark_callees(&cg, BELOW_CB);
+
 	/*
+	 * What only the kernel calls returns to it: the main prog, the callback of a timer.
 	 * Callers of a global subprog look at can_unwind before the subprog is verified.
-	 * The main prog returns to the kernel.
 	 */
 	for (s = 0; s < cnt; s++) {
-		if (plain_callx && si[s].addr_taken)
-			si[s].plain_call = true;
 		si[s].bail_unwinds = si[s].can_unwind ||
-				     (s && !si[s].plain_call && !bpf_subprog_is_global(env, s) &&
-				      bpf_jit_supports_unwind() &&
-				      !bpf_prog_is_offloaded(env->prog->aux));
+				     (s && !bpf_subprog_is_global(env, s) &&
+				      env->prog->jit_requested && bpf_jit_supports_unwind() &&
+				      !bpf_prog_is_offloaded(env->prog->aux) && bpf_may_unwind(env) &&
+				      (cg.marks[s] & (CALLED | BELOW_CB)) == CALLED);
+		si[s].did_unwind = si[s].can_unwind;
 	}
 
-	bpf_call_graph_sort(&cg, 0);
-
 	for (s = 0; s < cnt; s++) {
 		if (!bpf_call_graph_recursive(&cg, s))
 			continue;
@@ -11609,6 +11632,12 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 	err = check_cb_unwind(env, insn, insn_idx, subprog);
 	if (err)
 		return err;
+	/* the helper has no pad, or nothing takes the program from its call to a pad */
+	if (!insn_has_cb_pad(insn) || !bpf_is_unwind_goto(insn + 1)) {
+		err = subprog_cannot_unwind(env, subprog);
+		if (err)
+			return err;
+	}
 
 	/* for callback functions enqueue entry to callback and
 	 * proceed with next instruction within current frame.
@@ -11809,6 +11838,18 @@ static int exit_func_on_its_own(struct bpf_verifier_env *env, int exit_idx)
 	return err ?: PROCESS_BPF_EXIT;
 }
 
+/*
+ * @callee was left with unwind_exit and comes back to the call at @call_idx. From there the program
+ * goes to unwind_goto that follows the call. If it has none the verifier adds it, see
+ * check_unwound_arrival().
+ */
+static int check_unwound_return(struct bpf_verifier_env *env, int call_idx, int callee)
+{
+	if (bpf_is_unwind_goto(&env->prog->insnsi[call_idx + 1]))
+		return 0;
+	return bpf_pad_note_callee(env, call_idx, callee);
+}
+
 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, bool is_null);
 
 static u32 returned_id(u32 id)
@@ -11845,10 +11886,10 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 		env->subprog_info[callee->subprogno].releases_inherited = true;
 		return BPF_EXIT_NEEDS_CALLER;
 	}
-	if (exit->unwound && !bpf_is_unwind_goto(&env->prog->insnsi[call_idx + 1])) {
-		verbose(env, "unwind_exit, but no unwind_goto after the call at insn %d\n",
-			call_idx);
-		return -EINVAL;
+	if (exit->unwound) {
+		err = check_unwound_return(env, call_idx, callee->subprogno);
+		if (err)
+			return err;
 	}
 	caller->unwound = exit->unwound;
 	caller->max_held_cnt = max(caller->max_held_cnt, exit->max_held_cnt);
@@ -12060,10 +12101,9 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		if (env->subprog_info[subprog].can_unwind) {
 			struct bpf_verifier_state *branch;
 
-			if (!bpf_is_unwind_goto(insn + 1)) {
-				verbose(env, "no unwind_goto after the call of %s()\n", sub_name);
-				return -EINVAL;
-			}
+			err = check_unwound_return(env, *insn_idx, subprog);
+			if (err)
+				return err;
 			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
 			if (IS_ERR(branch))
 				return PTR_ERR(branch);
@@ -12575,12 +12615,10 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 		 * r0 of the callback as it is: the pad gets its state, as the
 		 * pad after a subprog call does.
 		 */
-		if (!bpf_is_unwind_goto(&env->prog->insnsi[callee->callsite + 1])) {
-			verbose(env, "unwind_exit, but no unwind_goto after the call at insn %d\n",
-				callee->callsite);
-			return -EINVAL;
-		}
-		state->unwound = true;
+		err = check_unwound_return(env, callee->callsite, callee->subprogno);
+		if (err)
+			return err;
+		state->unwound = callee->in_callback_fn ? BPF_UNWOUND_CB : BPF_UNWOUND;
 	}
 	if (callee->in_callback_fn && !unwinds) {
 		/* the helper continues after the barrier of its call */
@@ -21487,6 +21525,11 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge
 	if (infeasible_state_ends(env))
 		return 1;
 
+	/* what comes back from a call with unwind_exit goes to a landing pad, not to the insn */
+	if (env->cur_state->unwound == BPF_UNWOUND &&
+	    !bpf_is_unwind_goto(&env->prog->insnsi[env->insn_idx]))
+		return 0;
+
 	/* The callback came back to the helper that calls it, in the same trip. */
 	if (frame->callback_depth)
 		return enter_callback(env, true, backedge_loop);
@@ -21599,17 +21642,16 @@ static bool frame_holds_resources(const struct bpf_verifier_state *st)
 }
 
 /*
- * A loop or a recursion is out of budget in the current frame of @st. What the
- * program computed so far is not what it was meant to compute, so it's better
- * not to go on. The way to stop is to unwind: 'r0 = 0; unwind_exit'. The landing
- * pads of the callers are code like any other. They release what the callers
- * hold, or the program is rejected.
+ * A loop or a recursion is out of budget in the current frame of @st, or what it called came back
+ * with unwind_exit. What the program computed so far is not what it was meant to compute, so it's
+ * better not to go on. The way to stop is to unwind: 'r0 = 0; unwind_exit'. The landing
+ * pads that the callers have in the program are code like any other. They release what
+ * 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.
- * - There is a call of the subprog that unwind_goto doesn't follow. That is every
- *   program that is compiled without unwinding.
+ * - 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
  * its own. It releases what it holds there.
@@ -21617,7 +21659,7 @@ static bool frame_holds_resources(const struct bpf_verifier_state *st)
  * @or_exit: there is no such path. 'r0 = 0; exit' has to do where the subprog
  * cannot unwind, and the caller goes on with 0 in place of the result.
  */
-static bool state_can_unwind(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+static bool frame_can_unwind(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 			     bool or_exit)
 {
 	const struct bpf_func_state *frame = st->frame[st->curframe];
@@ -21725,13 +21767,13 @@ static int check_loop_guard(struct bpf_verifier_env *env)
 		aux->guard_no_unwind = false;
 	}
 	if (!aux->guard_no_unwind &&
-	    !state_can_unwind(env, env->cur_state, aux->guard_unset_reg)) {
+	    !frame_can_unwind(env, env->cur_state, aux->guard_unset_reg)) {
 		env->guards_late |= aux->loop_guard;
 		aux->guard_no_unwind = true;
 	}
 	/* another state selected the target, possibly a state that only a join makes */
 	env->run_has_guess |= aux->guard_no_unwind &&
-			      state_can_unwind(env, env->cur_state, aux->guard_unset_reg);
+			      frame_can_unwind(env, env->cur_state, aux->guard_unset_reg);
 out:
 	aux->loop_guard = true;
 	aux->guard_unwinds = !aux->guard_no_unwind;
@@ -21742,6 +21784,12 @@ static int check_loop_guard(struct bpf_verifier_env *env)
 	/* more peeled trips can show that the edge is dead */
 	if (!err && env->head)
 		env->head->st.suspect_loops |= loop->suspect_bit;
+	/*
+	 * The state on that edge leaves the subprog. So far it left the loop, and the code that
+	 * follows the loop had the suspect of its errors from there.
+	 */
+	if (!err && env->head && !aux->guard_no_unwind && !frame_is_top(env->cur_state))
+		env->cur_state->suspect_loops |= loop->suspect_bit;
 	return err;
 }
 
@@ -21806,11 +21854,13 @@ static int release_frame_resources(struct bpf_verifier_env *env)
  *
  * With a conflict there is no pad: the site is an unproven insn in @st, which ends here. The pass
  * goes on, and a pass that keeps more apart may have no such state.
+ * A frame that cannot unwind and waits in a call that comes back with unwind_exit is a conflict.
  */
 static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int insn_idx,
 			enum bpf_site_kind kind)
 {
 	struct bpf_func_state *frame = st->frame[st->curframe];
+	struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
 	struct bpf_verifier_state *cur = env->cur_state;
 	int cur_idx = env->insn_idx, err;
 	struct bpf_pad_plan *plan;
@@ -21821,7 +21871,14 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	env->insn_idx = insn_idx;
 	/* its suspects are those of a conflict that only bpf_pads_settle() finds */
 	env->insn_aux_data[insn_idx].suspect_loops |= st->suspect_loops;
-	plan = bpf_pad_visit(env, st, insn_idx, kind);
+	/* there is no other way out of a call */
+	if (kind == BPF_SITE_CALL && !frame_can_unwind(env, st, false)) {
+		plan = bpf_pad_plan_get(env, insn_idx, kind) ?: ERR_PTR(-ENOMEM);
+		if (!IS_ERR(plan))
+			plan->conflict = BPF_CONFLICT_CANNOT_UNWIND;
+	} else {
+		plan = bpf_pad_visit(env, st, insn_idx, kind);
+	}
 	err = PTR_ERR_OR_ZERO(plan);
 	if (err)
 		goto out;
@@ -21841,7 +21898,8 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_0));
 	bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_2));
 
-	st->unwound = env->subprog_info[frame->subprogno].bail_unwinds;
+	st->unwound = sub->bail_unwinds && !frame_is_top(st);
+	sub->did_unwind |= st->unwound;
 	if (env->log.level & BPF_LOG_LEVEL2)
 		verbose(env, "from %d to %s of func#%d\n", insn_idx,
 			st->unwound ? "unwind_exit" : "exit", frame->subprogno);
@@ -21876,6 +21934,17 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	return err;
 }
 
+/*
+ * The call before this insn came back with unwind_exit, and the program has no unwind_goto
+ * there. The verifier adds it: the call is a site of the current frame, which is unwound in turn.
+ * The current state is taken.
+ */
+static int check_unwound_arrival(struct bpf_verifier_env *env)
+{
+	env->cur_state->unwound = false;
+	return unwind_frame(env, env->cur_state, env->insn_idx - 1, BPF_SITE_CALL);
+}
+
 /* 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)
 {
@@ -22176,6 +22245,16 @@ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
 		insn = &insns[env->insn_idx];
 		insn_aux = &env->insn_aux_data[env->insn_idx];
 
+		/* A callback unwound: the call of its helper is visited once more. */
+		if (state->unwound == BPF_UNWOUND_CB) {
+			state->unwound = BPF_UNWOUND;
+		} else if (state->unwound && !bpf_is_unwind_goto(insn)) {
+			err = check_unwound_arrival(env);
+			if (err)
+				return err;
+			goto process_bpf_exit;
+		}
+
 		account_processed_insn(env);
 
 		state->last_insn_idx = env->prev_insn_idx;
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
index b90127d1f36b..6d188a19206f 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
@@ -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);
 }
 
diff --git a/tools/testing/selftests/bpf/progs/verifier_barrier.c b/tools/testing/selftests/bpf/progs/verifier_barrier.c
index aaef593976ec..b012235a76a4 100644
--- a/tools/testing/selftests/bpf/progs/verifier_barrier.c
+++ b/tools/testing/selftests/bpf/progs/verifier_barrier.c
@@ -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)
 {
diff --git a/tools/testing/selftests/bpf/progs/verifier_budget.c b/tools/testing/selftests/bpf/progs/verifier_budget.c
index 3b75af1d1fbd..d741cf8dbffa 100644
--- a/tools/testing/selftests/bpf/progs/verifier_budget.c
+++ b/tools/testing/selftests/bpf/progs/verifier_budget.c
@@ -7,11 +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, when unwind_goto follows every call of the subprog. The pads of the callers are
- *   verified.
- * - the main prog and an async callback end
- * - what the frame holds takes a landing pad, which the verifier emits
- * - otherwise it leaves the loop, or returns 0 from the subprog
+ * - 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 takes unwinding, per-cpu insns and timed may_goto in JIT. Some of the progs never end
  * on their own.
@@ -44,13 +43,6 @@ struct {
 	__type(value, long);
 } empty SEC(".maps");
 
-struct {
-	__uint(type, BPF_MAP_TYPE_ARRAY);
-	__uint(max_entries, 2);
-	__type(key, int);
-	__type(value, long[2]);
-} pairs SEC(".maps");
-
 SEC("socket")
 __description("budget: a loop in the main prog ends it")
 __arch_x86_64
@@ -195,10 +187,21 @@ static unsigned long spins_caught(void)
 }
 
 SEC("socket")
-__description("budget: a loop in a subprog is left when there is no unwind_goto")
+__description("budget: a loop in a subprog unwinds, the verifier adds unwind_goto")
 __arch_x86_64
 __arch_arm64
-__success __retval(7)
+__success __retval(0)
+__xlated("...")
+__xlated("call pc+4")
+__xlated("unwind_goto pc+1")
+__xlated("exit")
+__xlated("r0 = 0")
+__xlated("exit")
+__xlated("...")
+__xlated("r0 = 7")
+__xlated("exit")
+__xlated("r0 = 0")
+__xlated("unwind_exit")
 __naked void loop_in_subprog(void)
 {
 	asm volatile (
@@ -340,24 +343,17 @@ __naked void recursion(void)
 	);
 }
 
-/*
- * The one that is called too deep returns 0: 1000 + 999 + ... down to where it was: more than
- * 1000, less than 500500
- */
+/* The one that is called too deep unwinds them all */
 SEC("socket")
-__description("budget: recursion that is too deep returns 0 when there is no unwind_goto")
+__description("budget: recursion that is too deep unwinds, the verifier adds unwind_goto")
 __arch_x86_64
 __arch_arm64
-__success __retval(1)
+__success __retval(0)
 __naked void recursion_too_deep(void)
 {
 	asm volatile (
 		"r1 = 1000;"
 		"call sum_to;"
-		"r1 = r0;"
-		"r0 = 0;"
-		"if r1 <= 1000 goto +2;"
-		"if r1 >= 500500 goto +1;"
 		"r0 = 1;"
 		"exit;"
 		::: __clobber_all
@@ -393,6 +389,7 @@ __naked void recursion_ends_in_the_middle(void)
 {
 	asm volatile (
 		"call goes_down;"
+		unwind_goto(0)
 		"r1 = %[lowest_r10] ll;"
 		"r1 = *(u64 *)(r1 + 0);"
 		"r1 += 64;"
@@ -402,7 +399,8 @@ __naked void recursion_ends_in_the_middle(void)
 		"r0 = 0;"
 		"exit;"
 		:
-		: __imm_addr(lowest_r10)
+		: __imm_addr(lowest_r10),
+		  __imm_unwind_goto(0)
 		: __clobber_all
 	);
 }
@@ -576,8 +574,7 @@ __naked void loop_calls_recursion_tree(void)
 
 /*
  * Every frame loops forever and calls itself in every trip. The call that finds no room in the
- * stack returns at once. When the time slice is over every frame that is on the stack leaves
- * its loop.
+ * stack unwinds them all.
  */
 __naked __noinline __used
 static unsigned long calls_itself_in_a_loop(void)
@@ -599,7 +596,7 @@ SEC("socket")
 __description("budget: a subprog that calls itself in a loop that never ends")
 __arch_x86_64
 __arch_arm64
-__success __retval(1)
+__success __retval(0)
 __naked void recursion_in_a_loop(void)
 {
 	asm volatile (
@@ -1013,47 +1010,10 @@ __naked void nest_of_17_loops(void)
 }
 
 /*
- * The loops below spin and have no jump that every trip goes through, so may_goto is at the head.
- * It goes to the code behind the loop, past what the loop makes for that code, with the registers
- * and the stack as they are at the head.
- *
- * r6 is 5 on every edge of the program that gets behind the loop. At the head it's 7.
+ * The loop has no jump that every trip goes through, so may_goto is at its head. Only the loop sets
+ * r6.
  */
 __naked __noinline __used
-static unsigned long spins_and_makes(void)
-{
-	asm volatile (
-		"r8 = %[one] ll;"
-		"r6 = 7;"
-	"1:"
-		"r1 = *(u64 *)(r8 + 0);"
-		"if r1 == 1 goto 1b;"
-		"r6 = 5;"
-		"if r1 != 2 goto 1b;"
-		"r0 = r6;"
-		"exit;"
-		:
-		: __imm_addr(one)
-		: __clobber_all
-	);
-}
-
-SEC("socket")
-__description("budget: may_goto at the head of a loop keeps a register that the loop sets")
-__arch_x86_64
-__arch_arm64
-__success __retval(7)
-__naked void guard_at_head_keeps_reg(void)
-{
-	asm volatile (
-		"call spins_and_makes;"
-		"exit;"
-		::: __clobber_all
-	);
-}
-
-/* Only the loop sets r6: there is no way from the head to the code behind the loop */
-__naked __noinline __used
 static unsigned long spins_and_makes_unset(void)
 {
 	asm volatile (
@@ -1085,454 +1045,6 @@ __naked void guard_at_head_unset_reg(void)
 	);
 }
 
-SEC("socket")
-__description("budget: may_goto at the head of a loop, the caller counts on what the loop sets")
-__failure __msg("R9 !read_ok")
-__naked void guard_at_head_unset_reg_caller(void)
-{
-	asm volatile (
-		"call spins_and_makes_unset;"
-		"if r0 == 5 goto 1f;"
-		"r0 = r9;"
-	"1:"
-		"exit;"
-		::: __clobber_all
-	);
-}
-
-/* fp-8 is 0 on every edge of the program that leaves the loop. It's 1 at the header. */
-__naked __noinline __used
-static unsigned long spins_and_makes_slot(void)
-{
-	asm volatile (
-		"r8 = %[zero] ll;"
-		"r7 = 1;"
-		"*(u64 *)(r10 - 8) = r7;"
-		"r7 = 0;"
-	"1:"
-		"r1 = *(u64 *)(r8 + 0);"
-		"if r1 == 1 goto 1b;"
-		"*(u64 *)(r10 - 8) = r7;"
-		"if r1 != 2 goto 1b;"
-		"r0 = *(u64 *)(r10 - 8);"
-		"r0 <<= 12;"
-		"r8 += r0;"
-		"r0 = *(u64 *)(r8 + 0);"
-		"exit;"
-		:
-		: __imm_addr(zero)
-		: __clobber_all
-	);
-}
-
-SEC("socket")
-__description("budget: may_goto at the header of a loop, a stack slot that the body writes")
-__failure __msg("invalid access to map value")
-__naked void guard_at_head_dead_slot(void)
-{
-	asm volatile (
-		"call spins_and_makes_slot;"
-		"exit;"
-		::: __clobber_all
-	);
-}
-
-/*
- * The low half of r7 is live at the head of the loop, all of it where may_goto goes. On the edges
- * of the program that get there it's 3. 'w7 &= 7' has to clear the upper half.
- */
-__naked __noinline __used
-static unsigned long spins_with_half_of_reg(void)
-{
-	asm volatile (
-		"r8 = %[zero] ll;"
-		"r7 = *(u64 *)(r8 + 0);"
-		"w7 &= 7;"
-	"1:"
-		"r1 = *(u64 *)(r8 + 0);"
-		"if w1 == w7 goto 1b;"
-		"r7 = 3;"
-		"if r1 == 2 goto 2f;"
-		"w7 = 5;"
-		"goto 1b;"
-	"2:"
-		"r0 = r7;"
-		"r0 >>= 32;"
-		"exit;"
-		:
-		: __imm_addr(zero)
-		: __clobber_all
-	);
-}
-
-SEC("socket")
-__description("budget: may_goto at the head of a loop, one half of a register is live there")
-__arch_x86_64
-__arch_arm64
-__flag(BPF_F_TEST_RND_HI32)
-__success __retval(0)
-__naked void guard_at_head_half_of_reg(void)
-{
-	asm volatile (
-		"call spins_with_half_of_reg;"
-		"exit;"
-		::: __clobber_all
-	);
-}
-
-/*
- * From the head of a loop to the code behind it is not an edge of the program. What holds on
- * every edge of the program that gets there doesn't hold when may_goto does.
- */
-const volatile unsigned long four = 4;
-char five_bytes[5] SEC(".data.five_bytes");
-
-/*
- * r7 points to 'four' on every edge. At the head of the first loop it points to @at_head.
- * The second loop goes on while r6 is less than what r7 points to.
- */
-#define SPINS_THEN_COUNTS(at_head)			\
-		"r8 = %[zero] ll;"			\
-		"r7 = %[" #at_head "] ll;"		\
-	"1:"						\
-		"r2 = *(u64 *)(r7 + 0);"		\
-		"r1 = *(u64 *)(r8 + 0);"		\
-		"if r1 == 1 goto 1b;"			\
-		"r7 = %[four] ll;"			\
-		"if r1 == 2 goto 2f;"			\
-		"r7 = %[" #at_head "] ll;"		\
-		"goto 1b;"				\
-	"2:"						\
-		"r6 = 0;"				\
-	"3:"						\
-		"r2 = *(u64 *)(r7 + 0);"		\
-		"if r6 >= r2 goto 4f;"			\
-		"r1 = %[five_bytes] ll;"		\
-		"r1 += r6;"				\
-		"r3 = 1;"				\
-		"*(u8 *)(r1 + 0) = r3;"			\
-		"r6 += 1;"				\
-		"goto 3b;"				\
-	"4:"						\
-		"r0 = r6;"				\
-		"exit;"					\
-		:					\
-		: __imm_addr(zero),			\
-		  __imm_addr(one),			\
-		  __imm_addr(four),			\
-		  __imm_addr(five_bytes)		\
-		: __clobber_all
-
-__naked __noinline __used
-static unsigned long spins_then_counts_to_anything(void)
-{
-	asm volatile (SPINS_THEN_COUNTS(one));
-}
-
-SEC("socket")
-__description("budget: may_goto at the head of a loop, another bound for the next loop")
-__arch_x86_64
-__arch_arm64
-__failure __msg("invalid access to map value, value_size=5")
-__naked void guard_at_head_bound_of_next_loop(void)
-{
-	asm volatile (
-		"call spins_then_counts_to_anything;"
-		"exit;"
-		::: __clobber_all
-	);
-}
-
-/*
- * r7 is fp-8 on every edge and fp-16 at the head of the first loop. The second loop
- * counts in fp-16 and stores a number that nobody knows through r7.
- */
-__naked __noinline __used
-static unsigned long spins_then_counts_on_stack(void)
-{
-	asm volatile (
-		"r8 = %[zero] ll;"
-		"r3 = 0;"
-		"*(u64 *)(r10 - 8) = r3;"
-		"*(u64 *)(r10 - 16) = r3;"
-		"r7 = r10;"
-		"r7 += -16;"
-	"1:"
-		"r2 = *(u64 *)(r7 + 0);"
-		"r1 = *(u64 *)(r8 + 0);"
-		"if r1 == 1 goto 1b;"
-		"r7 = r10;"
-		"r7 += -8;"
-		"if r1 == 2 goto 2f;"
-		"r7 = r10;"
-		"r7 += -16;"
-		"goto 1b;"
-	"2:"
-		"r3 = 0;"
-		"*(u64 *)(r10 - 16) = r3;"
-	"3:"
-		"r6 = *(u64 *)(r10 - 16);"
-		"if r6 == 4 goto 4f;"
-		"r1 = %[five_bytes] ll;"
-		"r1 += r6;"
-		"r3 = 1;"
-		"*(u8 *)(r1 + 0) = r3;"
-		"r6 += 1;"
-		"*(u64 *)(r10 - 16) = r6;"
-		"r3 = *(u64 *)(r8 + 0);"
-		"*(u64 *)(r7 + 0) = r3;"
-		"goto 3b;"
-	"4:"
-		"r0 = r6;"
-		"exit;"
-		:
-		: __imm_addr(zero),
-		  __imm_addr(five_bytes)
-		: __clobber_all
-	);
-}
-
-SEC("socket")
-__description("budget: may_goto at the head of a loop, another pointer to the stack")
-__arch_x86_64
-__arch_arm64
-__failure __msg("math between map_value pointer and register with unbounded min value")
-__naked void guard_at_head_stack_pointer(void)
-{
-	asm volatile (
-		"call spins_then_counts_on_stack;"
-		"exit;"
-		::: __clobber_all
-	);
-}
-
-/*
- * Two states that have no join enter a loop. One has no count, so the loop gets may_goto.
- * The other one has a count. may_goto is there when it runs too, and a loop in front
- * may have used up the time slice. Then it leaves the loop in the first trip.
- *
- * r7 = the value, 16 bytes, and r8 = count, or r7 = 0 and r8 = anything
- */
-#define VALUE_AND_COUNT_OR_NEITHER(count)		\
-		"r1 = 0;"				\
-		"*(u32 *)(r10 - 4) = r1;"		\
-		"r2 = r10;"				\
-		"r2 += -4;"				\
-		"r1 = %[pairs] ll;"			\
-		"call %[bpf_map_lookup_elem];"		\
-		"if r0 == 0 goto 9f;"			\
-		"r9 = %[zero] ll;"			\
-		"r2 = *(u64 *)(r9 + 0);"		\
-		"if r2 == 0 goto 3f;"			\
-		"r7 = r0;"				\
-		"r8 = " #count ";"			\
-		"goto 4f;"				\
-	"3:"						\
-		"r7 = 0;"				\
-		"r8 = *(u64 *)(r9 + 0);"		\
-	"4:"
-
-/* It's in the value when r6 is what it is at the end of the loop that was counted: last */
-#define LOAD_IF_VALUE(last)				\
-		"if r7 == 0 goto 9f;"			\
-		"r2 = " #last ";"			\
-		"r2 -= r6;"				\
-		"r2 &= 1;"				\
-		"r2 <<= 4;"				\
-		"r7 += r2;"				\
-		"r0 = *(u64 *)(r7 + 0);"		\
-		"exit;"					\
-	"9:"						\
-		"r0 = 0;"				\
-		"exit;"					\
-		:					\
-		: __imm_addr(pairs),			\
-		  __imm_addr(zero),			\
-		  __imm(bpf_map_lookup_elem)		\
-		: __clobber_all
-
-__naked __noinline __used
-static unsigned long counted_or_not(void)
-{
-	asm volatile (
-		VALUE_AND_COUNT_OR_NEITHER(10)
-		"r6 = 0;"
-	"1:"
-		"r6 += 1;"
-		"if r6 < r8 goto 1b;"
-		LOAD_IF_VALUE(10)
-	);
-}
-
-SEC("socket")
-__description("budget: may_goto that another state needs, the loop is counted")
-__arch_x86_64
-__arch_arm64
-__failure __msg("invalid access to map value, value_size=16 off=16 size=8")
-__naked void guard_in_counted_loop(void)
-{
-	asm volatile (
-		"call counted_or_not;"
-		"exit;"
-		::: __clobber_all
-	);
-}
-
-/* 2 4 8 16 is not counted. Constants decide the jump. */
-__naked __noinline __used
-static unsigned long walked_or_not(void)
-{
-	asm volatile (
-		VALUE_AND_COUNT_OR_NEITHER(16)
-		"r6 = 1;"
-	"1:"
-		"r6 <<= 1;"
-		"if r6 < r8 goto 1b;"
-		"r6 >>= 1;"
-		LOAD_IF_VALUE(8)
-	);
-}
-
-SEC("socket")
-__description("budget: may_goto that another state needs, constants decide the exit of the loop")
-__arch_x86_64
-__arch_arm64
-__failure __msg("invalid access to map value, value_size=16 off=16 size=8")
-__naked void guard_in_walked_loop(void)
-{
-	asm volatile (
-		"call walked_or_not;"
-		"exit;"
-		::: __clobber_all
-	);
-}
-
-/* i = 0; do { i++; } while (i < n); return v ? v[((10 - i) & 1) * 2] : 0; */
-__naked __noinline __used
-static unsigned long counts(unsigned long n, long *v)
-{
-	asm volatile (
-		"r0 = 0;"
-	"1:"
-		"r0 += 1;"
-		"if r0 < r1 goto 1b;"
-		"if r2 == 0 goto 2f;"
-		"r3 = 10;"
-		"r3 -= r0;"
-		"r3 &= 1;"
-		"r3 <<= 4;"
-		"r2 += r3;"
-		"r0 = *(u64 *)(r2 + 0);"
-	"2:"
-		"exit;"
-		::: __clobber_all
-	);
-}
-
-#define LOOKUP_PAIR					\
-		"r1 = 0;"				\
-		"*(u32 *)(r10 - 4) = r1;"		\
-		"r2 = r10;"				\
-		"r2 += -4;"				\
-		"r1 = %[pairs] ll;"			\
-		"call %[bpf_map_lookup_elem];"		\
-		"if r0 == 0 goto 9f;"			\
-		"r6 = r0;"
-
-SEC("socket")
-__description("budget: a subprog is called without a count, then with a count")
-__arch_x86_64
-__arch_arm64
-__failure __msg("invalid access to map value, value_size=16 off=16 size=8")
-__naked void two_callers(void)
-{
-	asm volatile (
-		LOOKUP_PAIR
-		"r1 = %[zero] ll;"
-		"r1 = *(u64 *)(r1 + 0);"
-		"r2 = 0;"
-		"call counts;"
-		"r1 = 10;"
-		"r2 = r6;"
-		"call counts;"
-	"9:"
-		"r0 = 0;"
-		"exit;"
-		:
-		: __imm_addr(pairs),
-		  __imm_addr(zero),
-		  __imm(bpf_map_lookup_elem)
-		: __clobber_all
-	);
-}
-
-SEC("socket")
-__description("budget: a subprog is called with a count, then without a count")
-__arch_x86_64
-__arch_arm64
-__failure __msg("invalid access to map value, value_size=16 off=16 size=8")
-__naked void two_callers_counted_first(void)
-{
-	asm volatile (
-		LOOKUP_PAIR
-		"r1 = 10;"
-		"r2 = r6;"
-		"call counts;"
-		"r1 = %[zero] ll;"
-		"r1 = *(u64 *)(r1 + 0);"
-		"r2 = 0;"
-		"call counts;"
-	"9:"
-		"r0 = 0;"
-		"exit;"
-		:
-		: __imm_addr(pairs),
-		  __imm_addr(zero),
-		  __imm(bpf_map_lookup_elem)
-		: __clobber_all
-	);
-}
-
-/* A global subprog is verified after the main prog */
-__naked __noinline __used
-int counts_anything(void)
-{
-	asm volatile (
-		"r1 = %[zero] ll;"
-		"r1 = *(u64 *)(r1 + 0);"
-		"r2 = 0;"
-		"call counts;"
-		"r0 = 0;"
-		"exit;"
-		:
-		: __imm_addr(zero)
-		: __clobber_all
-	);
-}
-
-SEC("socket")
-__description("budget: a subprog is called with a count, then without a count by a global subprog")
-__arch_x86_64
-__arch_arm64
-__failure __msg("invalid access to map value, value_size=16 off=16 size=8")
-__naked void two_callers_two_passes(void)
-{
-	asm volatile (
-		LOOKUP_PAIR
-		"r1 = 10;"
-		"r2 = r6;"
-		"call counts;"
-		"call counts_anything;"
-	"9:"
-		"r0 = 0;"
-		"exit;"
-		:
-		: __imm_addr(pairs),
-		  __imm(bpf_map_lookup_elem)
-		: __clobber_all
-	);
-}
-
 /*
  * if (x) lock(); do { p = lookup(); } while (!p); if (x) { unlock(); return 0; } return *p;
  * looks(0) holds nothing at may_goto, looks(1) is in a section: the program counter does not tell
@@ -1692,12 +1204,12 @@ static unsigned long spins_all_regs_live(void)
 	);
 }
 
-/* The time is up: the loop is left with r1 = 1 and all the other registers as they are */
+/* The time is up */
 SEC("socket")
 __description("budget: may_goto where all registers are live, out of budget")
 __arch_x86_64
 __arch_arm64
-__success __retval(38)
+__success __retval(0)
 __naked void guard_all_regs_live_spins(void)
 {
 	asm volatile (
@@ -1791,8 +1303,8 @@ static unsigned long zero_at_the_bottom(unsigned long n)
 
 /*
  * The call of a recursive subprog waits for what comes out of it. The call of the second trip is
- * within the one that waits. A recursive subprog that has no time or no stack left returns 0 at
- * once, so that doesn't stop the loop.
+ * within the one that waits. The check at the entry of the recursive subprog doesn't stop the
+ * loop: the recursion is not deep.
  */
 SEC("socket")
 __description("budget: a trip is dropped at a call that waits")
diff --git a/tools/testing/selftests/bpf/progs/verifier_passes.c b/tools/testing/selftests/bpf/progs/verifier_passes.c
index 8938135698b4..cc95688120e5 100644
--- a/tools/testing/selftests/bpf/progs/verifier_passes.c
+++ b/tools/testing/selftests/bpf/progs/verifier_passes.c
@@ -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
diff --git a/tools/testing/selftests/bpf/progs/verifier_unwind.c b/tools/testing/selftests/bpf/progs/verifier_unwind.c
index 668e1d1b94b4..6be56387a825 100644
--- a/tools/testing/selftests/bpf/progs/verifier_unwind.c
+++ b/tools/testing/selftests/bpf/progs/verifier_unwind.c
@@ -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 (
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 16/73] bpf: Let the kernel cancel a program in a global subprog
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (14 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 15/73] bpf: Add unwind_goto after calls of subprogs Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 17/73] bpf: Release references in landing pads Kumar Kartikeya Dwivedi
                   ` (56 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 893125e651d8..b2cd2f42b951 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 0614a48b90e5..9e4e4a239ed9 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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);
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 1e97448f989f..bd6d1b2cd642 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -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]);
 }
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 81086ac450ed..6a3c539ebead 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -3380,6 +3380,30 @@ static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)
 	return 0;
 }
 
+/*
+ * A subprog unwinds. What calls it without unwind_goto is unwound in turn, and so on. The callers
+ * of a global subprog among them have to know, see unwind_frame(): one more round will do for all.
+ */
+static void mark_unwind_above(struct bpf_verifier_env *env)
+{
+	struct bpf_subprog_info *si = env->subprog_info, *caller;
+	const struct bpf_insn *insn = env->prog->insnsi;
+	bool changed;
+	int i;
+
+	do {
+		changed = false;
+		for (i = 0; i < env->prog->len; i++) {
+			if (!bpf_pseudo_call(&insn[i]) || bpf_is_unwind_goto(&insn[i + 1]) ||
+			    !si[bpf_find_subprog(env, i + insn[i].imm + 1)].did_unwind)
+				continue;
+			caller = bpf_find_containing_subprog(env, i);
+			changed |= !caller->did_unwind;
+			caller->did_unwind = true;
+		}
+	} while (changed);
+}
+
 /*
  * 'call foo; unwind_goto pad' goes to the pad when foo left with unwind_exit.
  * JITs don't emit a branch for it. unwind_exit finds the pad by its return
@@ -6064,13 +6088,13 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 	bpf_call_graph_mark_callees(&cg, BELOW_CB);
 
 	/*
-	 * What only the kernel calls returns to it: the main prog, the callback of a timer.
-	 * Callers of a global subprog look at can_unwind before the subprog is verified.
+	 * A function that the program calls can leave with unwind_exit or cancel_exit, if the JIT
+	 * supports them and the loader has CAP_PERFMON. A function that only the kernel calls, like
+	 * the main program or a timer callback, returns to the kernel.
 	 */
 	for (s = 0; s < cnt; s++) {
 		si[s].bail_unwinds = si[s].can_unwind ||
-				     (s && !bpf_subprog_is_global(env, s) &&
-				      env->prog->jit_requested && bpf_jit_supports_unwind() &&
+				     (s && env->prog->jit_requested && bpf_jit_supports_unwind() &&
 				      !bpf_prog_is_offloaded(env->prog->aux) && bpf_may_unwind(env) &&
 				      (cg.marks[s] & (CALLED | BELOW_CB)) == CALLED);
 		si[s].did_unwind = si[s].can_unwind;
@@ -12098,7 +12122,9 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 			}
 		}
 
-		if (env->subprog_info[subprog].can_unwind) {
+		/* No state comes out of a global subprog, see unwind_frame() */
+		if (env->subprog_info[subprog].did_unwind &&
+		    env->subprog_info[subprog].bail_unwinds) {
 			struct bpf_verifier_state *branch;
 
 			err = check_unwound_return(env, *insn_idx, subprog);
@@ -21899,6 +21925,15 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_2));
 
 	st->unwound = sub->bail_unwinds && !frame_is_top(st);
+	/*
+	 * The callers of a global subprog were verified before it. Mark them, and start the pass
+	 * again if the subprog still unwinds when the pass ends, see settle_late_unwinds().
+	 */
+	if (st->unwound && !sub->did_unwind && bpf_subprog_is_global(env, frame->subprogno)) {
+		sub->did_unwind = true;
+		mark_unwind_above(env);
+		env->pads_late = true;
+	}
 	sub->did_unwind |= st->unwound;
 	if (env->log.level & BPF_LOG_LEVEL2)
 		verbose(env, "from %d to %s of func#%d\n", insn_idx,
@@ -22438,7 +22473,8 @@ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
 /* What the pass assumed about loops does not hold, see do_check_all() */
 static bool pass_needs_restart(struct bpf_verifier_env *env)
 {
-	return (env->restart && bpf_flow_loops_lost_bound(env)) || env->guards_late;
+	return (env->restart && bpf_flow_loops_lost_bound(env)) || env->guards_late ||
+	       env->pads_late;
 }
 
 /*
@@ -24024,12 +24060,41 @@ static int check_after_pass(struct bpf_verifier_env *env)
 	return 0;
 }
 
+/*
+ * A state left a global subprog with unwind_exit or cancel_exit, and the callers did not know. If
+ * the subprog still leaves that way after the pass, as bpf_insert_sites() will see it, did_unwind
+ * and did_cancel go to the next pass, in which the callers expect it.
+ */
+static void settle_late_unwinds(struct bpf_verifier_env *env, const struct bpf_snapshot *initial)
+{
+	struct bpf_subprog_info *sub = env->subprog_info;
+	bool unwinds, late = false;
+	int s;
+
+	bpf_flow_drop_guards(env);
+	bpf_mark_subprogs_that_unwind(env);
+	for (s = 0; s < env->subprog_cnt; s++, sub++) {
+		unwinds = sub->can_unwind;
+		sub->can_unwind = initial->subprogs[s].can_unwind;
+		late |= unwinds && !initial->subprogs[s].did_unwind &&
+			bpf_subprog_is_global(env, s);
+		sub->did_unwind = unwinds;
+	}
+	if (late)
+		mark_unwind_above(env);
+	env->pads_late = late;
+}
+
 /* Returns the first error */
 static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initial)
 {
 	u32 level = env->log.level;
-	int ret;
+	int i, ret;
 
+	/* see settle_late_unwinds() */
+	for (i = 1; i < env->subprog_cnt; i++)
+		if (bpf_subprog_is_global(env, i))
+			initial->subprogs[i].did_unwind |= env->subprog_info[i].did_unwind;
 	restore_snapshot(env, initial);
 	kvfree(env->callx_edges);
 	kvfree(env->callx_index.slots);
@@ -24038,6 +24103,8 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
 	bpf_flow_new_pass(env);
 	bpf_pads_new_round(env);
 	ret = do_check_main(env) ?: do_check_subprogs(env) ?: bpf_check_limits(env);
+	if (env->pads_late)
+		settle_late_unwinds(env, initial);
 	env->log.level = level;
 	env->pass_max_cost = U64_MAX;
 	return ret == -EINTR ? ret : env->err ?: ret;
@@ -24200,7 +24267,8 @@ static int log_failing_path(struct bpf_verifier_env *env, struct bpf_snapshot *i
  * There is no more precision when the budget is used up, or when no state was imprecise.
  *
  * A pass assumes what stops each loop, and checks it, see pass_needs_restart(). If the
- * assumption is wrong, the pass starts again.
+ * assumption is wrong, the pass starts again. It also starts again when a global subprog turns
+ * out to unwind and its callers did not know, see settle_late_unwinds().
  *
  * The log has the failing path. If there is none, or if it has a guess and the error of a pass
  * is real, the log has the basic block of an error. Below level 2 the later passes and the
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 17/73] bpf: Release references in landing pads
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (15 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 16/73] bpf: Let the kernel cancel a program in a global subprog Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 18/73] bpf: Release iterators and dynptrs " Kumar Kartikeya Dwivedi
                   ` (55 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index b2cd2f42b951..f658a8aeeae0 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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)
diff --git a/include/linux/btf.h b/include/linux/btf.h
index 7bb3cc973c1f..6014282feacb 100644
--- a/include/linux/btf.h
+++ b/include/linux/btf.h
@@ -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)
 {
diff --git a/kernel/bpf/btf.c b/kernel/bpf/btf.c
index f2d2f4fdeca5..477947829b25 100644
--- a/kernel/bpf/btf.c
+++ b/kernel/bpf/btf.c
@@ -10211,6 +10211,49 @@ int btf_kfunc_check_flag(const struct btf *btf, u32 kfunc_btf_id, u32 flag)
 	return res;
 }
 
+/* Does @func_id of @btf have the prototype void (*)(struct T *), where T is @btf_id? */
+static bool btf_kfunc_takes_only(const struct btf *btf, u32 func_id, u32 btf_id)
+{
+	const struct btf_type *proto, *t;
+	u32 arg_id;
+
+	proto = btf_type_by_id(btf, btf_type_by_id(btf, func_id)->type);
+	if (btf_type_vlen(proto) != 1 || !btf_type_is_void(btf_type_by_id(btf, proto->type)))
+		return false;
+	t = btf_type_skip_modifiers(btf, btf_params(proto)[0].type, NULL);
+	if (!btf_type_is_ptr(t))
+		return false;
+	t = btf_type_skip_modifiers(btf, t->type, &arg_id);
+	return __btf_type_is_struct(t) && arg_id == btf_id;
+}
+
+/*
+ * Find a kfunc of @btf that @prog may call to release a reference to struct @btf_id. A program may
+ * release a reference with any KF_RELEASE kfunc that takes the type, whichever kfunc acquired it,
+ * so the first one that takes nothing else will do. A kfunc with a flag other than KF_SLEEPABLE or
+ * KF_SPINLOCK_SAFE is skipped: such a flag asks for what the caller may not have, like a
+ * capability or an RCU section. Returns the BTF id of the kfunc, or -ENOENT.
+ */
+s32 btf_find_release_kfunc(const struct btf *btf, u32 btf_id, const struct bpf_prog *prog)
+{
+	enum btf_kfunc_hook hooks[] = { BTF_KFUNC_HOOK_COMMON,
+					bpf_prog_type_to_kfunc_hook(resolve_prog_type(prog)) };
+	const struct btf_id_set8 *set;
+	u32 i, h, id;
+
+	for (h = 0; btf->kfunc_set_tab && h < ARRAY_SIZE(hooks); h++) {
+		set = hooks[h] < BTF_KFUNC_HOOK_MAX ? btf->kfunc_set_tab->sets[hooks[h]] : NULL;
+		for (i = 0; set && i < set->cnt; i++) {
+			id = set->pairs[i].id;
+			if ((set->pairs[i].flags & ~(KF_SLEEPABLE | KF_SPINLOCK_SAFE)) == KF_RELEASE &&
+			    btf_kfunc_takes_only(btf, id, btf_id) &&
+			    __btf_kfunc_is_allowed(btf, hooks[h], id, prog))
+				return id;
+		}
+	}
+	return -ENOENT;
+}
+
 u32 *btf_kfunc_is_modify_return(const struct btf *btf, u32 kfunc_btf_id,
 				const struct bpf_prog *prog)
 {
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 9e4e4a239ed9..25c0b0552b4d 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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++)
 					;
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index bd6d1b2cd642..b13ba84269ff 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -41,10 +41,11 @@
  * the record has a count. Every other resource is one release of the record (struct bpf_pad_ent): a
  * call, and for each argument a LOCATION (struct bpf_pad_place). A location is a register or a
  * stack slot of the program that holds the pointer at the site, plus a constant offset. For a frame
- * that holds a lock at R6 the pad is 'r1 = r6; call bpf_spin_unlock; r0 = 0; exit'. A pointer into
+ * that keeps a task in R6 the pad is 'r1 = r6; call bpf_task_release; r0 = 0; exit'. A pointer into
  * a map value is a location for the lock in that value, and R10 is one for an object in the stack
  * of the frame. A location has to be live at the site, because later passes reuse dead registers
- * and remove dead stores, see find_cands().
+ * and remove dead stores, see find_cands(). The type of a pointer says which function releases it,
+ * see ref_release().
  *
  * All states at a site have to share a location for each release, and the pad has to know whether
  * the resource is held. Only the program counter tells the pad, so all states have to hold it.
@@ -80,12 +81,16 @@ BTF_ID(func, bpf_local_irq_restore)
 BTF_ID(func, bpf_res_spin_unlock)
 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
 
+BTF_ID_LIST(pad_obj_drop)
+BTF_ID(func, bpf_obj_drop)
+BTF_ID(func, bpf_percpu_obj_drop)
+
 static struct bpf_insn helper_call(enum bpf_func_id func_id)
 {
 	return BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, func_id);
 }
 
-/* The insn of a pad that releases one resource of @class */
+/* The call that releases a section, a lock or irq flags of @class */
 static struct bpf_insn release_call(enum bpf_pad_class class)
 {
 	if (class == BPF_PAD_SPIN_LOCK)
@@ -93,6 +98,123 @@ static struct bpf_insn release_call(enum bpf_pad_class class)
 	return BPF_CALL_KFUNC(0, pad_kfuncs[class]);
 }
 
+static bool is_obj_drop(const struct bpf_insn *insn)
+{
+	return bpf_pseudo_kfunc_call(insn) && !insn->off &&
+	       (insn->imm == pad_obj_drop[0] || insn->imm == pad_obj_drop[1]);
+}
+
+/* Does the helper that @insn calls take flags as its second argument? */
+static bool takes_flags(const struct bpf_insn *insn)
+{
+	if (!bpf_helper_call(insn))
+		return false;
+	switch (insn->imm) {
+	case BPF_FUNC_ringbuf_discard:
+	case BPF_FUNC_ringbuf_discard_dynptr:
+		return true;
+	}
+	return false;
+}
+
+/* Does bpf_sk_release() take @reg: a socket, or what a helper has cast a socket to? */
+static bool reg_is_sock(const struct bpf_reg_state *reg)
+{
+	if (type_is_sk_pointer(base_type(reg->type)))
+		return true;
+#ifdef CONFIG_NET
+	if (base_type(reg->type) == PTR_TO_BTF_ID && btf_is_vmlinux(reg->btf))
+		for (int i = 0; i < MAX_BTF_SOCK_TYPE; i++)
+			if (reg->btf_id == btf_sock_ids[i])
+				return true;
+#endif
+	return false;
+}
+
+/*
+ * Set *@release to the call that releases the pointer in @reg, by its type alone: an object of the
+ * program is freed, and for a kernel object btf_find_release_kfunc() finds the kfunc, in the BTF of
+ * a module before that of vmlinux. @off is the index in fd_array of the BTF of the module whose
+ * kfunc returned the pointer, or 0. Returns 0, or a negative errno if nothing releases the pointer.
+ */
+static int type_release(struct bpf_verifier_env *env, const struct bpf_reg_state *reg, s16 off,
+			struct bpf_insn *release)
+{
+	const struct btf *btf = reg->btf;
+	s32 id = -ENOENT;
+
+	if (base_type(reg->type) != PTR_TO_BTF_ID)
+		return -ENOENT;
+	if (!btf_is_kernel(btf)) {
+		*release = BPF_CALL_KFUNC(0, pad_obj_drop[!!(reg->type & MEM_PERCPU)]);
+		return 0;
+	}
+	if (btf_is_module(btf)) {
+		id = btf_find_release_kfunc(btf, reg->btf_id, env->prog);
+		/* the module has the kfunc, and nothing says where its BTF is in fd_array */
+		if (id >= 0 && !off)
+			return -ENOENT;
+		if (id < 0) {
+			btf = btf_base_btf(btf);
+			off = 0;
+		}
+	}
+	if (id < 0)
+		id = btf_find_release_kfunc(btf, reg->btf_id, env->prog);
+	*release = BPF_CALL_KFUNC(off, id);
+	return min(id, 0);
+}
+
+/*
+ * The call that releases the pointer @ref, which is in @reg.
+ * What the main pass compares before one state stands for another decides: the type of what is in
+ * @reg and whether @ref came with a __ref argument, see same_refs() and bpf_same_join_key(). The
+ * insn that acquired @ref is not compared, and a join keeps one of two.
+ * It is asked what the type leaves open:
+ *   - Which helper made a socket or a record of a ring buffer. That is believed only where @reg
+ *     is what such a helper returns.
+ *   - Where the BTF of a module is in fd_array, if the insn is a call of a kfunc. Its index is
+ *     taken as it is, with no test of @reg. R0 of a kfunc has the BTF of that kfunc, see
+ *     check_kfunc_call(), a helper that casts a socket gives it a type of vmlinux, and a join
+ *     keeps a register only where both states have one type in it. So a pointer to a type of
+ *     a module that a kfunc acquired came out of a kfunc of that module, and the index is that
+ *     of the BTF in which type_release() finds the kfunc. Where @reg has a type of vmlinux and
+ *     the index is one of a module, the kfunc is looked up in the sets of that module like any
+ *     call of the program, see get_release(): unless the module has registered that very
+ *     function it is no kfunc there, and that is a conflict.
+ */
+static int ref_release(struct bpf_verifier_env *env, const struct bpf_reference_state *ref,
+		       const struct bpf_reg_state *reg, struct bpf_insn *release)
+{
+	const struct bpf_insn *insn = &env->prog->insnsi[ref->insn_idx];
+
+	/* no insn acquired a __ref argument of struct_ops */
+	if (ref->ctx_arg)
+		return type_release(env, reg, 0, release);
+	if (bpf_pseudo_kfunc_call(insn))
+		return type_release(env, reg, insn->off, release);
+	if (!bpf_helper_call(insn))
+		return type_release(env, reg, 0, release);
+	switch (insn->imm) {
+	case BPF_FUNC_sk_lookup_tcp:
+	case BPF_FUNC_sk_lookup_udp:
+	case BPF_FUNC_skc_lookup_tcp:
+	case BPF_FUNC_map_lookup_elem:
+		if (!reg_is_sock(reg))
+			break;
+		*release = helper_call(BPF_FUNC_sk_release);
+		return 0;
+	case BPF_FUNC_ringbuf_reserve:
+		if (base_type(reg->type) != PTR_TO_MEM || !(reg->type & MEM_RINGBUF))
+			break;
+		*release = helper_call(BPF_FUNC_ringbuf_discard);
+		return 0;
+	case BPF_FUNC_kptr_xchg:
+		return type_release(env, reg, 0, release);
+	}
+	return -ENOENT;
+}
+
 /*
  * Check that the program may call what @insn calls, and add the kfunc descriptor that the passes
  * after the emission look up. Returns 0, BPF_CONFLICT_NO_RELEASE or -ENOMEM.
@@ -256,6 +378,8 @@ static u32 frame_sections(const struct bpf_verifier_state *st, enum bpf_pad_clas
 static int ref_class(const struct bpf_reference_state *ref)
 {
 	switch (ref->type) {
+	case REF_TYPE_PTR:
+		return BPF_PAD_REF;
 	case REF_TYPE_IRQ:
 		return BPF_PAD_IRQ;
 	case REF_TYPE_LOCK:
@@ -306,6 +430,28 @@ static void add_lock_cand(struct bpf_pad_place *cand, int *nr, const struct bpf_
 	cand[(*nr)++] = (struct bpf_pad_place){ .loc = loc, .at = at, .delta = delta };
 }
 
+/*
+ * Add (@loc, @at) to @cand if @reg, which is there, is the pointer of @ref plus a constant: a copy,
+ * a pointer to a node in the object, a socket that a helper has cast. The result of
+ * bpf_skc_to_mptcp_sock() does not count: it has the id of the socket and is another socket.
+ */
+static void add_ref_cand(struct bpf_pad_place *cand, int *nr, const struct bpf_reg_state *reg,
+			 const struct bpf_reference_state *ref, enum bpf_place_loc loc, int at)
+{
+	s64 delta = reg->var_off.value;
+
+	if (*nr == BPF_PAD_MAX_CANDS || reg->id != ref->id || reg->type == SCALAR_VALUE ||
+	    reg->type == NOT_INIT || !tnum_is_const(reg->var_off) ||
+	    delta < -S32_MAX || delta > S32_MAX)
+		return;
+#ifdef CONFIG_NET
+	if (base_type(reg->type) == PTR_TO_BTF_ID && btf_is_vmlinux(reg->btf) &&
+	    reg->btf_id == btf_sock_ids[BTF_SOCK_TYPE_MPTCP])
+		return;
+#endif
+	cand[(*nr)++] = (struct bpf_pad_place){ .loc = loc, .at = at, .delta = delta };
+}
+
 /* Add (@loc, @at) to @cand if @reg points to the stack of the frame of @obj at a constant offset */
 static void add_obj_cand(struct bpf_pad_place *cand, int *nr, const struct bpf_reg_state *reg,
 			 const struct bpf_reg_state *obj, enum bpf_place_loc loc, int at)
@@ -324,13 +470,16 @@ static void add_cand(struct bpf_pad_place *cand, int *nr, const struct bpf_reg_s
 {
 	if (obj)
 		add_obj_cand(cand, nr, reg, obj, loc, at);
+	else if (ref->type == REF_TYPE_PTR)
+		add_ref_cand(cand, nr, reg, ref, loc, at);
 	else
 		add_lock_cand(cand, nr, reg, ref, loc, at);
 }
 
 /*
- * The places of the current frame of @st that have the address of the lock @ref at @insn_idx: R6-R9
- * and stack slots. If @ref is an object in the stack of a caller @obj is its address.
+ * The places of the current frame of @st that have the handle of @ref, a lock or a pointer, at
+ * @insn_idx: R6-R9 and stack slots, then R0-R5, which are dead after a call. If @ref is an object
+ * in the stack of a caller @obj is its address.
  * A register or a stack slot that is not live there is no place: the passes that follow use
  * such a register, remove the store to such a slot, and states that differ in it are the same to
  * the main pass. Nor is a slot of the spills around bpf_fastcall calls: they are removed unless the
@@ -356,6 +505,9 @@ static int find_cands(struct bpf_verifier_env *env, const struct bpf_verifier_st
 		    off >= fastcall_off)
 			add_cand(cand, &nr, &slot->spilled_ptr, ref, obj, BPF_PLACE_SPILL, off);
 	}
+	for (i = BPF_REG_0; i < BPF_REG_6; i++)
+		if (aux->live_regs_before & BIT(i))
+			add_cand(cand, &nr, &frame->regs[i], ref, obj, BPF_PLACE_REG, i);
 	return nr;
 }
 
@@ -381,6 +533,28 @@ static int find_lock_cands(struct bpf_verifier_env *env, const struct bpf_verifi
 	return ref->id ? find_cands(env, st, insn_idx, ref, NULL, cand) : nr;
 }
 
+/*
+ * Returns a register of the current frame of @st, spilled or not, live or not, that holds the
+ * pointer of @ref: it tells the type. R0-R5 are tried last. NULL if there is none.
+ */
+static const struct bpf_reg_state *ref_reg(const struct bpf_verifier_state *st,
+					   const struct bpf_reference_state *ref)
+{
+	const struct bpf_func_state *frame = st->frame[st->curframe];
+	const struct bpf_stack_state *slot;
+	int i;
+
+	for (i = 0; i < bpf_stack_nr_slots(frame); i++) {
+		slot = bpf_stack_slot(frame, i);
+		if (bpf_is_spilled_reg(slot) && slot->spilled_ptr.id == ref->id)
+			return &slot->spilled_ptr;
+	}
+	for (i = BPF_REG_9; i >= BPF_REG_0; i--)
+		if (frame->regs[i].type != NOT_INIT && frame->regs[i].id == ref->id)
+			return &frame->regs[i];
+	return NULL;
+}
+
 /* Is slot @spi of @frame the irq flags @ref? */
 static bool slot_is_obj(const struct bpf_func_state *frame, int spi,
 			const struct bpf_reference_state *ref)
@@ -447,6 +621,93 @@ static int common_cands(const struct bpf_pad_ent *ent, const struct bpf_pad_ent
 	return n;
 }
 
+/*
+ * Can a pad free an object of type @btf_id of the program with the call @release? The free runs the
+ * destructors of the fields. A program that may run in NMI context must not do that to fields that
+ * are not NMI safe, see check_kfunc_call(). And bpf_fixup_kfunc_call() takes bpf_percpu_obj_drop()
+ * of a type with special fields for a verifier bug.
+ */
+static bool can_free_obj(struct bpf_verifier_env *env, const struct bpf_insn *release, u32 btf_id)
+{
+	const struct btf *btf = env->prog->aux->btf;
+	const struct btf_struct_meta *meta = btf_find_struct_meta(btf, btf_id);
+
+	if (meta && release->imm == pad_obj_drop[1])
+		return false;
+	if (meta && bpf_prog_may_run_in_nmi(env) && btf_record_has_nmi_unsafe_fields(meta->record))
+		return false;
+	return true;
+}
+
+/*
+ * Can a pad of @frame make the call of @ent, which releases a pointer, an iterator or a dynptr,
+ * under the locks of its callers? What the callers hold is in the first entry_refs of refs[] of
+ * @st. The pad has released the locks of its own frame by then.
+ * Under a lock a program may call only a kfunc that is KF_SPINLOCK_SAFE, see do_check_insn(), and
+ * so may its pad: the release of a kernel object runs code of its owner. The program has no such
+ * call for an object of its own. The pad frees one there all the same if that runs no destructor
+ * of a field, see bpf_obj_free_runs_dtor(): it only gives the memory back.
+ */
+static bool can_release_under_lock(struct bpf_verifier_env *env,
+				   const struct bpf_verifier_state *st,
+				   const struct bpf_func_state *frame, const struct bpf_pad_ent *ent)
+{
+	struct bpf_call_arg_meta meta;
+	u32 i;
+
+	if (ent->class < BPF_PAD_REF)
+		return true;
+	for (i = 0; i < frame->entry_refs && !(st->refs[i].type & REF_TYPE_LOCK_MASK); i++)
+		;
+	if (i == frame->entry_refs)
+		return true;
+	if (is_obj_drop(&ent->release))
+		return !bpf_obj_free_runs_dtor(env->prog->aux->btf, ent->obj_type);
+	return bpf_pseudo_kfunc_call(&ent->release) &&
+	       !bpf_fetch_kfunc_arg_meta(env, ent->release.imm, ent->release.off, &meta) &&
+	       (meta.kfunc_flags & KF_SPINLOCK_SAFE);
+}
+
+/*
+ * Set what the release of @ent needs beside the pointer, which is in @reg: 0 for the flags of a
+ * helper, and for a free of an object of the program the BTF id of its type. The type is aux data
+ * of the call, see kptr_struct_meta, so one call of a pad frees one type. Returns 0 or why the pad
+ * cannot be generated.
+ */
+static int ent_imm(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
+		   const struct bpf_reg_state *reg)
+{
+	if (is_obj_drop(&ent->release)) {
+		if (reg->btf != env->prog->aux->btf)
+			return BPF_CONFLICT_NO_PLACE;
+		if (!can_free_obj(env, &ent->release, reg->btf_id))
+			return BPF_CONFLICT_NO_RELEASE;
+		ent->obj_type = reg->btf_id;
+	}
+	if (takes_flags(&ent->release))
+		ent->cand[1][ent->nr_cands[1]++] = (struct bpf_pad_place){ .loc = BPF_PLACE_IMM };
+	return 0;
+}
+
+/* The part of ref_ent() for @ref that is a pointer */
+static int ptr_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
+		   const struct bpf_verifier_state *st, int insn_idx,
+		   const struct bpf_reference_state *ref)
+{
+	const struct bpf_reg_state *regs = st->frame[st->curframe]->regs, *reg = ref_reg(st, ref);
+
+	if (!reg)
+		return BPF_CONFLICT_NO_PLACE;
+	if (type_may_be_null(reg->type))
+		return BPF_CONFLICT_NOT_ALWAYS_HELD;
+	if (ref_release(env, ref, reg, &ent->release))
+		return BPF_CONFLICT_NO_RELEASE;
+	ent->nr_cands[0] = find_cands(env, st, insn_idx, ref, NULL, ent->cand[0]);
+	if (!ent->nr_cands[0] && reg >= &regs[BPF_REG_0] && reg <= &regs[BPF_REG_5])
+		return BPF_CONFLICT_CALLER_SAVED;
+	return ent_imm(env, ent, reg);
+}
+
 /*
  * Fill @ent with the release of @ref, one of refs[] of @st, for a pad at @insn_idx: the call that
  * releases it, and the candidate locations of its arguments in the current frame. Returns 0, the
@@ -457,18 +718,21 @@ static int ref_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
 		   const struct bpf_reference_state *ref)
 {
 	const struct bpf_stack_state *obj = NULL;
-	int class = ref_class(ref);
+	int class = ref_class(ref), err = 0;
 
 	if (verifier_bug_if(class < 0, env, "no landing pad releases reference type %d", ref->type))
 		return -EFAULT;
 	memset(ent, 0, sizeof(*ent));
 	ent->origin = ref->origin;
 	ent->class = class;
-	ent->release = release_call(class);
-	if (class == BPF_PAD_IRQ)
+	if (class != BPF_PAD_REF)
+		ent->release = release_call(class);
+	if (class == BPF_PAD_REF || class == BPF_PAD_IRQ)
 		ent->nr_cands[0] = find_obj_cands(env, st, insn_idx, ref, ent->cand[0], &obj);
 	else
 		ent->nr_cands[0] = find_lock_cands(env, st, insn_idx, ref, ent->cand[0]);
+	if (class == BPF_PAD_REF)
+		err = ptr_ent(env, ent, st, insn_idx, ref);
 	if (class == BPF_PAD_RES_LOCK_IRQ) {
 		/* the same insn saved irq flags, the next of refs[]: the second argument */
 		if (verifier_bug_if(ref + 1 == st->refs + st->acquired_refs ||
@@ -479,7 +743,11 @@ static int ref_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
 		if (!ent->nr_cands[1])
 			return BPF_CONFLICT_NO_PLACE;
 	}
-	return ent->nr_cands[0] ? 0 : BPF_CONFLICT_NO_PLACE;
+	if (!err && !can_release_under_lock(env, st, st->frame[st->curframe], ent))
+		return BPF_CONFLICT_NO_RELEASE;
+	if (!err && !ent->nr_cands[0])
+		return BPF_CONFLICT_NO_PLACE;
+	return err;
 }
 
 /* Returns the release of @plan that refs[@ref] of the current state was matched with, or NULL */
@@ -508,7 +776,8 @@ static struct bpf_pad_ent *match_ent(const struct bpf_pad_plan *plan, const stru
 	for (i = 0; i < plan->nr_ents; i++) {
 		ent = &plan->ents[i];
 		if (ent->ref >= 0 || (origin && ent->origin != new->origin) ||
-		    memcmp(&ent->release, &new->release, sizeof(ent->release)))
+		    memcmp(&ent->release, &new->release, sizeof(ent->release)) ||
+		    ent->obj_type != new->obj_type)
 			continue;
 		for (arg = 0; arg < BPF_PAD_MAX_ARGS; arg++)
 			if (new->nr_cands[arg] && !common_cands(ent, new, arg, cand))
@@ -578,7 +847,7 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 	}
 	for (i = st->frame[st->curframe]->entry_refs, pos = 0; i < st->acquired_refs; i++) {
 		ent = held_ent(plan, i);
-		if (!ent)
+		if (!ent || ent->class >= BPF_PAD_REF)
 			continue;
 		if (ent - plan->ents < pos)
 			return BPF_CONFLICT_ORDER_DIFFERS;
@@ -657,23 +926,45 @@ static int load_handle(struct bpf_verifier_env *env, struct bpf_insn *buf,
 					(u32)addr);
 		buf[n++] = BPF_RAW_INSN(0, 0, 0, 0, addr >> 32);
 		return n;
+	case BPF_PLACE_IMM:
+		buf[n++] = BPF_MOV64_IMM(reg, place->delta);
+		return n;
 	}
 	if (place->delta)
 		buf[n++] = BPF_ALU64_IMM(BPF_ADD, reg, -place->delta);
 	return n;
 }
 
-/* The insns that release the entries of @plan, the youngest first */
+/*
+ * The turns of a pad. Few functions can be called under a lock, and a release may sleep: locks and
+ * irq flags go first, then the pad leaves the sections, pointers go last.
+ */
+enum pad_turn {
+	PAD_TURN_LOCKS,
+	PAD_TURN_POINTERS,
+};
+
+static enum pad_turn release_turn(const struct bpf_pad_ent *ent)
+{
+	return ent->class < BPF_PAD_REF ? PAD_TURN_LOCKS : PAD_TURN_POINTERS;
+}
+
+/* Emit the releases of @plan whose turn it is, the last one first. Returns the number of insns. */
 static int release_ents(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
-			struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
+			enum pad_turn turn, struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
 {
 	const struct bpf_pad_ent *ent;
 	int i, arg, n = 0;
 
 	for (i = plan->nr_ents - 1; i >= 0; i--) {
 		ent = &plan->ents[i];
+		if (release_turn(ent) != turn)
+			continue;
 		for (arg = 0; arg < BPF_PAD_MAX_ARGS && ent->nr_cands[arg]; arg++)
 			n += load_handle(env, &buf[n], &aux[n], BPF_REG_1 + arg, &ent->cand[arg][0]);
+		if (is_obj_drop(&ent->release))
+			aux[n].kptr_struct_meta = btf_find_struct_meta(env->prog->aux->btf,
+								       ent->obj_type);
 		buf[n++] = ent->release;
 	}
 	return n;
@@ -689,16 +980,56 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 {
 	int class, i, n;
 
-	n = release_ents(env, plan, buf, aux);
+	n = release_ents(env, plan, PAD_TURN_LOCKS, buf, aux);
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
 		for (i = 0; i < plan->sections[class]; i++)
 			buf[n++] = release_call(class);
+	n += release_ents(env, plan, PAD_TURN_POINTERS, &buf[n], &aux[n]);
 	buf[n++] = BPF_MOV64_IMM(BPF_REG_0, bpf_cancelled_retval(env, subprog));
 	if (bpf_ret_reg_pair(env, subprog))
 		buf[n++] = BPF_MOV64_IMM(BPF_REG_2, 0);
 	return n;
 }
 
+/* Is the release of @ent the first call of the pad of @plan? See bpf_pad_insns(). */
+static bool released_first(const struct bpf_pad_plan *plan, const struct bpf_pad_ent *ent)
+{
+	const struct bpf_pad_ent *other;
+	int i;
+
+	for (i = 0; i < plan->nr_ents; i++) {
+		other = &plan->ents[i];
+		if (release_turn(other) < release_turn(ent) ||
+		    (release_turn(other) == release_turn(ent) && other > ent))
+			return false;
+	}
+	return release_turn(ent) != PAD_TURN_POINTERS ||
+	       (!plan->sections[BPF_PAD_RCU] && !plan->sections[BPF_PAD_PREEMPT]);
+}
+
+/* Is @place one of R0-R5, which the calls of a pad clobber? */
+static bool place_is_caller_saved(const struct bpf_pad_place *place)
+{
+	return place->loc == BPF_PLACE_REG && place->at < BPF_REG_6;
+}
+
+/*
+ * The first candidate of @ent is emitted. Can the pad of @plan use it?
+ * Returns the reason of a conflict.
+ */
+static int settle_ent(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
+		      struct bpf_pad_ent *ent)
+{
+	struct bpf_pad_place *cand = ent->cand[0];
+
+	if (place_is_caller_saved(&cand[0]) && !released_first(plan, ent))
+		return BPF_CONFLICT_CALLER_SAVED;
+	/* R1 is loaded first */
+	if (ent->nr_cands[1] && place_is_caller_saved(&ent->cand[1][0]))
+		return BPF_CONFLICT_CALLER_SAVED;
+	return get_release(env, &ent->release);
+}
+
 /* All states have reached the site of @plan. Returns 0 or why its pad cannot be generated. */
 static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 {
@@ -706,7 +1037,7 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 	int i, class, err = plan->conflict;
 
 	for (i = 0; !err && i < plan->nr_ents; i++)
-		err = get_release(env, &plan->ents[i].release);
+		err = settle_ent(env, plan, &plan->ents[i]);
 	for (class = 0; !err && class < BPF_PAD_NR_SECTIONS; class++) {
 		release = release_call(class);
 		if (plan->sections[class])
@@ -715,6 +1046,20 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 	return err;
 }
 
+/*
+ * Sites whose pads have the same insns share one pad. A pad that frees an object of the program is
+ * not shared: the same insns free another type at another site, see ent_imm().
+ */
+bool bpf_pad_can_be_shared(const struct bpf_pad_plan *plan)
+{
+	int i;
+
+	for (i = 0; i < plan->nr_ents; i++)
+		if (is_obj_drop(&plan->ents[i].release))
+			return false;
+	return true;
+}
+
 /* 'spin_lock@5(r6-8)': what insn 5 brought to the frame, the arguments of its release */
 static void print_ent(struct bpf_verifier_env *env, const struct bpf_pad_ent *ent)
 {
@@ -723,6 +1068,7 @@ static void print_ent(struct bpf_verifier_env *env, const struct bpf_pad_ent *en
 		[BPF_PAD_RES_LOCK]		= "res_lock",
 		[BPF_PAD_RES_LOCK_IRQ]		= "res_lock_irq",
 		[BPF_PAD_SPIN_LOCK]		= "spin_lock",
+		[BPF_PAD_REF]			= "ref",
 	};
 	const struct bpf_pad_place *place;
 	int arg;
@@ -735,11 +1081,13 @@ static void print_ent(struct bpf_verifier_env *env, const struct bpf_pad_ent *en
 			verbose(env, "*fp%d", place->at);
 		else if (place->loc == BPF_PLACE_MAP_VALUE)
 			verbose(env, "map#%d", place->at);
+		else if (place->loc == BPF_PLACE_IMM)
+			verbose(env, "%d", place->delta);
 		else if (place->at == BPF_REG_FP)
 			verbose(env, "fp");
 		else
 			verbose(env, "r%d", place->at);
-		if (place->delta)
+		if (place->delta && place->loc != BPF_PLACE_IMM)
 			verbose(env, "%+d", -place->delta);
 	}
 	verbose(env, ") ");
@@ -761,6 +1109,7 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 		[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_CALLER_SAVED]	= "a handle is in R0-R5 only",
 	};
 	int j;
 
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 6a3c539ebead..1419f5e3fe2d 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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 ||
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 18/73] bpf: Release iterators and dynptrs in landing pads
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (16 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 17/73] bpf: Release references in landing pads Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 19/73] bpf: Check pointers for NULL " Kumar Kartikeya Dwivedi
                   ` (54 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |   6 ++
 kernel/bpf/pads.c            | 179 +++++++++++++++++++++++++++--------
 kernel/bpf/verifier.c        |  40 +++++---
 3 files changed, 173 insertions(+), 52 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index f658a8aeeae0..dc4694dc55f9 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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)
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index b13ba84269ff..1a0229f754bc 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -85,6 +85,9 @@ BTF_ID_LIST(pad_obj_drop)
 BTF_ID(func, bpf_obj_drop)
 BTF_ID(func, bpf_percpu_obj_drop)
 
+/* Releases the dynptr of bpf_dynptr_from_file() */
+BTF_ID_LIST_SINGLE(pad_file_discard, func, bpf_dynptr_file_discard)
+
 static struct bpf_insn helper_call(enum bpf_func_id func_id)
 {
 	return BPF_RAW_INSN(BPF_JMP | BPF_CALL, 0, 0, 0, func_id);
@@ -117,6 +120,30 @@ static bool takes_flags(const struct bpf_insn *insn)
 	return false;
 }
 
+/*
+ * Returns the BTF id of bpf_iter_<type>_destroy() for the iterator whose first slot is @iter, or a
+ * negative errno. For a type of a module, *@off gets the index of its BTF in fd_array. It is taken
+ * from @insn, which has to be a call of a kfunc of the same BTF.
+ */
+static s32 iter_destroy_kfunc(struct bpf_verifier_env *env, const struct bpf_reg_state *iter,
+			      const struct bpf_insn *insn, s16 *off)
+{
+	const struct btf *btf = iter->iter.btf;
+	const struct btf_type *t = btf_type_by_id(btf, iter->iter.btf_id);
+	struct bpf_call_arg_meta meta;
+	char name[128];
+
+	*off = 0;
+	if (btf_is_module(btf)) {
+		if (!bpf_pseudo_kfunc_call(insn) || !insn->imm ||
+		    bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) || meta.btf != btf)
+			return -ENOENT;
+		*off = insn->off;
+	}
+	snprintf(name, sizeof(name), "%s_destroy", btf_name_by_offset(btf, t->name_off));
+	return btf_find_by_name_kind(btf, name, BTF_KIND_FUNC);
+}
+
 /* Does bpf_sk_release() take @reg: a socket, or what a helper has cast a socket to? */
 static bool reg_is_sock(const struct bpf_reg_state *reg)
 {
@@ -166,28 +193,37 @@ static int type_release(struct bpf_verifier_env *env, const struct bpf_reg_state
 }
 
 /*
- * The call that releases the pointer @ref, which is in @reg.
- * What the main pass compares before one state stands for another decides: the type of what is in
- * @reg and whether @ref came with a __ref argument, see same_refs() and bpf_same_join_key(). The
- * insn that acquired @ref is not compared, and a join keeps one of two.
- * It is asked what the type leaves open:
- *   - Which helper made a socket or a record of a ring buffer. That is believed only where @reg
- *     is what such a helper returns.
- *   - Where the BTF of a module is in fd_array, if the insn is a call of a kfunc. Its index is
- *     taken as it is, with no test of @reg. R0 of a kfunc has the BTF of that kfunc, see
- *     check_kfunc_call(), a helper that casts a socket gives it a type of vmlinux, and a join
- *     keeps a register only where both states have one type in it. So a pointer to a type of
- *     a module that a kfunc acquired came out of a kfunc of that module, and the index is that
- *     of the BTF in which type_release() finds the kfunc. Where @reg has a type of vmlinux and
- *     the index is one of a module, the kfunc is looked up in the sets of that module like any
- *     call of the program, see get_release(): unless the module has registered that very
- *     function it is no kfunc there, and that is a conflict.
+ * Set *@release to the call that releases the reference @ref, whose pointer is in @reg. For an
+ * object in the stack @reg is its first slot, and @iter says that it is an iterator. Returns 0, or
+ * a negative errno if nothing releases it.
+ *
+ * The choice depends only on what the verifier compares before it merges two states: the type in
+ * @reg, the kind of the object, and whether @ref is a __ref argument of struct_ops. The insn that
+ * acquired @ref is not compared. It only says which helper made a socket or a record of a ring
+ * buffer, which is believed only if @reg has the type that the helper returns, and where the BTF of
+ * a module is in fd_array. get_release() looks a kfunc up there like any call of the program.
  */
 static int ref_release(struct bpf_verifier_env *env, const struct bpf_reference_state *ref,
-		       const struct bpf_reg_state *reg, struct bpf_insn *release)
+		       const struct bpf_reg_state *reg, bool iter, struct bpf_insn *release)
 {
 	const struct bpf_insn *insn = &env->prog->insnsi[ref->insn_idx];
+	s16 off;
+	s32 id;
 
+	if (iter) {
+		id = iter_destroy_kfunc(env, reg, insn, &off);
+		*release = BPF_CALL_KFUNC(off, id);
+		return min(id, 0);
+	}
+	if (reg->type == CONST_PTR_TO_DYNPTR) {
+		if (reg->dynptr.type == BPF_DYNPTR_TYPE_FILE)
+			*release = BPF_CALL_KFUNC(0, pad_file_discard[0]);
+		else if (reg->dynptr.type == BPF_DYNPTR_TYPE_RINGBUF)
+			*release = helper_call(BPF_FUNC_ringbuf_discard_dynptr);
+		else
+			return -ENOENT;
+		return 0;
+	}
 	/* no insn acquired a __ref argument of struct_ops */
 	if (ref->ctx_arg)
 		return type_release(env, reg, 0, release);
@@ -555,7 +591,23 @@ static const struct bpf_reg_state *ref_reg(const struct bpf_verifier_state *st,
 	return NULL;
 }
 
-/* Is slot @spi of @frame the irq flags @ref? */
+/*
+ * Slot @spi of @frame is the first slot of an iterator. Does its destructor accept it? Not if the
+ * program wrote to another of its slots, or left what protects an iterator that RCU protects.
+ */
+static bool iter_is_valid(const struct bpf_func_state *frame, int spi)
+{
+	const struct bpf_reg_state *reg = &bpf_stack_slot(frame, spi)->spilled_ptr;
+	const struct btf_type *t = btf_type_by_id(reg->iter.btf, reg->iter.btf_id);
+
+	return !bpf_iter_slots_valid_init(frame, spi, reg->iter.btf, reg->iter.btf_id,
+					  t->size / BPF_REG_SIZE);
+}
+
+/*
+ * Is slot @spi of @frame the first slot of the object @ref: irq flags, an iterator or a dynptr? A
+ * store to a slot of irq flags or of a dynptr leaves nothing of them.
+ */
 static bool slot_is_obj(const struct bpf_func_state *frame, int spi,
 			const struct bpf_reference_state *ref)
 {
@@ -564,15 +616,22 @@ static bool slot_is_obj(const struct bpf_func_state *frame, int spi,
 	switch (bpf_stack_slot(frame, spi)->slot_type[BPF_REG_SIZE - 1]) {
 	case STACK_IRQ_FLAG:
 		return reg->id == ref->id;
+	case STACK_ITER:
+		return reg->id == ref->id && iter_is_valid(frame, spi);
+	case STACK_DYNPTR:
+		/* any other dynptr is made from a pointer, and @ref is that pointer */
+		return reg->dynptr.first_slot && reg->parent_id == ref->id &&
+		       (reg->dynptr.type == BPF_DYNPTR_TYPE_RINGBUF ||
+			reg->dynptr.type == BPF_DYNPTR_TYPE_FILE);
 	}
 	return false;
 }
 
 /*
- * If @ref is an object in the stack: the places that have its address at @insn_idx. R10 if the
- * current frame of @st has the object. If a caller has it, what find_cands() finds: the function
- * got a pointer and made the object there, like the constructor of a guard.
- * *@obj: the first slot of the object.
+ * If @ref is an object in the stack, find the locations of its address at @insn_idx and set *@obj
+ * to its first slot. The location is R10 if the current frame of @st has the object. If a caller
+ * has it, the function got a pointer to it, like the constructor of a guard, which find_cands()
+ * finds. A clone of a dynptr is one more location. Returns the number of candidates in @cand.
  */
 static int find_obj_cands(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 			  int insn_idx, const struct bpf_reference_state *ref,
@@ -641,25 +700,25 @@ static bool can_free_obj(struct bpf_verifier_env *env, const struct bpf_insn *re
 
 /*
  * Can a pad of @frame make the call of @ent, which releases a pointer, an iterator or a dynptr,
- * under the locks of its callers? What the callers hold is in the first entry_refs of refs[] of
- * @st. The pad has released the locks of its own frame by then.
- * Under a lock a program may call only a kfunc that is KF_SPINLOCK_SAFE, see do_check_insn(), and
- * so may its pad: the release of a kernel object runs code of its owner. The program has no such
- * call for an object of its own. The pad frees one there all the same if that runs no destructor
- * of a field, see bpf_obj_free_runs_dtor(): it only gives the memory back.
+ * under the locks that are held then? The pad has released the locks of its own frame, so those are
+ * the locks of the callers, in the first entry_refs of refs[] of @st. An iterator that RCU protects
+ * is destroyed first, see enum pad_turn, so every lock in refs[] counts for it. Under a lock a pad
+ * calls what the program may call there, a kfunc that is KF_SPINLOCK_SAFE. It also frees an object
+ * of the program if that runs no destructor of a field and only gives the memory back, see
+ * bpf_obj_free_runs_dtor().
  */
 static bool can_release_under_lock(struct bpf_verifier_env *env,
 				   const struct bpf_verifier_state *st,
 				   const struct bpf_func_state *frame, const struct bpf_pad_ent *ent)
 {
+	u32 i, nr = ent->rcu ? st->acquired_refs : frame->entry_refs;
 	struct bpf_call_arg_meta meta;
-	u32 i;
 
 	if (ent->class < BPF_PAD_REF)
 		return true;
-	for (i = 0; i < frame->entry_refs && !(st->refs[i].type & REF_TYPE_LOCK_MASK); i++)
+	for (i = 0; i < nr && !(st->refs[i].type & REF_TYPE_LOCK_MASK); i++)
 		;
-	if (i == frame->entry_refs)
+	if (i == nr)
 		return true;
 	if (is_obj_drop(&ent->release))
 		return !bpf_obj_free_runs_dtor(env->prog->aux->btf, ent->obj_type);
@@ -700,7 +759,7 @@ static int ptr_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
 		return BPF_CONFLICT_NO_PLACE;
 	if (type_may_be_null(reg->type))
 		return BPF_CONFLICT_NOT_ALWAYS_HELD;
-	if (ref_release(env, ref, reg, &ent->release))
+	if (ref_release(env, ref, reg, false, &ent->release))
 		return BPF_CONFLICT_NO_RELEASE;
 	ent->nr_cands[0] = find_cands(env, st, insn_idx, ref, NULL, ent->cand[0]);
 	if (!ent->nr_cands[0] && reg >= &regs[BPF_REG_0] && reg <= &regs[BPF_REG_5])
@@ -708,6 +767,21 @@ static int ptr_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
 	return ent_imm(env, ent, reg);
 }
 
+/* The part of ref_ent() for @ref that is an iterator or a dynptr. @slot is its first slot. */
+static int obj_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
+		   const struct bpf_reference_state *ref, const struct bpf_stack_state *slot)
+{
+	if (ref_release(env, ref, &slot->spilled_ptr, slot->slot_type[0] == STACK_ITER, &ent->release))
+		return BPF_CONFLICT_NO_RELEASE;
+	if (slot->slot_type[0] == STACK_ITER) {
+		ent->class = BPF_PAD_ITER;
+		ent->rcu = slot->spilled_ptr.type & MEM_RCU;
+	} else {
+		ent->class = BPF_PAD_DYNPTR;
+	}
+	return ent_imm(env, ent, &slot->spilled_ptr);
+}
+
 /*
  * Fill @ent with the release of @ref, one of refs[] of @st, for a pad at @insn_idx: the call that
  * releases it, and the candidate locations of its arguments in the current frame. Returns 0, the
@@ -731,7 +805,9 @@ static int ref_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
 		ent->nr_cands[0] = find_obj_cands(env, st, insn_idx, ref, ent->cand[0], &obj);
 	else
 		ent->nr_cands[0] = find_lock_cands(env, st, insn_idx, ref, ent->cand[0]);
-	if (class == BPF_PAD_REF)
+	if (class == BPF_PAD_REF && obj)
+		err = obj_ent(env, ent, ref, obj);
+	else if (class == BPF_PAD_REF)
 		err = ptr_ent(env, ent, st, insn_idx, ref);
 	if (class == BPF_PAD_RES_LOCK_IRQ) {
 		/* the same insn saved irq flags, the next of refs[]: the second argument */
@@ -777,7 +853,7 @@ static struct bpf_pad_ent *match_ent(const struct bpf_pad_plan *plan, const stru
 		ent = &plan->ents[i];
 		if (ent->ref >= 0 || (origin && ent->origin != new->origin) ||
 		    memcmp(&ent->release, &new->release, sizeof(ent->release)) ||
-		    ent->obj_type != new->obj_type)
+		    ent->obj_type != new->obj_type || ent->rcu != new->rcu)
 			continue;
 		for (arg = 0; arg < BPF_PAD_MAX_ARGS; arg++)
 			if (new->nr_cands[arg] && !common_cands(ent, new, arg, cand))
@@ -799,13 +875,23 @@ static struct bpf_pad_ent *add_ent(struct bpf_pad_plan *plan, const struct bpf_p
 	return &plan->ents[plan->nr_ents++];
 }
 
+/* Was refs[@child] of @st made from the pointer refs[@parent]? See invalidate_reference(). */
+static bool ref_is_child(const struct bpf_verifier_state *st, int child, int parent)
+{
+	return st->refs[child].type == REF_TYPE_PTR && st->refs[parent].type == REF_TYPE_PTR &&
+	       st->refs[child].parent_id == st->refs[parent].id;
+}
+
 /*
  * The resources with a handle that the current frame of @st acquired: refs[] from
  * entry_refs on, oldest first. Which entry is one of them? What a pad does with an entry is a call
  * with what it finds at a place, so that is what an entry is, like a variable with a destructor. It
- * does not matter which insn acquired what is there. Where that leaves a choice the origin decides.
+ * does not matter which insn acquired what is there: an iterator that is destroyed and made again
+ * is one entry, two nodes that one insn in a loop took off a list are two. Where that leaves a
+ * choice the origin decides.
  * Every visit has to hold every entry.
- * Locks and irq flags have to be in refs[] in the order of the plan.
+ * Locks and irq flags have to be in refs[] in the order of the plan, and so do a pointer and what
+ * was made from it.
  * Returns the reason of a conflict.
  */
 static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
@@ -813,7 +899,7 @@ 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;
-	int i, arg, pass, pos, 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;
@@ -853,6 +939,11 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 			return BPF_CONFLICT_ORDER_DIFFERS;
 		pos = ent - plan->ents;
 	}
+	for (i = 0; i < plan->nr_ents; i++)
+		for (j = 0; j < i; j++)
+			if (plan->ents[i].ref >= 0 && plan->ents[j].ref >= 0 &&
+			    ref_is_child(st, plan->ents[j].ref, plan->ents[i].ref))
+				return BPF_CONFLICT_ORDER_DIFFERS;
 	for (i = 0; i < plan->nr_ents; i++)
 		if (plan->ents[i].ref < 0)
 			return BPF_CONFLICT_NOT_ALWAYS_HELD;
@@ -936,16 +1027,21 @@ static int load_handle(struct bpf_verifier_env *env, struct bpf_insn *buf,
 }
 
 /*
- * The turns of a pad. Few functions can be called under a lock, and a release may sleep: locks and
- * irq flags go first, then the pad leaves the sections, pointers go last.
+ * The order of the releases in a pad. Few functions may be called under a lock, and a release may
+ * sleep. So locks and irq flags go first, then the pad leaves the sections, and pointers and
+ * objects go last. An iterator that RCU protects goes before all of them, under the locks of the
+ * frame: a section or irq flags may be all that protects it, see in_rcu_cs().
  */
 enum pad_turn {
+	PAD_TURN_RCU_ITERS,
 	PAD_TURN_LOCKS,
 	PAD_TURN_POINTERS,
 };
 
 static enum pad_turn release_turn(const struct bpf_pad_ent *ent)
 {
+	if (ent->rcu)
+		return PAD_TURN_RCU_ITERS;
 	return ent->class < BPF_PAD_REF ? PAD_TURN_LOCKS : PAD_TURN_POINTERS;
 }
 
@@ -980,7 +1076,8 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 {
 	int class, i, n;
 
-	n = release_ents(env, plan, PAD_TURN_LOCKS, buf, aux);
+	n = release_ents(env, plan, PAD_TURN_RCU_ITERS, buf, aux);
+	n += release_ents(env, plan, PAD_TURN_LOCKS, &buf[n], &aux[n]);
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
 		for (i = 0; i < plan->sections[class]; i++)
 			buf[n++] = release_call(class);
@@ -1069,6 +1166,8 @@ static void print_ent(struct bpf_verifier_env *env, const struct bpf_pad_ent *en
 		[BPF_PAD_RES_LOCK_IRQ]		= "res_lock_irq",
 		[BPF_PAD_SPIN_LOCK]		= "spin_lock",
 		[BPF_PAD_REF]			= "ref",
+		[BPF_PAD_ITER]			= "iter",
+		[BPF_PAD_DYNPTR]		= "dynptr",
 	};
 	const struct bpf_pad_place *place;
 	int arg;
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 1419f5e3fe2d..7549ddd3968c 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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));
 		}
 	}));
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 19/73] bpf: Check pointers for NULL in landing pads
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (17 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 18/73] bpf: Release iterators and dynptrs " Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 20/73] bpf: Let the kernel cancel a frame that holds references Kumar Kartikeya Dwivedi
                   ` (53 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  21 ++-
 kernel/bpf/liveness.c        |   1 +
 kernel/bpf/pads.c            | 289 ++++++++++++++++++++++++++++-------
 3 files changed, 253 insertions(+), 58 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index dc4694dc55f9..5c34ace286df 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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.
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index 4d04d17603ae..28044f12e9c7 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -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
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 1a0229f754bc..6027e9cca9cc 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -48,7 +48,9 @@
  * see ref_release().
  *
  * All states at a site have to share a location for each release, and the pad has to know whether
- * the resource is held. Only the program counter tells the pad, so all states have to hold it.
+ * the resource is held. If all states hold it, the pad releases it without a test. If a location is
+ * 0 in all states that do not hold it, the pad tests the location first, as a program tests a
+ * pointer for NULL before it releases it. Otherwise the verifier cannot generate the pad.
  *
  * The frames of a program are cancelled one at a time. The pad of a function that the program calls
  * ends in unwind_exit. That returns to the unwind_goto after the call, which leads to the pad of
@@ -325,6 +327,8 @@ struct bpf_pad_plan *bpf_pad_plan_get(struct bpf_verifier_env *env, int insn_idx
 	if (!plan)
 		return NULL;
 	plan->kind = kind;
+	plan->nulls.regs = U16_MAX;
+	bitmap_fill(plan->nulls.slots, MAX_BPF_STACK_SLOTS);
 	plan->next = aux->pad_plans;
 	aux->pad_plans = plan;
 	return plan;
@@ -485,7 +489,8 @@ static void add_ref_cand(struct bpf_pad_place *cand, int *nr, const struct bpf_r
 	    reg->btf_id == btf_sock_ids[BTF_SOCK_TYPE_MPTCP])
 		return;
 #endif
-	cand[(*nr)++] = (struct bpf_pad_place){ .loc = loc, .at = at, .delta = delta };
+	cand[(*nr)++] = (struct bpf_pad_place){ .loc = loc, .at = at, .delta = delta,
+						.maybe_null = type_may_be_null(reg->type) };
 }
 
 /* Add (@loc, @at) to @cand if @reg points to the stack of the frame of @obj at a constant offset */
@@ -513,13 +518,15 @@ static void add_cand(struct bpf_pad_place *cand, int *nr, const struct bpf_reg_s
 }
 
 /*
- * The places of the current frame of @st that have the handle of @ref, a lock or a pointer, at
- * @insn_idx: R6-R9 and stack slots, then R0-R5, which are dead after a call. If @ref is an object
- * in the stack of a caller @obj is its address.
- * A register or a stack slot that is not live there is no place: the passes that follow use
- * such a register, remove the store to such a slot, and states that differ in it are the same to
- * the main pass. Nor is a slot of the spills around bpf_fastcall calls: they are removed unless the
- * main pass sees another access to the slot, and it does not see the pad.
+ * Find the locations in the current frame of @st that hold the pointer of @ref at @insn_idx: R6-R9
+ * and stack slots, then R0-R5, which a call clobbers. @obj is the address of @ref if that is an
+ * object in the stack of a caller. Returns the number of candidates in @cand.
+ *
+ * A register or a stack slot that is not live at @insn_idx is no location: later passes reuse such
+ * a register and remove the store to such a slot. Nor is a register of which only the lower half is
+ * live: the pad reads 64 bits, and 'w6 = 0' is zero extended only if the program reads the upper
+ * half, see zext_dst. Nor is the slot of a bpf_fastcall spill, which is removed unless the main
+ * pass sees another access to it.
  */
 static int find_cands(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 		      int insn_idx, const struct bpf_reference_state *ref,
@@ -532,7 +539,7 @@ static int find_cands(struct bpf_verifier_env *env, const struct bpf_verifier_st
 	int i, off, nr = 0;
 
 	for (i = BPF_REG_6; i < BPF_REG_FP; i++)
-		if (aux->live_regs_before & BIT(i))
+		if (aux->live_hi32_before & BIT(i))
 			add_cand(cand, &nr, &frame->regs[i], ref, obj, BPF_PLACE_REG, i);
 	for (i = 0; i < bpf_stack_nr_slots(frame); i++) {
 		slot = bpf_stack_slot(frame, i);
@@ -542,7 +549,7 @@ static int find_cands(struct bpf_verifier_env *env, const struct bpf_verifier_st
 			add_cand(cand, &nr, &slot->spilled_ptr, ref, obj, BPF_PLACE_SPILL, off);
 	}
 	for (i = BPF_REG_0; i < BPF_REG_6; i++)
-		if (aux->live_regs_before & BIT(i))
+		if (aux->live_hi32_before & BIT(i))
 			add_cand(cand, &nr, &frame->regs[i], ref, obj, BPF_PLACE_REG, i);
 	return nr;
 }
@@ -661,6 +668,39 @@ static int find_obj_cands(struct bpf_verifier_env *env, const struct bpf_verifie
 	return nr;
 }
 
+static bool reg_is_null(const struct bpf_reg_state *reg)
+{
+	return reg->type == SCALAR_VALUE && tnum_equals_const(reg->var_off, 0);
+}
+
+static void find_nulls(const struct bpf_func_state *frame, struct bpf_pad_nulls *nulls)
+{
+	const struct bpf_stack_state *slot;
+	int i, j;
+
+	memset(nulls, 0, sizeof(*nulls));
+	for (i = BPF_REG_0; i < BPF_REG_FP; i++)
+		if (reg_is_null(&frame->regs[i]))
+			nulls->regs |= BIT(i);
+	for (i = 0; i < bpf_stack_nr_slots(frame); i++) {
+		slot = bpf_stack_slot(frame, i);
+		for (j = 0; j < BPF_REG_SIZE && slot->slot_type[j] == STACK_ZERO; j++)
+			;
+		if (j == BPF_REG_SIZE ||
+		    (bpf_spill_size(slot) == BPF_REG_SIZE && reg_is_null(&slot->spilled_ptr)))
+			__set_bit(i, nulls->slots);
+	}
+}
+
+/* An address in the stack and the address of a map value are never 0 */
+static bool place_is_null(const struct bpf_pad_nulls *nulls, const struct bpf_pad_place *place)
+{
+	if (place->loc == BPF_PLACE_REG)
+		return nulls->regs & BIT(place->at);
+	return place->loc == BPF_PLACE_SPILL &&
+	       test_bit(-place->at / BPF_REG_SIZE - 1, nulls->slots);
+}
+
 /* Copy the candidates for argument @arg that @ent and @new share to @cand. Returns their number. */
 static int common_cands(const struct bpf_pad_ent *ent, const struct bpf_pad_ent *new, int arg,
 			struct bpf_pad_place *cand)
@@ -673,7 +713,8 @@ static int common_cands(const struct bpf_pad_ent *ent, const struct bpf_pad_ent
 			if (old[i].loc != place[j].loc || old[i].at != place[j].at ||
 			    old[i].delta != place[j].delta)
 				continue;
-			cand[n++] = old[i];
+			cand[n] = old[i];
+			cand[n++].maybe_null |= place[j].maybe_null;
 			break;
 		}
 	}
@@ -757,8 +798,6 @@ static int ptr_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
 
 	if (!reg)
 		return BPF_CONFLICT_NO_PLACE;
-	if (type_may_be_null(reg->type))
-		return BPF_CONFLICT_NOT_ALWAYS_HELD;
 	if (ref_release(env, ref, reg, false, &ent->release))
 		return BPF_CONFLICT_NO_RELEASE;
 	ent->nr_cands[0] = find_cands(env, st, insn_idx, ref, NULL, ent->cand[0]);
@@ -864,15 +903,115 @@ static struct bpf_pad_ent *match_ent(const struct bpf_pad_plan *plan, const stru
 	return NULL;
 }
 
-/* @new is one more entry of @plan. Returns it, or NULL if there is no memory. */
-static struct bpf_pad_ent *add_ent(struct bpf_pad_plan *plan, const struct bpf_pad_ent *new)
+/*
+ * Insert @new into the releases of @plan at @pos. No state that reached the site before held it.
+ * Returns the new release, or NULL if there is no memory.
+ */
+static struct bpf_pad_ent *add_ent(struct bpf_pad_plan *plan, const struct bpf_pad_ent *new,
+				   int pos)
 {
+	struct bpf_pad_ent *ent;
+	int i;
+
 	if (!plan->ents)
 		plan->ents = kzalloc_objs(*plan->ents, BPF_PAD_MAX_ENTS, BPF_VERIFIER_GFP);
 	if (!plan->ents)
 		return NULL;
-	plan->ents[plan->nr_ents] = *new;
-	return &plan->ents[plan->nr_ents++];
+	ent = &plan->ents[pos];
+	memmove(ent + 1, ent, (plan->nr_ents++ - pos) * sizeof(*ent));
+	*ent = *new;
+	ent->always = !plan->visited;
+	/* the address of an object in the stack does not tell whether the object is set up */
+	if (ent->class == BPF_PAD_IRQ || ent->class >= BPF_PAD_ITER)
+		return ent;
+	for (i = 0; i < ent->nr_cands[0]; i++)
+		ent->cand[0][i].null = place_is_null(&plan->nulls, &ent->cand[0][i]);
+	return ent;
+}
+
+/*
+ * A state holds the releases @a and @b of @plan and needs @b released before @a. Record that @a
+ * stands before @b. Returns false if another state needs the opposite, directly or through other
+ * releases: no order suits both.
+ */
+static bool put_before(struct bpf_pad_plan *plan, int a, int b)
+{
+	int i;
+
+	if (plan->before[b] & BIT(a))
+		return false;
+	for (i = 0; i < plan->nr_ents; i++)
+		if (i == a || (plan->before[i] & BIT(a)))
+			plan->before[i] |= BIT(b) | plan->before[b];
+	return true;
+}
+
+/* Is @place one of R0-R5, which the calls of a pad clobber? */
+static bool place_is_caller_saved(const struct bpf_pad_place *place)
+{
+	return place->loc == BPF_PLACE_REG && place->at < BPF_REG_6;
+}
+
+/* Is the candidate that settle_ent() is going to take for @ent one of R0-R5? */
+static bool ent_is_clobbered(const struct bpf_pad_ent *ent)
+{
+	int i;
+
+	for (i = 0; i < ent->nr_cands[0] && !ent->always && !ent->cand[0][i].null; i++)
+		;
+	return i < ent->nr_cands[0] && place_is_caller_saved(&ent->cand[0][i]);
+}
+
+/*
+ * Does @a stand before @b where no state orders the two? The pad releases the last one first, and
+ * that has to be the one whose pointer is in R0-R5, see released_first(). Otherwise the one that
+ * came to the frame at the lower insn stands first.
+ */
+static bool ent_stands_before(const struct bpf_pad_ent *a, const struct bpf_pad_ent *b)
+{
+	bool a_clobbered = ent_is_clobbered(a), b_clobbered = ent_is_clobbered(b);
+
+	return a_clobbered != b_clobbered ? b_clobbered : a->origin < b->origin;
+}
+
+/*
+ * All states have reached the site of @plan: sort its releases into an order that suits each state,
+ * see visit_refs(). One exists, because put_before() refused what would close a cycle. Where the
+ * states leave a choice, ent_stands_before() decides, whichever state came first.
+ */
+static int order_ents(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
+{
+	int i, j, k, n = plan->nr_ents, next;
+	u8 row, bit;
+
+	if (plan->ordered)
+		return 0;
+	plan->ordered = true;
+	for (k = 0; k < n; k++) {
+		next = -1;
+		for (i = k; i < n; i++) {
+			for (j = k; j < n; j++)
+				if (plan->before[j] & BIT(i))
+					break;
+			if (j == n && (next < 0 ||
+				       ent_stands_before(&plan->ents[i], &plan->ents[next])))
+				next = i;
+		}
+		/* put_before() keeps cycles out */
+		if (verifier_bug_if(next < 0, env, "the entries of a landing pad have no order"))
+			return -EFAULT;
+		if (next == k)
+			continue;
+		/* swap the two releases, and their rows and columns in 'before' */
+		swap(plan->ents[k], plan->ents[next]);
+		swap(plan->before[k], plan->before[next]);
+		for (i = 0; i < n; i++) {
+			row = plan->before[i];
+			bit = (!!(row & BIT(k)) << next) | (!!(row & BIT(next)) << k);
+			plan->before[i] = (row & ~(BIT(k) | BIT(next))) | bit;
+		}
+	}
+	return 0;
 }
 
 /* Was refs[@child] of @st made from the pointer refs[@parent]? See invalidate_reference(). */
@@ -883,23 +1022,26 @@ static bool ref_is_child(const struct bpf_verifier_state *st, int child, int par
 }
 
 /*
- * The resources with a handle that the current frame of @st acquired: refs[] from
- * entry_refs on, oldest first. Which entry is one of them? What a pad does with an entry is a call
- * with what it finds at a place, so that is what an entry is, like a variable with a destructor. It
- * does not matter which insn acquired what is there: an iterator that is destroyed and made again
- * is one entry, two nodes that one insn in a loop took off a list are two. Where that leaves a
- * choice the origin decides.
- * Every visit has to hold every entry.
- * Locks and irq flags have to be in refs[] in the order of the plan, and so do a pointer and what
- * was made from it.
- * Returns the reason of a conflict.
+ * Add to @plan what the current frame of @st holds at @insn_idx beside its sections: refs[] from
+ * entry_refs on. Returns 0, the enum bpf_pad_conflict that says why the pad cannot be generated, or
+ * a negative errno.
+ *
+ * Each reference is matched with a release of @plan. Two references are one release if the same
+ * call releases them and they share a location, whichever insn acquired them: an iterator that is
+ * destroyed and created again is one release, two nodes that one insn in a loop took off a list are
+ * two. A release need not be held in all states, see settle_ent().
+ *
+ * The pad releases locks and irq flags in the reverse of the order in which a state took them, and
+ * what was made from a pointer before the pointer. Each state records the order of the releases
+ * that it holds, see put_before(), and order_ents() sorts them when all states have been here.
  */
 static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 		      const struct bpf_verifier_state *st, int insn_idx)
 {
 	const struct bpf_reference_state *ref;
-	struct bpf_pad_ent new, *ent;
-	int i, j, arg, pass, pos, err;
+	struct bpf_pad_ent new, *ent, *prev;
+	struct bpf_pad_nulls nulls;
+	int i, j, arg, pass, 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;
@@ -919,34 +1061,45 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 			ent = match_ent(plan, &new, !pass);
 			if (!ent && !pass)
 				continue;
-			if (!ent && plan->visited)
-				return BPF_CONFLICT_NOT_ALWAYS_HELD;
 			if (!ent && plan->nr_ents == BPF_PAD_MAX_ENTS)
 				return BPF_CONFLICT_TOO_MUCH;
-			ent = ent ?: add_ent(plan, &new);
+			if (!ent)
+				ent = add_ent(plan, &new, plan->nr_ents);
 			if (!ent)
 				return -ENOMEM;
 			ent->ref = i;
+			/* the lowest insn that brought it to the frame, in whichever state */
+			ent->origin = min(ent->origin, new.origin);
 			for (arg = 0; arg < BPF_PAD_MAX_ARGS; arg++)
 				ent->nr_cands[arg] = common_cands(ent, &new, arg, ent->cand[arg]);
 		}
 	}
-	for (i = st->frame[st->curframe]->entry_refs, pos = 0; i < st->acquired_refs; i++) {
+	prev = NULL;
+	for (i = st->frame[st->curframe]->entry_refs; i < st->acquired_refs; i++) {
 		ent = held_ent(plan, i);
 		if (!ent || ent->class >= BPF_PAD_REF)
 			continue;
-		if (ent - plan->ents < pos)
+		if (prev && !put_before(plan, prev - plan->ents, ent - plan->ents))
 			return BPF_CONFLICT_ORDER_DIFFERS;
-		pos = ent - plan->ents;
+		prev = ent;
 	}
 	for (i = 0; i < plan->nr_ents; i++)
-		for (j = 0; j < i; j++)
+		for (j = 0; j < plan->nr_ents; j++)
 			if (plan->ents[i].ref >= 0 && plan->ents[j].ref >= 0 &&
-			    ref_is_child(st, plan->ents[j].ref, plan->ents[i].ref))
+			    ref_is_child(st, plan->ents[j].ref, plan->ents[i].ref) &&
+			    !put_before(plan, i, j))
 				return BPF_CONFLICT_ORDER_DIFFERS;
-	for (i = 0; i < plan->nr_ents; i++)
-		if (plan->ents[i].ref < 0)
-			return BPF_CONFLICT_NOT_ALWAYS_HELD;
+	find_nulls(st->frame[st->curframe], &nulls);
+	for (i = 0; i < plan->nr_ents; i++) {
+		ent = &plan->ents[i];
+		if (ent->ref >= 0)
+			continue;
+		ent->always = false;
+		for (j = 0; j < ent->nr_cands[0]; j++)
+			ent->cand[0][j].null &= place_is_null(&nulls, &ent->cand[0][j]);
+	}
+	plan->nulls.regs &= nulls.regs;
+	bitmap_and(plan->nulls.slots, plan->nulls.slots, nulls.slots, MAX_BPF_STACK_SLOTS);
 	return 0;
 }
 
@@ -989,11 +1142,20 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 	return plan;
 }
 
+/* Does the pad test the location of @ent for 0 before the release? */
+static bool ent_is_tested(const struct bpf_pad_ent *ent)
+{
+	return !ent->always || ent->cand[0][0].maybe_null;
+}
+
 /*
- * R@reg = the handle that is at @place. Returns the number of insns.
+ * Emit the insns that load into R@reg the pointer that is at @place. With @test the second insn is
+ * a jump that is taken if the location has 0, and the caller sets its offset. The test comes before
+ * the constant offset of the location is subtracted. Returns the number of insns.
  */
 static int load_handle(struct bpf_verifier_env *env, struct bpf_insn *buf,
-		       struct bpf_insn_aux_data *aux, int reg, const struct bpf_pad_place *place)
+		       struct bpf_insn_aux_data *aux, int reg, const struct bpf_pad_place *place,
+		       bool test)
 {
 	const struct bpf_map *map;
 	u64 addr = 0;
@@ -1021,6 +1183,8 @@ static int load_handle(struct bpf_verifier_env *env, struct bpf_insn *buf,
 		buf[n++] = BPF_MOV64_IMM(reg, place->delta);
 		return n;
 	}
+	if (test)
+		buf[n++] = BPF_JMP_IMM(BPF_JEQ, reg, 0, 0);
 	if (place->delta)
 		buf[n++] = BPF_ALU64_IMM(BPF_ADD, reg, -place->delta);
 	return n;
@@ -1050,18 +1214,22 @@ static int release_ents(struct bpf_verifier_env *env, const struct bpf_pad_plan
 			enum pad_turn turn, struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
 {
 	const struct bpf_pad_ent *ent;
-	int i, arg, n = 0;
+	int i, arg, first, n = 0;
 
 	for (i = plan->nr_ents - 1; i >= 0; i--) {
 		ent = &plan->ents[i];
 		if (release_turn(ent) != turn)
 			continue;
+		first = n;
 		for (arg = 0; arg < BPF_PAD_MAX_ARGS && ent->nr_cands[arg]; arg++)
-			n += load_handle(env, &buf[n], &aux[n], BPF_REG_1 + arg, &ent->cand[arg][0]);
+			n += load_handle(env, &buf[n], &aux[n], BPF_REG_1 + arg, &ent->cand[arg][0],
+					 !arg && ent_is_tested(ent));
 		if (is_obj_drop(&ent->release))
 			aux[n].kptr_struct_meta = btf_find_struct_meta(env->prog->aux->btf,
 								       ent->obj_type);
 		buf[n++] = ent->release;
+		if (ent_is_tested(ent))
+			buf[first + 1].off = n - first - 2;
 	}
 	return n;
 }
@@ -1104,21 +1272,21 @@ static bool released_first(const struct bpf_pad_plan *plan, const struct bpf_pad
 	       (!plan->sections[BPF_PAD_RCU] && !plan->sections[BPF_PAD_PREEMPT]);
 }
 
-/* Is @place one of R0-R5, which the calls of a pad clobber? */
-static bool place_is_caller_saved(const struct bpf_pad_place *place)
-{
-	return place->loc == BPF_PLACE_REG && place->at < BPF_REG_6;
-}
-
 /*
- * The first candidate of @ent is emitted. Can the pad of @plan use it?
- * Returns the reason of a conflict.
+ * Decide how the pad of @plan tells whether @ent is held, see the comment at the top of this file,
+ * and put the candidate that the pad uses first. Returns 0 or why the pad cannot be generated.
  */
 static int settle_ent(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 		      struct bpf_pad_ent *ent)
 {
 	struct bpf_pad_place *cand = ent->cand[0];
+	int i;
 
+	for (i = 0; i < ent->nr_cands[0] && !ent->always && !cand[i].null; i++)
+		;
+	if (i == ent->nr_cands[0])
+		return BPF_CONFLICT_NOT_ALWAYS_HELD;
+	swap(cand[0], cand[i]);
 	if (place_is_caller_saved(&cand[0]) && !released_first(plan, ent))
 		return BPF_CONFLICT_CALLER_SAVED;
 	/* R1 is loaded first */
@@ -1157,7 +1325,10 @@ bool bpf_pad_can_be_shared(const struct bpf_pad_plan *plan)
 	return true;
 }
 
-/* 'spin_lock@5(r6-8)': what insn 5 brought to the frame, the arguments of its release */
+/*
+ * Print a release like 'spin_lock@5(r6-8)': what insn 5 brought to the frame, and the locations of
+ * the arguments of its release. 'if not 0' follows if the pad tests the first one.
+ */
 static void print_ent(struct bpf_verifier_env *env, const struct bpf_pad_ent *ent)
 {
 	static const char * const class[] = {
@@ -1189,7 +1360,7 @@ static void print_ent(struct bpf_verifier_env *env, const struct bpf_pad_ent *en
 		if (place->delta && place->loc != BPF_PLACE_IMM)
 			verbose(env, "%+d", -place->delta);
 	}
-	verbose(env, ") ");
+	verbose(env, ")%s ", ent_is_tested(ent) ? " if not 0" : "");
 }
 
 /* Print what the pad of the site at insn @i releases, or why it cannot be generated */
@@ -1239,6 +1410,14 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 	struct bpf_pad_plan *plan;
 	int i, err;
 
+	/* the entries take the places that suit all visits, see visit_refs() */
+	for (i = 0; i < env->prog->len; i++) {
+		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next) {
+			err = order_ents(env, plan);
+			if (err)
+				return err;
+		}
+	}
 	for (i = 0; i < env->prog->len; i++) {
 		if (env->insn_aux_data[i].pad_plans && bpf_must_abort())
 			return -EINTR;
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 20/73] bpf: Let the kernel cancel a frame that holds references
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (18 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 19/73] bpf: Check pointers for NULL " Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 21/73] bpf: Add unwind_goto after helpers with a callback Kumar Kartikeya Dwivedi
                   ` (52 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 7549ddd3968c..fc5934aa9d1d 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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;
diff --git a/tools/testing/selftests/bpf/progs/plain_c_rbtree_search_kptr.c b/tools/testing/selftests/bpf/progs/plain_c_rbtree_search_kptr.c
index 5808d873fedd..3f63979cf71b 100644
--- a/tools/testing/selftests/bpf/progs/plain_c_rbtree_search_kptr.c
+++ b/tools/testing/selftests/bpf/progs/plain_c_rbtree_search_kptr.c
@@ -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;
diff --git a/tools/testing/selftests/bpf/progs/verifier_budget.c b/tools/testing/selftests/bpf/progs/verifier_budget.c
index d741cf8dbffa..a6e1cd22f35b 100644
--- a/tools/testing/selftests/bpf/progs/verifier_budget.c
+++ b/tools/testing/selftests/bpf/progs/verifier_budget.c
@@ -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 (
diff --git a/tools/testing/selftests/bpf/progs/verifier_passes.c b/tools/testing/selftests/bpf/progs/verifier_passes.c
index cc95688120e5..523931868e65 100644
--- a/tools/testing/selftests/bpf/progs/verifier_passes.c
+++ b/tools/testing/selftests/bpf/progs/verifier_passes.c
@@ -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;
diff --git a/tools/testing/selftests/bpf/progs/verifier_trip_count.c b/tools/testing/selftests/bpf/progs/verifier_trip_count.c
index 70a2a549f115..23253770be58 100644
--- a/tools/testing/selftests/bpf/progs/verifier_trip_count.c
+++ b/tools/testing/selftests/bpf/progs/verifier_trip_count.c
@@ -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
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 21/73] bpf: Add unwind_goto after helpers with a callback
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (19 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 20/73] bpf: Let the kernel cancel a frame that holds references Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 22/73] bpf: Let a may_goto that the verifier adds go to its landing pad only Kumar Kartikeya Dwivedi
                   ` (51 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 4f9c2bf64643..915034e8acc2 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -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);
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 5c34ace286df..2853a463df52 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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;
 	/*
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 6027e9cca9cc..4e3a7894af84 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -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.
  */
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index fc5934aa9d1d..21c90ab2972d 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -538,6 +538,7 @@ static bool is_ptr_cast_function(enum bpf_func_id func_id)
 }
 
 static bool is_sync_callback_calling_kfunc(u32 btf_id);
+static bool insn_has_cb_pad(const struct bpf_insn *insn);
 static bool is_async_callback_calling_kfunc(u32 btf_id);
 static bool is_call_rcu_kfunc(u32 btf_id);
 static bool is_callback_calling_kfunc(u32 btf_id);
@@ -3368,6 +3369,15 @@ static int record_callx_edge(struct bpf_verifier_env *env, int caller, int calle
 	return 0;
 }
 
+/*
+ * callx, or the call of a helper that has an unwind label for its callback. Both leave the way
+ * their callee leaves, and only the main pass knows the callee, see record_callx_edge().
+ */
+static bool is_indirect_call(const struct bpf_insn *insn)
+{
+	return bpf_is_callx(insn) || insn_has_cb_pad(insn);
+}
+
 /*
  * The helper or kfunc at this insn cannot pass on a callback that unwinds, so its callback @subprog
  * must not leave with unwind_exit or cancel_exit. Mark @subprog 'stuck': its may_goto jumps and its
@@ -3386,22 +3396,39 @@ static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)
 	return 0;
 }
 
+static bool callee_did_unwind(struct bpf_verifier_env *env, int insn_idx)
+{
+	const struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
+	struct bpf_subprog_info *si = env->subprog_info;
+	u32 e;
+
+	if (bpf_pseudo_call(insn))
+		return si[bpf_find_subprog(env, insn_idx + insn->imm + 1)].did_unwind;
+	if (!is_indirect_call(insn))
+		return false;
+	/* the edges that the pass has so far */
+	for (e = bpf_find_containing_subprog(env, insn_idx)->callx_edge; e;
+	     e = env->callx_edges[e - 1].next)
+		if (si[env->callx_edges[e - 1].callee].did_unwind)
+			return true;
+	return false;
+}
+
 /*
  * A subprog unwinds. What calls it without unwind_goto is unwound in turn, and so on. The callers
  * of a global subprog among them have to know, see unwind_frame(): one more round will do for all.
  */
 static void mark_unwind_above(struct bpf_verifier_env *env)
 {
-	struct bpf_subprog_info *si = env->subprog_info, *caller;
 	const struct bpf_insn *insn = env->prog->insnsi;
+	struct bpf_subprog_info *caller;
 	bool changed;
 	int i;
 
 	do {
 		changed = false;
 		for (i = 0; i < env->prog->len; i++) {
-			if (!bpf_pseudo_call(&insn[i]) || bpf_is_unwind_goto(&insn[i + 1]) ||
-			    !si[bpf_find_subprog(env, i + insn[i].imm + 1)].did_unwind)
+			if (!callee_did_unwind(env, i) || bpf_is_unwind_goto(&insn[i + 1]))
 				continue;
 			caller = bpf_find_containing_subprog(env, i);
 			changed |= !caller->did_unwind;
@@ -6034,8 +6061,8 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 	struct bpf_insn *insn = env->prog->insnsi;
 	int cnt = env->subprog_cnt, i, j, s, err;
 	struct bpf_call_graph cg;
-	/* the program calls the subprog, or callx may | a helper may | such a subprog gets to it */
-	enum { CALLED = 1, CB = 2, BELOW_CB = 4 };
+	/* CALLED: the program can call the subprog, with a call insn or through its address */
+	enum { CALLED = 1 };
 
 	/* callx calls node 'cnt', which calls each subprog whose address is taken */
 	err = bpf_call_graph_init(&cg, cnt + 1);
@@ -6063,7 +6090,7 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 				if (bpf_pseudo_call(&insn[i]) ||
 				    !func_is_kept_for_later(env, i, si[s + 1].start)) {
 					err = bpf_call_graph_add(&cg, s, j);
-					cg.marks[j] |= bpf_pseudo_call(&insn[i]) ? CALLED : CB;
+					cg.marks[j] |= CALLED;
 				}
 				if (bpf_pseudo_func(&insn[i]))
 					si[j].addr_taken = true;
@@ -6087,12 +6114,6 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 
 	bpf_call_graph_sort(&cg, 0);
 
-	/* A helper doesn't expect its callback to unwind, so what the callback calls cannot either */
-	for (s = 0; s < cnt; s++)
-		if (cg.marks[s] & CB)
-			cg.marks[s] |= BELOW_CB;
-	bpf_call_graph_mark_callees(&cg, BELOW_CB);
-
 	/*
 	 * A function that the program calls can leave with unwind_exit or cancel_exit, if the JIT
 	 * supports them and the loader has CAP_PERFMON. A function that only the kernel calls, like
@@ -6102,7 +6123,7 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 		si[s].bail_unwinds = si[s].can_unwind ||
 				     (s && env->prog->jit_requested && bpf_jit_supports_unwind() &&
 				      !bpf_prog_is_offloaded(env->prog->aux) && bpf_may_unwind(env) &&
-				      (cg.marks[s] & (CALLED | BELOW_CB)) == CALLED);
+				      (cg.marks[s] & CALLED));
 		si[s].did_unwind = si[s].can_unwind;
 	}
 
@@ -11530,42 +11551,24 @@ static bool kfunc_has_cb_pad(u32 btf_id)
 	return is_bpf_rbtree_add_kfunc(btf_id);
 }
 
-static bool insn_has_cb_pad(struct bpf_insn *insn)
+static bool insn_has_cb_pad(const struct bpf_insn *insn)
 {
-	return (bpf_helper_call(insn) && helper_has_cb_pad(insn->imm)) ||
-	       (bpf_pseudo_kfunc_call(insn) && kfunc_has_cb_pad(insn->imm));
+	return BPF_HAS_CB_PADS &&
+	       ((bpf_helper_call(insn) && helper_has_cb_pad(insn->imm)) ||
+		(bpf_pseudo_kfunc_call(insn) && kfunc_has_cb_pad(insn->imm)));
 }
 
 /*
- * A sync callback is called by a helper or a kfunc, a C frame between the
- * callback and the BPF code that called it. unwind_exit of the callback returns
- * to the pad of its caller when there is one, and a helper or a kfunc that
- * calls a callback has one where BPF_HAS_CB_PADS and insn_has_cb_pad(): it
- * calls the callback with bpf_call_cb(), drops what it holds when the callback
- * unwinds and leaves to the pad of its own caller with the r0 of the callback.
- * So a call with such a callback that can unwind is a call of something that
- * can unwind, and unwind_goto has to follow it.
- *
- * A callback has no unwind_exit and unwinds all the same when it is recursive
- * and unwind_goto follows every call of it that mark_recursive_subprogs() saw:
- * its check of the recursion leaves with unwind_exit then, see
- * check_recursion_guard(). The call of a helper that got the callback from a
- * table of functions is not one of those calls. It is known here.
+ * A helper or a kfunc is a C frame between its callback and the BPF code that called it. When the
+ * callback unwinds, a helper with an unwind label releases what it holds and leaves to the
+ * unwind_goto or cancel_goto after its own call, with the R0 of the callback. Reject a callback
+ * that can unwind if the helper has no label. A callback without unwind_exit can unwind too, at
+ * the stack check of a recursive function, see check_recursion_guard().
  */
-static int check_cb_unwind(struct bpf_verifier_env *env, struct bpf_insn *insn,
-			   int insn_idx, int subprog)
+static int check_cb_unwind(struct bpf_verifier_env *env, struct bpf_insn *insn, int subprog)
 {
 	if (!bpf_subprog_unwinds(&env->subprog_info[subprog]))
 		return 0;
-	if (!bpf_is_unwind_goto(insn + 1)) {
-		if (bpf_helper_call(insn))
-			verbose(env, "no unwind_goto after the call of %s()\n",
-				func_id_name(insn->imm));
-		else
-			verbose(env, "no unwind_goto after the call of the kfunc at insn %d\n",
-				insn_idx);
-		return -EINVAL;
-	}
 	/* The helpers have unwind labels only with asm goto outputs, see bpf_call_cb(). */
 	if (!BPF_HAS_CB_PADS) {
 		verbose(env, "callback cannot unwind: the helpers have no pads\n");
@@ -11662,11 +11665,10 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 	else
 		env->subprog_info[subprog].is_other_cb = true;
 
-	err = check_cb_unwind(env, insn, insn_idx, subprog);
+	err = check_cb_unwind(env, insn, subprog);
 	if (err)
 		return err;
-	/* the helper has no pad, or nothing takes the program from its call to a pad */
-	if (!insn_has_cb_pad(insn) || !bpf_is_unwind_goto(insn + 1)) {
+	if (!insn_has_cb_pad(insn)) {
 		err = subprog_cannot_unwind(env, subprog);
 		if (err)
 			return err;
@@ -12647,10 +12649,10 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 		/*
 		 * A callback returns into the helper that called it, and to the
 		 * pad of the helper when the helper has one. check_cb_unwind()
-		 * has seen to that, and to the unwind_goto after the call of
-		 * the helper, where the helper leaves to right away, with the
-		 * r0 of the callback as it is: the pad gets its state, as the
-		 * pad after a subprog call does.
+		 * has seen to that. From there the helper leaves right away to
+		 * the unwind_goto after its call, with the r0 of the callback
+		 * as it is: the pad gets its state, as the pad after a subprog
+		 * call does.
 		 */
 		err = check_unwound_return(env, callee->callsite, callee->subprogno);
 		if (err)
@@ -16166,18 +16168,22 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 
 	if (is_bpf_rbtree_add_kfunc(meta.func_id)) {
 		/*
-		 * The pad of the kfunc drops the node when the comparator
-		 * unwinds, the destructors of its fields included, which is a
-		 * bpf_obj_drop() under the rule above. The comparator unwinds
-		 * from the check of its recursion too, see check_cb_unwind().
+		 * When the comparator unwinds, the kfunc drops the node at its unwind label. That
+		 * runs the destructors of its fields, so the rule of bpf_obj_drop() above applies.
+		 * Reject a comparator that unwinds, and mark any other so that it is not cancelled.
 		 */
-		if (bpf_subprog_unwinds(&env->subprog_info[meta.subprogno]) && nmi_prog) {
+		if (nmi_prog) {
 			struct_meta = btf_find_struct_meta(meta.arg_btf, meta.arg_btf_id);
 			if (struct_meta && btf_record_has_nmi_unsafe_fields(struct_meta->record)) {
-				verbose(env,
-					"%s with a comparator that unwinds cannot be used in tracing programs on types with NMI unsafe fields\n",
-					func_name);
-				return -EINVAL;
+				if (bpf_subprog_unwinds(&env->subprog_info[meta.subprogno])) {
+					verbose(env,
+						"%s with a comparator that unwinds cannot be used in tracing programs on types with NMI unsafe fields\n",
+						func_name);
+					return -EINVAL;
+				}
+				err = subprog_cannot_unwind(env, meta.subprogno);
+				if (err)
+					return err;
 			}
 		}
 		/*
@@ -16185,12 +16191,16 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		 * releases an object, so no destructor of a field may run. A list head's would take
 		 * 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]) &&
-		    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);
-			return -EINVAL;
+		if (bpf_obj_free_runs_dtor(meta.arg_btf, meta.arg_btf_id)) {
+			if (bpf_subprog_unwinds(&env->subprog_info[meta.subprogno])) {
+				verbose(env,
+					"%s with a comparator that unwinds cannot be used on types with a list head, an rb root or a referenced kptr\n",
+					func_name);
+				return -EINVAL;
+			}
+			err = subprog_cannot_unwind(env, meta.subprogno);
+			if (err)
+				return err;
 		}
 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
 					 set_rbtree_add_callback_state);
@@ -21683,7 +21693,7 @@ static bool frame_holds_resources(const struct bpf_verifier_state *st)
  *
  * False when it cannot:
  * - The subprog cannot leave with unwind_exit, see bail_unwinds.
- * - A helper that calls a callback doesn't expect it to unwind.
+ * - A helper that has no pad for its callback doesn't expect it to unwind.
  * Then the program goes on along a path that it has, like after may_goto of
  * its own. It releases what it holds there.
  *
@@ -21702,7 +21712,7 @@ 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;
-	if (frame->in_callback_fn)
+	if (frame->in_callback_fn && !sub->bail_unwinds)
 		return false;
 	return frame_is_top(st) || sub->bail_unwinds || or_exit;
 }
diff --git a/tools/testing/selftests/bpf/progs/verifier_unwind.c b/tools/testing/selftests/bpf/progs/verifier_unwind.c
index 6be56387a825..b4d7dfdc675b 100644
--- a/tools/testing/selftests/bpf/progs/verifier_unwind.c
+++ b/tools/testing/selftests/bpf/progs/verifier_unwind.c
@@ -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 (
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 22/73] bpf: Let a may_goto that the verifier adds go to its landing pad only
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (20 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 21/73] bpf: Add unwind_goto after helpers with a callback Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 23/73] bpf: Record why a callee is cancelled when its call gets no landing pad Kumar Kartikeya Dwivedi
                   ` (50 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
index 0bffb2b1476a..21c92b7e829a 100644
--- a/Documentation/bpf/verifier.rst
+++ b/Documentation/bpf/verifier.rst
@@ -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
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 2853a463df52..f548d38d8708 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/const_fold.c b/kernel/bpf/const_fold.c
index 1a7e521a4b92..1a84ba1d27bf 100644
--- a/kernel/bpf/const_fold.c
+++ b/kernel/bpf/const_fold.c
@@ -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);
diff --git a/kernel/bpf/failing_path.c b/kernel/bpf/failing_path.c
index 26469e41f04a..3c7dfb3270f9 100644
--- a/kernel/bpf/failing_path.c
+++ b/kernel/bpf/failing_path.c
@@ -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);
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 25c0b0552b4d..97a885c077ee 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -591,8 +591,6 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
 {
 	int n = 0;
 
-	if (!env->bypass_spec_v1)
-		buf[n++] = BPF_ST_NOSPEC();
 	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);
@@ -603,7 +601,7 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
 /*
  * The landing pad of a site in subprog @s. The only exit of a pad is its last insn. Nothing in a
  * pad is hardened against a cpu that mispredicts: only a program that is loaded with CAP_PERFMON
- * gets one, see frame_can_unwind().
+ * gets one, see frame_cannot_unwind().
  * Returns the number of insns, BPF_PAD_MAX_INSNS + 1 at most.
  */
 static int emit_pad(struct bpf_verifier_env *env, int s, const struct bpf_pad_plan *plan,
@@ -616,23 +614,21 @@ static int emit_pad(struct bpf_verifier_env *env, int s, const struct bpf_pad_pl
 	return n;
 }
 
-static bool guard_leaves_subprog(const struct bpf_insn_aux_data *aux)
-{
-	return aux->loop_guard && aux->guard_unwinds;
-}
-
-/* Does the program leave the frame at the site of @plan, which is at insn @i? */
-static bool site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
+/*
+ * Does the program keep the site of @plan at insn @i? The main pass records more sites than that:
+ * a loop that turns out to have a trip count gets no may_goto, for example.
+ */
+bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
 {
 	int s;
 
 	switch (plan->kind) {
 	case BPF_SITE_GUARD:
-		return guard_leaves_subprog(&env->insn_aux_data[i]);
+		return env->insn_aux_data[i].loop_guard;
 	case BPF_SITE_RECURSION:
 		return bpf_find_containing_subprog(env, i)->recursive;
 	case BPF_SITE_CALL:
-		if (!plan->visited || plan->conflict)
+		if (!plan->visited)
 			return false;
 		bpf_pad_for_each_callee(plan, s)
 			if (env->subprog_info[s].can_unwind)
@@ -662,9 +658,9 @@ void bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env)
 			if (sub->can_unwind || !sub->bail_unwinds)
 				continue;
 			for (i = sub->start; i < sub[1].start && !sub->can_unwind; i++) {
-				sub->can_unwind = guard_leaves_subprog(&aux[i]);
+				sub->can_unwind = aux[i].loop_guard;
 				for (plan = aux[i].pad_plans; plan; plan = plan->next)
-					sub->can_unwind |= site_is_used(env, i, plan);
+					sub->can_unwind |= bpf_site_is_used(env, i, plan);
 			}
 			changed |= sub->can_unwind;
 		}
@@ -675,7 +671,21 @@ void bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env)
 static bool plan_has_pad(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
 {
 	/* bpf_insert_recursion_checks() emits the pad of the check */
-	return plan->kind != BPF_SITE_RECURSION && site_is_used(env, i, plan);
+	return plan->kind != BPF_SITE_RECURSION && bpf_site_is_used(env, i, plan);
+}
+
+/* The record of the site of @kind at insn @i. An empty one is made if no state reached the site. */
+static struct bpf_pad_plan *unvisited_plan(struct bpf_verifier_env *env, int i,
+					   enum bpf_site_kind kind)
+{
+	struct bpf_pad_plan *plan = bpf_pad_plan(&env->insn_aux_data[i], kind);
+
+	if (plan)
+		return plan;
+	plan = bpf_pad_plan_get(env, i, kind);
+	if (plan)
+		plan->used = true;
+	return plan;
 }
 
 /*
@@ -692,12 +702,15 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 	struct bpf_pad_plan *plan;
 
 	for (i = env->subprog_info[s].start; i <= last; i++) {
-		/* no state got there in the pass: the empty plan will do */
-		if (guard_leaves_subprog(&aux[i]) && !bpf_pad_plan_get(env, i, BPF_SITE_GUARD))
+		if (aux[i].loop_guard && !unvisited_plan(env, i, BPF_SITE_GUARD))
 			return -ENOMEM;
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
 			if (!plan_has_pad(env, i, plan))
 				continue;
+			/* bpf_pads_settle() settled every site that the program keeps */
+			if (verifier_bug_if(!plan->used || plan->conflict, env,
+					    "the landing pad of insn %d was not settled", i))
+				return -EFAULT;
 			n = emit_pad(env, s, plan, new, new_aux);
 			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);
@@ -740,7 +753,7 @@ static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added)
 		sub = &env->subprog_info[s];
 		for (i = sub->start; added[s] && i < sub[1].start - added[s]; i++) {
 			plan = bpf_pad_plan(&aux[i], BPF_SITE_CALL);
-			if (!plan || !site_is_used(env, i, plan))
+			if (!plan || !bpf_site_is_used(env, i, plan))
 				continue;
 			/* the insn that follows the call may be dead code, what is appended is not */
 			err = bpf_patch_list_append(env, i, &unwind_goto, 1);
@@ -756,25 +769,23 @@ static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added)
 
 /*
  * Emit what the main pass decided about the sites: may_goto before the insns that it
- * marked, see check_loop_guard(), unwind_goto after calls, and the landing pads. It verified the
- * edge from the insn to where may_goto goes. What a pad does it did to the states that left the
- * frame at the site, see unwind_frame().
+ * marked, see check_loop_guard(), unwind_goto after calls, and the landing pads. What a pad does it
+ * did to the states that left the frame at the site, see unwind_frame().
  *
- *	may_goto to		or	may_goto pad
- *	insn				insn
- *					...
- *					last insn of the subprog
- *				pad:	the releases
- *					r0 = bpf_cancelled_retval()
- *					exit
+ *	may_goto pad		before an insn of a loop, see check_loop_guard(). A may_goto
+ *	insn			of the program that is a site jumps to its pad too.
+ *	call foo		or an access to arena
+ *	unwind_goto pad		or cancel_goto, or both, see insert_unwind_gotos()
+ *	gotol pad		in place of a call of bpf_throw()
+ *	...
+ *	last insn of the subprog
+ * pad:	the releases		each site has its own pad, see collect_pads()
+ *	r0 = bpf_cancelled_retval()
+ *	cancel_exit		or exit, see unwind_exit_insn()
  *
  * bpf_do_misc_fixups() keeps the address of the count of may_goto in a register that is
  * dead at the may_goto. What is live in front of the insn is live in front of its guard.
- * Nothing else is:
- *  - The guard of a jump goes where the jump goes.
- *  - What is live where the guard at the head of a loop goes is live at the head,
- *    see bpf_head_guard_target().
- *  - A landing pad reads places, which are live before the insn.
+ * Nothing else is: a landing pad reads only locations that are live before the insn.
  */
 int bpf_insert_sites(struct bpf_verifier_env *env)
 {
@@ -819,10 +830,6 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 				err = PTR_ERR(insn);
 				goto out;
 			}
-			if (!aux[i].guard_unwinds) {
-				bpf_patch_list_jump(&env->patch_list, insn - 1, aux[i].guard_to, 0);
-				continue;
-			}
 			/* however far the pad is, see bpf_patch_list_jump() */
 			plan = bpf_pad_plan(&aux[i], BPF_SITE_GUARD);
 			bpf_patch_list_jump(&env->patch_list, insn - 1, sub[1].start,
diff --git a/kernel/bpf/flow.c b/kernel/bpf/flow.c
index 33e50e1ad8cb..0a464969d9de 100644
--- a/kernel/bpf/flow.c
+++ b/kernel/bpf/flow.c
@@ -252,29 +252,15 @@ static bool flow_is_bound(struct bpf_verifier_env *env, int h, int idx)
  * an iterator that is older than the loop, that every trip goes through. A loop without
  * it gets may_goto unless the number of its trips turns out to be known.
  *
- * The place for it is in front of a conditional jump that leaves the loop, with
- * the same target. The registers and the stack are what they are when
- * the program leaves the loop there. One such jump that every trip goes
- * through is enough. Otherwise every back edge needs one.
+ * The may_goto goes before a conditional jump that leaves the loop. One such jump that every trip
+ * goes through is enough. Otherwise every back edge needs one, and if a back edge has no such
+ * jump, the may_goto goes before the head of the loop.
  */
-static void flow_set_guard(struct bpf_verifier_env *env, int h, int n)
-{
-	struct bpf_insn_aux_data *aux = env->insn_aux_data;
-	int t = n + env->prog->insnsi[n].off + 1;
-	int i = bpf_loop_at_index(env, t);
-
-	if (i == h || bpf_is_nested_loop(env, i, h))
-		t = n + 1;
-	aux[n].guard_place = true;
-	aux[n].guard_to = t;
-	aux[h].loop->has_guards = true;
-}
-
 static void flow_place_guards(struct bpf_verifier_env *env, int h)
 {
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	struct bpf_loop *loop = aux[h].loop;
-	int i, n, o, t;
+	int i, n;
 
 	if (loop->backedges_overflow)
 		goto header;
@@ -290,42 +276,26 @@ static void flow_place_guards(struct bpf_verifier_env *env, int h)
 			if (loop->backedges[i].latch != loop->backedges[i].from)
 				goto header;
 		for (i = 0; i < loop->backedges_cnt; i++)
-			flow_set_guard(env, h, loop->backedges[i].from);
+			aux[loop->backedges[i].from].guard_place = true;
 		return;
 	}
 
-	for (n = bpf_loop_spine_end(env, loop); n >= 0; n = n == h ? -1 : env->idoms[n])
-		if (bpf_insn_leaves_loop(env, h, n))
-			return flow_set_guard(env, h, n);
+	for (n = bpf_loop_spine_end(env, loop); n >= 0; n = n == h ? -1 : env->idoms[n]) {
+		if (bpf_insn_leaves_loop(env, h, n)) {
+			aux[n].guard_place = true;
+			return;
+		}
+	}
 
 	for (i = 0; i < loop->backedges_cnt; i++)
 		if (loop->backedges[i].latch < 0)
 			goto header;
 	for (i = 0; i < loop->backedges_cnt; i++)
-		flow_set_guard(env, h, loop->backedges[i].latch);
+		aux[loop->backedges[i].latch].guard_place = true;
 	return;
 
 header:
-	/*
-	 * In front of a jump may_goto goes where the jump goes. From the head to where the loop
-	 * is left is not an edge of the program: it skips what is in the loop. If that is what
-	 * stops a loop around this one, bpf_iter_*_next() or i++, and the exit leads back to
-	 * the head of that loop, the program goes round and round from may_goto to may_goto.
-	 * So leave all loops.
-	 *
-	 * What is derived from the graph in the direction of the edges has to know about this
-	 * one, see bpf_head_guard_target().
-	 */
-	for (o = h; aux[o].loop_header >= 0; o = aux[o].loop_header)
-		;
-	/* a loop that has no exit can only be stopped together with the program */
-	t = aux[o].loop->exit_to;
-	if (t < 0)
-		return;
 	aux[h].guard_place = true;
-	aux[h].guard_at_header = true;
-	aux[h].guard_to = t;
-	loop->has_guards = true;
 }
 
 /* Does every trip of the loop @h go through an insn that stops it? */
@@ -388,20 +358,15 @@ bool bpf_flow_loops_lost_bound(struct bpf_verifier_env *env)
  * got to the end of the loop in a peeled trip. A loop before this one can use up the budget
  * of may_goto. So if a state did not take the edges of may_goto, the pass restarts.
  */
-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)
 {
 	if (loop->rt_bounded)
-		return 0;
+		return;
 	loop->no_first_trips_guess = true;
-	if (!loop->has_guards) {
-		verbose(env, "loop at insn %d never exits\n", loop->header);
-		return -EINVAL;
-	}
 	if (!loop->this_pass.needs_guard && (env->log.level & BPF_LOG_LEVEL2))
 		verbose(env, "loop at %d has no trip count\n", loop->header);
 	loop->this_pass.needs_guard = loop->guarded = true;
 	env->guards_late |= loop->this_pass.no_guard_edges;
-	return 0;
 }
 
 /* This pass peels more trips. What the last pass found about @loop can be wrong. */
@@ -415,7 +380,6 @@ static void flow_forget_loop(struct bpf_verifier_env *env, struct bpf_loop *loop
 	for (i = loop->header; n--; i = bpf_flow_insn_after(env, i)) {
 		if (bpf_loop_at_index(env, i) != loop->header)
 			continue;
-		aux[i].guard_no_unwind = aux[i].guard_unset_reg = false;
 		aux[i].not_stopped = -1;
 	}
 	loop->rt_bounded = flow_loop_is_bounded(env, loop->header);
@@ -465,13 +429,25 @@ void bpf_flow_drop_guards(struct bpf_verifier_env *env)
 }
 
 /*
- * Which loops have something that stops them at run time, and where may_goto goes in the others.
- * Returns 1 if a place is at the head of a loop.
+ * Is the may_goto before the insn at @idx only a guess of this pass? A pass takes the edge of
+ * may_goto in every loop that may need one before it knows the trip counts. Until a state of the
+ * pass has gone around the loop without a trip count ('needs_guard'), the program may turn out to
+ * have no may_goto there, see bpf_flow_drop_guards(). A path-sensitive run does not guess: it takes
+ * the edge only in a loop that it found to be infinite, see check_loop_guard().
  */
+bool bpf_flow_guard_is_guess(struct bpf_verifier_env *env, int idx)
+{
+	int h = bpf_loop_at_index(env, idx);
+
+	return !env->path_sensitive && h >= 0 &&
+	       !env->insn_aux_data[h].loop->this_pass.needs_guard;
+}
+
+/* Find the loops that something stops at run time, and the places for may_goto in the others */
 int bpf_flow_place_guards(struct bpf_verifier_env *env)
 {
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
-	int len = env->prog->len, h, i, ret = 0, err = 0;
+	int len = env->prog->len, h, i, err = 0;
 	struct bpf_loop *loop;
 
 	for (i = 0; i < len; i++) {
@@ -492,11 +468,9 @@ int bpf_flow_place_guards(struct bpf_verifier_env *env)
 		/* also when it's bounded: the main pass may find that it's not */
 		flow_place_guards(env, h);
 		/* pass 0 does not know the trip count before it ends */
-		loop->guarded = loop->has_guards && !bpf_prog_is_offloaded(env->prog->aux);
-		if (aux[h].guard_at_header)
-			ret = 1;
+		loop->guarded = !bpf_prog_is_offloaded(env->prog->aux);
 	}
-	return err ?: ret;
+	return err;
 }
 
 static bool flow_may_load_pkt_end(struct bpf_verifier_env *env, const struct bpf_insn *insn)
@@ -1134,13 +1108,12 @@ static bool flow_same_entry(struct bpf_loop *loop, const struct flow_state *t,
  * A loop that can run longer than that gets may_goto.
  * There is no trip count without CAP_PERFMON (allow_uninit_stack).
  */
-static int flow_check_trip_counts(struct bpf_verifier_env *env, const struct flow_state *t,
-				  const struct flow_state *s)
+static void flow_check_trip_counts(struct bpf_verifier_env *env, const struct flow_state *t,
+				   const struct flow_state *s)
 {
 	const struct loop_stack_entry *e;
 	u32 fr, i;
 	u64 max_trip;
-	int err;
 
 	for (fr = 0; fr <= s->st.curframe && !s->st.speculative; fr++) {
 		e = s->st.frame[fr]->loop_stack;
@@ -1156,12 +1129,9 @@ static int flow_check_trip_counts(struct bpf_verifier_env *env, const struct flo
 						e->loop->header, max_trip + 1);
 				continue;
 			}
-			err = bpf_flow_needs_guard(env, e->loop);
-			if (err)
-				return err;
+			bpf_flow_needs_guard(env, e->loop);
 		}
 	}
-	return 0;
 }
 
 /* @t is from an earlier walk over a leftover. The header state of @s subsumes that of @t. */
@@ -1224,14 +1194,12 @@ static int flow_prune_or_join(struct bpf_verifier_env *env, struct flow_state *s
 		if (subsumed) {
 			if (env->log.level & BPF_LOG_LEVEL2)
 				verbose(env, "from %d to %d: pruned\n", prev, insn_idx);
-			err = flow_check_trip_counts(env, t, s);
+			flow_check_trip_counts(env, t, s);
 			goto free;
 		}
 		/* what grows in a loop is widened, it is not replaced */
 		if (!leftover_loop && bpf_state_subsumes(env, &s->st, &t->st)) {
-			err = flow_check_trip_counts(env, s, t);
-			if (err)
-				goto free;
+			flow_check_trip_counts(env, s, t);
 			/* it goes on with the leftover that @t started */
 			if (s->kind == FLOW_LEFTOVER)
 				bpf_top_loop(s->st.frame[s->st.curframe])->entry_id =
@@ -1310,7 +1278,8 @@ static int flow_prune_peeled(struct bpf_verifier_env *env, struct flow_state *s,
 		if (env->log.level & BPF_LOG_LEVEL2)
 			verbose(env, "from %d to %d: pruned\n", s->prev_insn_idx, s->st.insn_idx);
 		entry->trip = trip;
-		ret = flow_check_trip_counts(env, t, s) ?: 1;
+		flow_check_trip_counts(env, t, s);
+		ret = 1;
 		break;
 	}
 	s->kind = FLOW_AT;
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index 28044f12e9c7..aac5f2860121 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -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;
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 4e3a7894af84..464e26a67819 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -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);
 }
diff --git a/kernel/bpf/precision.c b/kernel/bpf/precision.c
index 042ae3ddef92..75e4e25ec7db 100644
--- a/kernel/bpf/precision.c
+++ b/kernel/bpf/precision.c
@@ -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) {
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 21c90ab2972d..074a5fa4cf13 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -6124,7 +6124,7 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 				     (s && env->prog->jit_requested && bpf_jit_supports_unwind() &&
 				      !bpf_prog_is_offloaded(env->prog->aux) && bpf_may_unwind(env) &&
 				      (cg.marks[s] & CALLED));
-		si[s].did_unwind = si[s].can_unwind;
+		si[s].did_unwind = si[s].unwinds_for_sure = si[s].can_unwind;
 	}
 
 	for (s = 0; s < cnt; s++) {
@@ -16880,7 +16880,6 @@ static void sanitize_mark_insn_seen(struct bpf_verifier_env *env)
  * edges have their own barrier, and a speculative state does not take them:
  *
  *	exit of a callback --> call of the helper	barrier at the exit
- *	may_goto --> r0 = 0; exit			see emit_unwind_exit()
  *	return --> dead code				see bpf_opt_hard_wire_dead_code_branches()
  */
 static void need_nospec(struct bpf_verifier_env *env, u32 idx)
@@ -21449,7 +21448,8 @@ static int failing_path_trip(struct bpf_verifier_env *env, struct loop_stack_ent
 			loop->infinite = true;
 			/* the next runs keep it */
 			loop->infinite_is_guess = env->run_has_guess;
-			return bpf_flow_needs_guard(env, loop);
+			bpf_flow_needs_guard(env, loop);
+			return 0;
 		} else if (err && !bpf_values_grew_in_deps(env, old, cur)) {
 			return 1;
 		}
@@ -21690,44 +21690,23 @@ static bool frame_holds_resources(const struct bpf_verifier_state *st)
  * better not to go on. The way to stop is to unwind: 'r0 = 0; unwind_exit'. The landing
  * pads that the callers have in the program are code like any other. They release what
  * the callers hold, or the program is rejected. Where a caller has none the verifier emits it.
- *
- * False when it cannot:
- * - The subprog cannot leave with unwind_exit, see bail_unwinds.
- * - A helper that has no pad for its callback doesn't expect it to unwind.
- * Then the program goes on along a path that it has, like after may_goto of
- * its own. It releases what it holds there.
- *
- * @or_exit: there is no such path. 'r0 = 0; exit' has to do where the subprog
- * cannot unwind, and the caller goes on with 0 in place of the result.
+ * There is no other way out. Returns why the frame cannot unwind, 0 if it can.
  */
-static bool frame_can_unwind(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
-			     bool or_exit)
+static enum bpf_pad_conflict frame_cannot_unwind(struct bpf_verifier_env *env,
+						 const struct bpf_verifier_state *st)
 {
 	const struct bpf_func_state *frame = st->frame[st->curframe];
 	const struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
 
 	/* unwind_frame() needs an insn at which the state leaves the function. */
 	if (sub->exit_idx == U32_MAX)
-		return false;
+		return BPF_CONFLICT_NO_EXIT;
 	/* A landing pad has no nospec barrier, so only a loader with CAP_PERFMON gets one. */
 	if (!bpf_may_unwind(env))
-		return false;
-	if (frame->in_callback_fn && !sub->bail_unwinds)
-		return false;
-	return frame_is_top(st) || sub->bail_unwinds || or_exit;
-}
-
-/* May_goto at the head of a loop skips the body. Does it go to code that reads what is not set? */
-static bool guard_reads_unset_reg(struct bpf_verifier_env *env,
-				  const struct bpf_insn_aux_data *aux)
-{
-	u16 live = env->insn_aux_data[aux->guard_to].live_regs_before;
-	int r;
-
-	for (r = BPF_REG_0; r < BPF_REG_FP; r++)
-		if ((live & BIT(r)) && cur_regs(env)[r].type == NOT_INIT)
-			return true;
-	return false;
+		return BPF_CONFLICT_NO_PERFMON;
+	if (!frame_is_top(st) && !sub->bail_unwinds)
+		return BPF_CONFLICT_CANNOT_UNWIND;
+	return BPF_NO_CONFLICT;
 }
 
 /* This insn is a site of @kind. Push a copy of the current state that leaves its frame here. */
@@ -21746,8 +21725,8 @@ static int push_unwind_edge(struct bpf_verifier_env *env, enum bpf_site_kind kin
 
 /*
  * A loop has no trip count, and nothing stops it at run time. It gets may_goto
- * before this insn. When may_goto is out of budget, the program goes to its
- * target with the registers and the stack that it has here.
+ * before this insn. When the time of may_goto is up, the frame is cancelled here,
+ * with the registers and the stack as they are, see unwind_frame().
  * Every state that goes through the loop does that, see bpf_flow_needs_guard().
  */
 static int check_loop_guard(struct bpf_verifier_env *env)
@@ -21777,55 +21756,16 @@ static int check_loop_guard(struct bpf_verifier_env *env)
 		return -EINVAL;
 	}
 
-	/*
-	 * A guard has one way out, and only that one is verified.
-	 *
-	 * Leave the subprog, if that is possible every time the program gets here:
-	 *	do { p = lookup(); } while (!p); *p
-	 * The code after the loop relies on the result of the jump that leaves it.
-	 *
-	 * Otherwise leave the loop:
-	 *	lock(); do { ... } while (...); unlock();
-	 * The code after the loop releases what is held.
-	 *
-	 * The program has no edge from the header of a loop to the exit of the loop:
-	 *	for (;;) { c = *s++; if (!c) return 0; if (c == '*') return 1; }
-	 * The loop is left to 'exit', and only its body sets r0. Then leave the subprog. Use
-	 * a plain exit if it cannot unwind, like check_recursion_guard().
-	 *
-	 * All states that get here take the same way, or the pass starts again.
-	 * A speculative state does not select the way.
-	 */
-	if (env->cur_state->speculative)
-		goto out;
-	if (aux->guard_at_header && !aux->guard_unset_reg && guard_reads_unset_reg(env, aux)) {
-		aux->guard_unset_reg = true;
-		env->guards_late |= aux->guard_no_unwind && aux->loop_guard;
-		aux->guard_no_unwind = false;
-	}
-	if (!aux->guard_no_unwind &&
-	    !frame_can_unwind(env, env->cur_state, aux->guard_unset_reg)) {
-		env->guards_late |= aux->loop_guard;
-		aux->guard_no_unwind = true;
-	}
-	/* another state selected the target, possibly a state that only a join makes */
-	env->run_has_guess |= aux->guard_no_unwind &&
-			      frame_can_unwind(env, env->cur_state, aux->guard_unset_reg);
-out:
 	aux->loop_guard = true;
-	aux->guard_unwinds = !aux->guard_no_unwind;
-	if (aux->guard_no_unwind)
-		err = PTR_ERR_OR_ZERO(push_stack(env, aux->guard_to, env->insn_idx, false));
-	else
-		err = push_unwind_edge(env, BPF_SITE_GUARD);
+	err = push_unwind_edge(env, BPF_SITE_GUARD);
 	/* more peeled trips can show that the edge is dead */
 	if (!err && env->head)
 		env->head->st.suspect_loops |= loop->suspect_bit;
 	/*
-	 * The state on that edge leaves the subprog. So far it left the loop, and the code that
-	 * follows the loop had the suspect of its errors from there.
+	 * The state on that edge leaves the function and never gets to the code after the loop.
+	 * So the state that stays carries the loop as a suspect for errors in that code.
 	 */
-	if (!err && env->head && !aux->guard_no_unwind && !frame_is_top(env->cur_state))
+	if (!err && env->head && !frame_is_top(env->cur_state))
 		env->cur_state->suspect_loops |= loop->suspect_bit;
 	return err;
 }
@@ -21893,18 +21833,46 @@ static int release_frame_resources(struct bpf_verifier_env *env)
 	return 0;
 }
 
+/*
+ * Does the program have the site of @plan at @insn_idx for sure? Pass 0 takes the edge of may_goto
+ * in every loop that nothing stops, a later pass in every loop that had no trip count before, and
+ * a loop that turns out to have a trip count gets no may_goto, see bpf_flow_drop_guards() and
+ * bpf_flow_guard_is_guess(). A call is a site only if a callee is left at one.
+ * bpf_pads_settle() knows them all. Until then a conflict at a site that may go is no error.
+ */
+static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
+			    int insn_idx)
+{
+	int s;
+
+	switch (plan->kind) {
+	case BPF_SITE_GUARD:
+		return !bpf_flow_guard_is_guess(env, insn_idx);
+	case BPF_SITE_CALL:
+		bpf_pad_for_each_callee(plan, s)
+			if (env->subprog_info[s].unwinds_for_sure)
+				return true;
+		return false;
+	default:
+		return true;
+	}
+}
+
 /*
  * The current frame of @st is left at @insn_idx, a site of @kind. The program has no code for
  * that: the verifier emits a landing pad after the main pass, see kernel/bpf/pads.c. No insn
  * stands for it in the main pass. @st visits the plan of the site, which notes what the pad has to
  * do. Then what the pad does to a state is done to @st: the releases, see
- * release_frame_resources(), the value in place of the result, then unwind_exit if the subprog can
- * do that, exit otherwise. What is left of @st goes where the frame returns to, through the
+ * release_frame_resources(), the value in place of the result, then unwind_exit, or exit in a frame
+ * that the kernel called. What is left of @st goes where the frame returns to, through the
  * worklist like every other state. @st is taken.
  *
  * With a conflict there is no pad: the site is an unproven insn in @st, which ends here. The pass
  * goes on, and a pass that keeps more apart may have no such state.
- * A frame that cannot unwind and waits in a call that comes back with unwind_exit is a conflict.
+ * A frame that cannot unwind is a conflict.
+ * Nor is it one at a site that the program may not have in the end, see site_is_certain(): @st is
+ * dropped, the plan keeps the conflict, and bpf_pads_settle() makes it an error of the pass if the
+ * site is still there.
  */
 static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int insn_idx,
 			enum bpf_site_kind kind)
@@ -21914,29 +21882,28 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	struct bpf_verifier_state *cur = env->cur_state;
 	int cur_idx = env->insn_idx, err;
 	struct bpf_pad_plan *plan;
-	bool print_state;
+	bool print_state, certain;
 	u32 cnt;
 
 	env->cur_state = st;
 	env->insn_idx = insn_idx;
 	/* its suspects are those of a conflict that only bpf_pads_settle() finds */
 	env->insn_aux_data[insn_idx].suspect_loops |= st->suspect_loops;
-	/* there is no other way out of a call */
-	if (kind == BPF_SITE_CALL && !frame_can_unwind(env, st, false)) {
-		plan = bpf_pad_plan_get(env, insn_idx, kind) ?: ERR_PTR(-ENOMEM);
-		if (!IS_ERR(plan))
-			plan->conflict = BPF_CONFLICT_CANNOT_UNWIND;
-	} else {
-		plan = bpf_pad_visit(env, st, insn_idx, kind);
-	}
+	plan = bpf_pad_visit(env, st, insn_idx, kind);
 	err = PTR_ERR_OR_ZERO(plan);
 	if (err)
 		goto out;
-	if (plan->conflict) {
+	/* there is no other way out */
+	if (!plan->conflict)
+		plan->conflict = frame_cannot_unwind(env, st);
+	certain = site_is_certain(env, plan, insn_idx);
+	if (plan->conflict && certain) {
 		bpf_pad_log(env, insn_idx, plan);
 		err = -EINVAL;
 		goto unproven;
 	}
+	if (plan->conflict)
+		goto out;
 
 	err = release_frame_resources(env);
 	if (err)
@@ -21959,6 +21926,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		env->pads_late = true;
 	}
 	sub->did_unwind |= st->unwound;
+	sub->unwinds_for_sure |= st->unwound && certain;
 	if (env->log.level & BPF_LOG_LEVEL2)
 		verbose(env, "from %d to %s of func#%d\n", insn_idx,
 			st->unwound ? "unwind_exit" : "exit", frame->subprogno);
@@ -22028,8 +21996,7 @@ static int flow_drain(struct bpf_verifier_env *env)
 /*
  * A subprog on a cycle of the call graph checks the stack at run time, see
  * bpf_insert_recursion_checks(). When there is no room, or the time slice is over, it leaves
- * at once with 0 in place of the result: it unwinds if it can, see bail_unwinds, otherwise
- * it returns and callers have to be fine with that.
+ * at once: the frame is cancelled here, see unwind_frame().
  */
 static int check_recursion_guard(struct bpf_verifier_env *env)
 {
@@ -24120,6 +24087,22 @@ static void settle_late_unwinds(struct bpf_verifier_env *env, const struct bpf_s
 	env->pads_late = late;
 }
 
+/*
+ * The pass has no error so far. Mark the sites that the program keeps, as bpf_insert_sites() will
+ * see them: a loop that turned out to have a trip count has no may_goto, and a call is no site if
+ * its callees leave at no site. can_unwind and can_cancel are restored afterwards.
+ */
+static void mark_used_sites(struct bpf_verifier_env *env, const struct bpf_snapshot *initial)
+{
+	int s;
+
+	bpf_flow_drop_guards(env);
+	bpf_mark_subprogs_that_unwind(env);
+	bpf_pads_mark_used(env);
+	for (s = 0; s < env->subprog_cnt; s++)
+		env->subprog_info[s].can_unwind = initial->subprogs[s].can_unwind;
+}
+
 /* Returns the first error */
 static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initial)
 {
@@ -24156,6 +24139,7 @@ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial
 	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)
 		bpf_find_unproven_after_pass(env);
@@ -26499,14 +26483,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (ret < 0)
 		goto skip_full_check;
 
-	/*
-	 * It took the constants to remove dead branches and find the loops. Now it's known
-	 * which edges the verifier may add, see bpf_head_guard_target(). What follows
-	 * believes the constants.
-	 */
 	ret = bpf_flow_place_guards(env);
-	if (ret > 0)
-		ret = bpf_compute_const_regs(env);
 	if (ret < 0)
 		goto skip_full_check;
 
diff --git a/tools/testing/selftests/bpf/progs/compute_live_registers.c b/tools/testing/selftests/bpf/progs/compute_live_registers.c
index f1a0c2187c6c..9a6580bca311 100644
--- a/tools/testing/selftests/bpf/progs/compute_live_registers.c
+++ b/tools/testing/selftests/bpf/progs/compute_live_registers.c
@@ -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)
diff --git a/tools/testing/selftests/bpf/progs/plain_c_arena_htab.c b/tools/testing/selftests/bpf/progs/plain_c_arena_htab.c
index 10a50b5058dd..7122815667e9 100644
--- a/tools/testing/selftests/bpf/progs/plain_c_arena_htab.c
+++ b/tools/testing/selftests/bpf/progs/plain_c_arena_htab.c
@@ -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")
diff --git a/tools/testing/selftests/bpf/progs/plain_c_arena_strsearch.c b/tools/testing/selftests/bpf/progs/plain_c_arena_strsearch.c
index f05cf023c4d2..ebec872aa9a1 100644
--- a/tools/testing/selftests/bpf/progs/plain_c_arena_strsearch.c
+++ b/tools/testing/selftests/bpf/progs/plain_c_arena_strsearch.c
@@ -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)
 {
diff --git a/tools/testing/selftests/bpf/progs/plain_c_verifier_arena_large.c b/tools/testing/selftests/bpf/progs/plain_c_verifier_arena_large.c
index 4c5339edb06f..411e9afaa3f3 100644
--- a/tools/testing/selftests/bpf/progs/plain_c_verifier_arena_large.c
+++ b/tools/testing/selftests/bpf/progs/plain_c_verifier_arena_large.c
@@ -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)
 {
diff --git a/tools/testing/selftests/bpf/progs/verifier_barrier.c b/tools/testing/selftests/bpf/progs/verifier_barrier.c
index b012235a76a4..302dccd68de9 100644
--- a/tools/testing/selftests/bpf/progs/verifier_barrier.c
+++ b/tools/testing/selftests/bpf/progs/verifier_barrier.c
@@ -129,10 +129,15 @@ __naked void exit_of_callback(void)
 	"exit;");
 }
 
+/*
+ * The loop gets may_goto, which goes to a landing pad. A pad has no barrier, so a prog that is
+ * loaded without CAP_PERFMON gets none: nothing ends its loop.
+ */
 SEC("tc")
-__description("barrier: on the way out of a loop that is out of budget")
-__success SPECULATES __success_unpriv
-__naked void unwind_exit(void)
+__description("a loop that needs may_goto of the verifier needs CAP_PERFMON")
+__success SPECULATES __failure_unpriv
+__msg_unpriv("landing pad of may_goto at 4: conflict: the program is loaded without CAP_PERFMON")
+__naked void guard_needs_perfmon(void)
 {
 	ASM(START
 "1:	r1 = *(u64 *)(r6 + 8);"
@@ -141,61 +146,6 @@ __naked void unwind_exit(void)
 	"exit;");
 }
 
-SEC("tc")
-__description("barrier: before may_goto")
-__success SPECULATES __success_unpriv
-#ifdef SPEC_V1
-__xlated_unpriv("r1 = *(u64 *)(r6 +8)")
-__xlated_unpriv("nospec")
-__xlated_unpriv("...")
-__xlated_unpriv("if r1 > 0x7 goto")
-#endif
-__naked void in_front_of_guard(void)
-{
-	ASM(START
-"1:	r1 = r6;"
-	NEVER("2f")
-	"r1 = *(u64 *)(r6 + 8);"
-"2:	if r1 > 7 goto 1b;"
-	"r0 = 0;"
-	"exit;");
-}
-
-static __naked __noinline __used int recurse(void)
-{
-	ASM(START
-	"r8 = r1;"
-	"if r8 == 0 goto 2f;"
-	"r9 = r7;"
-	"r9 &= 1;"
-	"if r9 == 0 goto 1f;"
-	"call bpf_rcu_read_lock;"
-"1:	r1 = r8;"
-	"r1 += -1;"
-	"call recurse;"
-	"if r9 == 0 goto 2f;"
-	"call bpf_rcu_read_unlock;"
-"2:	r0 = 0;"
-	"exit;");
-}
-
-SEC("tc")
-__description("barrier: a speculative state holds more in a recursion")
-__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)
-{
-	ASM(START
-	"call bpf_rcu_read_lock;"
-	NEVER("1f")
-	"call bpf_rcu_read_unlock;"
-"1:	r1 = 1;"
-	"call recurse;"
-	"r0 = 0;"
-	"exit;");
-}
-
 /* It releases what its caller holds */
 static __naked __noinline __used int recurse_in_frames(void)
 {
@@ -218,13 +168,14 @@ static __naked __noinline __used int recurse_in_frames(void)
  * 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.
+ * Without CAP_PERFMON there is no pad, and no way out of a recursion that is too deep.
  */
 SEC("tc")
-__description("barrier: at the call of a recursion in the frames of the callers")
+__description("a recursion needs CAP_PERFMON")
 __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")
+__failure_unpriv
+__msg_unpriv("landing pad of recursion check at 6: conflict: the program is loaded without CAP_PERFMON")
 __naked void recursion_in_frames(void)
 {
 	ASM("call bpf_rcu_read_lock;"
diff --git a/tools/testing/selftests/bpf/progs/verifier_budget.c b/tools/testing/selftests/bpf/progs/verifier_budget.c
index a6e1cd22f35b..7f6bb13b5d16 100644
--- a/tools/testing/selftests/bpf/progs/verifier_budget.c
+++ b/tools/testing/selftests/bpf/progs/verifier_budget.c
@@ -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")
diff --git a/tools/testing/selftests/bpf/progs/verifier_loop_walk.c b/tools/testing/selftests/bpf/progs/verifier_loop_walk.c
index cd834d776d8a..0327597a902d 100644
--- a/tools/testing/selftests/bpf/progs/verifier_loop_walk.c
+++ b/tools/testing/selftests/bpf/progs/verifier_loop_walk.c
@@ -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)
 {
diff --git a/tools/testing/selftests/bpf/progs/verifier_passes.c b/tools/testing/selftests/bpf/progs/verifier_passes.c
index 523931868e65..708e35fcceb4 100644
--- a/tools/testing/selftests/bpf/progs/verifier_passes.c
+++ b/tools/testing/selftests/bpf/progs/verifier_passes.c
@@ -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")
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 23/73] bpf: Record why a callee is cancelled when its call gets no landing pad
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (21 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 22/73] bpf: Let a may_goto that the verifier adds go to its landing pad only Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:26   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 24/73] bpf: Record what each call acquires and releases Kumar Kartikeya Dwivedi
                   ` (49 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index f548d38d8708..76e5a2db3f06 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
 
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 464e26a67819..5c0973e2e241 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -1471,6 +1471,158 @@ bool bpf_pads_conflict(const struct bpf_insn_aux_data *aux)
 	return false;
 }
 
+static bool loop_is_in(struct bpf_verifier_env *env, int l, int h)
+{
+	return l == h || bpf_is_nested_loop(env, l, h);
+}
+
+/*
+ * Is @n a conditional jump that leaves the loop @h? Unlike bpf_insn_leaves_loop(), this counts a
+ * jump in a loop inside @h: a loop can have its only exit there.
+ */
+static bool jump_leaves_loop(struct bpf_verifier_env *env, int h, int n)
+{
+	const struct bpf_insn *insn = &env->prog->insnsi[n];
+
+	if (!bpf_insn_is_cond_jump(insn->code) || BPF_OP(insn->code) == BPF_JCOND ||
+	    !loop_is_in(env, bpf_loop_at_index(env, n), h))
+		return false;
+	return !loop_is_in(env, bpf_loop_at_index(env, n + insn->off + 1), h) ||
+	       !loop_is_in(env, bpf_loop_at_index(env, n + 1), h);
+}
+
+/*
+ * The landing pad of the call of @plan has a conflict, and that is an error: what the call calls
+ * is unwound. Where that is at may_goto that the verifier adds, it depends on the
+ * values that got to the loop: may_goto is there because a state went around without a trip
+ * count. A function is verified for its calls together, and two calls of which each has a trip
+ * count can make such a state between them:
+ *
+ *	static long count(long step, long end)		count(1, 1000000);
+ *	{						count(-1, -999993);
+ *		long i = 0;
+ *		do i += step; while (i != end);
+ *		return i;
+ *	}
+ *
+ * Kept apart, neither call is cancelled. The calls do not say what to keep apart, because their
+ * arguments are constants, so the causes are recorded in the callee.
+ */
+static void note_causes(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+{
+	struct bpf_subprog_info *sub = env->subprog_info;
+	int s;
+
+	if (plan->kind != BPF_SITE_CALL)
+		return;
+	bpf_pad_for_each_callee(plan, s)
+		sub[s].below_conflict = true;
+}
+
+/*
+ * Record the causes of the errors of the pass in the functions that note_causes() and
+ * note_entered() marked, and in the functions that were cancelled below them: the calls, accesses
+ * to arena and may_gotos of the program at which a function is cancelled, and the conditional jumps
+ * that leave a loop which has a may_goto of the verifier. One walk serves all errors.
+ */
+static void note_causes_below(struct bpf_verifier_env *env)
+{
+	const struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	struct bpf_subprog_info *sub = env->subprog_info;
+	int i, n, h, s, c, top = 0, cnt = env->subprog_cnt;
+	const struct bpf_pad_plan *below;
+	bool guards;
+	int *stack;
+
+	for (s = 0; s < cnt && !sub[s].below_conflict; s++)
+		;
+	if (s == cnt)
+		return;
+	/* a function is pushed once, when it gets its mark */
+	stack = kvmalloc_array(cnt, sizeof(*stack), BPF_VERIFIER_GFP);
+	if (!stack) {
+		env->no_mem = true;
+		return;
+	}
+	for (; s < cnt; s++)
+		if (sub[s].below_conflict)
+			stack[top++] = s;
+	while (top) {
+		s = stack[--top];
+		/*
+		 * A signal ends the walk. The budget of the pass does not: the pass that has the
+		 * error can be over it already, and the next passes need the causes all the same.
+		 */
+		bpf_add_cost(env, sub[s + 1].start - sub[s].start, BPF_COST_SCAN);
+		env->aborted |= bpf_must_abort();
+		if (env->aborted)
+			break;
+		for (i = sub[s].start; i < sub[s + 1].start; i++) {
+			for (below = aux[i].pad_plans; below; below = below->next) {
+				if (below->kind != BPF_SITE_CALL || !below->visited)
+					continue;
+				/*
+				 * The frame is left at this call, whatever what it calls
+				 * was left at: the check of a recursion is no insn to
+				 * note. The jumps that can skip the call are a cause.
+				 */
+				bpf_note_controlled_cause(env, i);
+				bpf_pad_for_each_callee(below, c) {
+					if (sub[c].below_conflict)
+						continue;
+					sub[c].below_conflict = true;
+					stack[top++] = c;
+				}
+			}
+		}
+	}
+	kvfree(stack);
+	for (s = 0; s < cnt; s++) {
+		guards = false;
+		for (i = sub[s].start; sub[s].below_conflict && i < sub[s + 1].start; i++) {
+			if (!aux[i].loop_guard || bpf_flow_guard_is_guess(env, i))
+				continue;
+			h = bpf_loop_at_index(env, i);
+			aux[h].loop->guard_is_cause = guards = true;
+		}
+		if (!guards)
+			continue;
+		/* a jump is asked about the marked loops that it is in: LOOP_STACK_SIZE at most */
+		bpf_add_cost(env, sub[s + 1].start - sub[s].start, BPF_COST_SCAN);
+		for (n = sub[s].start; n < sub[s + 1].start; n++) {
+			for (h = bpf_loop_at_index(env, n); h >= 0; h = aux[h].loop_header) {
+				if (!aux[h].loop->guard_is_cause || !jump_leaves_loop(env, h, n))
+					continue;
+				bpf_note_unproven_cause(env, n);
+				break;
+			}
+		}
+		for (n = sub[s].start; n < sub[s + 1].start; n++)
+			if (aux[n].loop)
+				aux[n].loop->guard_is_cause = false;
+	}
+}
+
+/*
+ * The pass is over and has an error. Note the causes of the conflicts that are one: those that a
+ * state made an error where it visited, see unwind_frame(), and those that bpf_pads_settle() found.
+ */
+void bpf_pads_note_causes(struct bpf_verifier_env *env)
+{
+	const struct bpf_pad_plan *plan;
+	int i, s;
+
+	for (s = 0; s < env->subprog_cnt; s++)
+		env->subprog_info[s].below_conflict = false;
+	for (i = 0; i < env->prog->len; i++)
+		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next)
+			if (plan->failed || (plan->used && plan->conflict))
+				note_causes(env, plan);
+	note_causes_below(env);
+	/* The caller checks the limits before the next pass. This is for a load that ends here. */
+	bpf_check_limits(env);
+}
+
 /* The plans of the sites that the program has */
 void bpf_pads_log(struct bpf_verifier_env *env)
 {
diff --git a/kernel/bpf/precision.c b/kernel/bpf/precision.c
index 75e4e25ec7db..2576ba62da5d 100644
--- a/kernel/bpf/precision.c
+++ b/kernel/bpf/precision.c
@@ -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)
 {
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 074a5fa4cf13..5636d74dbe0d 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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;
 }
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 24/73] bpf: Record what each call acquires and releases
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (22 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 23/73] bpf: Record why a callee is cancelled when its call gets no landing pad Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:31   ` sashiko-bot
  2026-12-01  4:38 ` [PATCH bpf-next v1 25/73] bpf: Add hidden stack slots for landing pads Kumar Kartikeya Dwivedi
                   ` (48 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 76e5a2db3f06..cbfaba7e7628 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 97a885c077ee..ad9b63289d83 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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;
 	}
 }
 
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 5c0973e2e241..657f17f2aaab 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -367,44 +367,55 @@ void bpf_pad_plans_free(struct bpf_insn_aux_data *aux)
 /* A pass or a path-sensitive run begins */
 void bpf_pads_new_round(struct bpf_verifier_env *env)
 {
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	int i;
 
 	env->pads_late = false;
-	for (i = 0; i < env->prog->len; i++)
-		bpf_pad_plans_free(&env->insn_aux_data[i]);
+	for (i = 0; i < env->prog->len; i++, aux++) {
+		bpf_pad_plans_free(aux);
+		kfree(aux->pad_note);
+		aux->pad_note = NULL;
+	}
 }
 
 /*
- * The plans are what a pass found, like the fixups of the insns, and a pass that is kept can
- * become the result when a later one has an error. So the plans move with the snapshot of the
- * pass, see copy_snapshot(): to @plans, which has an entry per insn, if @save, else back from
- * there. What was at the destination is freed, and the source has no plans after that.
+ * The records and the notes are results of a pass, so they move with the snapshot of the pass, see
+ * copy_snapshot(): to @moved, which has an element per insn, if @save, and back otherwise. What was
+ * at the destination is freed.
  */
-void bpf_pads_move(struct bpf_verifier_env *env, struct bpf_pad_plan **plans, bool save)
+void bpf_pads_move(struct bpf_verifier_env *env, struct bpf_pads_moved *moved, bool save)
 {
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	int i;
 
-	for (i = 0; i < env->prog->len; i++, aux++) {
+	for (i = 0; i < env->prog->len; i++, aux++, moved++) {
 		if (save) {
-			free_plans(plans[i]);
-			plans[i] = aux->pad_plans;
+			free_plans(moved->plans);
+			kfree(moved->note);
+			moved->plans = aux->pad_plans;
+			moved->note = aux->pad_note;
 			aux->pad_plans = NULL;
+			aux->pad_note = NULL;
 		} else {
 			free_plans(aux->pad_plans);
-			aux->pad_plans = plans[i];
-			plans[i] = NULL;
+			kfree(aux->pad_note);
+			aux->pad_plans = moved->plans;
+			aux->pad_note = moved->note;
+			moved->plans = NULL;
+			moved->note = NULL;
 		}
 	}
 }
 
-/* The snapshot that has @plans of @cnt insns is freed */
-void bpf_pads_free_moved(struct bpf_pad_plan **plans, u32 cnt)
+/* The snapshot that has @moved of @cnt insns is freed */
+void bpf_pads_free_moved(struct bpf_pads_moved *moved, u32 cnt)
 {
 	u32 i;
 
-	for (i = 0; i < cnt; i++)
-		free_plans(plans[i]);
+	for (i = 0; i < cnt; i++) {
+		free_plans(moved[i].plans);
+		kfree(moved[i].note);
+	}
 }
 
 /* How many sections of @class the current frame of @st has entered and not left */
@@ -1144,6 +1155,278 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 	return plan;
 }
 
+static int class_group(int class)
+{
+	if (class < BPF_PAD_NR_SECTIONS)
+		return class;
+	return class < BPF_PAD_REF ? BPF_PAD_GROUP_LOCKS : BPF_PAD_GROUP_REFS;
+}
+
+/* Returns how many of refs[@from] to refs[@to - 1] of @st are of @group */
+static int count_refs(const struct bpf_verifier_state *st, int from, int to, int group)
+{
+	int i, n = 0;
+
+	for (i = from; i < to; i++)
+		n += class_group(ref_class(&st->refs[i])) == group;
+	return n;
+}
+
+/* Returns the note of the insn, which is allocated if there is none, or NULL */
+static struct bpf_pad_note *pad_note_get(struct bpf_verifier_env *env, int insn_idx)
+{
+	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
+
+	if (!aux->pad_note)
+		aux->pad_note = kzalloc_obj(*aux->pad_note, BPF_VERIFIER_GFP);
+	return aux->pad_note;
+}
+
+/*
+ * The current insn changes a resource of @group that a caller of its frame holds, and no store in
+ * the caller can follow that. Another frame may hold the same object as well. So no function on the
+ * stack gets hidden slots for @group.
+ */
+void bpf_pad_no_slots(struct bpf_verifier_env *env, enum bpf_pad_group group)
+{
+	const struct bpf_verifier_state *st = env->cur_state;
+	int f;
+
+	for (f = 0; f <= st->curframe; f++)
+		env->subprog_info[st->frame[f]->subprogno].no_slots |= BIT(group);
+}
+
+/*
+ * Fill @ent with the release of @ref, one of refs[] of @st, through a hidden slot. The slot gets
+ * what is in @reg: the pointer that the release takes, plus a constant. @by_type: no insn of the
+ * function acquired @ref, so its type alone says what releases it. Returns false if nothing does.
+ */
+static bool slot_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
+		     const struct bpf_verifier_state *st, const struct bpf_reference_state *ref,
+		     const struct bpf_reg_state *reg, bool by_type)
+{
+	s64 off = reg->var_off.value;
+	int err = 0;
+
+	if (!tnum_is_const(reg->var_off))
+		return false;
+	memset(ent, 0, sizeof(*ent));
+	ent->ref = -1;
+	ent->class = ref_class(ref);
+	ent->nr_cands[0] = 1;
+	ent->cand[0][0] = (struct bpf_pad_place){ .loc = BPF_PLACE_SPILL, .null = true };
+	if (ent->class == BPF_PAD_RES_LOCK_IRQ)
+		ent->cand[1][ent->nr_cands[1]++] = ent->cand[0][0];
+	if (ent->class != BPF_PAD_REF) {
+		ent->release = release_call(ent->class);
+	} else if (reg->type == PTR_TO_STACK) {
+		err = obj_ent(env, ent, ref, bpf_stack_slot(st->frame[reg->frameno],
+							    -off / BPF_REG_SIZE - 1));
+	} else {
+		ent->cand[0][0].delta = off;
+		err = by_type ? type_release(env, reg, 0, &ent->release) :
+				ref_release(env, ref, reg, false, &ent->release);
+		err = err ?: ent_imm(env, ent, reg);
+		err = err ?: off != (s16)off;
+	}
+	return !err;
+}
+
+/*
+ * Record in @note that the insn at @insn_idx, in @sub, acquires @ent while the frame holds @held of
+ * the same group, with the pointer in R@src. The stores are code, so all states at the insn have to
+ * agree on them, or @sub gets no hidden slots for the group. It gets none for locks either if a
+ * frame can hold two of them at once: slots do not record the order of release.
+ */
+static void note_acquire(struct bpf_verifier_env *env, struct bpf_subprog_info *sub, int insn_idx,
+			 const struct bpf_pad_ent *ent, int src, int held)
+{
+	struct bpf_pad_note *note = pad_note_get(env, insn_idx);
+	int group = class_group(ent->class);
+
+	if (!note) {
+		sub->no_slots |= BIT(group);
+		return;
+	}
+	if (!note->acquires) {
+		note->acquires = true;
+		note->src = src;
+		note->ent = *ent;
+		note->ent.origin = insn_idx;
+	}
+	if (note->src != src || note->ent.class != ent->class || note->ent.rcu != ent->rcu ||
+	    memcmp(&note->ent.release, &ent->release, sizeof(ent->release)) ||
+	    note->ent.obj_type != ent->obj_type ||
+	    note->ent.cand[0][0].delta != ent->cand[0][0].delta ||
+	    held >= BPF_PAD_MAX_ENTS || (held && group == BPF_PAD_GROUP_LOCKS))
+		sub->no_slots |= BIT(group) | BIT(class_group(note->ent.class));
+	else
+		note->held = max_t(int, note->held, held);
+}
+
+/*
+ * The current insn acquired the youngest of refs[]. Record it for the hidden slots. @reg holds the
+ * pointer that the release takes: R0, or the argument with the address of the lock or of the object
+ * in the stack. The function gets no slots for the group if the argument is in the stack, if the
+ * reference was made from another one, which has to be released after it, or if the insn calls
+ * bpf_map_lookup_elem(), which acquires only if the map has sockets.
+ */
+void bpf_pad_note_acquire(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
+{
+	const struct bpf_insn *insn = &env->prog->insnsi[env->insn_idx];
+	const struct bpf_verifier_state *st = env->cur_state;
+	const struct bpf_func_state *frame = st->frame[st->curframe];
+	const struct bpf_reference_state *ref = &st->refs[st->acquired_refs - 1];
+	struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
+	int group = class_group(ref_class(ref));
+	struct bpf_pad_ent ent;
+
+	if (reg < &frame->regs[BPF_REG_0] || reg > &frame->regs[BPF_REG_5] ||
+	    (ref->type == REF_TYPE_PTR && ref->parent_id) ||
+	    (bpf_helper_call(insn) && insn->imm == BPF_FUNC_map_lookup_elem) ||
+	    !slot_ent(env, &ent, st, ref, reg, false) ||
+	    !can_release_under_lock(env, st, frame, &ent))
+		sub->no_slots |= BIT(group);
+	else
+		note_acquire(env, sub, env->insn_idx, &ent, reg - frame->regs,
+			     count_refs(st, frame->entry_refs, st->acquired_refs - 1, group));
+}
+
+/* If @ref is an object in the stack: its first slot, with its address in *@addr. Else NULL. */
+static const struct bpf_stack_state *find_obj(const struct bpf_verifier_state *st,
+					      const struct bpf_reference_state *ref,
+					      struct bpf_reg_state *addr)
+{
+	int f, i;
+
+	for (f = st->curframe; f >= 0 && !(ref->type & REF_TYPE_LOCK_MASK); f--) {
+		for (i = 0; i < bpf_stack_nr_slots(st->frame[f]); i++) {
+			if (!slot_is_obj(st->frame[f], i, ref))
+				continue;
+			*addr = st->frame[f]->regs[BPF_REG_FP];
+			addr->var_off = tnum_const(-(i + 1) * BPF_REG_SIZE);
+			return bpf_stack_slot(st->frame[f], i);
+		}
+	}
+	return NULL;
+}
+
+/* Record that the current insn releases a resource of @group whose pointer is R@reg - @delta */
+static void note_release(struct bpf_verifier_env *env, struct bpf_subprog_info *sub, int group,
+			 int reg, int delta)
+{
+	struct bpf_pad_note *note = pad_note_get(env, env->insn_idx);
+
+	if (!note) {
+		sub->no_slots |= BIT(group);
+		return;
+	}
+	if (!note->releases) {
+		note->releases = true;
+		note->group = group;
+		note->reg = reg;
+		note->delta = delta;
+	}
+	if (note->group != group || note->reg != reg || note->delta != delta)
+		sub->no_slots |= BIT(group) | BIT(note->group);
+}
+
+/*
+ * The current insn releases refs[@idx] of the current state. The slot that has the handle is found
+ * at run time, by the register among R1-R5 that has it too. A register that the insn does not
+ * read may have anything in a state that was not looked at.
+ */
+void bpf_pad_note_release(struct bpf_verifier_env *env, int idx)
+{
+	const struct bpf_verifier_state *st = env->cur_state;
+	const struct bpf_func_state *frame = st->frame[st->curframe];
+	const struct bpf_reference_state *ref = &st->refs[idx];
+	struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
+	int r, nr = 0, group = class_group(ref_class(ref));
+	const struct bpf_stack_state *obj;
+	struct bpf_pad_place place = {};
+	struct bpf_reg_state addr;
+
+	if (env->pad_releases)
+		return;
+	if (idx < frame->entry_refs) {
+		bpf_pad_no_slots(env, group);
+		return;
+	}
+	obj = find_obj(st, ref, &addr);
+	/* irq flags that a lock saved are the second word of its slot */
+	if (ref->type == REF_TYPE_IRQ && obj && obj->spilled_ptr.irq.kfunc_class == IRQ_LOCK_KFUNC)
+		return;
+	for (r = BPF_REG_1; r <= BPF_REG_5 && !nr; r++)
+		if (env->insn_aux_data[env->insn_idx].live_regs_before & BIT(r))
+			add_cand(&place, &nr, &frame->regs[r], ref, obj ? &addr : NULL,
+				 BPF_PLACE_REG, r);
+	if (!nr || place.delta != (s16)place.delta)
+		sub->no_slots |= BIT(group);
+	else
+		note_release(env, sub, group, place.at, place.delta);
+}
+
+/* The current insn enters a section of @class, or leaves one. It has not changed the state yet. */
+void bpf_pad_note_section(struct bpf_verifier_env *env, enum bpf_pad_class class, bool enter)
+{
+	const struct bpf_verifier_state *st = env->cur_state;
+	struct bpf_subprog_info *sub = &env->subprog_info[st->frame[st->curframe]->subprogno];
+	struct bpf_pad_ent ent = {
+		.ref = -1,
+		.class = class,
+		.release = release_call(class),
+		.nr_cands[0] = 1,
+		.cand[0][0] = { .loc = BPF_PLACE_SPILL, .null = true },
+	};
+
+	if (enter)
+		note_acquire(env, sub, env->insn_idx, &ent, 0, frame_sections(st, class));
+	else if (frame_sections(st, class))
+		note_release(env, sub, class, 0, 0);
+	else
+		bpf_pad_no_slots(env, class_group(class));
+}
+
+/*
+ * The current frame of @st returns to the call at @call_idx in @caller, with what it acquired and
+ * did not release. @plain: with exit, and it is no callback.
+ * One pointer that is in R0 is what a kfunc returns: the call acquires it. What releases it follows
+ * from its type: states with the same pointer from different insns are the same to the main pass.
+ * The store after the call takes R0 as it is, so it has to be 0 when nothing comes with it.
+ * Nothing else has a store: it goes past the store if the frame unwinds.
+ */
+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)
+{
+	const struct bpf_func_state *callee = st->frame[st->curframe];
+	const struct bpf_reference_state *ref = &st->refs[callee->entry_refs];
+	struct bpf_subprog_info *sub = &env->subprog_info[caller->subprogno];
+	struct bpf_insn_aux_data *aux = &env->insn_aux_data[call_idx];
+	const struct bpf_reg_state *r0 = &callee->regs[BPF_REG_0];
+	int i, nr = st->acquired_refs - callee->entry_refs, in_r0 = 0;
+	struct bpf_pad_place place;
+	struct bpf_pad_ent ent;
+
+	for (i = 0; i < BPF_PAD_NR_SECTIONS; i++)
+		if (frame_sections(st, i))
+			sub->no_slots |= BIT(i);
+	if (plain && nr == 1 && ref->type == REF_TYPE_PTR && !ref->parent_id)
+		add_ref_cand(&place, &in_r0, r0, ref, BPF_PLACE_REG, BPF_REG_0);
+	if (in_r0 && slot_ent(env, &ent, st, ref, r0, true) &&
+	    can_release_under_lock(env, st, caller, &ent)) {
+		note_acquire(env, sub, call_idx, &ent, BPF_REG_0,
+			     count_refs(st, caller->entry_refs, callee->entry_refs,
+					BPF_PAD_GROUP_REFS));
+	} else {
+		for (i = 0; i < nr; i++)
+			sub->no_slots |= BIT(class_group(ref_class(&ref[i])));
+		aux->call_brings_nothing |= plain && !reg_is_null(r0);
+	}
+	if (aux->call_brings_nothing && aux->pad_note && aux->pad_note->acquires)
+		sub->no_slots |= BIT(BPF_PAD_GROUP_REFS);
+}
+
 /* Does the pad test the location of @ent for 0 before the release? */
 static bool ent_is_tested(const struct bpf_pad_ent *ent)
 {
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 5636d74dbe0d..bca2afd20ef5 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -208,7 +208,8 @@ struct bpf_verifier_stack_elem {
 #define BPF_PRIV_STACK_MIN_SIZE		64
 
 static int acquire_reference(struct bpf_verifier_env *env, int insn_idx, int parent_id);
-static int release_reference_nomark(struct bpf_verifier_state *state, int id);
+static int __release_reference_nomark(struct bpf_verifier_state *state, int id);
+static int release_reference_nomark(struct bpf_verifier_env *env, int id);
 static int release_reference(struct bpf_verifier_env *env, int id);
 static int invalidate_reference(struct bpf_verifier_env *env, int id);
 static u32 reg_lifetime_id(struct bpf_verifier_env *env,
@@ -819,6 +820,12 @@ static int mark_stack_slots_dynptr(struct bpf_verifier_env *env, struct bpf_reg_
 	mark_dynptr_stack_regs(env, &bpf_stack_slot(state, spi)->spilled_ptr,
 			       &bpf_stack_slot(state, spi - 1)->spilled_ptr, type, parent_id);
 
+	/* Either a dynptr or its clone releases their reference, so no hidden slot can track it. */
+	if (dynptr_type_referenced(type) && dynptr->type != BPF_DYNPTR_TYPE_INVALID)
+		bpf_pad_no_slots(env, BPF_PAD_GROUP_REFS);
+	else if (dynptr_type_referenced(type))
+		bpf_pad_note_acquire(env, reg);
+
 	return 0;
 }
 
@@ -1082,6 +1089,7 @@ static int mark_stack_slots_iter(struct bpf_verifier_env *env,
 
 		mark_stack_slot_scratched(env, spi - i);
 	}
+	bpf_pad_note_acquire(env, reg);
 
 	return 0;
 }
@@ -1215,6 +1223,9 @@ static int mark_stack_slot_irq_flag(struct bpf_verifier_env *env,
 		slot->slot_type[i] = STACK_IRQ_FLAG;
 
 	mark_stack_slot_scratched(env, spi);
+	/* Irq flags that bpf_res_spin_lock_irqsave() saves are recorded with the lock. */
+	if (kfunc_class == IRQ_NATIVE_KFUNC)
+		bpf_pad_note_acquire(env, reg);
 	return 0;
 }
 
@@ -1684,6 +1695,7 @@ static int release_lock_state(struct bpf_verifier_env *env, int type, int id, vo
 	for (i = 0; i < state->acquired_refs; i++) {
 		if (state->refs[i].type == type && state->refs[i].id == id &&
 		    state->refs[i].ptr == ptr) {
+			bpf_pad_note_release(env, i);
 			release_reference_state(state, i);
 			state->active_locks--;
 			/* Reassign active lock (id, ptr). */
@@ -1714,6 +1726,7 @@ static int release_irq_state(struct bpf_verifier_env *env, int id)
 		if (state->refs[i].type != REF_TYPE_IRQ)
 			continue;
 		if (state->refs[i].id == id) {
+			bpf_pad_note_release(env, i);
 			release_reference_state(state, i);
 			state->active_irq_id = prev_id;
 			bpf_diag_record_context(env, env->insn_idx, BPF_DIAG_CONTEXT_IRQ,
@@ -8505,6 +8518,7 @@ static int process_spin_lock(struct bpf_verifier_env *env, struct bpf_reg_state
 			verbose(env, "Failed to acquire lock state\n");
 			return err;
 		}
+		bpf_pad_note_acquire(env, reg);
 	} else {
 		void *ptr;
 		int type;
@@ -11123,7 +11137,7 @@ static void mark_pkt_end(struct bpf_verifier_state *vstate, int regn, bool range
 		reg->range = AT_PKT_END;
 }
 
-static int release_reference_nomark(struct bpf_verifier_state *state, int id)
+static int __release_reference_nomark(struct bpf_verifier_state *state, int id)
 {
 	int i;
 
@@ -11138,6 +11152,18 @@ static int release_reference_nomark(struct bpf_verifier_state *state, int id)
 	return -EINVAL;
 }
 
+/* The current insn releases the reference @id. Record that for the hidden slots, then drop it. */
+static int release_reference_nomark(struct bpf_verifier_env *env, int id)
+{
+	struct bpf_verifier_state *state = env->cur_state;
+	int i;
+
+	for (i = 0; i < state->acquired_refs; i++)
+		if (state->refs[i].type == REF_TYPE_PTR && state->refs[i].id == id)
+			bpf_pad_note_release(env, i);
+	return __release_reference_nomark(state, id);
+}
+
 static int idstack_push(struct bpf_idmap *idmap, u32 id)
 {
 	int i;
@@ -11234,7 +11260,7 @@ static int invalidate_reference(struct bpf_verifier_env *env, int id)
 static int release_reference(struct bpf_verifier_env *env, int id)
 {
 	if (find_reference_state(env->cur_state, id))
-		WARN_ON_ONCE(release_reference_nomark(env->cur_state, id));
+		WARN_ON_ONCE(release_reference_nomark(env, id));
 
 	return invalidate_reference(env, id);
 }
@@ -11278,7 +11304,7 @@ static int ref_convert_alloc_rcu_protected(struct bpf_verifier_env *env, u32 id)
 	struct bpf_reg_state *reg;
 	int err;
 
-	err = release_reference_nomark(env->cur_state, id);
+	err = release_reference_nomark(env, id);
 	if (err)
 		return err;
 
@@ -11944,6 +11970,7 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 		return BPF_EXIT_NEEDS_CALLER;
 	}
 
+	bpf_pad_note_return(env, exit, frame, call_idx, !exit->unwound);
 	for (i = 0; i < CALLER_SAVED_REGS; i++)
 		bpf_mark_reg_not_init(env, &frame->regs[caller_saved[i]]);
 	for (i = 0; i < frame->out_stack_arg_cnt; i++)
@@ -12659,6 +12686,8 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 			return err;
 		state->unwound = callee->in_callback_fn ? BPF_UNWOUND_CB : BPF_UNWOUND;
 	}
+	bpf_pad_note_return(env, state, caller, callee->callsite,
+			    !unwinds && !callee->in_callback_fn);
 	if (callee->in_callback_fn && !unwinds) {
 		/* the helper continues after the barrier of its call */
 		if (state->speculative)
@@ -13633,6 +13662,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 			return id;
 
 		regs[BPF_REG_0].id = id;
+		bpf_pad_note_acquire(env, &regs[BPF_REG_0]);
 	}
 
 	if (func_id == BPF_FUNC_dynptr_data)
@@ -15083,7 +15113,7 @@ static void ref_convert_owning_non_owning(struct bpf_verifier_env *env, u32 id)
 	struct bpf_reg_state *reg;
 	int err;
 
-	err = release_reference_nomark(env->cur_state, id);
+	err = release_reference_nomark(env, id);
 	WARN_ON_ONCE(err);
 
 	bpf_for_each_reg_in_vstate(env->cur_state, unused, reg, ({
@@ -16248,6 +16278,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	preempt_enable = is_kfunc_bpf_preempt_enable(&meta);
 
 	if (rcu_lock) {
+		bpf_pad_note_section(env, BPF_PAD_RCU, true);
 		env->cur_state->active_rcu_locks++;
 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, true,
 					env->cur_state->active_rcu_locks);
@@ -16259,6 +16290,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 				"Remove the extra bpf_rcu_read_unlock() call, or ensure this path first enters an RCU read lock region.");
 			return -EINVAL;
 		}
+		bpf_pad_note_section(env, BPF_PAD_RCU, false);
 		env->cur_state->active_rcu_locks--;
 		release_context_state(env->cur_state);
 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_RCU, false,
@@ -16266,6 +16298,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		if (!in_rcu_cs(env))
 			invalidate_rcu_protected_refs(env);
 	} else if (preempt_disable) {
+		bpf_pad_note_section(env, BPF_PAD_PREEMPT, true);
 		env->cur_state->active_preempt_locks++;
 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, true,
 					env->cur_state->active_preempt_locks);
@@ -16277,6 +16310,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 				"Remove the extra bpf_preempt_enable() call, or ensure this path first disables preemption.");
 			return -EINVAL;
 		}
+		bpf_pad_note_section(env, BPF_PAD_PREEMPT, false);
 		env->cur_state->active_preempt_locks--;
 		release_context_state(env->cur_state);
 		bpf_diag_record_context(env, insn_idx, BPF_DIAG_CONTEXT_PREEMPT, false,
@@ -16556,6 +16590,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 			if (id < 0)
 				return id;
 			regs[BPF_REG_0].id = id;
+			bpf_pad_note_acquire(env, &regs[BPF_REG_0]);
 		} else if (is_rbtree_node_type(ptr_type) || is_list_node_type(ptr_type)) {
 			ref_set_non_owning(env, &regs[BPF_REG_0]);
 		}
@@ -19319,7 +19354,7 @@ static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
 		 * No one could have freed the reference state before
 		 * doing the NULL check.
 		 */
-		WARN_ON_ONCE(release_reference_nomark(vstate, id));
+		WARN_ON_ONCE(__release_reference_nomark(vstate, id));
 
 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
 		mark_ptr_or_null_reg(state, reg, id, is_null);
@@ -21810,6 +21845,8 @@ static int release_frame_resources(struct bpf_verifier_env *env)
 	struct bpf_reference_state *ref;
 	int id, err;
 
+	/* The landing pad releases them, not an insn: nothing is recorded for the hidden slots. */
+	env->pad_releases = true;
 	while (st->acquired_refs > frame->entry_refs) {
 		ref = &st->refs[st->acquired_refs - 1];
 		id = ref->id;
@@ -21823,6 +21860,7 @@ static int release_frame_resources(struct bpf_verifier_env *env)
 			return -EFAULT;
 		unmark_stack_obj(env, id);
 	}
+	env->pad_releases = false;
 	/* 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);
@@ -23806,8 +23844,11 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog,
 				goto out;
 
 			aux->ctx_arg_info[i].ref_arg = ret ? i + 1 : 0;
-			if (ret)
+			if (ret) {
 				state->refs[state->acquired_refs - 1].ctx_arg = i + 1;
+				/* No insn acquires a __ref argument: no store fills a slot. */
+				bpf_pad_no_slots(env, BPF_PAD_GROUP_REFS);
+			}
 		}
 	}
 
@@ -23927,7 +23968,7 @@ struct bpf_snapshot {
 	struct bpf_env_per_pass env;
 	struct bpf_prog_aux aux;
 	struct bpf_insn_fixups *insns;
-	struct bpf_pad_plan **plans;	/* per insn, see bpf_pads_move() */
+	struct bpf_pads_moved *pads;	/* per insn, see bpf_pads_move() */
 	struct bpf_subprog_info *subprogs;
 	struct bpf_func_info_aux *funcs;
 	struct bpf_prog prog;
@@ -23959,7 +24000,7 @@ static void copy_snapshot(struct bpf_verifier_env *env, struct bpf_snapshot *sna
 	COPY_AUX(kprobe_write_ctx);
 	for (i = 0; i < env->prog->len; i++)
 		COPY(snapshot->insns[i], env->insn_aux_data[i].fixups);
-	bpf_pads_move(env, snapshot->plans, save);
+	bpf_pads_move(env, snapshot->pads, save);
 	for (i = 0, sub = env->subprog_info; i < env->subprog_cnt; i++, sub++) {
 		/* the sum over all passes */
 		snapshot->subprogs[i].insns_total = sub->insns_total;
@@ -23977,21 +24018,21 @@ static struct bpf_snapshot *save_snapshot(struct bpf_verifier_env *env,
 					  struct bpf_snapshot *snapshot)
 {
 	size_t insns = array_size(env->prog->len, sizeof(*snapshot->insns));
-	size_t plans = array_size(env->prog->len, sizeof(*snapshot->plans));
+	size_t pads = array_size(env->prog->len, sizeof(*snapshot->pads));
 	size_t subprogs = env->subprog_cnt * sizeof(*snapshot->subprogs);
 
 	if (!snapshot) {
 		snapshot = kvmalloc(size_add(sizeof(*snapshot) + subprogs +
 					     env->prog->aux->func_info_cnt *
-					     sizeof(*snapshot->funcs), size_add(insns, plans)),
+					     sizeof(*snapshot->funcs), size_add(insns, pads)),
 				    BPF_VERIFIER_GFP);
 		if (!snapshot)
 			return NULL;
-		env->mem += insns + plans + subprogs;
+		env->mem += insns + pads + subprogs;
 		snapshot->insns = (void *)(snapshot + 1);
-		snapshot->plans = (void *)snapshot->insns + insns;
-		memset(snapshot->plans, 0, plans);
-		snapshot->subprogs = (void *)snapshot->plans + plans;
+		snapshot->pads = (void *)snapshot->insns + insns;
+		memset(snapshot->pads, 0, pads);
+		snapshot->subprogs = (void *)snapshot->pads + pads;
 		snapshot->funcs = (void *)snapshot->subprogs + subprogs;
 	}
 	copy_snapshot(env, snapshot, true);
@@ -24002,7 +24043,7 @@ static void free_snapshot(struct bpf_verifier_env *env, struct bpf_snapshot *sna
 {
 	if (!snapshot)
 		return;
-	bpf_pads_free_moved(snapshot->plans, env->prog->len);
+	bpf_pads_free_moved(snapshot->pads, env->prog->len);
 	kvfree(snapshot);
 }
 
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 25/73] bpf: Add hidden stack slots for landing pads
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (23 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 24/73] bpf: Record what each call acquires and releases Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:40   ` sashiko-bot
  2026-12-01  5:42   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 26/73] bpf: Use hidden slots for a pointer that has no location at a site Kumar Kartikeya Dwivedi
                   ` (47 subsequent siblings)
  72 siblings, 2 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index cbfaba7e7628..7027734c315e 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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,
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index ad9b63289d83..46ff571ef76e 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -767,10 +767,70 @@ static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added)
 	return bpf_patch_list_commit(env);
 }
 
+/*
+ * Add the stores that keep the hidden slots up to date, see kernel/bpf/pads.c. @buf has room for
+ * BPF_PAD_MAX_SLOT_INSNS. @added is the number of insns that were appended to each subprog.
+ *
+ *	stores			at the entry: inserted before the first insn, so a jump back to
+ *	first insn		that insn skips them
+ *	...
+ *	stores			before a call: they replace the call together with it, so a
+ *	call foo		jump to the call runs them
+ *	unwind_goto pad		the program's, or added later
+ *	stores			after a call: appended, so a jump to the next insn skips them.
+ *				A frame that is cancelled in the call does not run them.
+ *
+ * The stores at the entry follow the insn that takes the frame in the stack in arena, which
+ * bpf_insert_recursion_checks() expects to be the first insn.
+ */
+static int insert_slot_stores(struct bpf_verifier_env *env, struct bpf_insn *buf, const int *added)
+{
+	const struct bpf_pad_note *notes[BPF_PAD_MAX_ENTS];
+	const struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	const struct bpf_subprog_info *sub;
+	const struct bpf_insn *insn, *last;
+	int i, s, n, nr, call, entry, err;
+
+	for (s = 0; s < env->subprog_cnt; s++) {
+		sub = &env->subprog_info[s];
+		if (!sub->slots || !added[s])
+			continue;
+		nr = bpf_pad_slot_notes(env, s, notes);
+		if (nr < 0)
+			return nr;
+		entry = sub->start + is_arena_sp_adj(&env->prog->insnsi[sub->start]);
+		for (i = sub->start; i < sub[1].start; i++) {
+			insn = &env->prog->insnsi[i];
+			/* the patches are queued in the order of the insns */
+			n = 0;
+			if (i == entry && i > sub->start)
+				n = bpf_pad_entry_insns(notes, nr, 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]);
+			err = n ? bpf_patch_list_append(env, i - 1, buf, n) : 0;
+			if (err)
+				return err;
+			n = bpf_pad_insns_before(sub, notes, nr, aux[i].pad_note, buf);
+			buf[n] = *insn;
+			last = n ? bpf_patch_list_add(env, i, buf, n + 1) : NULL;
+			if (IS_ERR(last))
+				return PTR_ERR(last);
+			n = i == entry && i == sub->start ? bpf_pad_entry_insns(notes, nr, buf) : 0;
+			err = n ? bpf_patch_list_insert(env, i, buf, n) : 0;
+			if (err)
+				return err;
+		}
+	}
+	return bpf_patch_list_commit(env);
+}
+
 /*
  * Emit what the main pass decided about the sites: may_goto before the insns that it
- * marked, see check_loop_guard(), unwind_goto after calls, and the landing pads. What a pad does it
- * did to the states that left the frame at the site, see unwind_frame().
+ * marked, see check_loop_guard(), unwind_goto after calls, the landing pads, and the stores to the
+ * hidden slots that the pads read. What a pad does it did to the states that left the frame at the
+ * site, see unwind_frame().
  *
  *	may_goto pad		before an insn of a loop, see check_loop_guard(). A may_goto
  *	insn			of the program that is a site jumps to its pad too.
@@ -799,7 +859,8 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 
 	/* how many insns the pads after the subprog have */
 	added = kvzalloc_objs(int, env->subprog_cnt, BPF_VERIFIER_GFP);
-	new = kvzalloc_objs(*new, BPF_PAD_MAX_INSNS + 1, BPF_VERIFIER_GFP);
+	new = kvzalloc_objs(*new, max(BPF_PAD_MAX_INSNS + 1, BPF_PAD_MAX_SLOT_INSNS),
+			    BPF_VERIFIER_GFP);
 	pad_aux = kvzalloc_objs(*pad_aux, BPF_PAD_MAX_INSNS + 1, BPF_VERIFIER_GFP);
 	if (!added || !new || !pad_aux) {
 		err = -ENOMEM;
@@ -851,7 +912,8 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 					emit_pad(env, s, plan, new,
 						 &aux[sub[1].start - added[s] + plan->pad]);
 	}
-	err = insert_unwind_gotos(env, added);
+	err = insert_slot_stores(env, new, added);
+	err = err ?: insert_unwind_gotos(env, added);
 out:
 	kvfree(added);
 	kvfree(new);
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 657f17f2aaab..a9a2b56364ab 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -50,7 +50,36 @@
  * All states at a site have to share a location for each release, and the pad has to know whether
  * the resource is held. If all states hold it, the pad releases it without a test. If a location is
  * 0 in all states that do not hold it, the pad tests the location first, as a program tests a
- * pointer for NULL before it releases it. Otherwise the verifier cannot generate the pad.
+ * pointer for NULL before it releases it. Otherwise the function gets 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 reaches. Stores on the normal path record in the slot what the frame holds,
+ * and the pad releases what it finds there. Here only the program knows what 'own' means, and
+ * wait() can be cancelled:
+ *
+ *	t = bpf_task_from_pid(pid);		   +	   *(u64 *)(r10 - 8) = 0
+ *	own = !!t;					   call bpf_task_from_pid
+ *	if (!t)					   +	   *(u64 *)(r10 - 8) = r0
+ *		t = bpf_get_current_task_btf();		   ...
+ *	v = wait(t);					   call wait
+ *	if (own)				   +	   unwind_goto pad
+ *		bpf_task_release(t);			   ...
+ *						   +	   ax = *(u64 *)(r10 - 8)
+ *						   +	   if ax != r1 goto +1
+ *						   +	   *(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, and a release finds its slot by comparing at run
+ * time. The stores follow from what the main pass records at each call (struct bpf_pad_note), see
+ * bpf_pad_note_acquire(). They never follow from the states at a site, because the verifier does
+ * not compare which insn acquired a reference when it merges two states. Slots go by group (enum
+ * bpf_pad_group): RCU sections, preempt sections, locks and irq flags, references. A function gets
+ * slots for a group only if one of its sites cannot do without them, see settle_slots(). All its
+ * pads then release that group through the slots alone.
  *
  * The frames of a program are cancelled one at a time. The pad of a function that the program calls
  * ends in unwind_exit. That returns to the unwind_goto after the call, which leads to the pad of
@@ -1122,7 +1151,7 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
  * says why the pad cannot be generated, or an ERR_PTR().
  *
  * Sections: the pad leaves as many as the frame has entered. That is a number of calls in the
- * code of the pad, so it has to be the same on all visits.
+ * code of the pad, so it has to be the same on all visits, or the function gets hidden slots.
  *
  * Returns the plan. It tells whether there is a conflict.
  */
@@ -1148,7 +1177,7 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 		if (nr > BPF_PAD_MAX_SECTIONS)
 			plan->conflict = BPF_CONFLICT_TOO_MUCH;
 		else if (plan->visited && plan->sections[class] != nr)
-			plan->conflict = BPF_CONFLICT_SECTIONS_DIFFER;
+			plan->sections_differ |= BIT(class);
 		plan->sections[class] = nr;
 	}
 	plan->visited = true;
@@ -1586,6 +1615,8 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 	struct bpf_insn release;
 	int i, class, err = plan->conflict;
 
+	if (!err && plan->sections_differ)
+		err = BPF_CONFLICT_SECTIONS_DIFFER;
 	for (i = 0; !err && i < plan->nr_ents; i++)
 		err = settle_ent(env, plan, &plan->ents[i]);
 	for (class = 0; !err && class < BPF_PAD_NR_SECTIONS; class++) {
@@ -1596,6 +1627,320 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 	return err;
 }
 
+/*
+ * The groups of which @plan has something that its pad cannot tell whether it is held. None for a
+ * site that the program does not have.
+ */
+static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+{
+	u8 groups = plan->sections_differ;
+	int i, err;
+
+	if (!plan->used || plan->conflict)
+		return 0;
+	for (i = 0; i < plan->nr_ents; i++) {
+		err = settle_ent(env, plan, &plan->ents[i]);
+		if (err == BPF_CONFLICT_NOT_ALWAYS_HELD || err == BPF_CONFLICT_CALLER_SAVED)
+			groups |= BIT(class_group(plan->ents[i].class));
+	}
+	return groups;
+}
+
+/* The slot of bpf_res_spin_lock_irqsave() has a second word, for the irq flags */
+static int slot_words(const struct bpf_pad_note *note)
+{
+	return note->ent.class == BPF_PAD_RES_LOCK_IRQ ? 2 : 1;
+}
+
+/* Does the pad of @plan run in a frame that has set up its hidden slots? */
+static bool plan_has_slots(const struct bpf_pad_plan *plan)
+{
+	return plan->kind != BPF_SITE_RECURSION && !plan->conflict;
+}
+
+/*
+ * The pad of @plan releases what the frame holds of @group through the hidden slots of the @nr
+ * calls @notes and in no other way. A slot is an entry that is tested. For the order of a pad, see
+ * enum pad_turn, the slots of sections go before all entries, those of references after
+ * them, those of locks and irq flags after all entries.
+ */
+static int plan_take_slots(struct bpf_pad_plan *plan, int group, struct bpf_pad_note **notes,
+			   int nr)
+{
+	struct bpf_pad_ent new, *ent;
+	int i, k, pos = 0;
+
+	for (i = 0, k = 0; i < plan->nr_ents; i++)
+		if (class_group(plan->ents[i].class) != group)
+			plan->ents[k++] = plan->ents[i];
+	plan->nr_ents = k;
+	if (group < BPF_PAD_NR_SECTIONS) {
+		plan->sections[group] = 0;
+		plan->sections_differ &= ~BIT(group);
+	}
+	if (group == BPF_PAD_GROUP_LOCKS)
+		pos = plan->nr_ents;
+	while (group == BPF_PAD_GROUP_REFS && pos < plan->nr_ents &&
+	       plan->ents[pos].class < BPF_PAD_NR_SECTIONS)
+		pos++;
+	for (i = 0; i < nr; i++) {
+		for (k = 0; k < notes[i]->nr_slots; k++) {
+			new = notes[i]->ent;
+			new.cand[0][0].at = notes[i]->off - k * BPF_REG_SIZE;
+			if (slot_words(notes[i]) == 2)
+				new.cand[1][0].at = notes[i]->off - BPF_REG_SIZE;
+			ent = add_ent(plan, &new, pos++);
+			if (!ent)
+				return -ENOMEM;
+			ent->always = false;
+			ent->cand[0][0].null = true;
+		}
+	}
+	return 0;
+}
+
+/*
+ * Give subprog @s hidden slots for all that it acquires of @group. A call outside of a loop gets
+ * one slot. A call in a loop can run again while the frame holds what it acquired before, so it
+ * gets one slot more than the frame holds of the group when it gets there. Returns 1, 0 if the
+ * subprog cannot have the slots, or a negative errno.
+ */
+static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
+{
+	struct bpf_subprog_info *sub = &env->subprog_info[s];
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	struct bpf_pad_note *note, *notes[BPF_PAD_MAX_ENTS];
+	int i, j, err, left, nr = 0, slots = 0, words = 0;
+	struct bpf_pad_plan *plan;
+
+	for (i = sub->start; i < sub[1].start; i++) {
+		note = aux[i].pad_note;
+		if (!note || !note->acquires || class_group(note->ent.class) != group)
+			continue;
+		err = nr < BPF_PAD_MAX_ENTS ? get_release(env, &note->ent.release) : 1;
+		if (err)
+			return min(err, 0);
+		notes[nr++] = note;
+		note->nr_slots = bpf_loop_at_index(env, i) < 0 ? 1 : 1 + note->held;
+		note->off = -(int)bpf_stack_depth_with_slots(sub) - (words + 1) * BPF_REG_SIZE;
+		slots += note->nr_slots;
+		words += note->nr_slots * slot_words(note);
+	}
+	if (!nr)
+		return 0;
+	for (i = sub->start; i < sub[1].start; i++) {
+		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
+			for (j = 0, left = 0; j < plan->nr_ents; j++)
+				left += class_group(plan->ents[j].class) != group;
+			if (plan->used && plan_has_slots(plan) &&
+			    left + slots > BPF_PAD_MAX_ENTS)
+				return 0;
+		}
+	}
+	sub->hidden_words += words;
+	err = bpf_hidden_slots_fit(env);
+	if (err <= 0) {
+		sub->hidden_words -= words;
+		return err;
+	}
+	for (i = sub->start; i < sub[1].start; i++) {
+		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
+			err = plan_has_slots(plan) ? plan_take_slots(plan, group, notes, nr) : 0;
+			if (err)
+				return err;
+		}
+	}
+	sub->slots |= BIT(group);
+	return 1;
+}
+
+/*
+ * Hidden slots are the fallback: a subprog gets them for the groups that one of its sites needs
+ * them for, see plan_needs_slots(). The release of a slot can become the first call of a pad, which
+ * is the only call that R0-R5 serve, so ask again after each group. A subprog that cannot have the
+ * slots keeps its records as they are.
+ */
+static int settle_slots(struct bpf_verifier_env *env)
+{
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	struct bpf_subprog_info *sub;
+	struct bpf_pad_plan *plan;
+	int i, s, err;
+	u8 need;
+
+	for (s = 0; s < env->subprog_cnt; s++) {
+		env->subprog_info[s].slots = 0;
+		env->subprog_info[s].hidden_words = 0;
+	}
+	for (s = 0; s < env->subprog_cnt; s++) {
+		sub = &env->subprog_info[s];
+		do {
+			if (bpf_must_abort())
+				return -EINTR;
+			need = 0;
+			for (i = sub->start; i < sub[1].start; i++)
+				for (plan = aux[i].pad_plans; plan; plan = plan->next)
+					need |= plan_needs_slots(env, plan);
+			need &= ~sub->no_slots;
+			err = need ? subprog_take_slots(env, s, __ffs(need)) : 0;
+			if (err < 0)
+				return err;
+			if (need && !err)
+				sub->no_slots |= BIT(__ffs(need));
+		} while (need);
+	}
+	return 0;
+}
+
+static bool note_has_slots(const struct bpf_subprog_info *sub, const struct bpf_pad_note *note)
+{
+	return note && note->acquires && (sub->slots & BIT(class_group(note->ent.class)));
+}
+
+/*
+ * The calls of subprog @s that have hidden slots go to @notes, which has room for BPF_PAD_MAX_ENTS.
+ * A slot is an entry of each plan of the subprog, so all groups together have no more slots than
+ * that, see plan_has_room(), and the insns of the stores are sized for as many, see
+ * BPF_PAD_MAX_SLOT_INSNS. Nothing else keeps the calls that few: check it where they are written.
+ * Returns how many there are.
+ */
+int bpf_pad_slot_notes(struct bpf_verifier_env *env, int s, const struct bpf_pad_note **notes)
+{
+	const struct bpf_subprog_info *sub = &env->subprog_info[s];
+	const struct bpf_pad_note *note;
+	int i, nr = 0, slots = 0;
+
+	for (i = sub->start; i < sub[1].start; i++) {
+		note = env->insn_aux_data[i].pad_note;
+		if (!note_has_slots(sub, note))
+			continue;
+		slots += note->nr_slots;
+		if (verifier_bug_if(slots > BPF_PAD_MAX_ENTS, env,
+				    "func#%d has %d hidden slots, a landing pad has %d entries",
+				    s, slots, BPF_PAD_MAX_ENTS))
+			return -EFAULT;
+		notes[nr++] = note;
+	}
+	return nr;
+}
+
+/*
+ * The entry of a function: all words of its hidden slots are 0. The frame holds nothing of its own,
+ * and a pad reads all slots, also at a site that is before the calls that fill them.
+ */
+int bpf_pad_entry_insns(const struct bpf_pad_note **notes, int nr, struct bpf_insn *buf)
+{
+	int i, k, n = 0;
+
+	for (i = 0; i < nr; i++)
+		for (k = 0; k < notes[i]->nr_slots * slot_words(notes[i]); k++)
+			buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, notes[i]->off - k * BPF_REG_SIZE,
+					      0);
+	return n;
+}
+
+/*
+ * The call of @note acquires: a slot takes what the release takes, unconditionally. 0 in R0 means
+ * that nothing was acquired, and 0 in a slot means the same. A section has no handle: 1.
+ * If the call has several slots the first one that is 0 is filled. The frame holds no more than
+ * 'held' of the group, so there is one.
+ */
+static int set_insns(const struct bpf_pad_note *note, struct bpf_insn *buf)
+{
+	int k, n = 0, nr = note->nr_slots, off = note->off;
+
+	for (k = 0; k < nr; k++, off -= BPF_REG_SIZE) {
+		if (nr > 1) {
+			buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_FP, off);
+			buf[n++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, k == nr - 1 ? 1 : 2);
+		}
+		if (note->ent.class < BPF_PAD_NR_SECTIONS)
+			buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, off, 1);
+		else
+			buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, note->src, off);
+		if (k < nr - 1)
+			buf[n++] = BPF_JMP_A((nr - 1 - k) * 4 - 1);
+	}
+	/* the irq flags, the next argument: the pad reads the word if the slot is not 0 */
+	if (slot_words(note) == 2)
+		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, note->src + 1, off);
+	return n;
+}
+
+/*
+ * The call of @rel releases: the slot of the group that has the handle is cleared, whichever call
+ * filled it in this run. The first match ends the search: two references to one object are the
+ * same handle in two slots, and one of them is released. No match: the call was given NULL.
+ * Sections are all alike: the first slot that is not 0.
+ */
+static int clear_insns(const struct bpf_pad_note **notes, int nr, const struct bpf_pad_note *rel,
+		       struct bpf_insn *buf)
+{
+	int i, k, n = 0, off, delta, reg;
+
+	for (i = 0; i < nr; i++) {
+		if (class_group(notes[i]->ent.class) != rel->group)
+			continue;
+		delta = rel->delta - notes[i]->ent.cand[0][0].delta;
+		/*
+		 * The delta is made of constants that the program chose, the offsets of a node in
+		 * its object. It is added in R0, which a call is about to clobber: there the JIT
+		 * blinds it like any other constant of the program. An insn on AX is not blinded.
+		 */
+		reg = delta ? BPF_REG_0 : BPF_REG_AX;
+		for (k = 0; k < notes[i]->nr_slots; k++) {
+			off = notes[i]->off - k * BPF_REG_SIZE;
+			buf[n++] = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_FP, off);
+			if (delta)
+				buf[n++] = BPF_ALU64_IMM(BPF_ADD, reg, delta);
+			if (rel->group < BPF_PAD_NR_SECTIONS)
+				buf[n++] = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);
+			else
+				buf[n++] = BPF_JMP_REG(BPF_JNE, reg, rel->reg, 2);
+			buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, off, 0);
+			buf[n++] = BPF_JMP_A(0);
+		}
+	}
+	/* nothing follows the last slot */
+	buf[--n - 2].off = 1;
+	for (i = 0; i < n; i++)
+		if (buf[i].code == (BPF_JMP | BPF_JA))
+			buf[i].off = n - i - 1;
+	return n;
+}
+
+/* The insns that go before the call of @note in @sub. @notes: the @nr calls with slots. */
+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 n = 0;
+
+	if (note && note->releases && (sub->slots & BIT(note->group)))
+		n = clear_insns(notes, nr, note, buf);
+	/* an address that the call takes. The resource is held when the call returns. */
+	if (note_has_slots(sub, note) && note->ent.class != BPF_PAD_REF)
+		n += set_insns(note, &buf[n]);
+	return n;
+}
+
+/* The insns that go after the call of @note, which is in @sub */
+int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad_note *note,
+			struct bpf_insn *buf)
+{
+	int n = 0;
+
+	if (!note_has_slots(sub, note))
+		return 0;
+	if (note->ent.class == BPF_PAD_REF)
+		return set_insns(note, buf);
+	/* the lock was not taken. The upper half of an int is not defined. */
+	if (note->ent.class == BPF_PAD_RES_LOCK || note->ent.class == BPF_PAD_RES_LOCK_IRQ) {
+		buf[n++] = BPF_JMP32_IMM(BPF_JEQ, BPF_REG_0, 0, 1);
+		buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, note->off, 0);
+	}
+	return n;
+}
+
 /*
  * Sites whose pads have the same insns share one pad. A pad that frees an object of the program is
  * not shared: the same insns free another type at another site, see ent_imm().
@@ -1617,6 +1962,8 @@ bool bpf_pad_can_be_shared(const struct bpf_pad_plan *plan)
 static void print_ent(struct bpf_verifier_env *env, const struct bpf_pad_ent *ent)
 {
 	static const char * const class[] = {
+		[BPF_PAD_RCU]			= "rcu",
+		[BPF_PAD_PREEMPT]		= "preempt",
 		[BPF_PAD_IRQ]			= "irq",
 		[BPF_PAD_RES_LOCK]		= "res_lock",
 		[BPF_PAD_RES_LOCK_IRQ]		= "res_lock_irq",
@@ -1713,10 +2060,11 @@ void bpf_pads_mark_used(struct bpf_verifier_env *env)
  */
 int bpf_pads_settle(struct bpf_verifier_env *env)
 {
+	struct bpf_subprog_info *sub;
 	struct bpf_pad_plan *plan;
-	int i, err;
+	int i, s, err;
 
-	/* the entries take the places that suit all visits, see visit_refs() */
+	/* sort the releases first: hidden slots are inserted into that order */
 	for (i = 0; i < env->prog->len; i++) {
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next) {
 			err = order_ents(env, plan);
@@ -1724,6 +2072,9 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 				return err;
 		}
 	}
+	err = settle_slots(env);
+	if (err)
+		return err;
 	for (i = 0; i < env->prog->len; i++) {
 		if (env->insn_aux_data[i].pad_plans && bpf_must_abort())
 			return -EINTR;
@@ -1740,6 +2091,15 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 			}
 		}
 	}
+	/* all accesses of the program to its stack are known: the hidden words go below them */
+	for (s = 0; s < env->subprog_cnt; s++) {
+		sub = &env->subprog_info[s];
+		if (!sub->hidden_words)
+			continue;
+		sub->stack_depth = bpf_stack_depth_with_slots(sub);
+		/* check_max_stack_depth() would put the stack of the callees there */
+		sub->keep_fastcall_stack = true;
+	}
 	return 0;
 }
 
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index bca2afd20ef5..d168f7b6e677 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -6253,6 +6253,59 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)
 	return ret;
 }
 
+/*
+ * Run check_max_stack_depth() as a trial, with the hidden words in the frames if @with_slots.
+ * Nothing is logged, and what the check changes in the subprogs is restored.
+ */
+static int try_max_stack_depth(struct bpf_verifier_env *env, bool with_slots)
+{
+	size_t size = (env->subprog_cnt + 1) * sizeof(env->subprog_info[0]);
+	bool priv_stack = env->prog->aux->jits_use_priv_stack;
+	u32 max_depth = env->max_stack_depth, log_level = env->log.level;
+	u32 max_arena_depth = env->max_arena_stack_depth;
+	struct bpf_subprog_info *sub, *saved;
+	int s, err;
+
+	saved = kvmemdup(env->subprog_info, size, BPF_VERIFIER_GFP);
+	if (!saved)
+		return -ENOMEM;
+	for (s = 0; with_slots && s < env->subprog_cnt; s++) {
+		sub = &env->subprog_info[s];
+		if (!sub->hidden_words)
+			continue;
+		sub->stack_depth = bpf_stack_depth_with_slots(sub);
+		/* or check_max_stack_depth() takes the spills of bpf_fastcall off the stack */
+		sub->keep_fastcall_stack = true;
+	}
+	env->log.level = 0;
+	err = check_max_stack_depth(env);
+	env->log.level = log_level;
+	memcpy(env->subprog_info, saved, size);
+	env->max_stack_depth = max_depth;
+	env->max_arena_stack_depth = max_arena_depth;
+	env->prog->aux->jits_use_priv_stack = priv_stack;
+	kvfree(saved);
+	return err;
+}
+
+/*
+ * Returns 1 if the stack has room for the hidden words of the subprogs, 0 if not. Also returns 1 if
+ * check_max_stack_depth() fails without the hidden words as well: that error is not about them,
+ * and check_after_pass() reports it.
+ */
+int bpf_hidden_slots_fit(struct bpf_verifier_env *env)
+{
+	int err = try_max_stack_depth(env, true);
+
+	if (!err)
+		return 1;
+	if (err != -ENOMEM)
+		err = try_max_stack_depth(env, false);
+	if (err == -ENOMEM)
+		return err;
+	return !!err;
+}
+
 static int __check_buffer_access(struct bpf_verifier_env *env,
 				 const char *buf_info,
 				 const struct bpf_reg_state *reg,
@@ -24184,9 +24237,12 @@ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial
 		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 */
+	/*
+	 * Only the sites that the program keeps count. Hidden slots add to the stack of a
+	 * function, so the landing pads are settled before the stack is checked.
+	 */
 	mark_used_sites(env, initial);
-	ret = check_after_pass(env) ?: bpf_pads_settle(env);
+	ret = bpf_pads_settle(env) ?: check_after_pass(env);
 	if (ret) {
 		bpf_find_unproven_after_pass(env);
 		bpf_pads_note_causes(env);
diff --git a/tools/testing/selftests/bpf/progs/verifier_budget.c b/tools/testing/selftests/bpf/progs/verifier_budget.c
index 7f6bb13b5d16..ddf5f9168c53 100644
--- a/tools/testing/selftests/bpf/progs/verifier_budget.c
+++ b/tools/testing/selftests/bpf/progs/verifier_budget.c
@@ -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 (
diff --git a/tools/testing/selftests/bpf/progs/verifier_passes.c b/tools/testing/selftests/bpf/progs/verifier_passes.c
index 708e35fcceb4..8b6db6898570 100644
--- a/tools/testing/selftests/bpf/progs/verifier_passes.c
+++ b/tools/testing/selftests/bpf/progs/verifier_passes.c
@@ -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);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 26/73] bpf: Use hidden slots for a pointer that has no location at a site
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (24 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 25/73] bpf: Add hidden stack slots for landing pads Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 27/73] bpf: Restore the sections of the call when a frame is cancelled Kumar Kartikeya Dwivedi
                   ` (46 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  1 +
 kernel/bpf/pads.c            | 56 +++++++++++++++++++++++++++++-------
 2 files changed, 47 insertions(+), 10 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 7027734c315e..ae407b6a14ab 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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. */
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index a9a2b56364ab..7dbb09ce6c2b 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -1098,6 +1098,12 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 			if (held_ent(plan, i))
 				continue;
 			err = ref_ent(env, &new, st, insn_idx, ref);
+			/* no location: a hidden slot may hold it, see plan_needs_slots() */
+			if (ref->type == REF_TYPE_PTR &&
+			    (err == BPF_CONFLICT_NO_PLACE || err == BPF_CONFLICT_CALLER_SAVED)) {
+				plan->no_place = err;
+				continue;
+			}
 			if (err)
 				return err;
 			ent = match_ent(plan, &new, !pass);
@@ -1617,6 +1623,7 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 
 	if (!err && plan->sections_differ)
 		err = BPF_CONFLICT_SECTIONS_DIFFER;
+	err = err ?: plan->no_place;
 	for (i = 0; !err && i < plan->nr_ents; i++)
 		err = settle_ent(env, plan, &plan->ents[i]);
 	for (class = 0; !err && class < BPF_PAD_NR_SECTIONS; class++) {
@@ -1628,16 +1635,38 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 }
 
 /*
- * The groups of which @plan has something that its pad cannot tell whether it is held. None for a
- * site that the program does not have.
+ * Does an insn of @sub acquire an iterator or a dynptr? If none does, a reference of its frame that
+ * has no location is always a pointer, and the hidden slot of the call that returned it holds it.
+ * Otherwise it can stand for an object in the stack that the program has overwritten.
+ */
+static bool acquires_stack_obj(struct bpf_verifier_env *env, const struct bpf_subprog_info *sub)
+{
+	const struct bpf_pad_note *note;
+	int i;
+
+	for (i = sub->start; i < sub[1].start; i++) {
+		note = env->insn_aux_data[i].pad_note;
+		if (note && note->acquires && note->ent.class > BPF_PAD_REF)
+			return true;
+	}
+	return false;
+}
+
+/*
+ * The groups of which @plan has something that its pad cannot tell whether it is held, or where.
+ * None for a site that the program does not have.
+ * @all_ptrs: no insn of the function acquires an iterator or a dynptr.
  */
-static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
+			   bool all_ptrs)
 {
 	u8 groups = plan->sections_differ;
 	int i, err;
 
 	if (!plan->used || plan->conflict)
 		return 0;
+	if (plan->no_place && all_ptrs)
+		groups |= BIT(BPF_PAD_GROUP_REFS);
 	for (i = 0; i < plan->nr_ents; i++) {
 		err = settle_ent(env, plan, &plan->ents[i]);
 		if (err == BPF_CONFLICT_NOT_ALWAYS_HELD || err == BPF_CONFLICT_CALLER_SAVED)
@@ -1659,13 +1688,14 @@ static bool plan_has_slots(const struct bpf_pad_plan *plan)
 }
 
 /*
- * The pad of @plan releases what the frame holds of @group through the hidden slots of the @nr
- * calls @notes and in no other way. A slot is an entry that is tested. For the order of a pad, see
- * enum pad_turn, the slots of sections go before all entries, those of references after
- * them, those of locks and irq flags after all entries.
+ * Make the pad of @plan release what the frame holds of @group through the hidden slots of the @nr
+ * calls in @notes, and in no other way. Each slot becomes a release that is tested for 0. To fit
+ * the order of enum pad_turn, the slots of sections go before all other releases, those of
+ * references after them, and those of locks and irq flags last. @all_ptrs: the slots hold every
+ * reference of the frame. Returns 0 or -ENOMEM.
  */
 static int plan_take_slots(struct bpf_pad_plan *plan, int group, struct bpf_pad_note **notes,
-			   int nr)
+			   int nr, bool all_ptrs)
 {
 	struct bpf_pad_ent new, *ent;
 	int i, k, pos = 0;
@@ -1678,6 +1708,8 @@ static int plan_take_slots(struct bpf_pad_plan *plan, int group, struct bpf_pad_
 		plan->sections[group] = 0;
 		plan->sections_differ &= ~BIT(group);
 	}
+	if (all_ptrs)
+		plan->no_place = 0;
 	if (group == BPF_PAD_GROUP_LOCKS)
 		pos = plan->nr_ents;
 	while (group == BPF_PAD_GROUP_REFS && pos < plan->nr_ents &&
@@ -1710,6 +1742,7 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 	struct bpf_subprog_info *sub = &env->subprog_info[s];
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	struct bpf_pad_note *note, *notes[BPF_PAD_MAX_ENTS];
+	bool all_ptrs = group == BPF_PAD_GROUP_REFS && !acquires_stack_obj(env, sub);
 	int i, j, err, left, nr = 0, slots = 0, words = 0;
 	struct bpf_pad_plan *plan;
 
@@ -1745,7 +1778,8 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 	}
 	for (i = sub->start; i < sub[1].start; i++) {
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
-			err = plan_has_slots(plan) ? plan_take_slots(plan, group, notes, nr) : 0;
+			err = plan_has_slots(plan) ?
+			      plan_take_slots(plan, group, notes, nr, all_ptrs) : 0;
 			if (err)
 				return err;
 		}
@@ -1766,6 +1800,7 @@ static int settle_slots(struct bpf_verifier_env *env)
 	struct bpf_subprog_info *sub;
 	struct bpf_pad_plan *plan;
 	int i, s, err;
+	bool all_ptrs;
 	u8 need;
 
 	for (s = 0; s < env->subprog_cnt; s++) {
@@ -1774,13 +1809,14 @@ static int settle_slots(struct bpf_verifier_env *env)
 	}
 	for (s = 0; s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
+		all_ptrs = !acquires_stack_obj(env, sub);
 		do {
 			if (bpf_must_abort())
 				return -EINTR;
 			need = 0;
 			for (i = sub->start; i < sub[1].start; i++)
 				for (plan = aux[i].pad_plans; plan; plan = plan->next)
-					need |= plan_needs_slots(env, plan);
+					need |= plan_needs_slots(env, plan, all_ptrs);
 			need &= ~sub->no_slots;
 			err = need ? subprog_take_slots(env, s, __ffs(need)) : 0;
 			if (err < 0)
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 27/73] bpf: Restore the sections of the call when a frame is cancelled
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (25 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 26/73] bpf: Use hidden slots for a pointer that has no location at a site Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 28/73] bpf: Let hidden slots follow what a subprog does for its caller Kumar Kartikeya Dwivedi
                   ` (45 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index ae407b6a14ab..d101bda70824 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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;
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 7dbb09ce6c2b..e8632ba11e0b 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -98,6 +98,9 @@
  * 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.
+ *
+ * A frame can be in fewer sections than it was called in. Its pad enters the sections that the
+ * frame left, so that the caller is in the sections of its call wherever the callee is cancelled.
  */
 #include <linux/bpf.h>
 #include <linux/bpf_verifier.h>
@@ -114,6 +117,11 @@ BTF_ID(func, bpf_local_irq_restore)
 BTF_ID(func, bpf_res_spin_unlock)
 BTF_ID(func, bpf_res_spin_unlock_irqrestore)
 
+/* The kfuncs that enter a section, indexed by enum bpf_pad_class */
+BTF_ID_LIST(pad_enter_kfuncs)
+BTF_ID(func, bpf_rcu_read_lock)
+BTF_ID(func, bpf_preempt_disable)
+
 BTF_ID_LIST(pad_obj_drop)
 BTF_ID(func, bpf_obj_drop)
 BTF_ID(func, bpf_percpu_obj_drop)
@@ -134,6 +142,11 @@ static struct bpf_insn release_call(enum bpf_pad_class class)
 	return BPF_CALL_KFUNC(0, pad_kfuncs[class]);
 }
 
+static struct bpf_insn enter_call(enum bpf_pad_class class)
+{
+	return BPF_CALL_KFUNC(0, pad_enter_kfuncs[class]);
+}
+
 static bool is_obj_drop(const struct bpf_insn *insn)
 {
 	return bpf_pseudo_kfunc_call(insn) && !insn->off &&
@@ -306,6 +319,17 @@ static int get_release(struct bpf_verifier_env *env, const struct bpf_insn *insn
 	return err ? BPF_CONFLICT_NO_RELEASE : 0;
 }
 
+static bool call_sleeps(struct bpf_verifier_env *env, const struct bpf_insn *insn)
+{
+	const struct bpf_func_proto *fn;
+	struct bpf_call_arg_meta meta;
+
+	if (bpf_helper_call(insn))
+		return !bpf_get_helper_proto(env, insn->imm, &fn) && fn->might_sleep;
+	return !bpf_fetch_kfunc_arg_meta(env, insn->imm, insn->off, &meta) &&
+	       bpf_is_kfunc_sleepable(&meta);
+}
+
 struct bpf_pad_plan *bpf_pad_plan(const struct bpf_insn_aux_data *aux, enum bpf_site_kind kind)
 {
 	struct bpf_pad_plan *plan;
@@ -447,14 +471,53 @@ void bpf_pads_free_moved(struct bpf_pads_moved *moved, u32 cnt)
 	}
 }
 
-/* How many sections of @class the current frame of @st has entered and not left */
-static u32 frame_sections(const struct bpf_verifier_state *st, enum bpf_pad_class class)
+/*
+ * Returns how many sections of @class the current frame of @st is in beyond those of its call. The
+ * number is negative if the frame has left sections of its callers.
+ */
+static int frame_sections(const struct bpf_verifier_state *st, enum bpf_pad_class class)
+{
+	const struct bpf_func_state *frame = st->frame[st->curframe];
+
+	if (class == BPF_PAD_RCU)
+		return st->active_rcu_locks - frame->call_rcu_locks;
+	return st->active_preempt_locks - frame->call_preempt_locks;
+}
+
+/*
+ * Returns how many sections of @class of its callers the current frame of @st is still in. Its pad
+ * is in that many when it releases pointers.
+ */
+static int caller_sections(const struct bpf_verifier_state *st, enum bpf_pad_class class)
 {
 	const struct bpf_func_state *frame = st->frame[st->curframe];
 
 	if (class == BPF_PAD_RCU)
-		return st->active_rcu_locks - frame->entry_rcu_locks;
-	return st->active_preempt_locks - frame->entry_preempt_locks;
+		return min(st->active_rcu_locks, frame->call_rcu_locks);
+	return min(st->active_preempt_locks, frame->call_preempt_locks);
+}
+
+/*
+ * Can the pad of the current frame of @st call a function that may sleep, when it releases
+ * pointers? It has released the locks of the frame and left its sections by then. So the program
+ * has to be sleepable, and the callers must hold no lock or irq flags and be in no section. With
+ * @leaves the pad leaves the sections of the callers too, see bpf_pad_visit(). It may do that only
+ * if the frame has left each of them since its call: entry_rcu_locks and entry_preempt_locks are 0.
+ */
+static bool pad_can_sleep(const struct bpf_verifier_state *st, bool leaves)
+{
+	const struct bpf_func_state *frame = st->frame[st->curframe];
+	int i;
+
+	if (!st->in_sleepable || frame->entry_rcu_locks || frame->entry_preempt_locks)
+		return false;
+	for (i = 0; i <= st->curframe; i++)
+		if (st->frame[i]->in_rcu_callback_fn)
+			return false;
+	for (i = 0; i < frame->entry_refs; i++)
+		if (st->refs[i].type != REF_TYPE_PTR)
+			return false;
+	return leaves || (!caller_sections(st, BPF_PAD_RCU) && !caller_sections(st, BPF_PAD_PREEMPT));
 }
 
 static int ref_class(const struct bpf_reference_state *ref)
@@ -1102,6 +1165,8 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 			if (ref->type == REF_TYPE_PTR &&
 			    (err == BPF_CONFLICT_NO_PLACE || err == BPF_CONFLICT_CALLER_SAVED)) {
 				plan->no_place = err;
+				/* nothing here says what releases it: see settle_plan() */
+				plan->no_place_atomic |= !pad_can_sleep(st, false);
 				continue;
 			}
 			if (err)
@@ -1156,18 +1221,21 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
  * holds to the record of the site, also if it holds nothing. Returns the record, whose 'conflict'
  * says why the pad cannot be generated, or an ERR_PTR().
  *
- * Sections: the pad leaves as many as the frame has entered. That is a number of calls in the
- * code of the pad, so it has to be the same on all visits, or the function gets hidden slots.
- *
- * Returns the plan. It tells whether there is a conflict.
+ * The pad leaves as many sections as the frame has entered and enters as many as the frame has left
+ * of its callers, see frame_sections(). These calls are code of the pad, so the number has to be
+ * the same in all states, or the function needs hidden slots. If a release may sleep while the
+ * frame is back in a section of a caller, the pad leaves the sections of the callers too before it
+ * releases pointers, and enters them again afterwards ('outside' of the record). pad_can_sleep()
+ * says whether it may.
  */
 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)
 {
+	const struct bpf_pad_ent *ent;
 	struct bpf_pad_plan *plan;
-	u32 class, nr;
-	int err;
+	int i, class, nr, out, err;
+	bool sleeps = false;
 
 	plan = bpf_pad_plan_get(env, insn_idx, kind);
 	if (!plan)
@@ -1178,13 +1246,27 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 	if (err < 0)
 		return ERR_PTR(err);
 	plan->conflict = err;
+	for (i = 0; !err && i < plan->nr_ents; i++) {
+		ent = &plan->ents[i];
+		if (ent->ref < 0 || ent->class < BPF_PAD_REF || !call_sleeps(env, &ent->release))
+			continue;
+		sleeps = true;
+		/* an iterator that RCU protects is destroyed first, where the pad cannot sleep */
+		if (ent->rcu || !pad_can_sleep(st, true))
+			plan->conflict = BPF_CONFLICT_NO_RELEASE;
+	}
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++) {
 		nr = frame_sections(st, class);
-		if (nr > BPF_PAD_MAX_SECTIONS)
+		out = sleeps ? caller_sections(st, class) : 0;
+		if (abs(nr) + 2 * out > BPF_PAD_MAX_SECTIONS)
 			plan->conflict = BPF_CONFLICT_TOO_MUCH;
 		else if (plan->visited && plan->sections[class] != nr)
 			plan->sections_differ |= BIT(class);
+		/* no hidden slot tells how many sections of its callers a frame is in */
+		if (plan->visited && plan->outside[class] != out && !plan->conflict)
+			plan->conflict = BPF_CONFLICT_SECTIONS_DIFFER;
 		plan->sections[class] = nr;
+		plan->outside[class] = out;
 	}
 	plan->visited = true;
 	return plan;
@@ -1416,8 +1498,8 @@ void bpf_pad_note_section(struct bpf_verifier_env *env, enum bpf_pad_class class
 	};
 
 	if (enter)
-		note_acquire(env, sub, env->insn_idx, &ent, 0, frame_sections(st, class));
-	else if (frame_sections(st, class))
+		note_acquire(env, sub, env->insn_idx, &ent, 0, max(frame_sections(st, class), 0));
+	else if (frame_sections(st, class) > 0)
 		note_release(env, sub, class, 0, 0);
 	else
 		bpf_pad_no_slots(env, class_group(class));
@@ -1517,6 +1599,7 @@ static int load_handle(struct bpf_verifier_env *env, struct bpf_insn *buf,
  * frame: a section or irq flags may be all that protects it, see in_rcu_cs().
  */
 enum pad_turn {
+	/* the sections of the callers that the frame left are entered after all three */
 	PAD_TURN_RCU_ITERS,
 	PAD_TURN_LOCKS,
 	PAD_TURN_POINTERS,
@@ -1529,6 +1612,24 @@ static enum pad_turn release_turn(const struct bpf_pad_ent *ent)
 	return ent->class < BPF_PAD_REF ? PAD_TURN_LOCKS : PAD_TURN_POINTERS;
 }
 
+/*
+ * Returns how many sections of @class the pad of @plan leaves before it releases pointers: those
+ * that the frame entered, and those of its callers if a release may sleep
+ */
+static int pad_leaves(const struct bpf_pad_plan *plan, enum bpf_pad_class class)
+{
+	return max(plan->sections[class], 0) + plan->outside[class];
+}
+
+/*
+ * Returns how many sections of @class the pad of @plan enters after the pointers: those of its
+ * callers that the frame left, and those that the pad left for a release that may sleep
+ */
+static int pad_enters(const struct bpf_pad_plan *plan, enum bpf_pad_class class)
+{
+	return max(-plan->sections[class], 0) + plan->outside[class];
+}
+
 /* Emit the releases of @plan whose turn it is, the last one first. Returns the number of insns. */
 static int release_ents(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 			enum pad_turn turn, struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
@@ -1567,9 +1668,13 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 	n = release_ents(env, plan, PAD_TURN_RCU_ITERS, buf, aux);
 	n += release_ents(env, plan, PAD_TURN_LOCKS, &buf[n], &aux[n]);
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
-		for (i = 0; i < plan->sections[class]; i++)
+		for (i = 0; i < pad_leaves(plan, class); i++)
 			buf[n++] = release_call(class);
 	n += release_ents(env, plan, PAD_TURN_POINTERS, &buf[n], &aux[n]);
+	/* the sections of the callers: last, a release of a pointer may sleep */
+	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
+		for (i = 0; i < pad_enters(plan, class); i++)
+			buf[n++] = enter_call(class);
 	buf[n++] = BPF_MOV64_IMM(BPF_REG_0, bpf_cancelled_retval(env, subprog));
 	if (bpf_ret_reg_pair(env, subprog))
 		buf[n++] = BPF_MOV64_IMM(BPF_REG_2, 0);
@@ -1588,8 +1693,9 @@ static bool released_first(const struct bpf_pad_plan *plan, const struct bpf_pad
 		    (release_turn(other) == release_turn(ent) && other > ent))
 			return false;
 	}
+	/* the pad leaves sections before it releases pointers, and enters sections after them */
 	return release_turn(ent) != PAD_TURN_POINTERS ||
-	       (!plan->sections[BPF_PAD_RCU] && !plan->sections[BPF_PAD_PREEMPT]);
+	       (!pad_leaves(plan, BPF_PAD_RCU) && !pad_leaves(plan, BPF_PAD_PREEMPT));
 }
 
 /*
@@ -1626,9 +1732,19 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 	err = err ?: plan->no_place;
 	for (i = 0; !err && i < plan->nr_ents; i++)
 		err = settle_ent(env, plan, &plan->ents[i]);
+	/*
+	 * A pointer that had no location is released through its hidden slot. In a state that had
+	 * such a pointer the pad could not sleep, so no release of the pad may sleep.
+	 */
+	for (i = 0; !err && plan->no_place_atomic && i < plan->nr_ents; i++)
+		if (plan->ents[i].class >= BPF_PAD_REF && call_sleeps(env, &plan->ents[i].release))
+			err = BPF_CONFLICT_NO_RELEASE;
 	for (class = 0; !err && class < BPF_PAD_NR_SECTIONS; class++) {
 		release = release_call(class);
-		if (plan->sections[class])
+		if (pad_leaves(plan, class))
+			err = get_release(env, &release);
+		release = enter_call(class);
+		if (!err && pad_enters(plan, class))
 			err = get_release(env, &release);
 	}
 	return err;
@@ -2059,6 +2175,10 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 		print_ent(env, &plan->ents[j]);
 	if (plan->conflict)
 		verbose(env, "conflict: %s\n", why[plan->conflict]);
+	else if (plan->outside[BPF_PAD_RCU] || plan->outside[BPF_PAD_PREEMPT])
+		verbose(env, "rcu=%d preempt=%d sleeps outside rcu=%d preempt=%d\n",
+			plan->sections[BPF_PAD_RCU], plan->sections[BPF_PAD_PREEMPT],
+			plan->outside[BPF_PAD_RCU], plan->outside[BPF_PAD_PREEMPT]);
 	else
 		verbose(env, "rcu=%d preempt=%d\n", plan->sections[BPF_PAD_RCU],
 			plan->sections[BPF_PAD_PREEMPT]);
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index d168f7b6e677..7681782ef66c 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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],
diff --git a/tools/testing/selftests/bpf/progs/verifier_barrier.c b/tools/testing/selftests/bpf/progs/verifier_barrier.c
index 302dccd68de9..cb6ae13141ae 100644
--- a/tools/testing/selftests/bpf/progs/verifier_barrier.c
+++ b/tools/testing/selftests/bpf/progs/verifier_barrier.c
@@ -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")
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 28/73] bpf: Let hidden slots follow what a subprog does for its caller
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (26 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 27/73] bpf: Restore the sections of the call when a frame is cancelled Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 29/73] bpf: Let a callee hold a reference that its call hands over Kumar Kartikeya Dwivedi
                   ` (44 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index d101bda70824..b4b19cc605df 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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,
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 46ff571ef76e..b3a7f739bde1 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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;
 	}
 }
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index e8632ba11e0b..01c5c23f8c5c 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -101,6 +101,10 @@
  *
  * A frame can be in fewer sections than it was called in. Its pad enters the sections that the
  * frame left, so that the caller is in the sections of its call wherever the callee is cancelled.
+ *
+ * A subprog can acquire or release for its caller, as lock() and unlock() functions do. Where the
+ * caller has hidden slots, the call stands for what the subprog does, like the call of a kfunc. The
+ * stores are in the caller, after the call, see bpf_pad_note_return().
  */
 #include <linux/bpf.h>
 #include <linux/bpf_verifier.h>
@@ -340,6 +344,19 @@ struct bpf_pad_plan *bpf_pad_plan(const struct bpf_insn_aux_data *aux, enum bpf_
 	return NULL;
 }
 
+/* Charge the memory of @plan to env->mem. Call it again when @plan has grown. */
+static void charge_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
+{
+	u32 bytes = sizeof(*plan);
+
+	if (plan->ents)
+		bytes += BPF_PAD_MAX_ENTS * sizeof(*plan->ents);
+	if (plan->nr_callees)
+		bytes += roundup_pow_of_two(plan->nr_callees) * sizeof(*plan->callee);
+	env->mem += bytes - (s64)plan->bytes;
+	plan->bytes = bytes;
+}
+
 /* @callee came back to the call of @plan: it takes its place in the list */
 static int plan_add_callee(struct bpf_verifier_env *env, struct bpf_pad_plan *plan, u32 callee)
 {
@@ -366,6 +383,7 @@ static int plan_add_callee(struct bpf_verifier_env *env, struct bpf_pad_plan *pl
 	memmove(&plan->callee[lo + 1], &plan->callee[lo], (n - lo) * sizeof(*list));
 	plan->callee[lo] = callee;
 	plan->nr_callees++;
+	charge_plan(env, plan);
 	return 0;
 }
 
@@ -386,6 +404,7 @@ struct bpf_pad_plan *bpf_pad_plan_get(struct bpf_verifier_env *env, int insn_idx
 	bitmap_fill(plan->nulls.slots, MAX_BPF_STACK_SLOTS);
 	plan->next = aux->pad_plans;
 	aux->pad_plans = plan;
+	charge_plan(env, plan);
 	return plan;
 }
 
@@ -399,22 +418,43 @@ int bpf_pad_note_callee(struct bpf_verifier_env *env, int call_idx, int callee)
 	return plan_add_callee(env, plan, callee);
 }
 
-static void free_plans(struct bpf_pad_plan *plan)
+/* Free a list of records. Returns the bytes that they had charged to env->mem. */
+static size_t free_plans(struct bpf_pad_plan *plan)
 {
 	struct bpf_pad_plan *next;
+	size_t bytes = 0;
 
 	for (; plan; plan = next) {
 		next = plan->next;
+		bytes += plan->bytes;
 		kfree(plan->ents);
 		kfree(plan->callee);
 		kfree(plan);
 	}
+	return bytes;
 }
 
-void bpf_pad_plans_free(struct bpf_insn_aux_data *aux)
+/* Free the records of an insn. Returns the bytes that they had charged to env->mem. */
+size_t bpf_pad_plans_free(struct bpf_insn_aux_data *aux)
 {
-	free_plans(aux->pad_plans);
+	size_t bytes = free_plans(aux->pad_plans);
+
 	aux->pad_plans = NULL;
+	return bytes;
+}
+
+/* Free the notes of an insn. Returns the bytes that they had charged to env->mem. */
+size_t bpf_pad_note_free(struct bpf_pad_note *note)
+{
+	struct bpf_pad_note *next;
+	size_t bytes = 0;
+
+	for (; note; note = next) {
+		next = note->next;
+		bytes += sizeof(*note);
+		kfree(note);
+	}
+	return bytes;
 }
 
 /* A pass or a path-sensitive run begins */
@@ -425,8 +465,8 @@ void bpf_pads_new_round(struct bpf_verifier_env *env)
 
 	env->pads_late = false;
 	for (i = 0; i < env->prog->len; i++, aux++) {
-		bpf_pad_plans_free(aux);
-		kfree(aux->pad_note);
+		env->mem -= bpf_pad_plans_free(aux);
+		env->mem -= bpf_pad_note_free(aux->pad_note);
 		aux->pad_note = NULL;
 	}
 }
@@ -443,15 +483,15 @@ void bpf_pads_move(struct bpf_verifier_env *env, struct bpf_pads_moved *moved, b
 
 	for (i = 0; i < env->prog->len; i++, aux++, moved++) {
 		if (save) {
-			free_plans(moved->plans);
-			kfree(moved->note);
+			env->mem -= free_plans(moved->plans);
+			env->mem -= bpf_pad_note_free(moved->note);
 			moved->plans = aux->pad_plans;
 			moved->note = aux->pad_note;
 			aux->pad_plans = NULL;
 			aux->pad_note = NULL;
 		} else {
-			free_plans(aux->pad_plans);
-			kfree(aux->pad_note);
+			env->mem -= free_plans(aux->pad_plans);
+			env->mem -= bpf_pad_note_free(aux->pad_note);
 			aux->pad_plans = moved->plans;
 			aux->pad_note = moved->note;
 			moved->plans = NULL;
@@ -460,15 +500,17 @@ void bpf_pads_move(struct bpf_verifier_env *env, struct bpf_pads_moved *moved, b
 	}
 }
 
-/* The snapshot that has @moved of @cnt insns is freed */
-void bpf_pads_free_moved(struct bpf_pads_moved *moved, u32 cnt)
+/* Free what a snapshot keeps in @moved for @cnt insns. Returns the bytes charged to env->mem. */
+size_t bpf_pads_free_moved(struct bpf_pads_moved *moved, u32 cnt)
 {
+	size_t bytes = 0;
 	u32 i;
 
 	for (i = 0; i < cnt; i++) {
-		free_plans(moved[i].plans);
-		kfree(moved[i].note);
+		bytes += free_plans(moved[i].plans);
+		bytes += bpf_pad_note_free(moved[i].note);
 	}
+	return bytes;
 }
 
 /*
@@ -970,6 +1012,27 @@ static int ref_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
 	return err;
 }
 
+/*
+ * Is @ref irq flags in the stack of a caller of the current frame of @st? The function got their
+ * address in an argument and saved the flags there, like a function that takes a lock for its
+ * caller. The compiler keeps the argument no longer than the function reads it, so a later site has
+ * no location for the address, and a hidden slot has to provide it, see bpf_pad_note_acquire(). The
+ * flags are still there when the pad runs: states are merged only if the same stack slots hold irq
+ * flags.
+ */
+static bool irq_in_caller(const struct bpf_verifier_state *st, const struct bpf_reference_state *ref)
+{
+	int f, i;
+
+	if (ref->type != REF_TYPE_IRQ)
+		return false;
+	for (f = st->curframe - 1; f >= 0; f--)
+		for (i = 0; i < bpf_stack_nr_slots(st->frame[f]); i++)
+			if (slot_is_obj(st->frame[f], i, ref))
+				return true;
+	return false;
+}
+
 /* Returns the release of @plan that refs[@ref] of the current state was matched with, or NULL */
 static struct bpf_pad_ent *held_ent(const struct bpf_pad_plan *plan, int ref)
 {
@@ -1169,6 +1232,11 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 				plan->no_place_atomic |= !pad_can_sleep(st, false);
 				continue;
 			}
+			/* the same for irq flags that a caller has, see irq_in_caller() */
+			if (err == BPF_CONFLICT_NO_PLACE && irq_in_caller(st, ref)) {
+				plan->no_irq_place = err;
+				continue;
+			}
 			if (err)
 				return err;
 			ent = match_ent(plan, &new, !pass);
@@ -1216,6 +1284,29 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 	return 0;
 }
 
+/* @sub gets no hidden slots for @groups, for what @st did */
+static void sub_no_slots(struct bpf_subprog_info *sub, const struct bpf_verifier_state *st,
+			 u8 groups)
+{
+	sub->no_slots |= groups;
+}
+
+/*
+ * A frame of @st has released locks of the frames in @took and leaves without a return to the
+ * stores after its call, see took_lock_of_caller(). The hidden slots of those frames would keep the
+ * addresses, so their functions get no hidden slots for locks.
+ */
+static void took_locks_no_slots(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+				u32 took)
+{
+	int f;
+
+	for (f = 0; took; f++, took >>= 1)
+		if (took & 1)
+			sub_no_slots(&env->subprog_info[st->frame[f]->subprogno], st,
+				     BIT(BPF_PAD_GROUP_LOCKS));
+}
+
 /*
  * The current frame of @st is about to be cancelled at the site of @kind at @insn_idx. Add what it
  * holds to the record of the site, also if it holds nothing. Returns the record, whose 'conflict'
@@ -1240,9 +1331,12 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 	plan = bpf_pad_plan_get(env, insn_idx, kind);
 	if (!plan)
 		return ERR_PTR(-ENOMEM);
+	/* the frame is cancelled before it returns to the stores after its call */
+	took_locks_no_slots(env, st, st->frame[st->curframe]->took_locks);
 	if (plan->conflict)
 		return plan;
 	err = visit_refs(env, plan, st, insn_idx);
+	charge_plan(env, plan);
 	if (err < 0)
 		return ERR_PTR(err);
 	plan->conflict = err;
@@ -1272,6 +1366,12 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 	return plan;
 }
 
+static bool same_release(const struct bpf_pad_ent *a, const struct bpf_pad_ent *b)
+{
+	return a->class == b->class && a->rcu == b->rcu && a->obj_type == b->obj_type &&
+	       !memcmp(&a->release, &b->release, sizeof(a->release));
+}
+
 static int class_group(int class)
 {
 	if (class < BPF_PAD_NR_SECTIONS)
@@ -1294,11 +1394,49 @@ static struct bpf_pad_note *pad_note_get(struct bpf_verifier_env *env, int insn_
 {
 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[insn_idx];
 
-	if (!aux->pad_note)
+	if (!aux->pad_note) {
 		aux->pad_note = kzalloc_obj(*aux->pad_note, BPF_VERIFIER_GFP);
+		if (aux->pad_note)
+			env->mem += sizeof(*aux->pad_note);
+	}
 	return aux->pad_note;
 }
 
+/*
+ * Returns the note of the insn at @insn_idx for what it acquires of @group, or NULL if there is no
+ * memory. An insn has one note. With @chain, for the call of a subprog, it has one per group: the
+ * subprog can return in a section and with irq flags, and each has slots of its own.
+ */
+static struct bpf_pad_note *acquire_note_get(struct bpf_verifier_env *env, int insn_idx, int group,
+					     bool chain)
+{
+	struct bpf_pad_note *head = pad_note_get(env, insn_idx), *note;
+
+	if (!head || !chain)
+		return head;
+	for (note = head; note; note = note->next)
+		if (!note->acquires || class_group(note->ent.class) == group)
+			return note;
+	note = kzalloc_obj(*note, BPF_VERIFIER_GFP);
+	if (!note)
+		return NULL;
+	env->mem += sizeof(*note);
+	note->next = head->next;
+	head->next = note;
+	return note;
+}
+
+/* Does the insn of @aux acquire something of @group, itself or through its callee? */
+static bool insn_acquires(const struct bpf_insn_aux_data *aux, int group)
+{
+	const struct bpf_pad_note *note;
+
+	for (note = aux->pad_note; note; note = note->next)
+		if (note->acquires && class_group(note->ent.class) == group)
+			return true;
+	return false;
+}
+
 /*
  * The current insn changes a resource of @group that a caller of its frame holds, and no store in
  * the caller can follow that. Another frame may hold the same object as well. So no function on the
@@ -1313,6 +1451,43 @@ void bpf_pad_no_slots(struct bpf_verifier_env *env, enum bpf_pad_group group)
 		env->subprog_info[st->frame[f]->subprogno].no_slots |= BIT(group);
 }
 
+/*
+ * The current insn leaves a section of @class that a caller of its frame entered. From here on the
+ * function is in one section less than it was called in, which no hidden slot can say, so it gets
+ * none for the class. Its callers keep theirs: if the frame is cancelled, its pad enters the
+ * section again, and if it returns, the call stands for the release, see bpf_pad_note_return().
+ */
+static void left_of_caller(struct bpf_verifier_env *env, enum bpf_pad_class class)
+{
+	const struct bpf_verifier_state *st = env->cur_state;
+
+	sub_no_slots(&env->subprog_info[st->frame[st->curframe]->subprogno], st, BIT(class));
+}
+
+/*
+ * The current insn releases refs[@idx], a lock or irq flags that a caller of its frame acquired. A
+ * hidden slot of that caller may hold the address, and the store that clears it is in the caller,
+ * after the call. So every frame between the two is marked ('took_locks'), and
+ * bpf_pad_note_return() looks at the mark of the frame that returns to the caller. If a marked
+ * frame is cancelled instead, the slot is not cleared, see bpf_pad_visit().
+ */
+static void took_lock_of_caller(struct bpf_verifier_env *env, int idx)
+{
+	struct bpf_verifier_state *st = env->cur_state;
+	int f, j;
+
+	for (f = st->curframe - 1; f > 0 && st->frame[f]->entry_refs > idx; f--)
+		;
+	/*
+	 * The function is verified separately, and no frame of this state holds the lock. The
+	 * frames are marked when the call is verified again in the frames of its caller.
+	 */
+	if (f < 0 || st->frame[f]->entry_refs > idx)
+		return;
+	for (j = f + 1; j <= st->curframe; j++)
+		st->frame[j]->took_locks |= BIT(f);
+}
+
 /*
  * Fill @ent with the release of @ref, one of refs[] of @st, through a hidden slot. The slot gets
  * what is in @reg: the pointer that the release takes, plus a constant. @by_type: no insn of the
@@ -1356,10 +1531,10 @@ static bool slot_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
  * frame can hold two of them at once: slots do not record the order of release.
  */
 static void note_acquire(struct bpf_verifier_env *env, struct bpf_subprog_info *sub, int insn_idx,
-			 const struct bpf_pad_ent *ent, int src, int held)
+			 const struct bpf_pad_ent *ent, int src, int held, bool chain, bool by_callee)
 {
-	struct bpf_pad_note *note = pad_note_get(env, insn_idx);
 	int group = class_group(ent->class);
+	struct bpf_pad_note *note = acquire_note_get(env, insn_idx, group, chain);
 
 	if (!note) {
 		sub->no_slots |= BIT(group);
@@ -1367,11 +1542,13 @@ static void note_acquire(struct bpf_verifier_env *env, struct bpf_subprog_info *
 	}
 	if (!note->acquires) {
 		note->acquires = true;
+		note->by_callee = by_callee;
 		note->src = src;
 		note->ent = *ent;
 		note->ent.origin = insn_idx;
 	}
-	if (note->src != src || note->ent.class != ent->class || note->ent.rcu != ent->rcu ||
+	if (note->src != src || note->by_callee != by_callee ||
+	    note->ent.class != ent->class || note->ent.rcu != ent->rcu ||
 	    memcmp(&note->ent.release, &ent->release, sizeof(ent->release)) ||
 	    note->ent.obj_type != ent->obj_type ||
 	    note->ent.cand[0][0].delta != ent->cand[0][0].delta ||
@@ -1406,7 +1583,8 @@ void bpf_pad_note_acquire(struct bpf_verifier_env *env, const struct bpf_reg_sta
 		sub->no_slots |= BIT(group);
 	else
 		note_acquire(env, sub, env->insn_idx, &ent, reg - frame->regs,
-			     count_refs(st, frame->entry_refs, st->acquired_refs - 1, group));
+			     count_refs(st, frame->entry_refs, st->acquired_refs - 1, group),
+			     false, false);
 }
 
 /* If @ref is an object in the stack: its first slot, with its address in *@addr. Else NULL. */
@@ -1467,7 +1645,10 @@ void bpf_pad_note_release(struct bpf_verifier_env *env, int idx)
 	if (env->pad_releases)
 		return;
 	if (idx < frame->entry_refs) {
-		bpf_pad_no_slots(env, group);
+		if (group == BPF_PAD_GROUP_LOCKS)
+			took_lock_of_caller(env, idx);
+		else
+			bpf_pad_no_slots(env, group);
 		return;
 	}
 	obj = find_obj(st, ref, &addr);
@@ -1498,49 +1679,241 @@ void bpf_pad_note_section(struct bpf_verifier_env *env, enum bpf_pad_class class
 	};
 
 	if (enter)
-		note_acquire(env, sub, env->insn_idx, &ent, 0, max(frame_sections(st, class), 0));
+		note_acquire(env, sub, env->insn_idx, &ent, 0, max(frame_sections(st, class), 0),
+			     false, false);
 	else if (frame_sections(st, class) > 0)
 		note_release(env, sub, class, 0, 0);
 	else
-		bpf_pad_no_slots(env, class_group(class));
+		left_of_caller(env, class);
+}
+
+/*
+ * Record in @callee what R1-R5 of @caller hold at the call, as far as bpf_pad_note_return() needs
+ * it: a pointer to the stack at a constant offset can be the address of irq flags that the callee
+ * saves for its caller. The verifier compares this before it merges two states of the callee: the
+ * callee stops reading an argument long before it returns, and a state that had something else in
+ * the register must not stand for one that had the address. @caller is NULL for a function that is
+ * verified separately.
+ */
+void bpf_pad_note_args(struct bpf_func_state *callee, const struct bpf_func_state *caller)
+{
+	const struct bpf_reg_state *reg;
+	struct bpf_pad_arg *arg;
+	int i;
+
+	memset(callee->call_args, 0, sizeof(callee->call_args));
+	for (i = 0; caller && i < MAX_BPF_FUNC_REG_ARGS; i++) {
+		reg = &caller->regs[BPF_REG_1 + i];
+		arg = &callee->call_args[i];
+		if (reg->type != PTR_TO_STACK || !tnum_is_const(reg->var_off) ||
+		    (s64)reg->var_off.value != (s16)reg->var_off.value)
+			continue;
+		arg->stack = true;
+		arg->frame = reg->frameno;
+		arg->off = reg->var_off.value;
+	}
+}
+
+/* What is known about the lower half of R0 at a return: BPF_RET_ZERO, NONZERO or UNKNOWN */
+static u8 ret_class(const struct bpf_reg_state *r0)
+{
+	if (r0->type != SCALAR_VALUE)
+		return BPF_RET_UNKNOWN;
+	if (tnum_subreg_is_const(r0->var_off) && !tnum_subreg(r0->var_off).value)
+		return BPF_RET_ZERO;
+	if (reg_u32_min(r0) > 0 || reg_s32_max(r0) < 0 || reg_s32_min(r0) > 0)
+		return BPF_RET_NONZERO;
+	return BPF_RET_UNKNOWN;
+}
+
+/* The release of a section of @class through a hidden slot, without the offset of the slot */
+static void section_ent(struct bpf_pad_ent *ent, enum bpf_pad_class class)
+{
+	*ent = (struct bpf_pad_ent){
+		.ref = -1,
+		.class = class,
+		.release = release_call(class),
+		.nr_cands[0] = 1,
+		.cand[0][0] = { .loc = BPF_PLACE_SPILL, .null = true },
+	};
+}
+
+/*
+ * The frame @callee of @st returns with the irq flags @ref, which it saved for its caller. Returns
+ * the argument register that had their address at the call, with what it had beyond the address in
+ * *@delta, or -1. An argument that had the address itself is preferred to one that pointed
+ * elsewhere into the same frame, like the address of a guard that contains the flags. Every state
+ * that this one stands for had the same in that register, see bpf_pad_note_args().
+ */
+static int irq_arg(const struct bpf_verifier_state *st, const struct bpf_func_state *callee,
+		   const struct bpf_reference_state *ref, int *delta)
+{
+	const struct bpf_stack_state *obj;
+	const struct bpf_pad_arg *arg;
+	struct bpf_reg_state addr;
+	int k, pass;
+
+	if (ref->type != REF_TYPE_IRQ)
+		return -1;
+	obj = find_obj(st, ref, &addr);
+	if (!obj || obj->spilled_ptr.irq.kfunc_class != IRQ_NATIVE_KFUNC ||
+	    addr.frameno >= callee->frameno)
+		return -1;
+	for (pass = 0; pass < 2; pass++) {
+		for (k = 0; k < MAX_BPF_FUNC_REG_ARGS; k++) {
+			arg = &callee->call_args[k];
+			if (!arg->stack || arg->frame != addr.frameno)
+				continue;
+			*delta = arg->off - (int)addr.var_off.value;
+			if (*delta != (s16)*delta || (!pass && *delta))
+				continue;
+			return BPF_REG_1 + k;
+		}
+	}
+	return -1;
 }
 
 /*
- * The current frame of @st returns to the call at @call_idx in @caller, with what it acquired and
- * did not release. @plain: with exit, and it is no callback.
- * One pointer that is in R0 is what a kfunc returns: the call acquires it. What releases it follows
- * from its type: states with the same pointer from different insns are the same to the main pass.
- * The store after the call takes R0 as it is, so it has to be 0 when nothing comes with it.
- * Nothing else has a store: it goes past the store if the frame unwinds.
+ * The current frame of @st returns to the call at @call_idx in @caller with what it acquired and
+ * did not release. @plain: it returns with exit and is no callback. For the hidden slots of the
+ * caller the call stands for what the subprog does, like the call of a kfunc. The stores are in the
+ * caller, after the call, where only a normal return gets. Here lock(l, &flags) returns 0 with irq
+ * flags saved and preemption disabled, or -EBUSY:
+ *
+ *	*(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
+ *
+ * A slot is filled if the subprog returns with one pointer in R0, in one section more, or with irq
+ * flags that it saved where an argument of the call points, see irq_arg(). A slot is cleared if the
+ * subprog has left a section of the frame, or has released the lock or the irq flags of the frame,
+ * or a pointer of the frame that an argument register of the call had, see took_ref_of_caller(). An
+ * argument register is dead after the call, so what it had waits over the call in a hidden word of
+ * the function, the PENDING WORD.
+ *
+ * What a call can stand for:
+ *   - One pointer that is in R0 is what a kfunc returns. What releases it follows from its type:
+ *     states with the same pointer from different insns are the same to the main pass. The store
+ *     takes R0 as it is, so it has to be 0 when nothing comes with it.
+ *   - One section more of a class.
+ *   - Irq flags that the subprog saved where an argument of the call points, see irq_arg(). The
+ *     argument is gone behind the call: it waits in a hidden word of the function, the PENDING
+ *     WORD, which the store behind the call reads.
+ *   - One section less of a class, of those that the frame itself is in. The first slot of the
+ *     class that is not 0 is cleared.
+ *   - The lock or the irq flags that the frame holds are released: a frame with slots for them
+ *     holds one at a time, see note_acquire(), so all of those slots are cleared.
+ * A subprog that returns with something on some returns only is like bpf_res_spin_lock(): R0 has
+ * to tell, 0 or not 0 in its lower half on all returns of the one kind and the opposite on all
+ * others. Each return is noted, and subprog_take_slots() decides when all have been here. One
+ * that has released on some returns only cannot be told: no slots for the group.
+ * Anything else that comes back has no store either, and the function gets no slots for its
+ * group: two pointers, an iterator, a lock, a section that the frame is not in, more than one
+ * section.
  */
 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)
 {
 	const struct bpf_func_state *callee = st->frame[st->curframe];
-	const struct bpf_reference_state *ref = &st->refs[callee->entry_refs];
+	const struct bpf_reference_state *ref = &st->refs[callee->entry_refs], *lock = NULL, *ptr = NULL;
 	struct bpf_subprog_info *sub = &env->subprog_info[caller->subprogno];
 	struct bpf_insn_aux_data *aux = &env->insn_aux_data[call_idx];
 	const struct bpf_reg_state *r0 = &callee->regs[BPF_REG_0];
-	int i, nr = st->acquired_refs - callee->entry_refs, in_r0 = 0;
+	int i, d, before, delta, arg, nr = st->acquired_refs - callee->entry_refs, in_r0 = 0;
+	int nr_locks = 0, nr_refs = 0;
+	u8 brings = 0, takes = 0, keeps = 0, cls;
+	struct bpf_pad_note *head;
 	struct bpf_pad_place place;
 	struct bpf_pad_ent ent;
 
-	for (i = 0; i < BPF_PAD_NR_SECTIONS; i++)
-		if (frame_sections(st, i))
-			sub->no_slots |= BIT(i);
-	if (plain && nr == 1 && ref->type == REF_TYPE_PTR && !ref->parent_id)
-		add_ref_cand(&place, &in_r0, r0, ref, BPF_PLACE_REG, BPF_REG_0);
-	if (in_r0 && slot_ent(env, &ent, st, ref, r0, true) &&
+	head = plain ? pad_note_get(env, call_idx) : NULL;
+	/*
+	 * No store follows this return: the frame is a callback, which returns to its helper, it
+	 * left with unwind_exit, or there is no memory for the note. The caller gets no slots for
+	 * what the frame returns with, nor for a lock that the frame has released for it.
+	 */
+	if (!head) {
+		for (i = 0; i < BPF_PAD_NR_SECTIONS; i++)
+			if (frame_sections(st, i))
+				sub_no_slots(sub, st, BIT(i));
+		for (i = 0; i < nr; i++)
+			sub_no_slots(sub, st, BIT(class_group(ref_class(&ref[i]))));
+		took_locks_no_slots(env, st, callee->took_locks & BIT(caller->frameno));
+		goto out;
+	}
+	for (i = 0; i < nr; i++) {
+		if (class_group(ref_class(&ref[i])) == BPF_PAD_GROUP_LOCKS) {
+			lock = &ref[i];
+			nr_locks++;
+		} else {
+			ptr = &ref[i];
+			nr_refs++;
+		}
+	}
+
+	for (i = 0; i < BPF_PAD_NR_SECTIONS; i++) {
+		/* the change of the number of sections, and how many the caller had entered */
+		d = frame_sections(st, i);
+		before = i == BPF_PAD_RCU ? callee->call_rcu_locks - caller->call_rcu_locks :
+					    callee->call_preempt_locks - caller->call_preempt_locks;
+		if (d == -1 && before > 0) {
+			takes |= BIT(i);
+			continue;
+		}
+		keeps |= BIT(i);
+		if (d == 1) {
+			brings |= BIT(i);
+			section_ent(&ent, i);
+			note_acquire(env, sub, call_idx, &ent, 0, max(before, 0), true, true);
+		} else if (d) {
+			sub_no_slots(sub, st, BIT(i));
+		}
+	}
+
+	arg = nr_locks == 1 ? irq_arg(st, callee, lock, &delta) : -1;
+	if (arg >= 0) {
+		brings |= BIT(BPF_PAD_GROUP_LOCKS);
+		section_ent(&ent, BPF_PAD_IRQ);
+		ent.cand[0][0].delta = delta;
+		note_acquire(env, sub, call_idx, &ent, arg,
+			     count_refs(st, caller->entry_refs, callee->entry_refs,
+					BPF_PAD_GROUP_LOCKS), true, true);
+	} else if (nr_locks) {
+		sub_no_slots(sub, st, BIT(BPF_PAD_GROUP_LOCKS));
+	}
+	if (callee->took_locks & BIT(caller->frameno))
+		takes |= BIT(BPF_PAD_GROUP_LOCKS);
+	else
+		keeps |= BIT(BPF_PAD_GROUP_LOCKS);
+
+	if (nr_refs == 1 && ptr->type == REF_TYPE_PTR && !ptr->parent_id)
+		add_ref_cand(&place, &in_r0, r0, ptr, BPF_PLACE_REG, BPF_REG_0);
+	if (in_r0 && slot_ent(env, &ent, st, ptr, r0, true) &&
 	    can_release_under_lock(env, st, caller, &ent)) {
 		note_acquire(env, sub, call_idx, &ent, BPF_REG_0,
 			     count_refs(st, caller->entry_refs, callee->entry_refs,
-					BPF_PAD_GROUP_REFS));
+					BPF_PAD_GROUP_REFS), true, false);
 	} else {
-		for (i = 0; i < nr; i++)
-			sub->no_slots |= BIT(class_group(ref_class(&ref[i])));
-		aux->call_brings_nothing |= plain && !reg_is_null(r0);
+		if (nr_refs)
+			sub->no_slots |= BIT(BPF_PAD_GROUP_REFS);
+		aux->call_brings_nothing |= !reg_is_null(r0);
 	}
-	if (aux->call_brings_nothing && aux->pad_note && aux->pad_note->acquires)
+
+	cls = ret_class(r0);
+	for (i = 0; i < BPF_PAD_NR_GROUPS; i++) {
+		if (brings & BIT(i))
+			head->hold_r0[i] |= cls;
+		else
+			head->nohold_r0[i] |= cls;
+	}
+	head->takes |= takes;
+	head->keeps |= keeps;
+out:
+	if (aux->call_brings_nothing && insn_acquires(aux, BPF_PAD_GROUP_REFS))
 		sub->no_slots |= BIT(BPF_PAD_GROUP_REFS);
 }
 
@@ -1730,6 +2103,7 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 	if (!err && plan->sections_differ)
 		err = BPF_CONFLICT_SECTIONS_DIFFER;
 	err = err ?: plan->no_place;
+	err = err ?: plan->no_irq_place;
 	for (i = 0; !err && i < plan->nr_ents; i++)
 		err = settle_ent(env, plan, &plan->ents[i]);
 	/*
@@ -1760,11 +2134,10 @@ static bool acquires_stack_obj(struct bpf_verifier_env *env, const struct bpf_su
 	const struct bpf_pad_note *note;
 	int i;
 
-	for (i = sub->start; i < sub[1].start; i++) {
-		note = env->insn_aux_data[i].pad_note;
-		if (note && note->acquires && note->ent.class > BPF_PAD_REF)
-			return true;
-	}
+	for (i = sub->start; i < sub[1].start; i++)
+		for (note = env->insn_aux_data[i].pad_note; note; note = note->next)
+			if (note->acquires && note->ent.class > BPF_PAD_REF)
+				return true;
 	return false;
 }
 
@@ -1783,6 +2156,8 @@ static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_pl
 		return 0;
 	if (plan->no_place && all_ptrs)
 		groups |= BIT(BPF_PAD_GROUP_REFS);
+	if (plan->no_irq_place)
+		groups |= BIT(BPF_PAD_GROUP_LOCKS);
 	for (i = 0; i < plan->nr_ents; i++) {
 		err = settle_ent(env, plan, &plan->ents[i]);
 		if (err == BPF_CONFLICT_NOT_ALWAYS_HELD || err == BPF_CONFLICT_CALLER_SAVED)
@@ -1826,8 +2201,10 @@ static int plan_take_slots(struct bpf_pad_plan *plan, int group, struct bpf_pad_
 	}
 	if (all_ptrs)
 		plan->no_place = 0;
-	if (group == BPF_PAD_GROUP_LOCKS)
+	if (group == BPF_PAD_GROUP_LOCKS) {
+		plan->no_irq_place = 0;
 		pos = plan->nr_ents;
+	}
 	while (group == BPF_PAD_GROUP_REFS && pos < plan->nr_ents &&
 	       plan->ents[pos].class < BPF_PAD_NR_SECTIONS)
 		pos++;
@@ -1847,6 +2224,22 @@ static int plan_take_slots(struct bpf_pad_plan *plan, int group, struct bpf_pad_
 	return 0;
 }
 
+/*
+ * Can the calls of @a and @b share a hidden slot? A frame with slots for locks holds one lock or
+ * one set of irq flags at a time, see note_fill(), so two calls that acquire the same kind never
+ * need a slot at the same time. The same holds for the sections of a class if no call enters one
+ * while the frame is in one. A function that takes a lock at sixteen calls has one slot for it.
+ */
+static bool notes_share_slot(const struct bpf_pad_note *a, const struct bpf_pad_note *b)
+{
+	int group = class_group(a->ent.class);
+
+	if (group == BPF_PAD_GROUP_REFS || a->held || b->held)
+		return false;
+	return same_release(&a->ent, &b->ent) &&
+	       a->ent.cand[0][0].delta == b->ent.cand[0][0].delta;
+}
+
 /*
  * Give subprog @s hidden slots for all that it acquires of @group. A call outside of a loop gets
  * one slot. A call in a loop can run again while the frame holds what it acquired before, so it
@@ -1857,26 +2250,57 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 {
 	struct bpf_subprog_info *sub = &env->subprog_info[s];
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
-	struct bpf_pad_note *note, *notes[BPF_PAD_MAX_ENTS];
+	struct bpf_pad_note *head, *note, *notes[BPF_PAD_MAX_ENTS];
 	bool all_ptrs = group == BPF_PAD_GROUP_REFS && !acquires_stack_obj(env, sub);
-	int i, j, err, left, nr = 0, slots = 0, words = 0;
+	int i, j, k, err, left, nr = 0, slots = 0, words = 0, pend_off = 0;
 	struct bpf_pad_plan *plan;
+	u8 hold, nohold;
 
 	for (i = sub->start; i < sub[1].start; i++) {
-		note = aux[i].pad_note;
-		if (!note || !note->acquires || class_group(note->ent.class) != group)
-			continue;
-		err = nr < BPF_PAD_MAX_ENTS ? get_release(env, &note->ent.release) : 1;
-		if (err)
-			return min(err, 0);
-		notes[nr++] = note;
-		note->nr_slots = bpf_loop_at_index(env, i) < 0 ? 1 : 1 + note->held;
-		note->off = -(int)bpf_stack_depth_with_slots(sub) - (words + 1) * BPF_REG_SIZE;
-		slots += note->nr_slots;
-		words += note->nr_slots * slot_words(note);
+		head = aux[i].pad_note;
+		/* a lock or section was released on some returns only: no store fits all returns */
+		if (head && (head->takes & head->keeps & BIT(group)))
+			return 0;
+		for (note = head; note; note = note->next) {
+			if (!note->acquires || class_group(note->ent.class) != group)
+				continue;
+			err = get_release(env, &note->ent.release);
+			if (err)
+				return min(err, 0);
+			/* when does the subprog return with it? See bpf_pad_note_return(). */
+			hold = head->hold_r0[group];
+			nohold = head->nohold_r0[group];
+			if (!note->by_callee || !nohold)
+				note->cond = BPF_PAD_ALWAYS;
+			else if (hold == BPF_RET_ZERO && nohold == BPF_RET_NONZERO)
+				note->cond = BPF_PAD_IF_ZERO;
+			else if (hold == BPF_RET_NONZERO && nohold == BPF_RET_ZERO)
+				note->cond = BPF_PAD_IF_NONZERO;
+			else
+				return 0;
+			/* the address of irq flags waits in the pending word over the call */
+			if (note->by_callee && note->ent.class == BPF_PAD_IRQ)
+				pend_off = -1;
+			note->nr_slots = bpf_loop_at_index(env, i) < 0 ? 1 : 1 + note->held;
+			for (k = 0; k < nr && !notes_share_slot(notes[k], note); k++)
+				;
+			if (k < nr) {
+				note->off = notes[k]->off;
+				continue;
+			}
+			if (nr == BPF_PAD_MAX_ENTS)
+				return 0;
+			notes[nr++] = note;
+			note->off = -(int)bpf_stack_depth_with_slots(sub) -
+				    (words + 1) * BPF_REG_SIZE;
+			slots += note->nr_slots;
+			words += note->nr_slots * slot_words(note);
+		}
 	}
 	if (!nr)
 		return 0;
+	if (pend_off)
+		pend_off = -(int)bpf_stack_depth_with_slots(sub) - ++words * BPF_REG_SIZE;
 	for (i = sub->start; i < sub[1].start; i++) {
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
 			for (j = 0, left = 0; j < plan->nr_ents; j++)
@@ -1892,10 +2316,13 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 		sub->hidden_words -= words;
 		return err;
 	}
+	if (pend_off)
+		sub->pend_off = pend_off;
 	for (i = sub->start; i < sub[1].start; i++) {
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
 			err = plan_has_slots(plan) ?
 			      plan_take_slots(plan, group, notes, nr, all_ptrs) : 0;
+			charge_plan(env, plan);
 			if (err)
 				return err;
 		}
@@ -1922,6 +2349,7 @@ static int settle_slots(struct bpf_verifier_env *env)
 	for (s = 0; s < env->subprog_cnt; s++) {
 		env->subprog_info[s].slots = 0;
 		env->subprog_info[s].hidden_words = 0;
+		env->subprog_info[s].pend_off = 0;
 	}
 	for (s = 0; s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
@@ -1950,28 +2378,33 @@ static bool note_has_slots(const struct bpf_subprog_info *sub, const struct bpf_
 }
 
 /*
- * The calls of subprog @s that have hidden slots go to @notes, which has room for BPF_PAD_MAX_ENTS.
- * A slot is an entry of each plan of the subprog, so all groups together have no more slots than
- * that, see plan_has_room(), and the insns of the stores are sized for as many, see
- * BPF_PAD_MAX_SLOT_INSNS. Nothing else keeps the calls that few: check it where they are written.
- * Returns how many there are.
+ * Collect in @notes, which has room for BPF_PAD_MAX_ENTS, the calls of subprog @s that have hidden
+ * slots, one call for each slot. A slot is a release of every pad of the subprog, so there are no
+ * more than that, and BPF_PAD_MAX_SLOT_INSNS is sized for as many. Returns how many there are, or
+ * -EFAULT if there are more.
  */
 int bpf_pad_slot_notes(struct bpf_verifier_env *env, int s, const struct bpf_pad_note **notes)
 {
 	const struct bpf_subprog_info *sub = &env->subprog_info[s];
 	const struct bpf_pad_note *note;
-	int i, nr = 0, slots = 0;
+	int i, k, nr = 0, slots = 0;
 
 	for (i = sub->start; i < sub[1].start; i++) {
-		note = env->insn_aux_data[i].pad_note;
-		if (!note_has_slots(sub, note))
-			continue;
-		slots += note->nr_slots;
-		if (verifier_bug_if(slots > BPF_PAD_MAX_ENTS, env,
-				    "func#%d has %d hidden slots, a landing pad has %d entries",
-				    s, slots, BPF_PAD_MAX_ENTS))
-			return -EFAULT;
-		notes[nr++] = note;
+		for (note = env->insn_aux_data[i].pad_note; note; note = note->next) {
+			if (!note_has_slots(sub, note))
+				continue;
+			/* only the first of the calls that share a slot, see notes_share_slot() */
+			for (k = 0; k < nr && notes[k]->off != note->off; k++)
+				;
+			if (k < nr)
+				continue;
+			slots += note->nr_slots;
+			if (verifier_bug_if(slots > BPF_PAD_MAX_ENTS, env,
+					    "func#%d has %d hidden slots, a landing pad has %d entries",
+					    s, slots, BPF_PAD_MAX_ENTS))
+				return -EFAULT;
+			notes[nr++] = note;
+		}
 	}
 	return nr;
 }
@@ -1992,12 +2425,12 @@ int bpf_pad_entry_insns(const struct bpf_pad_note **notes, int nr, struct bpf_in
 }
 
 /*
- * The call of @note acquires: a slot takes what the release takes, unconditionally. 0 in R0 means
- * that nothing was acquired, and 0 in a slot means the same. A section has no handle: 1.
- * If the call has several slots the first one that is 0 is filled. The frame holds no more than
- * 'held' of the group, so there is one.
+ * Emit the stores that fill a hidden slot of the call of @note with R@src, the pointer that the
+ * release takes. The slot of a section takes 1. The store has no condition: 0 in R0 means that
+ * nothing was acquired, and 0 in a slot means the same. If the call has several slots, the first
+ * one that is 0 is filled. One is free, because the frame holds no more than 'held' of the group.
  */
-static int set_insns(const struct bpf_pad_note *note, struct bpf_insn *buf)
+static int set_insns(const struct bpf_pad_note *note, int src, struct bpf_insn *buf)
 {
 	int k, n = 0, nr = note->nr_slots, off = note->off;
 
@@ -2009,13 +2442,13 @@ static int set_insns(const struct bpf_pad_note *note, struct bpf_insn *buf)
 		if (note->ent.class < BPF_PAD_NR_SECTIONS)
 			buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, off, 1);
 		else
-			buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, note->src, off);
+			buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, src, off);
 		if (k < nr - 1)
 			buf[n++] = BPF_JMP_A((nr - 1 - k) * 4 - 1);
 	}
 	/* the irq flags, the next argument: the pad reads the word if the slot is not 0 */
 	if (slot_words(note) == 2)
-		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, note->src + 1, off);
+		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, src + 1, off);
 	return n;
 }
 
@@ -2061,7 +2494,10 @@ static int clear_insns(const struct bpf_pad_note **notes, int nr, const struct b
 	return n;
 }
 
-/* The insns that go before the call of @note in @sub. @notes: the @nr calls with slots. */
+/*
+ * Emit the insns that go before the insn of @note, the first note of an insn in @sub. @notes are
+ * the @nr calls that have slots. Returns the number of insns.
+ */
 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)
 {
@@ -2069,26 +2505,74 @@ int bpf_pad_insns_before(const struct bpf_subprog_info *sub, const struct bpf_pa
 
 	if (note && note->releases && (sub->slots & BIT(note->group)))
 		n = clear_insns(notes, nr, note, buf);
-	/* an address that the call takes. The resource is held when the call returns. */
-	if (note_has_slots(sub, note) && note->ent.class != BPF_PAD_REF)
-		n += set_insns(note, &buf[n]);
+	for (; note; note = note->next) {
+		if (!note_has_slots(sub, note))
+			continue;
+		/*
+		 * The callee saves irq flags where the argument points. The address waits in the
+		 * pending word until the callee has returned with them, see bpf_pad_insns_after().
+		 */
+		if (note->by_callee && note->ent.class == BPF_PAD_IRQ)
+			buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, note->src, sub->pend_off);
+		/* the call takes the address, and the resource is held when the call returns */
+		else if (!note->by_callee && note->ent.class != BPF_PAD_REF)
+			n += set_insns(note, note->src, &buf[n]);
+	}
 	return n;
 }
 
-/* The insns that go after the call of @note, which is in @sub */
-int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad_note *note,
-			struct bpf_insn *buf)
+/*
+ * The insns that go after the insn of @note, the first note of the insn, which is in @sub. @notes:
+ * the @nr calls with slots.
+ * Behind a call of a subprog, see bpf_pad_note_return(): the slots of what the subprog has
+ * released are cleared, then the slots of what it returned with are filled, if R0 says that it
+ * returned with it. R1-R5 are dead there: R1 takes the address from the pending word.
+ */
+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)
 {
-	int n = 0;
+	struct bpf_pad_note rel = {};
+	int g, i, k, n = 0, first;
+	u8 takes;
 
-	if (!note_has_slots(sub, note))
+	if (!note)
 		return 0;
-	if (note->ent.class == BPF_PAD_REF)
-		return set_insns(note, buf);
-	/* the lock was not taken. The upper half of an int is not defined. */
-	if (note->ent.class == BPF_PAD_RES_LOCK || note->ent.class == BPF_PAD_RES_LOCK_IRQ) {
-		buf[n++] = BPF_JMP32_IMM(BPF_JEQ, BPF_REG_0, 0, 1);
-		buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, note->off, 0);
+	takes = note->takes & sub->slots;
+	for (g = 0; g < BPF_PAD_NR_SECTIONS; g++) {
+		if (!(takes & BIT(g)))
+			continue;
+		rel.group = g;
+		n += clear_insns(notes, nr, &rel, &buf[n]);
+	}
+	/* the frame holds one lock or set of irq flags at a time: whichever slot had it */
+	for (i = 0; (takes & BIT(BPF_PAD_GROUP_LOCKS)) && i < nr; i++) {
+		if (class_group(notes[i]->ent.class) != BPF_PAD_GROUP_LOCKS)
+			continue;
+		for (k = 0; k < notes[i]->nr_slots * slot_words(notes[i]); k++)
+			buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
+					      notes[i]->off - k * BPF_REG_SIZE, 0);
+	}
+	for (; note; note = note->next) {
+		if (!note_has_slots(sub, note))
+			continue;
+		if (note->by_callee) {
+			first = n;
+			if (note->cond != BPF_PAD_ALWAYS)
+				buf[n++] = BPF_JMP32_IMM(note->cond == BPF_PAD_IF_ZERO ?
+							 BPF_JNE : BPF_JEQ, BPF_REG_0, 0, 0);
+			if (note->ent.class == BPF_PAD_IRQ)
+				buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_FP, sub->pend_off);
+			n += set_insns(note, BPF_REG_1, &buf[n]);
+			if (note->cond != BPF_PAD_ALWAYS)
+				buf[first].off = n - first - 1;
+		} else if (note->ent.class == BPF_PAD_REF) {
+			n += set_insns(note, note->src, &buf[n]);
+		} else if (note->ent.class == BPF_PAD_RES_LOCK ||
+			   note->ent.class == BPF_PAD_RES_LOCK_IRQ) {
+			/* the lock was not taken if the lower half of R0 is not 0 */
+			buf[n++] = BPF_JMP32_IMM(BPF_JEQ, BPF_REG_0, 0, 1);
+			buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, note->off, 0);
+		}
 	}
 	return n;
 }
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 7681782ef66c..34238772cc7a 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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);
 }
 
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 29/73] bpf: Let a callee hold a reference that its call hands over
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (27 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 28/73] bpf: Let hidden slots follow what a subprog does for its caller Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 30/73] bpf: Let a call clear the hidden slot of what its callee releases Kumar Kartikeya Dwivedi
                   ` (43 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
index 21c92b7e829a..03bf363b3d30 100644
--- a/Documentation/bpf/verifier.rst
+++ b/Documentation/bpf/verifier.rst
@@ -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
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index b4b19cc605df..a7ea1433f323 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/join.c b/kernel/bpf/join.c
index caaf711570a4..c6c250231aca 100644
--- a/kernel/bpf/join.c
+++ b/kernel/bpf/join.c
@@ -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;
 }
 
 /*
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 01c5c23f8c5c..f9e959b6a3df 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -105,6 +105,13 @@
  * A subprog can acquire or release for its caller, as lock() and unlock() functions do. Where the
  * caller has hidden slots, the call stands for what the subprog does, like the call of a kfunc. The
  * stores are in the caller, after the call, see bpf_pad_note_return().
+ *
+ * A call can also HAND a reference OVER: the callee owns it from its entry, as long as the call
+ * lasts, and the pads of the callee release it. This serves a caller that passes a pointer to a
+ * subprog which releases it, and keeps no copy. Take 'consume(t)', where consume() waits in a loop
+ * and then calls bpf_task_release(t): the pad of the loop in consume() releases t, and the pad
+ * after the call of consume() releases nothing. A hand-over is tried only where the program would
+ * be rejected without it, see bpf_pad_handed_ref() and hand_over_more() in verifier.c.
  */
 #include <linux/bpf.h>
 #include <linux/bpf_verifier.h>
@@ -1451,6 +1458,34 @@ void bpf_pad_no_slots(struct bpf_verifier_env *env, enum bpf_pad_group group)
 		env->subprog_info[st->frame[f]->subprogno].no_slots |= BIT(group);
 }
 
+/*
+ * The current insn releases refs[@idx], a reference that a caller of its frame holds. Record in
+ * 'releases_args' each function, from the callee of that caller down to this frame, that got the
+ * pointer in an argument which its call could hand over, see bpf_pad_handed_ref(). Such a function
+ * can own the argument from the next pass on, see note_causes(). A function that got the pointer in
+ * another way ends the walk.
+ */
+static void released_arg_of_caller(struct bpf_verifier_env *env, int idx)
+{
+	const struct bpf_verifier_state *st = env->cur_state;
+	const struct bpf_func_state *frame;
+	int f, k;
+
+	for (f = st->curframe; f >= 0 && st->frame[f]->entry_refs > idx; f--)
+		;
+	/* the function is verified separately: no frame of the state holds the reference */
+	if (f < 0)
+		return;
+	for (f++; f <= st->curframe; f++) {
+		frame = st->frame[f];
+		for (k = 0; k < MAX_BPF_FUNC_REG_ARGS && frame->arg_refs[k] != idx + 1; k++)
+			;
+		if (k == MAX_BPF_FUNC_REG_ARGS)
+			return;
+		env->subprog_info[frame->subprogno].releases_args |= BIT(k);
+	}
+}
+
 /*
  * The current insn leaves a section of @class that a caller of its frame entered. From here on the
  * function is in one section less than it was called in, which no hidden slot can say, so it gets
@@ -1645,10 +1680,12 @@ void bpf_pad_note_release(struct bpf_verifier_env *env, int idx)
 	if (env->pad_releases)
 		return;
 	if (idx < frame->entry_refs) {
-		if (group == BPF_PAD_GROUP_LOCKS)
+		if (group == BPF_PAD_GROUP_LOCKS) {
 			took_lock_of_caller(env, idx);
-		else
+		} else {
 			bpf_pad_no_slots(env, group);
+			released_arg_of_caller(env, idx);
+		}
 		return;
 	}
 	obj = find_obj(st, ref, &addr);
@@ -1714,6 +1751,41 @@ void bpf_pad_note_args(struct bpf_func_state *callee, const struct bpf_func_stat
 	}
 }
 
+/*
+ * A call of @subprog out of @caller, a frame of @st, has a pointer in R@regno whose reference
+ * @caller holds: its index in refs[], which is what the call can HAND OVER, see the comment at the
+ * top. -1 if there is none, or if it is not one that changes frames without more:
+ *   - A pointer that can be NULL: nothing is held where it is.
+ *   - An object in the stack, a reference that was made from another one, and one that another
+ *     one was made from: they are released in the order of refs[].
+ *   - @subprog is recursive: the check at its entry takes a frame that holds something for one
+ *     that got there by a jump, see check_recursion_guard() in verifier.c.
+ */
+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)
+{
+	const struct bpf_subprog_info *sub = &env->subprog_info[subprog];
+	const struct bpf_reg_state *reg = &caller->regs[regno];
+	u32 i, idx, end = st->acquired_refs;
+	struct bpf_reg_state addr;
+
+	if (!(env->insn_aux_data[sub->start].live_regs_before & BIT(regno)) || sub->recursive ||
+	    !reg->id || reg->type == SCALAR_VALUE || type_may_be_null(reg->type))
+		return -1;
+	/* @caller cannot hand over what a frame below it acquired */
+	if (caller->frameno < st->curframe)
+		end = st->frame[caller->frameno + 1]->entry_refs;
+	for (idx = caller->entry_refs; idx < end; idx++)
+		if (st->refs[idx].type == REF_TYPE_PTR && st->refs[idx].id == reg->id)
+			break;
+	if (idx >= end || st->refs[idx].parent_id || find_obj(st, &st->refs[idx], &addr))
+		return -1;
+	for (i = 0; i < st->acquired_refs; i++)
+		if (ref_is_child(st, i, idx))
+			return -1;
+	return idx;
+}
+
 /* What is known about the lower half of R0 at a return: BPF_RET_ZERO, NONZERO or UNKNOWN */
 static u8 ret_class(const struct bpf_reg_state *r0)
 {
@@ -2166,6 +2238,32 @@ static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_pl
 	return groups;
 }
 
+/*
+ * Is the pad of @plan impossible because of a reference, BPF_PAD_GROUP_REFS: no location holds the
+ * pointer, or nothing tells whether it is held? 'no_place' is always about a pointer. Otherwise the
+ * reason is that of the first release at which settle_plan() stopped.
+ */
+static bool conflict_of_ref(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+{
+	int i;
+
+	switch (plan->conflict) {
+	case BPF_CONFLICT_NO_PLACE:
+		return plan->no_place;
+	case BPF_CONFLICT_CALLER_SAVED:
+		if (plan->no_place)
+			return true;
+		fallthrough;
+	case BPF_CONFLICT_NOT_ALWAYS_HELD:
+		for (i = 0; i < plan->nr_ents; i++)
+			if (settle_ent(env, plan, &plan->ents[i]) == plan->conflict)
+				return class_group(plan->ents[i].class) == BPF_PAD_GROUP_REFS;
+		return false;
+	default:
+		return false;
+	}
+}
+
 /* The slot of bpf_res_spin_lock_irqsave() has a second word, for the irq flags */
 static int slot_words(const struct bpf_pad_note *note)
 {
@@ -2668,9 +2766,32 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 			plan->sections[BPF_PAD_PREEMPT]);
 }
 
+/*
+ * Log that @subprog owns the references that its calls hand over in the argument registers @args,
+ * see bpf_pad_handed_ref(). The log of an error about a reference at one of its sites says so,
+ * because no insn of the function acquired what its pad has to release.
+ */
+void bpf_pad_log_handed_over(struct bpf_verifier_env *env, int subprog, u8 args)
+{
+	int k;
+
+	for (k = 0; k < MAX_BPF_FUNC_REG_ARGS; k++)
+		if (args & BIT(k))
+			verbose(env, "func#%d holds the reference that its call hands over in R%d\n",
+				subprog, BPF_REG_1 + k);
+}
+
 /* Log what the pad of the site of @plan at @insn_idx releases, or why it cannot be generated */
 void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan)
 {
+	const struct bpf_subprog_info *sub = bpf_find_containing_subprog(env, insn_idx);
+
+	if (plan->conflict) {
+		/* a release that the pad may not make is one of a pointer or of an object */
+		if (sub->owns_args && (plan->conflict == BPF_CONFLICT_NO_RELEASE ||
+				       conflict_of_ref(env, plan)))
+			bpf_pad_log_handed_over(env, sub - env->subprog_info, sub->owns_args);
+	}
 	print_plan(env, insn_idx, plan);
 }
 
@@ -2790,12 +2911,22 @@ static bool jump_leaves_loop(struct bpf_verifier_env *env, int h, int n)
  *
  * Kept apart, neither call is cancelled. The calls do not say what to keep apart, because their
  * arguments are constants, so the causes are recorded in the callee.
+ *
+ * No pass that keeps more apart gives the frame of the call a place for a pointer that it passed
+ * on and kept no copy of, or a way to tell whether the callee has released it. Where that is the
+ * conflict, see conflict_of_ref(), and the callee is one that releases what the call could hand
+ * over, the callee asks for it, see hand_over_more() in verifier.c.
+ * @insn_idx: the site of @plan.
  */
-static void note_causes(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+static void note_causes(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan)
 {
 	struct bpf_subprog_info *sub = env->subprog_info;
 	int s;
 
+	if (plan->kind == BPF_SITE_CALL && conflict_of_ref(env, plan)) {
+		bpf_pad_for_each_callee(plan, s)
+			sub[s].asks_args |= sub[s].releases_args;
+	}
 	if (plan->kind != BPF_SITE_CALL)
 		return;
 	bpf_pad_for_each_callee(plan, s)
@@ -2895,12 +3026,14 @@ void bpf_pads_note_causes(struct bpf_verifier_env *env)
 	const struct bpf_pad_plan *plan;
 	int i, s;
 
-	for (s = 0; s < env->subprog_cnt; s++)
+	for (s = 0; s < env->subprog_cnt; s++) {
 		env->subprog_info[s].below_conflict = false;
+		env->subprog_info[s].asks_args = 0;
+	}
 	for (i = 0; i < env->prog->len; i++)
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next)
 			if (plan->failed || (plan->used && plan->conflict))
-				note_causes(env, plan);
+				note_causes(env, i, plan);
 	note_causes_below(env);
 	/* The caller checks the limits before the next pass. This is for a load that ends here. */
 	bpf_check_limits(env);
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 34238772cc7a..602d058dc107 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -1624,13 +1624,23 @@ static int acquire_irq_state(struct bpf_verifier_env *env, int insn_idx)
 
 static void release_reference_state(struct bpf_verifier_state *state, int idx)
 {
-	int last_idx, fr;
+	struct bpf_func_state *frame;
+	int last_idx, fr, i;
 	size_t rem;
 
 	/* the frames that were entered with it don't hold it ever since */
-	for (fr = 0; fr <= state->curframe; fr++)
-		if (idx < state->frame[fr]->entry_refs)
-			state->frame[fr]->entry_refs--;
+	for (fr = 0; fr <= state->curframe; fr++) {
+		frame = state->frame[fr];
+		if (idx < frame->entry_refs)
+			frame->entry_refs--;
+		/* arg_refs[] has 1 + an index of refs[]: clear the released one, shift the rest */
+		for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
+			if (frame->arg_refs[i] == idx + 1)
+				frame->arg_refs[i] = 0;
+			else if (frame->arg_refs[i] > idx + 1)
+				frame->arg_refs[i]--;
+		}
+	}
 
 	/* IRQ state requires the relative ordering of elements remaining the
 	 * same, since it relies on the refs array to behave as a stack, so that
@@ -11843,6 +11853,10 @@ static bool func_is_on_its_own(struct bpf_verifier_env *env, struct bpf_verifier
 			return false;
 		if (arg_needs_caller(env, state, sub, &caller->regs[i]))
 			return false;
+		/* A call that hands a reference over is verified in the frames of its caller. */
+		if ((sub->owns_args & BIT(i - BPF_REG_1)) &&
+		    bpf_pad_handed_ref(env, state, caller, subprog, i) >= 0)
+			return false;
 	}
 	/* callx of one function of a set asks before it is checked that the arguments are there */
 	for (i = 0; i < bpf_in_stack_arg_cnt(sub) && i < caller->out_stack_arg_cnt; i++) {
@@ -12059,6 +12073,41 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 	return 0;
 }
 
+/*
+ * The call that made the current frame of @state has pointers in its argument registers whose
+ * references the caller holds, see bpf_pad_handed_ref(). The frame notes each of them, for
+ * bpf_pad_note_release(). Where the function owns the argument, see hand_over_more(), the call
+ * HANDS the reference OVER, see kernel/bpf/pads.c: its entry goes to the end of refs[], where what
+ * a frame acquires is, and the frame of the callee was entered without it. All that looks at
+ * refs[] takes the reference for one of the callee from here on: its landing pads release it, and
+ * when it returns with the reference the caller holds it again, as it holds what a callee acquired
+ * and returned with. The id stays, so the registers of every frame mean what they meant, and the
+ * locks and irq flags stay in their order.
+ * No store follows a reference from one frame to another: the functions on the stack get no hidden
+ * slots for references.
+ */
+static void hand_over_refs(struct bpf_verifier_env *env, struct bpf_verifier_state *state)
+{
+	const struct bpf_func_state *caller = state->frame[state->curframe - 1];
+	struct bpf_func_state *callee = state->frame[state->curframe];
+	u8 owns = env->subprog_info[callee->subprogno].owns_args;
+	struct bpf_reference_state ref;
+	int i, idx;
+
+	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
+		idx = bpf_pad_handed_ref(env, state, caller, callee->subprogno, BPF_REG_1 + i);
+		if (idx < 0)
+			continue;
+		callee->arg_refs[i] = idx < U8_MAX ? idx + 1 : 0;
+		if (!(owns & BIT(i)))
+			continue;
+		ref = state->refs[idx];
+		release_reference_state(state, idx);
+		state->refs[state->acquired_refs++] = ref;
+		bpf_pad_no_slots(env, BPF_PAD_GROUP_REFS);
+	}
+}
+
 /*
  * Call of a static subprog. Unless the callee is verified on its own it is
  * verified in the context of the caller, hence set up a new frame and
@@ -12107,6 +12156,7 @@ static int check_static_func_call(struct bpf_verifier_env *env, int subprog,
 	err = setup_func_entry(env, subprog, *insn_idx, set_callee_state, state);
 	if (err)
 		return err;
+	hand_over_refs(env, state);
 
 	bpf_diag_record_scrub(env, &caller->regs[BPF_REG_0], BPF_DIAG_MOD_CALLER_SAVED);
 	clear_caller_saved_regs(env, caller->regs);
@@ -24228,10 +24278,14 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
 	u32 level = env->log.level;
 	int i, ret;
 
-	/* see settle_late_unwinds() */
-	for (i = 1; i < env->subprog_cnt; i++)
+	for (i = 1; i < env->subprog_cnt; i++) {
+		/* did_unwind and did_cancel of a global subprog go to the next pass. */
 		if (bpf_subprog_is_global(env, i))
 			initial->subprogs[i].did_unwind |= env->subprog_info[i].did_unwind;
+		/* 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;
+	}
 	restore_snapshot(env, initial);
 	kvfree(env->callx_edges);
 	kvfree(env->callx_index.slots);
@@ -24387,6 +24441,34 @@ static int log_failing_path(struct bpf_verifier_env *env, struct bpf_snapshot *i
 	return ret;
 }
 
+/*
+ * No pass is going to keep more apart, and the last one that had an error had a conflict that a
+ * function which releases what its call could hand over asks for: 'asks_args', see note_causes()
+ * in pads.c. From the next pass on the function owns such a reference while the call lasts, see
+ * hand_over_refs(), and its landing pads release what the frame of the call has no place for.
+ * That is no partition. It changes which frame releases, in every pass that follows, and a
+ * program that loads without it could load with other landing pads, or not at all: a callee
+ * that keeps no copy has no place either. So it is tried where the program would be rejected
+ * and nowhere else: what loads without it loads as it did.
+ * A function only ever owns more, so this comes to an end.
+ * Returns true if a function owns more than before.
+ */
+static bool hand_over_more(struct bpf_verifier_env *env, struct bpf_snapshot *initial)
+{
+	bool more = false;
+	u8 args;
+	int s;
+
+	for (s = 1; s < env->subprog_cnt; s++) {
+		args = env->subprog_info[s].asks_args & ~initial->subprogs[s].owns_args;
+		initial->subprogs[s].owns_args |= args;
+		more |= args;
+		if (env->log.level & BPF_LOG_LEVEL2)
+			bpf_pad_log_handed_over(env, s, args);
+	}
+	return more;
+}
+
 /*
  *          pass 0: join all numbers
  *                    |
@@ -24419,6 +24501,10 @@ static int log_failing_path(struct bpf_verifier_env *env, struct bpf_snapshot *i
  * The log has the failing path. If there is none, or if it has a guess and the error of a pass
  * is real, the log has the basic block of an error. Below level 2 the later passes and the
  * path-sensitive runs write no log. The one that gives the log runs once more.
+ *
+ * Where the answer would be REJECT and the last pass with an error had a conflict that a call
+ * which hands a reference to its callee can settle, the callee owns the reference from the next
+ * pass on, see hand_over_more(), and the passes go on with what is kept apart.
  */
 static int do_check_all(struct bpf_verifier_env *env)
 {
@@ -24428,7 +24514,7 @@ static int do_check_all(struct bpf_verifier_env *env)
 	struct bpf_snapshot *initial, *good_pass = NULL;
 	int ret, more, path_err = 0, err = 0;
 	bool guess = false, real;
-	u64 max_cost = 0;
+	u64 max_cost = 0, load_max_cost = env->max_cost;
 
 	initial = save_snapshot(env, NULL);
 	if (!initial || bpf_precision_init(env)) {
@@ -24527,6 +24613,13 @@ static int do_check_all(struct bpf_verifier_env *env)
 		if (!last)
 			continue;
 reject:
+		/* There is more to try: the passes continue, with the limit of the load. */
+		if (!limit && hand_over_more(env, initial)) {
+			path_err = 0;
+			guess = logged = false;
+			env->max_cost = load_max_cost;
+			continue;
+		}
 		if (logged || !quiet || (limit && !env->pass))
 			break;
 		/* Run a pass with an error once more, for the log. It has a limit of its own. */
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 30/73] bpf: Let a call clear the hidden slot of what its callee releases
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (28 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 29/73] bpf: Let a callee hold a reference that its call hands over Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:38 ` [PATCH bpf-next v1 31/73] bpf: Give a callee a hidden slot for the reference that it is handed Kumar Kartikeya Dwivedi
                   ` (42 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
index 03bf363b3d30..d2ea1b4c2a61 100644
--- a/Documentation/bpf/verifier.rst
+++ b/Documentation/bpf/verifier.rst
@@ -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".
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index a7ea1433f323..0f68e01ce036 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -647,6 +647,17 @@ struct bpf_pad_note {
 	u8 group;		/* enum bpf_pad_group */
 	u8 reg;			/* the register that has the pointer plus 'delta' */
 	s16 delta;
+	/*
+	 * In the first note of the call of a subprog that released a reference of the frame: the
+	 * register that had the pointer at the call, and BPF_RET_ZERO and BPF_RET_NONZERO of the
+	 * returns on which it had released (take_r0) and had not (keep_r0).
+	 */
+	u8 take_arg: 3;
+	u8 take_cond: 2;	/* enum bpf_pad_cond, see subprog_take_slots() */
+	u8 take_r0: 2;
+	u8 keep_r0: 2;
+	/* The insn releases a reference of a caller of the frame, see took_ref_of_caller() */
+	u8 for_caller: 1;
 };
 
 /* The plans and the notes of an insn in the snapshot of a pass, see bpf_pads_move() */
@@ -751,6 +762,13 @@ struct bpf_func_state {
 	 * call can hand over, see bpf_pad_handed_ref(). 0 if none. Not compared between states.
 	 */
 	u8 arg_refs[MAX_BPF_FUNC_REG_ARGS];
+	/* bit per argument register: its pointer was not at offset 0, as a hidden slot has it */
+	u8 args_off: 5;
+	/*
+	 * The argument register whose reference the frame, or a subprog that returned to it,
+	 * released for its caller, 0 if none. Not compared either, see bpf_pad_states_meet().
+	 */
+	u8 took_arg: 3;
 	/*
 	 * Unique diagnostic identity for this function invocation. Frame depth is
 	 * reused after returns, while this ID is preserved across state clones.
@@ -1425,8 +1443,9 @@ struct bpf_subprog_info {
 	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.
+	 * 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.
 	 */
 	s16 pend_off;
 	u32 insns_total;
@@ -1494,6 +1513,11 @@ 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 the verifier merged states in a callee of it that differ in which
+	 * references the arguments of the call had, see bpf_pad_states_meet()
+	 */
+	bool arg_refs_differ: 1;
 	/* 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. */
@@ -1684,6 +1708,21 @@ struct bpf_verifier_env {
 	bool replay;			/* the good pass, once more for the driver */
 	bool path_sensitive;		/* no joins, see run_path_sensitive() */
 	bool for_log;			/* the verdict is known, see do_check_all() */
+	/*
+	 * A call clears the hidden slot of a reference that its callee releases, see
+	 * took_ref_of_caller(). try_more() turns it on when a hand-over does not make the program
+	 * load.
+	 */
+	bool takes_refs;
+	/* with takes_refs off, a callee released a reference that its call had in a register */
+	bool could_take_refs;
+	/*
+	 * The last pass with an error had a landing pad that has no location for a reference,
+	 * cannot tell whether it is held, or can call nothing that releases what the frame holds,
+	 * see bpf_pads_note_causes(). Only then has try_more() more to try than a hand-over.
+	 */
+	bool ref_conflict;
+	bool handed_back;		/* what was handed over was taken back, see try_more() */
 	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() */
@@ -2202,6 +2241,9 @@ 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);
+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);
 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);
diff --git a/kernel/bpf/join.c b/kernel/bpf/join.c
index c6c250231aca..d07019e9e764 100644
--- a/kernel/bpf/join.c
+++ b/kernel/bpf/join.c
@@ -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],
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index f9e959b6a3df..7d768e4aa8fd 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -111,7 +111,7 @@
  * subprog which releases it, and keeps no copy. Take 'consume(t)', where consume() waits in a loop
  * and then calls bpf_task_release(t): the pad of the loop in consume() releases t, and the pad
  * after the call of consume() releases nothing. A hand-over is tried only where the program would
- * be rejected without it, see bpf_pad_handed_ref() and hand_over_more() in verifier.c.
+ * be rejected without it, see bpf_pad_handed_ref() and try_more() in verifier.c.
  */
 #include <linux/bpf.h>
 #include <linux/bpf_verifier.h>
@@ -1314,6 +1314,34 @@ static void took_locks_no_slots(struct bpf_verifier_env *env, const struct bpf_v
 				     BIT(BPF_PAD_GROUP_LOCKS));
 }
 
+/*
+ * The verifier is about to let one of @a and @b stand for both. It does not compare what their
+ * frames recorded about the arguments of their calls and about the references that they released
+ * for their callers, and the stores after a call rely on both, see took_ref_of_caller(). Where
+ * 'took_arg' differs, the function of the caller gets no hidden slots for references. Where the
+ * arguments differ, no call of that function can clear a slot for what its callee releases
+ * ('arg_refs_differ'). bpf_state_subsumes() also calls this where no state is dropped, which only
+ * costs slots.
+ */
+void bpf_pad_states_meet(struct bpf_verifier_env *env, const struct bpf_verifier_state *a,
+			 const struct bpf_verifier_state *b)
+{
+	const struct bpf_func_state *fa, *fb;
+	struct bpf_subprog_info *sub;
+	int j;
+
+	for (j = 1; j <= a->curframe; j++) {
+		fa = a->frame[j];
+		fb = b->frame[j];
+		sub = &env->subprog_info[a->frame[j - 1]->subprogno];
+		if (fa->took_arg != fb->took_arg)
+			sub_no_slots(sub, a, BIT(BPF_PAD_GROUP_REFS));
+		if (fa->args_off != fb->args_off ||
+		    memcmp(fa->arg_refs, fb->arg_refs, sizeof(fa->arg_refs)))
+			sub->arg_refs_differ = true;
+	}
+}
+
 /*
  * The current frame of @st is about to be cancelled at the site of @kind at @insn_idx. Add what it
  * holds to the record of the site, also if it holds nothing. Returns the record, whose 'conflict'
@@ -1523,6 +1551,57 @@ static void took_lock_of_caller(struct bpf_verifier_env *env, int idx)
 		st->frame[j]->took_locks |= BIT(f);
 }
 
+/* Does @reg hold the pointer of @ref at offset 0, as a hidden slot does? See add_ref_cand(). */
+bool bpf_pad_reg_is_handle(const struct bpf_reg_state *reg, const struct bpf_reference_state *ref)
+{
+	struct bpf_pad_place place;
+	int nr = 0;
+
+	add_ref_cand(&place, &nr, reg, ref, BPF_PLACE_REG, 0);
+	return nr && !place.delta;
+}
+
+/*
+ * The current insn releases refs[@idx], a pointer that a caller of its frame holds. If the call
+ * that this caller made had the pointer in an argument register, see hand_over_refs() in
+ * verifier.c, the call is what clears the hidden slot of the caller when the callee returns, as
+ * it is for a lock, see took_lock_of_caller(): the callee notes the register, 'took_arg'. Nothing
+ * else tells the slot at run time: the register waits in the pending word of the caller, and the
+ * store behind the call looks for the slot that has the same, see bpf_pad_note_return().
+ * The callee can be left before it returns, by itself or because a frame below it is unwound.
+ * Then the slot is not cleared and the reference is gone: see bpf_pad_note_return().
+ * False if the call cannot do that: no frame of this state holds the reference, no argument had
+ * the pointer at offset 0, the call took another reference before, or a callback is on the way,
+ * which returns to a helper.
+ * And false until the program would be rejected without it: these are stores on the normal path,
+ * and a call that hands the reference over needs none, see try_more() in verifier.c.
+ */
+static bool took_ref_of_caller(struct bpf_verifier_env *env, int idx)
+{
+	struct bpf_verifier_state *st = env->cur_state;
+	struct bpf_func_state *callee;
+	int f, j, k;
+
+	for (f = st->curframe - 1; f > 0 && st->frame[f]->entry_refs > idx; f--)
+		;
+	if (f < 0 || st->frame[f]->entry_refs > idx)
+		return false;
+	callee = st->frame[f + 1];
+	for (k = 0; k < MAX_BPF_FUNC_REG_ARGS && callee->arg_refs[k] != idx + 1; k++)
+		;
+	if (k == MAX_BPF_FUNC_REG_ARGS || (callee->args_off & BIT(k)) || callee->took_arg)
+		return false;
+	for (j = f + 1; j <= st->curframe; j++)
+		if (st->frame[j]->in_callback_fn)
+			return false;
+	/* try_more() has something to turn on, if a landing pad turns out to need it */
+	env->could_take_refs = true;
+	if (!env->takes_refs)
+		return false;
+	callee->took_arg = BPF_REG_1 + k;
+	return true;
+}
+
 /*
  * Fill @ent with the release of @ref, one of refs[] of @st, through a hidden slot. The slot gets
  * what is in @reg: the pointer that the release takes, plus a constant. @by_type: no insn of the
@@ -1657,14 +1736,20 @@ static void note_release(struct bpf_verifier_env *env, struct bpf_subprog_info *
 		note->reg = reg;
 		note->delta = delta;
 	}
-	if (note->group != group || note->reg != reg || note->delta != delta)
+	/* the search for the slot is code: it would run for the reference of a caller too */
+	if (note->group != group || note->reg != reg || note->delta != delta || note->for_caller)
 		sub->no_slots |= BIT(group) | BIT(note->group);
 }
 
 /*
- * The current insn releases refs[@idx] of the current state. The slot that has the handle is found
- * at run time, by the register among R1-R5 that has it too. A register that the insn does not
- * read may have anything in a state that was not looked at.
+ * The current insn releases refs[@idx] of the current state. Record for the hidden slots which of
+ * R1-R5 holds the pointer, so that the insns before the call can find the slot at run time. Only a
+ * register that the insn reads counts: a dead one can hold anything in a state that was pruned.
+ *
+ * A resource of a caller is in no slot of this frame. The call of that caller clears the slot, see
+ * took_lock_of_caller() and took_ref_of_caller(), or no function on the stack gets slots for the
+ * group. That includes a function that is verified separately, see call_func_on_its_own() in
+ * verifier.c: what it releases for its caller belongs to no frame.
  */
 void bpf_pad_note_release(struct bpf_verifier_env *env, int idx)
 {
@@ -1675,17 +1760,27 @@ void bpf_pad_note_release(struct bpf_verifier_env *env, int idx)
 	int r, nr = 0, group = class_group(ref_class(ref));
 	const struct bpf_stack_state *obj;
 	struct bpf_pad_place place = {};
+	struct bpf_pad_note *note;
 	struct bpf_reg_state addr;
 
 	if (env->pad_releases)
 		return;
+	if (idx < frame->entry_refs && group == BPF_PAD_GROUP_LOCKS) {
+		took_lock_of_caller(env, idx);
+		return;
+	}
 	if (idx < frame->entry_refs) {
-		if (group == BPF_PAD_GROUP_LOCKS) {
-			took_lock_of_caller(env, idx);
+		if (took_ref_of_caller(env, idx)) {
+			/* no slot of this frame is cleared: it may hold the same object itself */
+			note = pad_note_get(env, env->insn_idx);
+			if (!note || note->releases)
+				sub->no_slots |= BIT(group);
+			if (note)
+				note->for_caller = true;
 		} else {
 			bpf_pad_no_slots(env, group);
-			released_arg_of_caller(env, idx);
 		}
+		released_arg_of_caller(env, idx);
 		return;
 	}
 	obj = find_obj(st, ref, &addr);
@@ -1867,25 +1962,11 @@ static int irq_arg(const struct bpf_verifier_state *st, const struct bpf_func_st
  * argument register is dead after the call, so what it had waits over the call in a hidden word of
  * the function, the PENDING WORD.
  *
- * What a call can stand for:
- *   - One pointer that is in R0 is what a kfunc returns. What releases it follows from its type:
- *     states with the same pointer from different insns are the same to the main pass. The store
- *     takes R0 as it is, so it has to be 0 when nothing comes with it.
- *   - One section more of a class.
- *   - Irq flags that the subprog saved where an argument of the call points, see irq_arg(). The
- *     argument is gone behind the call: it waits in a hidden word of the function, the PENDING
- *     WORD, which the store behind the call reads.
- *   - One section less of a class, of those that the frame itself is in. The first slot of the
- *     class that is not 0 is cleared.
- *   - The lock or the irq flags that the frame holds are released: a frame with slots for them
- *     holds one at a time, see note_acquire(), so all of those slots are cleared.
- * A subprog that returns with something on some returns only is like bpf_res_spin_lock(): R0 has
- * to tell, 0 or not 0 in its lower half on all returns of the one kind and the opposite on all
- * others. Each return is noted, and subprog_take_slots() decides when all have been here. One
- * that has released on some returns only cannot be told: no slots for the group.
- * Anything else that comes back has no store either, and the function gets no slots for its
- * group: two pointers, an iterator, a lock, a section that the frame is not in, more than one
- * section.
+ * A subprog that returns with something, or releases a pointer, 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. Each return is
+ * recorded here, and subprog_take_slots() decides when all are known. What a call cannot stand for
+ * costs the function its slots for the group: two pointers, an iterator, a lock, or a lock or a
+ * section that is released on some returns only.
  */
 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)
@@ -1915,6 +1996,9 @@ void bpf_pad_note_return(struct bpf_verifier_env *env, const struct bpf_verifier
 		for (i = 0; i < nr; i++)
 			sub_no_slots(sub, st, BIT(class_group(ref_class(&ref[i]))));
 		took_locks_no_slots(env, st, callee->took_locks & BIT(caller->frameno));
+		/* the same for a reference that the frame has released for the caller */
+		if (callee->took_arg)
+			sub_no_slots(sub, st, BIT(BPF_PAD_GROUP_REFS));
 		goto out;
 	}
 	for (i = 0; i < nr; i++) {
@@ -1961,6 +2045,15 @@ void bpf_pad_note_return(struct bpf_verifier_env *env, const struct bpf_verifier
 		takes |= BIT(BPF_PAD_GROUP_LOCKS);
 	else
 		keeps |= BIT(BPF_PAD_GROUP_LOCKS);
+	if (callee->took_arg) {
+		takes |= BIT(BPF_PAD_GROUP_REFS);
+		/* one register goes to the pending word */
+		if (head->take_arg && head->take_arg != callee->took_arg)
+			sub->no_slots |= BIT(BPF_PAD_GROUP_REFS);
+		head->take_arg = callee->took_arg;
+	} else {
+		keeps |= BIT(BPF_PAD_GROUP_REFS);
+	}
 
 	if (nr_refs == 1 && ptr->type == REF_TYPE_PTR && !ptr->parent_id)
 		add_ref_cand(&place, &in_r0, r0, ptr, BPF_PLACE_REG, BPF_REG_0);
@@ -1982,6 +2075,13 @@ void bpf_pad_note_return(struct bpf_verifier_env *env, const struct bpf_verifier
 		else
 			head->nohold_r0[i] |= cls;
 	}
+	/* two bits: one that is not known is both */
+	if (cls == BPF_RET_UNKNOWN)
+		cls = BPF_RET_ZERO | BPF_RET_NONZERO;
+	if (takes & BIT(BPF_PAD_GROUP_REFS))
+		head->take_r0 |= cls;
+	else
+		head->keep_r0 |= cls;
 	head->takes |= takes;
 	head->keeps |= keeps;
 out:
@@ -2357,8 +2457,26 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 	for (i = sub->start; i < sub[1].start; i++) {
 		head = aux[i].pad_note;
 		/* a lock or section was released on some returns only: no store fits all returns */
-		if (head && (head->takes & head->keeps & BIT(group)))
+		if (head && (head->takes & head->keeps & BIT(group)) && group != BPF_PAD_GROUP_REFS)
 			return 0;
+		/* a pointer that the call had in a register: R0 has to tell */
+		if (head && (head->takes & BIT(group)) && group == BPF_PAD_GROUP_REFS) {
+			if (sub->arg_refs_differ)
+				return 0;
+			if (!(head->keeps & BIT(group)))
+				head->take_cond = BPF_PAD_ALWAYS;
+			else if (head->take_r0 == BPF_RET_ZERO && head->keep_r0 == BPF_RET_NONZERO)
+				head->take_cond = BPF_PAD_IF_ZERO;
+			else if (head->take_r0 == BPF_RET_NONZERO && head->keep_r0 == BPF_RET_ZERO)
+				head->take_cond = BPF_PAD_IF_NONZERO;
+			else
+				return 0;
+			/* the pending word has the address of the irq flags over this call */
+			for (note = head; note; note = note->next)
+				if (note->by_callee && note->ent.class == BPF_PAD_IRQ)
+					return 0;
+			pend_off = -1;
+		}
 		for (note = head; note; note = note->next) {
 			if (!note->acquires || class_group(note->ent.class) != group)
 				continue;
@@ -2397,8 +2515,10 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 	}
 	if (!nr)
 		return 0;
+	/* one pending word per function: it is written before a call and read after it */
 	if (pend_off)
-		pend_off = -(int)bpf_stack_depth_with_slots(sub) - ++words * BPF_REG_SIZE;
+		pend_off = sub->pend_off ?:
+			   -(int)bpf_stack_depth_with_slots(sub) - ++words * BPF_REG_SIZE;
 	for (i = sub->start; i < sub[1].start; i++) {
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
 			for (j = 0, left = 0; j < plan->nr_ents; j++)
@@ -2551,13 +2671,14 @@ static int set_insns(const struct bpf_pad_note *note, int src, struct bpf_insn *
 }
 
 /*
- * The call of @rel releases: the slot of the group that has the handle is cleared, whichever call
- * filled it in this run. The first match ends the search: two references to one object are the
- * same handle in two slots, and one of them is released. No match: the call was given NULL.
- * Sections are all alike: the first slot that is not 0.
+ * Emit the insns that clear the hidden slot of what the call of @rel releases: the slot of the
+ * group that holds the same pointer, whichever call filled it. The search stops at the first match:
+ * two references to one object are the same pointer in two slots, and one of them is released.
+ * Without a match the call was given NULL. For a section the first slot that is not 0 is cleared.
+ * @scratch is a register that is dead here.
  */
 static int clear_insns(const struct bpf_pad_note **notes, int nr, const struct bpf_pad_note *rel,
-		       struct bpf_insn *buf)
+		       int scratch, struct bpf_insn *buf)
 {
 	int i, k, n = 0, off, delta, reg;
 
@@ -2566,11 +2687,10 @@ static int clear_insns(const struct bpf_pad_note **notes, int nr, const struct b
 			continue;
 		delta = rel->delta - notes[i]->ent.cand[0][0].delta;
 		/*
-		 * The delta is made of constants that the program chose, the offsets of a node in
-		 * its object. It is added in R0, which a call is about to clobber: there the JIT
+		 * The offset is a constant of the program. It is added in @scratch, where a JIT
 		 * blinds it like any other constant of the program. An insn on AX is not blinded.
 		 */
-		reg = delta ? BPF_REG_0 : BPF_REG_AX;
+		reg = delta ? scratch : BPF_REG_AX;
 		for (k = 0; k < notes[i]->nr_slots; k++) {
 			off = notes[i]->off - k * BPF_REG_SIZE;
 			buf[n++] = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_FP, off);
@@ -2601,8 +2721,12 @@ int bpf_pad_insns_before(const struct bpf_subprog_info *sub, const struct bpf_pa
 {
 	int n = 0;
 
+	/* a call is about to clobber R0 */
 	if (note && note->releases && (sub->slots & BIT(note->group)))
-		n = clear_insns(notes, nr, note, buf);
+		n = clear_insns(notes, nr, note, BPF_REG_0, buf);
+	/* the pointer that the callee may release waits in the pending word */
+	if (note && (note->takes & sub->slots & BIT(BPF_PAD_GROUP_REFS)))
+		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, note->take_arg, sub->pend_off);
 	for (; note; note = note->next) {
 		if (!note_has_slots(sub, note))
 			continue;
@@ -2620,11 +2744,11 @@ int bpf_pad_insns_before(const struct bpf_subprog_info *sub, const struct bpf_pa
 }
 
 /*
- * The insns that go after the insn of @note, the first note of the insn, which is in @sub. @notes:
- * the @nr calls with slots.
- * Behind a call of a subprog, see bpf_pad_note_return(): the slots of what the subprog has
- * released are cleared, then the slots of what it returned with are filled, if R0 says that it
- * returned with it. R1-R5 are dead there: R1 takes the address from the pending word.
+ * Emit the insns that go after the insn of @note, the first note of an insn in @sub. @notes are the
+ * @nr calls that have slots. After the call of a subprog, see bpf_pad_note_return(), the slots of
+ * what the subprog released are cleared, and then the slots of what it returned with are filled,
+ * under a test of R0 where needed. R1 and R3-R5 are dead there, and R1 takes what waited in the
+ * pending word. R2 can be the second half of what the subprog returns.
  */
 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)
@@ -2640,7 +2764,20 @@ int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad
 		if (!(takes & BIT(g)))
 			continue;
 		rel.group = g;
-		n += clear_insns(notes, nr, &rel, &buf[n]);
+		n += clear_insns(notes, nr, &rel, BPF_REG_3, &buf[n]);
+	}
+	if (takes & BIT(BPF_PAD_GROUP_REFS)) {
+		first = n;
+		/* the upper half of an int is not defined */
+		if (note->take_cond != BPF_PAD_ALWAYS)
+			buf[n++] = BPF_JMP32_IMM(note->take_cond == BPF_PAD_IF_ZERO ?
+						 BPF_JNE : BPF_JEQ, BPF_REG_0, 0, 0);
+		buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_1, BPF_REG_FP, sub->pend_off);
+		rel.group = BPF_PAD_GROUP_REFS;
+		rel.reg = BPF_REG_1;
+		n += clear_insns(notes, nr, &rel, BPF_REG_3, &buf[n]);
+		if (note->take_cond != BPF_PAD_ALWAYS)
+			buf[first].off = n - first - 1;
 	}
 	/* the frame holds one lock or set of irq flags at a time: whichever slot had it */
 	for (i = 0; (takes & BIT(BPF_PAD_GROUP_LOCKS)) && i < nr; i++) {
@@ -2923,6 +3060,9 @@ static void note_causes(struct bpf_verifier_env *env, int insn_idx, const struct
 	struct bpf_subprog_info *sub = env->subprog_info;
 	int s;
 
+	/* what try_more() in verifier.c is for, see 'ref_conflict' */
+	env->ref_conflict |= conflict_of_ref(env, plan) ||
+			     plan->conflict == BPF_CONFLICT_NO_RELEASE;
 	if (plan->kind == BPF_SITE_CALL && conflict_of_ref(env, plan)) {
 		bpf_pad_for_each_callee(plan, s)
 			sub[s].asks_args |= sub[s].releases_args;
@@ -3030,6 +3170,7 @@ void bpf_pads_note_causes(struct bpf_verifier_env *env)
 		env->subprog_info[s].below_conflict = false;
 		env->subprog_info[s].asks_args = 0;
 	}
+	env->ref_conflict = false;
 	for (i = 0; i < env->prog->len; i++)
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next)
 			if (plan->failed || (plan->used && plan->conflict))
diff --git a/kernel/bpf/states.c b/kernel/bpf/states.c
index d80262956446..18f82546fa09 100644
--- a/kernel/bpf/states.c
+++ b/kernel/bpf/states.c
@@ -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;
 }
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 602d058dc107..ab7658f943bb 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -12099,6 +12099,8 @@ static void hand_over_refs(struct bpf_verifier_env *env, struct bpf_verifier_sta
 		if (idx < 0)
 			continue;
 		callee->arg_refs[i] = idx < U8_MAX ? idx + 1 : 0;
+		if (!bpf_pad_reg_is_handle(&caller->regs[BPF_REG_1 + i], &state->refs[idx]))
+			callee->args_off |= BIT(i);
 		if (!(owns & BIT(i)))
 			continue;
 		ref = state->refs[idx];
@@ -24442,16 +24444,12 @@ static int log_failing_path(struct bpf_verifier_env *env, struct bpf_snapshot *i
 }
 
 /*
- * No pass is going to keep more apart, and the last one that had an error had a conflict that a
- * function which releases what its call could hand over asks for: 'asks_args', see note_causes()
- * in pads.c. From the next pass on the function owns such a reference while the call lasts, see
- * hand_over_refs(), and its landing pads release what the frame of the call has no place for.
- * That is no partition. It changes which frame releases, in every pass that follows, and a
- * program that loads without it could load with other landing pads, or not at all: a callee
- * that keeps no copy has no place either. So it is tried where the program would be rejected
- * and nowhere else: what loads without it loads as it did.
- * A function only ever owns more, so this comes to an end.
- * Returns true if a function owns more than before.
+ * Called when the load would end in a reject. A function asks for an argument ('asks_args', see
+ * note_causes() in pads.c) if it releases a reference that its caller holds and the last pass with
+ * an error failed at the landing pad of its call. From the next pass on the function owns that
+ * reference from its entry, see hand_over_refs(). A hand-over can cost a location, where the
+ * caller has one for the pointer and the callee has none, so it is tried only here: a program that
+ * loads without it loads as before. Returns true if a function owns more than before.
  */
 static bool hand_over_more(struct bpf_verifier_env *env, struct bpf_snapshot *initial)
 {
@@ -24469,6 +24467,55 @@ static bool hand_over_more(struct bpf_verifier_env *env, struct bpf_snapshot *in
 	return more;
 }
 
+/*
+ * The answer would be REJECT. What is tried then, each step where the one before it has nothing
+ * more to give:
+ *   - Calls hand over what the last pass with an error asks for, see hand_over_more(). That
+ *     stores nothing at run time.
+ *   - A call clears the hidden slot of a reference that its callee releases, see
+ *     took_ref_of_caller() in pads.c. These are stores on the normal path, so hand-over comes
+ *     first. Once on, it stays on for the load.
+ *   - What was handed over is taken back, once: a callee that holds what it was handed can be
+ *     what stands in the way, where its landing pad would release under a lock of the caller.
+ *     The caller releases then, out of its hidden slots, and from there on calls hand over
+ *     again what the passes ask for.
+ * The last two are only for a load in which a callee released a reference that its call had in
+ * a register, and whose last pass with an error had a landing pad that has no place for a
+ * reference, cannot tell whether it is held, or can call nothing that releases what the frame
+ * holds: any other program is rejected as it was. They happen once per load, and a function
+ * only ever owns more in between, so this comes to an end.
+ * Each step costs at most about as many passes as the round before it took: a round starts from
+ * what is kept apart and ends as soon as the program loads. A program whose calls hand over
+ * again after the take-back pays those rounds a second time.
+ * Returns true if the passes are to go on.
+ */
+static bool try_more(struct bpf_verifier_env *env, struct bpf_snapshot *initial)
+{
+	bool owned = false;
+	int s;
+
+	if (hand_over_more(env, initial))
+		return true;
+	if (!env->ref_conflict || !env->could_take_refs)
+		return false;
+	if (!env->takes_refs) {
+		env->takes_refs = true;
+		if (env->log.level & BPF_LOG_LEVEL2)
+			verbose(env, "calls clear the hidden slots of what their callees release\n");
+		return true;
+	}
+	if (env->handed_back)
+		return false;
+	env->handed_back = true;
+	for (s = 1; s < env->subprog_cnt; s++) {
+		owned |= initial->subprogs[s].owns_args;
+		initial->subprogs[s].owns_args = 0;
+	}
+	if (owned && (env->log.level & BPF_LOG_LEVEL2))
+		verbose(env, "no call hands a reference over\n");
+	return owned;
+}
+
 /*
  *          pass 0: join all numbers
  *                    |
@@ -24502,9 +24549,9 @@ static bool hand_over_more(struct bpf_verifier_env *env, struct bpf_snapshot *in
  * is real, the log has the basic block of an error. Below level 2 the later passes and the
  * path-sensitive runs write no log. The one that gives the log runs once more.
  *
- * Where the answer would be REJECT and the last pass with an error had a conflict that a call
- * which hands a reference to its callee can settle, the callee owns the reference from the next
- * pass on, see hand_over_more(), and the passes go on with what is kept apart.
+ * Before the answer is REJECT, try_more() lets calls hand references over to their callees and
+ * clear hidden slots for what their callees release. If it finds something to try, the passes
+ * continue with what is kept apart.
  */
 static int do_check_all(struct bpf_verifier_env *env)
 {
@@ -24614,7 +24661,7 @@ static int do_check_all(struct bpf_verifier_env *env)
 			continue;
 reject:
 		/* There is more to try: the passes continue, with the limit of the load. */
-		if (!limit && hand_over_more(env, initial)) {
+		if (!limit && try_more(env, initial)) {
 			path_err = 0;
 			guess = logged = false;
 			env->max_cost = load_max_cost;
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 31/73] bpf: Give a callee a hidden slot for the reference that it is handed
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (29 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 30/73] bpf: Let a call clear the hidden slot of what its callee releases Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:26   ` bot+bpf-ci
  2026-12-01  4:38 ` [PATCH bpf-next v1 32/73] bpf: Give unwind_goto a 32 bit offset and prepare it for arena accesses Kumar Kartikeya Dwivedi
                   ` (41 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
index d2ea1b4c2a61..447df36c380b 100644
--- a/Documentation/bpf/verifier.rst
+++ b/Documentation/bpf/verifier.rst
@@ -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::
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 0f68e01ce036..79b0d5f7d4fa 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 7d768e4aa8fd..985369fbb57c 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -1437,6 +1437,19 @@ static struct bpf_pad_note *pad_note_get(struct bpf_verifier_env *env, int insn_
 	return aux->pad_note;
 }
 
+/* One more note for the insn of @head. NULL if there is no memory. */
+static struct bpf_pad_note *chain_note(struct bpf_verifier_env *env, struct bpf_pad_note *head)
+{
+	struct bpf_pad_note *note = kzalloc_obj(*note, BPF_VERIFIER_GFP);
+
+	if (!note)
+		return NULL;
+	env->mem += sizeof(*note);
+	note->next = head->next;
+	head->next = note;
+	return note;
+}
+
 /*
  * Returns the note of the insn at @insn_idx for what it acquires of @group, or NULL if there is no
  * memory. An insn has one note. With @chain, for the call of a subprog, it has one per group: the
@@ -1450,15 +1463,9 @@ static struct bpf_pad_note *acquire_note_get(struct bpf_verifier_env *env, int i
 	if (!head || !chain)
 		return head;
 	for (note = head; note; note = note->next)
-		if (!note->acquires || class_group(note->ent.class) == group)
+		if (!note->entry && (!note->acquires || class_group(note->ent.class) == group))
 			return note;
-	note = kzalloc_obj(*note, BPF_VERIFIER_GFP);
-	if (!note)
-		return NULL;
-	env->mem += sizeof(*note);
-	note->next = head->next;
-	head->next = note;
-	return note;
+	return chain_note(env, head);
 }
 
 /* Does the insn of @aux acquire something of @group, itself or through its callee? */
@@ -1467,7 +1474,7 @@ static bool insn_acquires(const struct bpf_insn_aux_data *aux, int group)
 	const struct bpf_pad_note *note;
 
 	for (note = aux->pad_note; note; note = note->next)
-		if (note->acquires && class_group(note->ent.class) == group)
+		if (note->acquires && !note->entry && class_group(note->ent.class) == group)
 			return true;
 	return false;
 }
@@ -1574,7 +1581,8 @@ bool bpf_pad_reg_is_handle(const struct bpf_reg_state *reg, const struct bpf_ref
  * the pointer at offset 0, the call took another reference before, or a callback is on the way,
  * which returns to a helper.
  * And false until the program would be rejected without it: these are stores on the normal path,
- * and a call that hands the reference over needs none, see try_more() in verifier.c.
+ * and a call that hands the reference over needs none in its caller, see try_more() in
+ * verifier.c.
  */
 static bool took_ref_of_caller(struct bpf_verifier_env *env, int idx)
 {
@@ -1644,11 +1652,10 @@ static bool slot_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
  * agree on them, or @sub gets no hidden slots for the group. It gets none for locks either if a
  * frame can hold two of them at once: slots do not record the order of release.
  */
-static void note_acquire(struct bpf_verifier_env *env, struct bpf_subprog_info *sub, int insn_idx,
-			 const struct bpf_pad_ent *ent, int src, int held, bool chain, bool by_callee)
+static void note_fill(struct bpf_subprog_info *sub, struct bpf_pad_note *note, int insn_idx,
+		      const struct bpf_pad_ent *ent, int src, int held, bool by_callee)
 {
 	int group = class_group(ent->class);
-	struct bpf_pad_note *note = acquire_note_get(env, insn_idx, group, chain);
 
 	if (!note) {
 		sub->no_slots |= BIT(group);
@@ -1672,6 +1679,50 @@ static void note_acquire(struct bpf_verifier_env *env, struct bpf_subprog_info *
 		note->held = max_t(int, note->held, held);
 }
 
+static void note_acquire(struct bpf_verifier_env *env, struct bpf_subprog_info *sub, int insn_idx,
+			 const struct bpf_pad_ent *ent, int src, int held, bool chain, bool by_callee)
+{
+	note_fill(sub, acquire_note_get(env, insn_idx, class_group(ent->class), chain), insn_idx,
+		  ent, src, held, by_callee);
+}
+
+/*
+ * The call that created the current frame of @st hands refs[@idx] over in R@regno, see
+ * hand_over_refs() in verifier.c. No insn of the function acquires that reference. If the function
+ * has hidden slots for references, its first insns fill a slot from the register, and its pads
+ * release the pointer by its type. The store runs however the function is entered, so every call
+ * has to hand the argument over, or the function gets no such slots, see enter_empty_handed() in
+ * verifier.c.
+ */
+void bpf_pad_note_entry(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			int regno, int idx)
+{
+	const struct bpf_func_state *callee = st->frame[st->curframe];
+	struct bpf_subprog_info *sub = &env->subprog_info[callee->subprogno];
+	const struct bpf_reg_state *reg = &st->frame[st->curframe - 1]->regs[regno];
+	struct bpf_pad_note *head = pad_note_get(env, sub->start), *note;
+	struct bpf_pad_place place;
+	struct bpf_pad_ent ent;
+	int nr = 0;
+
+	for (note = head; note && !(note->entry && note->src == regno); note = note->next)
+		;
+	if (head && !note) {
+		note = chain_note(env, head);
+		if (note) {
+			note->entry = true;
+			note->src = regno;
+		}
+	}
+	/* not another socket with the id of the reference, see add_ref_cand() */
+	add_ref_cand(&place, &nr, reg, &st->refs[idx], BPF_PLACE_REG, regno);
+	if (!nr || !slot_ent(env, &ent, st, &st->refs[idx], reg, true) ||
+	    !can_release_under_lock(env, st, callee, &ent))
+		sub->no_slots |= BIT(BPF_PAD_GROUP_REFS);
+	else
+		note_fill(sub, note, sub->start, &ent, regno, 0, false);
+}
+
 /*
  * The current insn acquired the youngest of refs[]. Record it for the hidden slots. @reg holds the
  * pointer that the release takes: R0, or the argument with the address of the lock or of the object
@@ -2629,16 +2680,23 @@ int bpf_pad_slot_notes(struct bpf_verifier_env *env, int s, const struct bpf_pad
 
 /*
  * The entry of a function: all words of its hidden slots are 0. The frame holds nothing of its own,
- * and a pad reads all slots, also at a site that is before the calls that fill them.
+ * and a pad reads all slots, also at a site that is before the calls that fill them. But for the
+ * slot of a reference that the call hands over: it takes the argument register.
  */
 int bpf_pad_entry_insns(const struct bpf_pad_note **notes, int nr, struct bpf_insn *buf)
 {
 	int i, k, n = 0;
 
-	for (i = 0; i < nr; i++)
+	for (i = 0; i < nr; i++) {
+		/* what the call handed over, see bpf_pad_note_entry() */
+		if (notes[i]->entry) {
+			buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, notes[i]->src, notes[i]->off);
+			continue;
+		}
 		for (k = 0; k < notes[i]->nr_slots * slot_words(notes[i]); k++)
 			buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, notes[i]->off - k * BPF_REG_SIZE,
 					      0);
+	}
 	return n;
 }
 
@@ -2728,7 +2786,7 @@ int bpf_pad_insns_before(const struct bpf_subprog_info *sub, const struct bpf_pa
 	if (note && (note->takes & sub->slots & BIT(BPF_PAD_GROUP_REFS)))
 		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, note->take_arg, sub->pend_off);
 	for (; note; note = note->next) {
-		if (!note_has_slots(sub, note))
+		if (!note_has_slots(sub, note) || note->entry)
 			continue;
 		/*
 		 * The callee saves irq flags where the argument points. The address waits in the
@@ -2788,7 +2846,7 @@ int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad
 					      notes[i]->off - k * BPF_REG_SIZE, 0);
 	}
 	for (; note; note = note->next) {
-		if (!note_has_slots(sub, note))
+		if (!note_has_slots(sub, note) || note->entry)
 			continue;
 		if (note->by_callee) {
 			first = n;
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index ab7658f943bb..478fdc2d6642 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -11673,6 +11673,17 @@ static int check_cb_unwind(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	return 0;
 }
 
+/*
+ * @subprog is entered without a call that hands a reference over: as a callback, or verified
+ * separately from its callers. If it owns an argument, the store at its entry would fill a hidden
+ * slot with a pointer that the frame does not hold. So it gets no hidden slots for references.
+ */
+static void enter_empty_handed(struct bpf_verifier_env *env, int subprog)
+{
+	if (env->subprog_info[subprog].owns_args)
+		env->subprog_info[subprog].no_slots |= BIT(BPF_PAD_GROUP_REFS);
+}
+
 static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 			      int insn_idx, int subprog,
 			      set_callee_state_fn set_callee_state_cb)
@@ -11700,6 +11711,7 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 	 * callbacks
 	 */
 	env->subprog_info[subprog].is_cb = true;
+	enter_empty_handed(env, subprog);
 	if (bpf_pseudo_kfunc_call(insn) &&
 	    !is_callback_calling_kfunc(insn->imm)) {
 		verifier_bug(env, "kfunc %s#%d not marked as callback-calling",
@@ -11920,6 +11932,7 @@ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int i
 
 	account_current_path(env);
 	env->subprog_info[subprog].on_its_own = true;
+	enter_empty_handed(env, subprog);
 	err = bpf_flow_call(env, state, &entry, subprog, insn_idx);
 	bpf_free_verifier_state(env, &entry, false);
 	/* the call waits, there is nothing to go on with */
@@ -12074,39 +12087,42 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 }
 
 /*
- * The call that made the current frame of @state has pointers in its argument registers whose
- * references the caller holds, see bpf_pad_handed_ref(). The frame notes each of them, for
- * bpf_pad_note_release(). Where the function owns the argument, see hand_over_more(), the call
- * HANDS the reference OVER, see kernel/bpf/pads.c: its entry goes to the end of refs[], where what
- * a frame acquires is, and the frame of the callee was entered without it. All that looks at
- * refs[] takes the reference for one of the callee from here on: its landing pads release it, and
- * when it returns with the reference the caller holds it again, as it holds what a callee acquired
- * and returned with. The id stays, so the registers of every frame mean what they meant, and the
- * locks and irq flags stay in their order.
- * No store follows a reference from one frame to another: the functions on the stack get no hidden
- * slots for references.
+ * At the entry of the current frame of @state, record which argument registers have a pointer whose
+ * reference the caller holds (arg_refs[]). If the function owns such an argument, see
+ * hand_over_more(), the call hands the reference over: it moves to the end of refs[] and counts as
+ * acquired by the callee, whose landing pads release it. The caller holds it again if the callee
+ * returns with it. No store follows a reference from one frame to another, so the callers get no
+ * hidden slots for references. Nor does the callee if a call passes an owned argument that the
+ * caller does not hold.
  */
 static void hand_over_refs(struct bpf_verifier_env *env, struct bpf_verifier_state *state)
 {
 	const struct bpf_func_state *caller = state->frame[state->curframe - 1];
 	struct bpf_func_state *callee = state->frame[state->curframe];
-	u8 owns = env->subprog_info[callee->subprogno].owns_args;
+	struct bpf_subprog_info *sub = &env->subprog_info[callee->subprogno];
+	u8 owns = sub->owns_args;
 	struct bpf_reference_state ref;
-	int i, idx;
+	int i, f, idx;
 
 	for (i = 0; i < MAX_BPF_FUNC_REG_ARGS; i++) {
 		idx = bpf_pad_handed_ref(env, state, caller, callee->subprogno, BPF_REG_1 + i);
-		if (idx < 0)
+		if (idx < 0) {
+			if (owns & BIT(i))
+				sub->no_slots |= BIT(BPF_PAD_GROUP_REFS);
 			continue;
+		}
 		callee->arg_refs[i] = idx < U8_MAX ? idx + 1 : 0;
 		if (!bpf_pad_reg_is_handle(&caller->regs[BPF_REG_1 + i], &state->refs[idx]))
 			callee->args_off |= BIT(i);
 		if (!(owns & BIT(i)))
 			continue;
+		bpf_pad_note_entry(env, state, BPF_REG_1 + i, idx);
 		ref = state->refs[idx];
 		release_reference_state(state, idx);
 		state->refs[state->acquired_refs++] = ref;
-		bpf_pad_no_slots(env, BPF_PAD_GROUP_REFS);
+		for (f = 0; f < state->curframe; f++)
+			env->subprog_info[state->frame[f]->subprogno].no_slots |=
+				BIT(BPF_PAD_GROUP_REFS);
 	}
 }
 
@@ -23855,6 +23871,7 @@ static int do_check_common(struct bpf_verifier_env *env, int subprog,
 			BPF_MAIN_FUNC /* callsite */,
 			0 /* frameno */,
 			subprog);
+	enter_empty_handed(env, subprog);
 	state->last_insn_idx = -1;
 
 	regs = state->frame[state->curframe]->regs;
@@ -24468,26 +24485,16 @@ static bool hand_over_more(struct bpf_verifier_env *env, struct bpf_snapshot *in
 }
 
 /*
- * The answer would be REJECT. What is tried then, each step where the one before it has nothing
- * more to give:
- *   - Calls hand over what the last pass with an error asks for, see hand_over_more(). That
- *     stores nothing at run time.
- *   - A call clears the hidden slot of a reference that its callee releases, see
- *     took_ref_of_caller() in pads.c. These are stores on the normal path, so hand-over comes
- *     first. Once on, it stays on for the load.
- *   - What was handed over is taken back, once: a callee that holds what it was handed can be
- *     what stands in the way, where its landing pad would release under a lock of the caller.
- *     The caller releases then, out of its hidden slots, and from there on calls hand over
- *     again what the passes ask for.
- * The last two are only for a load in which a callee released a reference that its call had in
- * a register, and whose last pass with an error had a landing pad that has no place for a
- * reference, cannot tell whether it is held, or can call nothing that releases what the frame
- * holds: any other program is rejected as it was. They happen once per load, and a function
- * only ever owns more in between, so this comes to an end.
- * Each step costs at most about as many passes as the round before it took: a round starts from
- * what is kept apart and ends as soon as the program loads. A program whose calls hand over
- * again after the take-back pays those rounds a second time.
- * Returns true if the passes are to go on.
+ * The load would end in a reject. Try three steps, each when the one before it has nothing more to
+ * give. Returns true if the passes are to continue.
+ *   1. Calls hand over what the last pass with an error asks for, see hand_over_more().
+ *   2. Calls clear the hidden slot of a reference that their callee releases, see
+ *      took_ref_of_caller() in pads.c. These are stores on the normal path, so they come second.
+ *   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 following passes ask for.
+ * Steps 2 and 3 happen once per load. They need a callee that released a reference which its call
+ * had in a register ('could_take_refs'), and a last pass with an error that failed at a landing
+ * pad because of a reference ('ref_conflict').
  */
 static bool try_more(struct bpf_verifier_env *env, struct bpf_snapshot *initial)
 {
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 32/73] bpf: Give unwind_goto a 32 bit offset and prepare it for arena accesses
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (30 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 31/73] bpf: Give a callee a hidden slot for the reference that it is handed Kumar Kartikeya Dwivedi
@ 2026-12-01  4:38 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 33/73] bpf, x86: Go to the landing pad when an access to arena faults Kumar Kartikeya Dwivedi
                   ` (40 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:38 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index fe41871e3d1c..00667ce5303c 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -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
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 4a934bab9c79..4d4dd004df20 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -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;
 
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 79b0d5f7d4fa..f03ecb8fe288 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 5e30a4e70660..5e71c55f3307 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -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)
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 87262e4d4c0c..737db347de97 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -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;
 }
 
diff --git a/kernel/bpf/disasm.c b/kernel/bpf/disasm.c
index 2e377a7ea262..43aa0656a588 100644
--- a/kernel/bpf/disasm.c
+++ b/kernel/bpf/disasm.c
@@ -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);
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index b3a7f739bde1..89a6bd52ef35 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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);
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index aac5f2860121..a7120ecb0e80 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -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");
 
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 33/73] bpf, x86: Go to the landing pad when an access to arena faults
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (31 preceding siblings ...)
  2026-12-01  4:38 ` [PATCH bpf-next v1 32/73] bpf: Give unwind_goto a 32 bit offset and prepare it for arena accesses Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 34/73] bpf, arm64: " Kumar Kartikeya Dwivedi
                   ` (39 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index 00667ce5303c..d1bf402bc42b 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -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)
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 4d4dd004df20..0f35aed5df7e 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -1815,14 +1815,12 @@ static int emit_atomic_ld_st_index(u8 **pprog, u32 atomic_op, u32 size,
  * in @dst_reg and @src_reg.
  *
  * Both the load and the CMPXCHG can fault when accessing the arena, so their
- * addresses are handed back in @fault[0] and @fault[1]. A fault has to resume
- * at @resume, which is past the loop and past the move that delivers the old
- * value, but before R0 is restored. Both are NULL for the non-arena case,
- * which needs no fixup.
+ * addresses are handed back in @fault[0] and @fault[1]. @fault is NULL for the
+ * non-arena case, which needs no fixup. At a fault ex_handler_bpf() skips the
+ * rest of the sequence and restores R0 itself, see FIXUP_ARENA_R0_IN_AX.
  */
 static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
-				 u32 src_reg, int index_reg,
-				 u8 **fault, u8 **resume)
+				 u32 src_reg, int index_reg, u8 **fault)
 {
 	bool is64 = BPF_SIZE(insn->code) == BPF_DW;
 	u8 *branch_target, *prog = *pprog;
@@ -1867,9 +1865,6 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
 	/* Return the pre-modification value */
 	emit_mov_reg(&prog, is64, src_reg, BPF_REG_0);
 
-	if (resume)
-		*resume = prog;
-
 	/* Restore R0 after clobbering RAX */
 	emit_mov_reg(&prog, true, BPF_REG_0, BPF_REG_AX);
 
@@ -1884,18 +1879,18 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
  *
  * Bit layout of `fixup` (32-bit):
  *
- * +-----------+-------------+--------+-----------+---------+----------+
- * | 31        | 30          | 29-24  |   23-16   |   15-8  |    7-0   |
- * |           |             |        |           |         |          |
- * | ARENA_ACC | ARENA_WRITE | Unused | ARENA_REG | DST_REG | INSN_LEN |
- * +-----------+-------------+--------+-----------+---------+----------+
+ * +-----------+-------------+----------+--------+-----------+---------+----------+
+ * | 31        | 30          | 29       | 28-24  |   23-16   |   15-8  |    7-0   |
+ * |           |             |          |        |           |         |          |
+ * | ARENA_ACC | ARENA_WRITE | R0_IN_AX | Unused | ARENA_REG | DST_REG | INSN_LEN |
+ * +-----------+-------------+----------+--------+-----------+---------+----------+
  *
- * - INSN_LEN (8 bits): How far past the faulting insn to resume. That is its own length
- *                      for a single-insn access, but the distance to the end of the whole
- *                      sequence where one BPF insn became several, as for the CMPXCHG loop
- *                      of a fetching AND/OR/XOR. A sequence long enough to overflow this
- *                      field would first have to exceed BPF_MAX_INSN_SIZE, which do_jit()
- *                      rejects with -EFAULT before the image is used.
+ * - INSN_LEN (8 bits): How far the end of the code of the BPF insn is from the faulting insn.
+ *                      That is its own length for a single-insn access, but the distance to
+ *                      the end of the whole sequence where one BPF insn became several, as for
+ *                      the CMPXCHG loop of a fetching AND/OR/XOR. A sequence long enough to
+ *                      overflow this field would first have to exceed BPF_MAX_INSN_SIZE, which
+ *                      do_jit() rejects with -EFAULT before the image is used.
  * - DST_REG  (8 bits): Offset of dst_reg from reg2pt_regs[] (max offset = 112 (fits in 8 bits)).
  *                      This is set to DONT_CLEAR if the insn does not read into a register.
  * - ARENA_REG (8 bits): Offset of the register that is used to calculate the
@@ -1904,6 +1899,9 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
  *                        It is independent of DST_REG, since a read-modify-write both writes to
  *                        memory and reads the old value into a register.
  * - ARENA_ACCESS (1 bit): This bit is set when the faulting instruction accessed the arena region.
+ * - R0_IN_AX (1 bit): R0 is in BPF_REG_AX while the faulting insn runs: the CMPXCHG loop of a
+ *                     fetching AND/OR/XOR keeps it there while RAX serves the CMPXCHG. The
+ *                     handler puts it back, since it leaves the sequence.
  *
  * Bit layout of `data` (32-bit):
  *
@@ -1921,6 +1919,7 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
 #define FIXUP_INSN_LEN_MASK	GENMASK(7, 0)
 #define FIXUP_REG_MASK		GENMASK(15, 8)
 #define FIXUP_ARENA_REG_MASK	GENMASK(23, 16)
+#define FIXUP_ARENA_R0_IN_AX	BIT(29)
 #define FIXUP_ARENA_WRITE	BIT(30)
 #define FIXUP_ARENA_ACCESS	BIT(31)
 #define DATA_ARENA_OFFSET_MASK	GENMASK(31, 16)
@@ -1931,6 +1930,7 @@ bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs)
 	u32 insn_len = FIELD_GET(FIXUP_INSN_LEN_MASK, x->fixup);
 	bool is_arena = !!(x->fixup & FIXUP_ARENA_ACCESS);
 	bool is_write = !!(x->fixup & FIXUP_ARENA_WRITE);
+	unsigned long end = regs->ip + insn_len, pad = end;
 	unsigned long addr;
 	s16 off;
 	u32 arena_reg;
@@ -1939,13 +1939,18 @@ bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs)
 		arena_reg = FIELD_GET(FIXUP_ARENA_REG_MASK, x->fixup);
 		off = FIELD_GET(DATA_ARENA_OFFSET_MASK, x->data);
 		addr = *(unsigned long *)((void *)regs + arena_reg) + off;
-		bpf_prog_report_arena_violation(is_write, addr, regs->ip);
+		pad = bpf_arena_fault(is_write, addr, regs->ip, end);
 	}
 
-	/* jump over the faulting access, or the sequence it is part of, and clear dest register */
-	if (reg != DONT_CLEAR)
+	/*
+	 * Without a landing pad, jump over the faulting access, or the sequence it is part of, and
+	 * clear dest register. A landing pad gets the registers as they were before the access.
+	 */
+	if (pad == end && reg != DONT_CLEAR)
 		*(unsigned long *)((void *)regs + reg) = 0;
-	regs->ip += insn_len;
+	if (x->fixup & FIXUP_ARENA_R0_IN_AX)
+		regs->ax = regs->r10;
+	regs->ip = pad;
 
 	return true;
 }
@@ -1954,11 +1959,11 @@ bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs)
  * Record an arena access that may fault. @fault_ip is the address of the
  * faulting insn in the RO image, @resume_off how far past it execution has to
  * resume: for a multi-insn lowering that is the end of the whole sequence, not
- * the end of the one insn.
+ * the end of the one insn. @flags are the FIXUP_ARENA_* bits of the entry.
  */
 static int emit_arena_exentry(struct bpf_prog *bpf_prog, u8 *image, u8 *rw_image,
 			      int *excnt, u8 *fault_ip, u32 resume_off,
-			      u32 fixup_reg, u32 arena_reg, bool is_write, s16 off)
+			      u32 fixup_reg, u32 arena_reg, u32 flags, s16 off)
 {
 	struct exception_table_entry *ex;
 	s64 delta;
@@ -1981,9 +1986,7 @@ static int emit_arena_exentry(struct bpf_prog *bpf_prog, u8 *image, u8 *rw_image
 	ex->fixup = FIELD_PREP(FIXUP_INSN_LEN_MASK, resume_off) |
 		    FIELD_PREP(FIXUP_ARENA_REG_MASK, arena_reg) |
 		    FIELD_PREP(FIXUP_REG_MASK, fixup_reg) |
-		    FIXUP_ARENA_ACCESS;
-	if (is_write)
-		ex->fixup |= FIXUP_ARENA_WRITE;
+		    FIXUP_ARENA_ACCESS | flags;
 
 	return 0;
 }
@@ -2409,6 +2412,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;
+}
+
 /*
  * unwind_exit: fix the return address of this frame. r0 and r2 are returned.
  * So is BPF_REG_ARENA_SP, when it's used.
@@ -3121,8 +3136,9 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 
 				err = emit_arena_exentry(bpf_prog, image, rw_image, &excnt,
 							 image + proglen + (start_of_ldx - temp),
-							 prog - start_of_ldx, fixup_reg,
-							 arena_reg, is_write, insn->off);
+							 prog - start_of_ldx, fixup_reg, arena_reg,
+							 is_write ? FIXUP_ARENA_WRITE : 0,
+							 insn->off);
 				if (err)
 					return err;
 			}
@@ -3299,8 +3315,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 			}
 			if (is_atomic_fetch) {
 				err = emit_atomic_fetch_rmw(&prog, insn, real_dst_reg,
-							    real_src_reg, -1,
-							    NULL, NULL);
+							    real_src_reg, -1, NULL);
 				if (err)
 					return err;
 				break;
@@ -3328,7 +3343,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		case BPF_STX | BPF_PROBE_ATOMIC | BPF_DW:
 			if (is_atomic_fetch_op(insn)) {
 				u32 real_src_reg = src_reg, real_dst_reg = dst_reg;
-				u8 *fault[2], *resume;
+				u8 *fault[2];
 				int j;
 
 				/* Will need RAX as a CMPXCHG operand so save R0 */
@@ -3339,25 +3354,26 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 					real_dst_reg = BPF_REG_AX;
 
 				err = emit_atomic_fetch_rmw(&prog, insn, real_dst_reg,
-							    real_src_reg, X86_REG_R12,
-							    fault, &resume);
+							    real_src_reg, X86_REG_R12, fault);
 				if (err)
 					return err;
 
 				/*
 				 * The page may be unmapped between the load and the
 				 * CMPXCHG, so both need an entry. Both report a write,
-				 * since the BPF insn is a read-modify-write.
+				 * since the BPF insn is a read-modify-write, and both
+				 * say that R0 is in BPF_REG_AX.
 				 */
 				for (j = 0; j < 2; j++) {
 					err = emit_arena_exentry(bpf_prog, image, rw_image,
 								 &excnt,
 								 image + proglen +
 									 (fault[j] - temp),
-								 resume - fault[j],
+								 prog - fault[j],
 								 reg2pt_regs[real_src_reg],
 								 reg2pt_regs[real_dst_reg],
-								 true, insn->off);
+								 FIXUP_ARENA_WRITE |
+								 FIXUP_ARENA_R0_IN_AX, insn->off);
 					if (err)
 						return err;
 				}
@@ -3492,6 +3508,9 @@ 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:
+			/* an access to arena is in front: no call, nothing to redo */
+			if (BPF_CLASS(insn[-1].code) != BPF_JMP)
+				after_call_len = 0;
 			if (!after_call_len) {
 				err = add_unwind_exentry(bpf_prog, image, rw_image, &excnt,
 							 addrs[i - 1],
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 915034e8acc2..f7ac105d9dd3 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -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 */
 
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 5e71c55f3307..3ce4609af05f 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -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);
diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c
index 1c118f3da5a4..2890c65ad26a 100644
--- a/kernel/bpf/arena.c
+++ b/kernel/bpf/arena.c
@@ -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;
 }
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 737db347de97..0f7199c5c1b8 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -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
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 34/73] bpf, arm64: Go to the landing pad when an access to arena faults
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (32 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 33/73] bpf, x86: Go to the landing pad when an access to arena faults Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 35/73] bpf: Let a register be the location of a lock in a global variable Kumar Kartikeya Dwivedi
                   ` (38 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 arch/arm64/net/bpf_jit_comp.c | 35 +++++++++++++++++++++++++++++------
 1 file changed, 29 insertions(+), 6 deletions(-)

diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index d1bf402bc42b..730f9d95bca1 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -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)
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 35/73] bpf: Let a register be the location of a lock in a global variable
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (33 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 34/73] bpf, arm64: " Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 36/73] bpf: Cancel a program at a fault in arena Kumar Kartikeya Dwivedi
                   ` (37 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 kernel/bpf/pads.c | 8 ++++++--
 1 file changed, 6 insertions(+), 2 deletions(-)

diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 985369fbb57c..60de6a42c756 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -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;
 }
 
 /*
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 36/73] bpf: Cancel a program at a fault in arena
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (34 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 35/73] bpf: Let a register be the location of a lock in a global variable Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:52   ` sashiko-bot
  2026-12-01  4:39 ` [PATCH bpf-next v1 37/73] bpf: Share one landing pad among accesses to arena where nothing is held Kumar Kartikeya Dwivedi
                   ` (36 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index f03ecb8fe288..0b3e9dcd6aef 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 89a6bd52ef35..8e007e4fad99 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -633,6 +633,9 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 		bpf_pad_for_each_callee(plan, s)
 			if (env->subprog_info[s].can_unwind)
 				return true;
+		return false;
+	case BPF_SITE_FAULT:
+		return !env->insn_aux_data[i].fault_skips;
 	}
 	return false;
 }
@@ -658,7 +661,8 @@ void bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env)
 			if (sub->can_unwind || !sub->bail_unwinds)
 				continue;
 			for (i = sub->start; i < sub[1].start && !sub->can_unwind; i++) {
-				sub->can_unwind = aux[i].loop_guard;
+				sub->can_unwind = aux[i].loop_guard ||
+						  (aux[i].fault_empty && !aux[i].fault_skips);
 				for (plan = aux[i].pad_plans; plan; plan = plan->next)
 					sub->can_unwind |= bpf_site_is_used(env, i, plan);
 			}
@@ -704,6 +708,9 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 	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;
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
 			if (!plan_has_pad(env, i, plan))
 				continue;
@@ -733,9 +740,20 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 	return cnt;
 }
 
+/* The plan of insn @i if it is a site that has unwind_goto after it: a call, an access to arena */
+static const struct bpf_pad_plan *unwind_goto_plan(struct bpf_verifier_env *env, int i)
+{
+	const struct bpf_insn_aux_data *aux = &env->insn_aux_data[i];
+	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;
+}
+
 /*
- * Add unwind_goto after the calls that are sites, see check_unwound_arrival(). Nothing stands
- * between a call and its unwind_goto, and jumps to the insn that follows the call go past it.
+ * Add unwind_goto after the calls that are sites, see check_unwound_arrival(), and after the
+ * accesses to arena that are, see check_arena_site(). Nothing stands between such an insn and its
+ * unwind_goto, and jumps to the insn that follows it go past unwind_goto.
  * 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.
  *
@@ -745,7 +763,6 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added)
 {
 	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;
 	const struct bpf_pad_plan *plan;
@@ -755,13 +772,15 @@ static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added)
 	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++) {
-			plan = bpf_pad_plan(&aux[i], BPF_SITE_CALL);
-			if (!plan || !bpf_site_is_used(env, i, plan))
+			plan = unwind_goto_plan(env, i);
+			if (!plan)
 				continue;
-			/* the insn that follows the call may be dead code, what is appended is not */
+			/* what is appended to the site is not dead code, the next insn may be */
 			err = bpf_patch_list_append(env, i, &unwind_goto, 1);
 			if (err)
 				return err;
+			/* for bpf_check_unwind_gotos() */
+			env->insn_aux_data[i].unwind_goto_follows = true;
 			p = &pl->patches[pl->cnt - 1];
 			bpf_patch_list_jump(pl, &pl->insns[p->start + p->len - 1],
 					    sub[1].start - added[s] + plan->pad, 0);
@@ -831,9 +850,9 @@ static int insert_slot_stores(struct bpf_verifier_env *env, struct bpf_insn *buf
 
 /*
  * Emit what the main pass decided about the sites: may_goto before the insns that it
- * marked, see check_loop_guard(), unwind_goto after calls, the landing pads, and the stores to the
- * hidden slots that the pads read. What a pad does it did to the states that left the frame at the
- * site, see unwind_frame().
+ * marked, see check_loop_guard(), unwind_goto after calls and after accesses to arena, the landing
+ * pads, and the stores to the hidden slots that the pads read. What a pad does it did to the states
+ * that left the frame at the site, see unwind_frame().
  *
  *	may_goto pad		before an insn of a loop, see check_loop_guard(). A may_goto
  *	insn			of the program that is a site jumps to its pad too.
@@ -2266,6 +2285,54 @@ int bpf_jit_subprogs(struct bpf_verifier_env *env)
 	return err;
 }
 
+/* Is @insn a load, a store or an atomic insn in arena? The native code of these can fault. */
+static bool is_arena_access(const struct bpf_insn *insn)
+{
+	u8 class = BPF_CLASS(insn->code), mode = BPF_MODE(insn->code);
+
+	if (class == BPF_LDX)
+		return mode == BPF_PROBE_MEM32 || mode == BPF_PROBE_MEM32SX;
+	if (class == BPF_ST)
+		return mode == BPF_PROBE_MEM32;
+	return class == BPF_STX && (mode == BPF_PROBE_MEM32 || mode == BPF_PROBE_ATOMIC);
+}
+
+/* A call or an access to arena: the exception table can have an entry for the end of the insn */
+static bool can_have_unwind_goto(const struct bpf_insn *insn)
+{
+	return insn->code == (BPF_JMP | BPF_CALL) || bpf_is_callx(insn) || is_arena_access(insn);
+}
+
+/*
+ * unwind_goto is no code. It is an entry of the exception table, which a JIT keys at the end of
+ * the insn in front: a call, or an access to arena. No pass may put anything between the two.
+ * After a call that would be a lost unwind_exit, which bpf_unwind_target() warns about when it
+ * happens. After an access nothing would tell: a fault finds no entry, see
+ * bpf_fault_unwind_target(), and the access is skipped as if no pad had been planned for it.
+ * So look at the insns once they are final, from both sides: unwind_goto has such an insn in
+ * front, and such an insn that the verifier gave unwind_goto still has it behind. An insn that a
+ * pass has replaced by other code is no site any more: the inlined bpf_loop() has unwind_goto of
+ * its own, see inline_bpf_loop().
+ */
+int bpf_check_unwind_gotos(struct bpf_verifier_env *env)
+{
+	const struct bpf_insn *insn = env->prog->insnsi;
+	int i, len = env->prog->len;
+
+	for (i = 0; i < len; i++, insn++) {
+		if (bpf_is_unwind_goto(insn) &&
+		    verifier_bug_if(!i || !can_have_unwind_goto(insn - 1), env,
+				    "unwind_goto at insn %d follows no call and no access to arena",
+				    i))
+			return -EFAULT;
+		if (env->insn_aux_data[i].unwind_goto_follows && can_have_unwind_goto(insn) &&
+		    verifier_bug_if(i + 1 == len || !bpf_is_unwind_goto(insn + 1), env,
+				    "insn %d has lost its unwind_goto", i))
+			return -EFAULT;
+	}
+	return 0;
+}
+
 int bpf_fixup_call_args(struct bpf_verifier_env *env)
 {
 #ifndef CONFIG_BPF_JIT_ALWAYS_ON
diff --git a/kernel/bpf/join.c b/kernel/bpf/join.c
index d07019e9e764..0d88c3477652 100644
--- a/kernel/bpf/join.c
+++ b/kernel/bpf/join.c
@@ -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))
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 60de6a42c756..c213e68ff8cb 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -6,6 +6,7 @@
  * SITE is an insn at which that can happen:
  *   - 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 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
@@ -101,6 +102,18 @@
  *
  * A frame can be in fewer sections than it was called in. Its pad enters the sections that the
  * frame left, so that the caller is in the sections of its call wherever the callee is cancelled.
+ * Here grow() is called with preemption disabled, and its load from arena can fault. The fault
+ * handler finds the pad through the unwind_goto after the load:
+ *
+ *	static void *grow(struct pool *pool)		grow:
+ *	{						   call bpf_preempt_enable
+ *		unlock(pool);				   ...
+ *		p = bpf_arena_alloc_pages(...);		   r1 = *(u64 *)(r0 + 0)
+ *		v = *p;				   +	   unwind_goto pad
+ *		lock(pool);				   call bpf_preempt_disable
+ *		return p;				   exit
+ *	}					   + pad:  call bpf_preempt_disable
+ *						   +	   r0 = 0; unwind_exit
  *
  * A subprog can acquire or release for its caller, as lock() and unlock() functions do. Where the
  * caller has hidden slots, the call stands for what the subprog does, like the call of a kfunc. The
@@ -2351,6 +2364,43 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 	return err;
 }
 
+/*
+ * Is the pad the only way out of the site of @plan? An access to arena that faults can be skipped.
+ * So can all of them below a call, unless a subprog comes back to the call that is left elsewhere.
+ */
+bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+{
+	int s;
+
+	if (plan->kind != BPF_SITE_CALL)
+		return plan->kind != BPF_SITE_FAULT;
+	bpf_pad_for_each_callee(plan, s)
+		if (env->subprog_info[s].must_unwind)
+			return true;
+	return false;
+}
+
+/* What a subprog is left for may be found after its callers were unwound: look at them again */
+void bpf_pads_must_unwind(struct bpf_verifier_env *env)
+{
+	struct bpf_subprog_info *sub;
+	const struct bpf_pad_plan *plan;
+	bool changed;
+	int i, s;
+
+	do {
+		changed = false;
+		for (s = 0; s < env->subprog_cnt; s++) {
+			sub = &env->subprog_info[s];
+			for (i = sub->start; i < sub[1].start && !sub->must_unwind; i++) {
+				plan = bpf_pad_plan(&env->insn_aux_data[i], BPF_SITE_CALL);
+				sub->must_unwind = plan && bpf_pad_must_unwind(env, plan);
+				changed |= sub->must_unwind;
+			}
+		}
+	} while (changed);
+}
+
 /*
  * Does an insn of @sub acquire an iterator or a dynptr? If none does, a reference of its frame that
  * has no location is always a pointer, and the hidden slot of the call that returned it holds it.
@@ -2370,7 +2420,8 @@ static bool acquires_stack_obj(struct bpf_verifier_env *env, const struct bpf_su
 
 /*
  * The groups of which @plan has something that its pad cannot tell whether it is held, or where.
- * None for a site that the program does not have.
+ * Slots are stores on the normal path: none where there is another way out, and none for a site
+ * that the program does not have.
  * @all_ptrs: no insn of the function acquires an iterator or a dynptr.
  */
 static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
@@ -2379,7 +2430,7 @@ static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_pl
 	u8 groups = plan->sections_differ;
 	int i, err;
 
-	if (!plan->used || plan->conflict)
+	if (!plan->used || plan->conflict || !bpf_pad_must_unwind(env, plan))
 		return 0;
 	if (plan->no_place && all_ptrs)
 		groups |= BIT(BPF_PAD_GROUP_REFS);
@@ -2431,6 +2482,16 @@ static bool plan_has_slots(const struct bpf_pad_plan *plan)
 	return plan->kind != BPF_SITE_RECURSION && !plan->conflict;
 }
 
+/* Does @plan have room for @slots releases instead of those that it has of @group? */
+static bool plan_has_room(const struct bpf_pad_plan *plan, int group, int slots)
+{
+	int i;
+
+	for (i = 0; i < plan->nr_ents; i++)
+		slots += class_group(plan->ents[i].class) != group;
+	return slots <= BPF_PAD_MAX_ENTS;
+}
+
 /*
  * Make the pad of @plan release what the frame holds of @group through the hidden slots of the @nr
  * calls in @notes, and in no other way. Each slot becomes a release that is tested for 0. To fit
@@ -2505,7 +2566,7 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	struct bpf_pad_note *head, *note, *notes[BPF_PAD_MAX_ENTS];
 	bool all_ptrs = group == BPF_PAD_GROUP_REFS && !acquires_stack_obj(env, sub);
-	int i, j, k, err, left, nr = 0, slots = 0, words = 0, pend_off = 0;
+	int i, k, err, nr = 0, slots = 0, words = 0, pend_off = 0;
 	struct bpf_pad_plan *plan;
 	u8 hold, nohold;
 
@@ -2574,15 +2635,11 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 	if (pend_off)
 		pend_off = sub->pend_off ?:
 			   -(int)bpf_stack_depth_with_slots(sub) - ++words * BPF_REG_SIZE;
-	for (i = sub->start; i < sub[1].start; i++) {
-		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
-			for (j = 0, left = 0; j < plan->nr_ents; j++)
-				left += class_group(plan->ents[j].class) != group;
+	for (i = sub->start; i < sub[1].start; i++)
+		for (plan = aux[i].pad_plans; plan; plan = plan->next)
 			if (plan->used && plan_has_slots(plan) &&
-			    left + slots > BPF_PAD_MAX_ENTS)
+			    !plan_has_room(plan, group, slots) && bpf_pad_must_unwind(env, plan))
 				return 0;
-		}
-	}
 	sub->hidden_words += words;
 	err = bpf_hidden_slots_fit(env);
 	if (err <= 0) {
@@ -2593,6 +2650,9 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 		sub->pend_off = pend_off;
 	for (i = sub->start; i < sub[1].start; i++) {
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
+			/* it has another way out */
+			if (plan_has_slots(plan) && !plan_has_room(plan, group, slots))
+				plan->conflict = BPF_CONFLICT_SLOTS_FULL;
 			err = plan_has_slots(plan) ?
 			      plan_take_slots(plan, group, notes, nr, all_ptrs) : 0;
 			charge_plan(env, plan);
@@ -2935,10 +2995,13 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 		[BPF_SITE_GUARD]		= "may_goto",
 		[BPF_SITE_RECURSION]		= "recursion check",
 		[BPF_SITE_CALL]			= "call",
+		[BPF_SITE_FAULT]		= "arena access",
 	};
 	static const char * const why[] = {
 		[BPF_CONFLICT_SECTIONS_DIFFER]	= "the number of sections differs",
 		[BPF_CONFLICT_TOO_MUCH]		= "too much is held",
+		[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",
 		[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",
@@ -2994,6 +3057,47 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pa
 	print_plan(env, insn_idx, plan);
 }
 
+/*
+ * The site of @plan, at insn @i, has no pad. An access to arena: it is skipped when it faults.
+ * What follows the access was verified, and less unwinds than the main pass looked at.
+ * Or it is a call, and only accesses to arena unwind below it. They are skipped: what came back to
+ * the call cannot unwind, nor can what came back to the calls in there. The pass is done again,
+ * and they cannot from its start, see check_funcs().
+ */
+static int skip_faults(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
+{
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	int s, c, cnt = env->subprog_cnt;
+	struct bpf_subprog_info *sub;
+	unsigned long *todo;
+
+	if (plan->kind == BPF_SITE_FAULT) {
+		aux[i].fault_skips = true;
+		return 0;
+	}
+	todo = bitmap_zalloc(cnt, BPF_VERIFIER_GFP);
+	if (!todo)
+		return -ENOMEM;
+	env->faults_late = true;
+	bpf_pad_for_each_callee(plan, c)
+		__set_bit(c, todo);
+	while ((s = find_first_bit(todo, cnt)) < cnt) {
+		__clear_bit(s, todo);
+		sub = &env->subprog_info[s];
+		if (!sub->bail_unwinds)
+			continue;
+		sub->bail_unwinds = false;
+		for (i = sub->start; i < sub[1].start; i++) {
+			plan = bpf_pad_plan(&aux[i], BPF_SITE_CALL);
+			if (plan)
+				bpf_pad_for_each_callee(plan, c)
+					__set_bit(c, todo);
+		}
+	}
+	bitmap_free(todo);
+	return 0;
+}
+
 /*
  * 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
@@ -3024,6 +3128,7 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 	struct bpf_pad_plan *plan;
 	int i, s, err;
 
+	bpf_pads_must_unwind(env);
 	/* sort the releases first: hidden slots are inserted into that order */
 	for (i = 0; i < env->prog->len; i++) {
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next) {
@@ -3045,14 +3150,17 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 			if (err < 0)
 				return err;
 			plan->conflict = err;
-			if (plan->conflict) {
+			if (plan->conflict && bpf_pad_must_unwind(env, plan)) {
 				print_plan(env, i, plan);
 				return -EINVAL;
 			}
+			err = plan->conflict ? skip_faults(env, i, plan) : 0;
+			if (err)
+				return err;
 		}
 	}
 	/* all accesses of the program to its stack are known: the hidden words go below them */
-	for (s = 0; s < env->subprog_cnt; s++) {
+	for (s = 0; !env->faults_late && s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
 		if (!sub->hidden_words)
 			continue;
@@ -3063,13 +3171,13 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 	return 0;
 }
 
-/* A site at the insn has no landing pad that serves all states, see bpf_pads_settle() */
-bool bpf_pads_conflict(const struct bpf_insn_aux_data *aux)
+/* Does a site at the insn of @aux reject the program, see bpf_pads_settle()? */
+bool bpf_pads_conflict(struct bpf_verifier_env *env, const struct bpf_insn_aux_data *aux)
 {
 	const struct bpf_pad_plan *plan;
 
 	for (plan = aux->pad_plans; plan; plan = plan->next)
-		if (plan->used && plan->conflict)
+		if (plan->used && plan->conflict && bpf_pad_must_unwind(env, plan))
 			return true;
 	return false;
 }
@@ -3235,7 +3343,8 @@ void bpf_pads_note_causes(struct bpf_verifier_env *env)
 	env->ref_conflict = false;
 	for (i = 0; i < env->prog->len; i++)
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next)
-			if (plan->failed || (plan->used && plan->conflict))
+			if (plan->failed || (plan->used && plan->conflict &&
+					     bpf_pad_must_unwind(env, plan)))
 				note_causes(env, i, plan);
 	note_causes_below(env);
 	/* The caller checks the limits before the next pass. This is for a load that ends here. */
diff --git a/kernel/bpf/precision.c b/kernel/bpf/precision.c
index 2576ba62da5d..feaab0485bdb 100644
--- a/kernel/bpf/precision.c
+++ b/kernel/bpf/precision.c
@@ -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))) {
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 478fdc2d6642..07fdc4fc7ebc 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -224,6 +224,7 @@ static bool is_trusted_reg(struct bpf_verifier_env *env, const struct bpf_reg_st
 static inline bool in_sleepable_context(struct bpf_verifier_env *env);
 static bool in_rcu_callback(struct bpf_verifier_env *env);
 static const char *non_sleepable_context_description(struct bpf_verifier_env *env);
+static int check_arena_site(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
 
 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
 			      struct bpf_map *map,
@@ -3409,12 +3410,17 @@ static bool is_indirect_call(const struct bpf_insn *insn)
 static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)
 {
 	struct bpf_subprog_info *sub = &env->subprog_info[subprog];
+	bool did_unwind = sub->did_unwind && sub->bail_unwinds;
 
-	if (sub->did_unwind) {
+	if (did_unwind)
+		bpf_pads_must_unwind(env);
+	if (did_unwind && sub->must_unwind) {
 		verbose(env, "callback cannot unwind at insn %d: %s() does\n",
 			env->insn_idx, bpf_subprog_name(env, subprog));
 		return -EINVAL;
 	}
+	/* It did at accesses to arena only. They are skipped, and the pass is done again. */
+	env->faults_late |= did_unwind;
 	sub->bail_unwinds = false;
 	return 0;
 }
@@ -4408,6 +4414,8 @@ static int check_stack_write(struct bpf_verifier_env *env,
 	int max_off = reg_smax(reg) + off + size;
 	int err;
 
+	if (state != cur_func(env))
+		cur_func(env)->fault_edge = false;
 	if (tnum_is_const(reg->var_off)) {
 		off += reg->var_off.value;
 		err = check_stack_write_fixed_off(env, state, off, size,
@@ -6147,7 +6155,15 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 				     (s && env->prog->jit_requested && bpf_jit_supports_unwind() &&
 				      !bpf_prog_is_offloaded(env->prog->aux) && bpf_may_unwind(env) &&
 				      (cg.marks[s] & CALLED));
-		si[s].did_unwind = si[s].unwinds_for_sure = si[s].can_unwind;
+		si[s].bail_unwinds_at_first = si[s].bail_unwinds;
+		si[s].must_unwind = si[s].unwinds_for_sure = si[s].can_unwind;
+		/*
+		 * The callers of a global subprog are verified ahead of it, see unwind_frame().
+		 * Where there is an arena expect it to unwind, that saves a pass.
+		 */
+		si[s].did_unwind = si[s].can_unwind ||
+				   (env->prog->aux->arena && si[s].bail_unwinds &&
+				    bpf_subprog_is_global(env, s));
 	}
 
 	for (s = 0; s < cnt; s++) {
@@ -7795,6 +7811,10 @@ static int check_load_mem(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		return err;
 
 	src_reg_type = regs[insn->src_reg].type;
+	err = check_arena_site(env, &regs[insn->src_reg]);
+	if (err)
+		return err;
+
 	/* A flexible array has no end, see btf_struct_access(). A far load from it can fault. */
 	if (base_type(src_reg_type) == PTR_TO_BTF_ID && offset_is_far(&regs[insn->src_reg])) {
 		if (BPF_CLASS(insn->code) != BPF_LDX) {
@@ -7865,6 +7885,9 @@ static int check_store_reg(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		return err;
 
 	dst_reg_type = regs[insn->dst_reg].type;
+	err = check_arena_site(env, &regs[insn->dst_reg]);
+	if (err)
+		return err;
 
 	/* Check if (dst_reg + off) is writeable. */
 	err = check_mem_access(env, env->insn_idx, regs + insn->dst_reg,
@@ -7924,6 +7947,11 @@ static int check_atomic_rmw(struct bpf_verifier_env *env,
 		return -EACCES;
 	}
 
+	/* load_reg may be dst_reg. Look at dst_reg before it's marked as unknown. */
+	err = check_arena_site(env, cur_regs(env) + insn->dst_reg);
+	if (err)
+		return err;
+
 	load_reg = bpf_atomic_load_reg(insn);
 	if (load_reg >= 0) {
 		/* check and record load of old value */
@@ -21134,6 +21162,11 @@ static int check_arena_sp_insn(struct bpf_verifier_env *env, struct bpf_insn *in
 		return err;
 	}
 
+	/* An access to the stack in arena can fault like any access to arena: it is a site. */
+	err = check_arena_site(env, &arena);
+	if (err)
+		return err;
+
 	if (is_arena_sp_ldx(insn)) {
 		err = check_reg_arg(env, insn->dst_reg, DST_OP_NO_MARK);
 		if (err)
@@ -21199,6 +21232,9 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
 			return err;
 
 		dst_reg_type = cur_regs(env)[insn->dst_reg].type;
+		err = check_arena_site(env, cur_regs(env) + insn->dst_reg);
+		if (err)
+			return err;
 
 		err = check_mem_access(env, env->insn_idx, cur_regs(env) + insn->dst_reg,
 				       argno_from_reg(insn->dst_reg),
@@ -21214,6 +21250,7 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
 		u8 opcode = BPF_OP(insn->code);
 
 		if (opcode == BPF_CALL) {
+			cur_func(env)->fault_edge = false;
 			if (env->cur_state->active_locks) {
 				/* similar to static subprog calls callx is allowed under a lock */
 				if (!bpf_is_callx(insn) &&
@@ -21936,6 +21973,79 @@ static int check_loop_guard(struct bpf_verifier_env *env)
 	return err;
 }
 
+/* Is all that the current frame of @st holds a pointer, which is NULL where nothing is held? */
+static bool frame_holds_pointers_only(const struct bpf_verifier_state *st)
+{
+	const struct bpf_func_state *frame = st->frame[st->curframe];
+	int i;
+
+	for (i = frame->entry_refs; i < st->acquired_refs; i++)
+		if (st->refs[i].type != REF_TYPE_PTR)
+			return false;
+	return st->active_rcu_locks == frame->entry_rcu_locks &&
+	       st->active_preempt_locks == frame->entry_preempt_locks;
+}
+
+/*
+ * An access through an arena pointer, @reg, faults when the page is not mapped. Then the program
+ * is unwound. The site is the access itself, with the state before it takes effect, since the
+ * fault precedes any write of its result.
+ *
+ * This site has another way out, which costs nothing: the access is skipped, a load reads 0. It
+ * is taken where the frame cannot unwind and where no pad serves all states: a conflict here does
+ * not reject the program. There are many of them. The normal path pays nothing, the main pass little:
+ *
+ *   The frame holds nothing, in all states that get here: there is no plan and no visit.
+ *
+ *   It holds something: each state visits the plan, as it is. If states went by without a visit
+ *   the plan does not know what is NULL where nothing is held, see visit_refs(). All is done again,
+ *   and then all states visit. Unless what is held is no pointer: no test tells.
+ *
+ *   A copy of the state leaves the frame, see unwind_frame(), once per stretch of insns
+ *   without a call and without a store to the stack of a caller. They alone change what gets to the
+ *   caller: what the frame holds is dropped, R0 is set. See 'fault_edge', and bpf_states_join().
+ */
+static int check_arena_site(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
+{
+	struct bpf_insn_aux_data *aux = cur_aux(env);
+	struct bpf_verifier_state *st = env->cur_state;
+	struct bpf_func_state *frame = cur_func(env);
+	struct bpf_pad_plan *plan;
+	bool visits;
+
+	/* frame_cannot_unwind() does not ask the JIT about a frame that the kernel called. */
+	if (reg->type != PTR_TO_ARENA || aux->fault_skips ||
+	    !bpf_jit_supports_unwind())
+		return 0;
+	visits = frame_holds_resources(st) || aux->fault_full || bpf_pad_plan(aux, BPF_SITE_FAULT);
+	if (!visits) {
+		aux->fault_empty = true;
+		if (frame->fault_edge)
+			return 0;
+	}
+	if (frame_cannot_unwind(env, st)) {
+		aux->fault_skips = true;
+		return 0;
+	}
+	if (visits) {
+		if (aux->fault_empty && !aux->fault_full) {
+			if (!frame_holds_pointers_only(st)) {
+				aux->fault_skips = true;
+				return 0;
+			}
+			aux->fault_full = true;
+			env->faults_late = true;
+		}
+		plan = bpf_pad_visit(env, st, env->insn_idx, BPF_SITE_FAULT);
+		if (IS_ERR(plan))
+			return PTR_ERR(plan);
+		if (plan->conflict || frame->fault_edge)
+			return 0;
+	}
+	frame->fault_edge = true;
+	return push_unwind_edge(env, BPF_SITE_FAULT);
+}
+
 /*
  * 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.
@@ -21963,11 +22073,11 @@ static void unmark_stack_obj(struct bpf_verifier_env *env, int id)
 }
 
 /*
- * The current frame is left at a site, and its landing pad releases what the frame acquired since
- * 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.
+ * The current frame leaves at a site. Do to the current state what the landing pad does: release
+ * what the frame acquired since its entry, youngest first, and bring the state back to the sections
+ * that it was in at the call. Pointers of the callers that are valid only under a lock or in a
+ * section are invalidated like after a release by the program.
+ * @plan: the record of the site, or NULL at an access to arena where no state holds anything.
  */
 static int release_frame_resources(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
 {
@@ -22003,8 +22113,10 @@ static int release_frame_resources(struct bpf_verifier_env *env, const struct bp
 	 */
 	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]);
+	if (plan) {
+		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))
@@ -22051,7 +22163,9 @@ static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_p
  *
  * With a conflict there is no pad: the site is an unproven insn in @st, which ends here. The pass
  * goes on, and a pass that keeps more apart may have no such state.
- * A frame that cannot unwind is a conflict.
+ * A frame that cannot unwind is a conflict. At an access to arena check_arena_site() saw to both.
+ * At a call that has only such accesses below it a conflict is no error: @st is dropped, and
+ * bpf_pads_settle() has the accesses skipped.
  * Nor is it one at a site that the program may not have in the end, see site_is_certain(): @st is
  * dropped, the plan keeps the conflict, and bpf_pads_settle() makes it an error of the pass if the
  * site is still there.
@@ -22062,34 +22176,37 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	struct bpf_func_state *frame = st->frame[st->curframe];
 	struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
 	struct bpf_verifier_state *cur = env->cur_state;
-	int cur_idx = env->insn_idx, err;
-	struct bpf_pad_plan *plan;
-	bool print_state, certain;
+	int cur_idx = env->insn_idx, err = 0;
+	struct bpf_pad_plan *plan = NULL;
+	bool print_state, certain = false;
 	u32 cnt;
 
 	env->cur_state = st;
 	env->insn_idx = insn_idx;
-	/* its suspects are those of a conflict that only bpf_pads_settle() finds */
-	env->insn_aux_data[insn_idx].suspect_loops |= st->suspect_loops;
-	plan = bpf_pad_visit(env, st, insn_idx, kind);
-	err = PTR_ERR_OR_ZERO(plan);
-	if (err)
-		goto out;
-	/* there is no other way out */
-	if (!plan->conflict)
-		plan->conflict = frame_cannot_unwind(env, st);
-	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;
+	if (kind != BPF_SITE_FAULT) {
+		/* Keep the suspects for an error that only bpf_pads_settle() raises. */
+		env->insn_aux_data[insn_idx].suspect_loops |= st->suspect_loops;
+		plan = bpf_pad_visit(env, st, insn_idx, kind);
+		err = PTR_ERR_OR_ZERO(plan);
+		if (err)
+			goto out;
+		if (!plan->conflict)
+			plan->conflict = frame_cannot_unwind(env, st);
+		certain = site_is_certain(env, plan, insn_idx);
+		/* there is no other way out */
+		if (plan->conflict && bpf_pad_must_unwind(env, plan) && certain) {
+			bpf_pad_log(env, insn_idx, plan);
+			/* for bpf_pads_note_causes() */
+			plan->failed = true;
+			err = -EINVAL;
+			goto unproven;
+		}
+		if (plan->conflict)
+			goto out;
 	}
-	if (plan->conflict)
-		goto out;
 
-	err = release_frame_resources(env, plan);
+	/* At an access to arena check_arena_site() has recorded the state, if anything is held. */
+	err = release_frame_resources(env, bpf_pad_plan(&env->insn_aux_data[insn_idx], kind));
 	if (err)
 		goto out;
 	bpf_mark_reg_known_scalar(&frame->regs[BPF_REG_0],
@@ -22110,7 +22227,8 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		env->pads_late = true;
 	}
 	sub->did_unwind |= st->unwound;
-	sub->unwinds_for_sure |= st->unwound && certain;
+	sub->must_unwind |= st->unwound && plan && bpf_pad_must_unwind(env, plan);
+	sub->unwinds_for_sure |= st->unwound && plan && bpf_pad_must_unwind(env, plan) && certain;
 	if (env->log.level & BPF_LOG_LEVEL2)
 		verbose(env, "from %d to %s of func#%d\n", insn_idx,
 			st->unwound ? "unwind_exit" : "exit", frame->subprogno);
@@ -22649,7 +22767,7 @@ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
 static bool pass_needs_restart(struct bpf_verifier_env *env)
 {
 	return (env->restart && bpf_flow_loops_lost_bound(env)) || env->guards_late ||
-	       env->pads_late;
+	       env->pads_late || env->faults_late;
 }
 
 /*
@@ -24301,10 +24419,25 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
 		/* did_unwind and did_cancel of a global subprog go to the next pass. */
 		if (bpf_subprog_is_global(env, i))
 			initial->subprogs[i].did_unwind |= env->subprog_info[i].did_unwind;
+		/*
+		 * The accesses to arena in it are skipped and the pass is done again, see
+		 * subprog_cannot_unwind() and skip_faults(). The second run has to know from its
+		 * start that the subprog cannot unwind, or it finds out late once more.
+		 * No other run knows: like all else about a subprog that is what one pass finds. A
+		 * pass that keeps more apart, and a path-sensitive run, may not get to the call
+		 * that has no landing pad for the subprog, or may have no conflict at its
+		 * caller. Then the subprog is left where it has to unwind, and it can.
+		 */
+		if (!env->pass_again)
+			initial->subprogs[i].bail_unwinds =
+				initial->subprogs[i].bail_unwinds_at_first;
+		else if (env->faults_late)
+			initial->subprogs[i].bail_unwinds &= env->subprog_info[i].bail_unwinds;
 		/* 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;
 	}
+	env->pass_again = false;
 	restore_snapshot(env, initial);
 	kvfree(env->callx_edges);
 	kvfree(env->callx_index.slots);
@@ -24338,7 +24471,11 @@ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial
 	 * function, so the landing pads are settled before the stack is checked.
 	 */
 	mark_used_sites(env, initial);
-	ret = bpf_pads_settle(env) ?: check_after_pass(env);
+	ret = bpf_pads_settle(env);
+	/* accesses to arena are skipped after all, see skip_faults() */
+	if (!ret && pass_needs_restart(env))
+		return 0;
+	ret = ret ?: check_after_pass(env);
 	if (ret) {
 		bpf_find_unproven_after_pass(env);
 		bpf_pads_note_causes(env);
@@ -24605,8 +24742,10 @@ static int do_check_all(struct bpf_verifier_env *env)
 			bpf_restore_precision(env);
 		} else if (!ret) {
 			bpf_flow_drop_guards(env);
-			if (pass_needs_restart(env))
+			if (pass_needs_restart(env)) {
+				env->pass_again = true;
 				continue;
+			}
 			if (env->for_log && (!offload || replay))
 				break;
 			max_cost = good_pass ? max_cost : env->max_cost;
@@ -26839,6 +26978,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 								     : false;
 	}
 
+	if (ret == 0)
+		ret = bpf_check_unwind_gotos(env);
+
 	if (ret == 0)
 		ret = bpf_fixup_call_args(env);
 
diff --git a/tools/testing/selftests/bpf/prog_tests/stream.c b/tools/testing/selftests/bpf/prog_tests/stream.c
index ae400dcfbf24..b1ad2dfe432f 100644
--- a/tools/testing/selftests/bpf/prog_tests/stream.c
+++ b/tools/testing/selftests/bpf/prog_tests/stream.c
@@ -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);
 
diff --git a/tools/testing/selftests/bpf/progs/arena_atomics.c b/tools/testing/selftests/bpf/progs/arena_atomics.c
index 2a9664f54399..c12f7e6894e9 100644
--- a/tools/testing/selftests/bpf/progs/arena_atomics.c
+++ b/tools/testing/selftests/bpf/progs/arena_atomics.c
@@ -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;
diff --git a/tools/testing/selftests/bpf/progs/arena_skipped.h b/tools/testing/selftests/bpf/progs/arena_skipped.h
new file mode 100644
index 000000000000..8b0a265ec6aa
--- /dev/null
+++ b/tools/testing/selftests/bpf/progs/arena_skipped.h
@@ -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; })
diff --git a/tools/testing/selftests/bpf/progs/jit_insns_arena.c b/tools/testing/selftests/bpf/progs/jit_insns_arena.c
index 8f71d907ee57..b3dbe53eb2f0 100644
--- a/tools/testing/selftests/bpf/progs/jit_insns_arena.c
+++ b/tools/testing/selftests/bpf/progs/jit_insns_arena.c
@@ -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)
diff --git a/tools/testing/selftests/bpf/progs/pro_epilogue_arena_stack.c b/tools/testing/selftests/bpf/progs/pro_epilogue_arena_stack.c
index 40fbcc004608..e901282c53a3 100644
--- a/tools/testing/selftests/bpf/progs/pro_epilogue_arena_stack.c
+++ b/tools/testing/selftests/bpf/progs/pro_epilogue_arena_stack.c
@@ -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")
diff --git a/tools/testing/selftests/bpf/progs/stream.c b/tools/testing/selftests/bpf/progs/stream.c
index 8c49a130150b..949c1b2fa6c0 100644
--- a/tools/testing/selftests/bpf/progs/stream.c
+++ b/tools/testing/selftests/bpf/progs/stream.c
@@ -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"
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena.c b/tools/testing/selftests/bpf/progs/verifier_arena.c
index 99856ee10795..e46ce213c34d 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena.c
@@ -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;
 }
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena_large.c b/tools/testing/selftests/bpf/progs/verifier_arena_large.c
index 89f32a7772ac..73dc5ac69a82 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena_large.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena_large.c
@@ -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;
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
index 6d188a19206f..c7d613669c38 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
@@ -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("...")
diff --git a/tools/testing/selftests/bpf/progs/verifier_ldsx.c b/tools/testing/selftests/bpf/progs/verifier_ldsx.c
index 232082428cb9..acf4f0471e4c 100644
--- a/tools/testing/selftests/bpf/progs/verifier_ldsx.c
+++ b/tools/testing/selftests/bpf/progs/verifier_ldsx.c
@@ -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
diff --git a/tools/testing/selftests/bpf/progs/verifier_zext.c b/tools/testing/selftests/bpf/progs/verifier_zext.c
index 9fce1dd8ef7b..fc8594542845 100644
--- a/tools/testing/selftests/bpf/progs/verifier_zext.c
+++ b/tools/testing/selftests/bpf/progs/verifier_zext.c
@@ -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)
 {
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 37/73] bpf: Share one landing pad among accesses to arena where nothing is held
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (35 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 36/73] bpf: Cancel a program at a fault in arena Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 38/73] bpf: Keep R0, R6-R9 and the stack live at a call of bpf_throw() Kumar Kartikeya Dwivedi
                   ` (35 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index 730f9d95bca1..5e4e08a65ea3 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -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();
 
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 0f35aed5df7e..e91148abbfbb 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -1879,18 +1879,18 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
  *
  * Bit layout of `fixup` (32-bit):
  *
- * +-----------+-------------+----------+--------+-----------+---------+----------+
- * | 31        | 30          | 29       | 28-24  |   23-16   |   15-8  |    7-0   |
- * |           |             |          |        |           |         |          |
- * | ARENA_ACC | ARENA_WRITE | R0_IN_AX | Unused | ARENA_REG | DST_REG | INSN_LEN |
- * +-----------+-------------+----------+--------+-----------+---------+----------+
+ * +-----------+-------------+----------+---------+--------+-----------+---------+----------+
+ * | 31        | 30          | 29       | 28      | 27-24  |   23-16   |   15-8  |    7-0   |
+ * |           |             |          |         |        |           |         |          |
+ * | ARENA_ACC | ARENA_WRITE | R0_IN_AX | UNWINDS | Unused | ARENA_REG | DST_REG | INSN_LEN |
+ * +-----------+-------------+----------+---------+--------+-----------+---------+----------+
  *
- * - INSN_LEN (8 bits): How far the end of the code of the BPF insn is from the faulting insn.
- *                      That is its own length for a single-insn access, but the distance to
- *                      the end of the whole sequence where one BPF insn became several, as for
- *                      the CMPXCHG loop of a fetching AND/OR/XOR. A sequence long enough to
- *                      overflow this field would first have to exceed BPF_MAX_INSN_SIZE, which
- *                      do_jit() rejects with -EFAULT before the image is used.
+ * - INSN_LEN (8 bits): How far past the faulting insn the BPF insn ends. That is its own length
+ *                      for a single-insn access, but the distance to the end of the whole
+ *                      sequence where one BPF insn became several, as for the CMPXCHG loop
+ *                      of a fetching AND/OR/XOR. A sequence long enough to overflow this
+ *                      field would first have to exceed BPF_MAX_INSN_SIZE, which do_jit()
+ *                      rejects with -EFAULT before the image is used.
  * - DST_REG  (8 bits): Offset of dst_reg from reg2pt_regs[] (max offset = 112 (fits in 8 bits)).
  *                      This is set to DONT_CLEAR if the insn does not read into a register.
  * - ARENA_REG (8 bits): Offset of the register that is used to calculate the
@@ -1899,9 +1899,12 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
  *                        It is independent of DST_REG, since a read-modify-write both writes to
  *                        memory and reads the old value into a register.
  * - ARENA_ACCESS (1 bit): This bit is set when the faulting instruction accessed the arena region.
- * - R0_IN_AX (1 bit): R0 is in BPF_REG_AX while the faulting insn runs: the CMPXCHG loop of a
- *                     fetching AND/OR/XOR keeps it there while RAX serves the CMPXCHG. The
- *                     handler puts it back, since it leaves the sequence.
+ * - R0_IN_AX (1 bit): R0 is in BPF_REG_AX when the insn faults. The CMPXCHG loop of a fetching
+ *                     AND/OR/XOR keeps it there while RAX serves the CMPXCHG. The handler skips
+ *                     the insn that moves it back, so it copies BPF_REG_AX to RAX itself.
+ * - 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.
  *
  * Bit layout of `data` (32-bit):
  *
@@ -1919,6 +1922,7 @@ static int emit_atomic_fetch_rmw(u8 **pprog, struct bpf_insn *insn, u32 dst_reg,
 #define FIXUP_INSN_LEN_MASK	GENMASK(7, 0)
 #define FIXUP_REG_MASK		GENMASK(15, 8)
 #define FIXUP_ARENA_REG_MASK	GENMASK(23, 16)
+#define FIXUP_ARENA_UNWINDS	BIT(28)
 #define FIXUP_ARENA_R0_IN_AX	BIT(29)
 #define FIXUP_ARENA_WRITE	BIT(30)
 #define FIXUP_ARENA_ACCESS	BIT(31)
@@ -1939,7 +1943,8 @@ bool ex_handler_bpf(const struct exception_table_entry *x, struct pt_regs *regs)
 		arena_reg = FIELD_GET(FIXUP_ARENA_REG_MASK, x->fixup);
 		off = FIELD_GET(DATA_ARENA_OFFSET_MASK, x->data);
 		addr = *(unsigned long *)((void *)regs + arena_reg) + off;
-		pad = bpf_arena_fault(is_write, addr, regs->ip, end);
+		pad = bpf_arena_fault(is_write, addr, regs->ip, end,
+				      x->fixup & FIXUP_ARENA_UNWINDS);
 	}
 
 	/*
@@ -2625,6 +2630,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		u8 *func;
 		int nops;
 		u32 jmp_op = BPF_OP(insn->code);
+		u32 fault_unwinds;
 		s32 cmp_imm;
 
 		if (priv_frame_ptr) {
@@ -2643,6 +2649,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 		accesses_stack_only =
 			env ? !env->insn_aux_data[insn_idx].non_stack_access :
 			      false;
+		fault_unwinds = bpf_insn_fault_unwinds(env, bpf_prog, i - 1) ?
+				FIXUP_ARENA_UNWINDS : 0;
 
 		switch (insn->code) {
 			/* ALU */
@@ -3137,8 +3145,8 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 				err = emit_arena_exentry(bpf_prog, image, rw_image, &excnt,
 							 image + proglen + (start_of_ldx - temp),
 							 prog - start_of_ldx, fixup_reg, arena_reg,
-							 is_write ? FIXUP_ARENA_WRITE : 0,
-							 insn->off);
+							 (is_write ? FIXUP_ARENA_WRITE : 0) |
+							 fault_unwinds, insn->off);
 				if (err)
 					return err;
 			}
@@ -3372,7 +3380,7 @@ static int do_jit(struct bpf_verifier_env *env, struct bpf_prog *bpf_prog, int *
 								 prog - fault[j],
 								 reg2pt_regs[real_src_reg],
 								 reg2pt_regs[real_dst_reg],
-								 FIXUP_ARENA_WRITE |
+								 FIXUP_ARENA_WRITE | fault_unwinds |
 								 FIXUP_ARENA_R0_IN_AX, insn->off);
 					if (err)
 						return err;
@@ -5059,6 +5067,10 @@ struct bpf_prog *bpf_int_jit_compile(struct bpf_verifier_env *env, struct bpf_pr
 		 * decrement proglen.
 		 */
 		prog->bpf_func = (void *)image + cfi_get_offset();
+		/* addrs[] counts from the image, not from bpf_func */
+		if (bpf_prog_fault_pad(env, prog))
+			prog->aux->fault_pad = (unsigned long)image +
+					       addrs[bpf_prog_fault_pad(env, prog)];
 		prog->jited = 1;
 		prog->jited_len = proglen - cfi_get_offset();
 	}
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index f7ac105d9dd3..e981d486a337 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -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;
 }
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 0b3e9dcd6aef..3d699dd1045f 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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;
 };
diff --git a/kernel/bpf/arena.c b/kernel/bpf/arena.c
index 2890c65ad26a..ebe4ac74f219 100644
--- a/kernel/bpf/arena.c
+++ b/kernel/bpf/arena.c
@@ -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;
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 0f7199c5c1b8..3582cde3cfe3 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -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;
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 8e007e4fad99..75ad6f567e14 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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;
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
index c7d613669c38..63697cbd5a92 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
@@ -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)
 {
diff --git a/tools/testing/selftests/bpf/progs/verifier_zext.c b/tools/testing/selftests/bpf/progs/verifier_zext.c
index fc8594542845..9fce1dd8ef7b 100644
--- a/tools/testing/selftests/bpf/progs/verifier_zext.c
+++ b/tools/testing/selftests/bpf/progs/verifier_zext.c
@@ -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)
 {
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 38/73] bpf: Keep R0, R6-R9 and the stack live at a call of bpf_throw()
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (36 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 37/73] bpf: Share one landing pad among accesses to arena where nothing is held Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 39/73] bpf: Refuse freplace on a function that can unwind Kumar Kartikeya Dwivedi
                   ` (34 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 kernel/bpf/liveness.c | 17 ++++++++++++++---
 1 file changed, 14 insertions(+), 3 deletions(-)

diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index a7120ecb0e80..93f8d1686496 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -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;
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 39/73] bpf: Refuse freplace on a function that can unwind
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (37 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 38/73] bpf: Keep R0, R6-R9 and the stack live at a call of bpf_throw() Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` bot+bpf-ci
  2026-12-01  5:51   ` sashiko-bot
  2026-12-01  4:39 ` [PATCH bpf-next v1 40/73] bpf: Let landing pads pass on the value of unwind_exit Kumar Kartikeya Dwivedi
                   ` (33 subsequent siblings)
  72 siblings, 2 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 3d699dd1045f..91d8831de4e9 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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 */
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 75ad6f567e14..a20830a628e7 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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);
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 07fdc4fc7ebc..784810772b11 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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;
diff --git a/tools/testing/selftests/bpf/prog_tests/unwind_attach.c b/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
index 674c5272cf75..5ec96f478493 100644
--- a/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
+++ b/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
@@ -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");
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 40/73] bpf: Let landing pads pass on the value of unwind_exit
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (38 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 39/73] bpf: Refuse freplace on a function that can unwind Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 41/73] bpf: Keep a reference of the caller that a function finds NULL Kumar Kartikeya Dwivedi
                   ` (32 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 91d8831de4e9..e53a9f8618f6 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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,
diff --git a/kernel/bpf/const_fold.c b/kernel/bpf/const_fold.c
index 1a84ba1d27bf..17d208f1ed0e 100644
--- a/kernel/bpf/const_fold.c
+++ b/kernel/bpf/const_fold.c
@@ -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: {
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index a20830a628e7..233eca6e0df0 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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)
 {
diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index bc6f2a8da05e..1b55e9158332 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -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);
diff --git a/kernel/bpf/join.c b/kernel/bpf/join.c
index 0d88c3477652..466693fa0b80 100644
--- a/kernel/bpf/join.c
+++ b/kernel/bpf/join.c
@@ -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);
 	/*
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index c213e68ff8cb..ba402a4e10e9 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -99,6 +99,8 @@
  * 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
+ * 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
  * frame left, so that the caller is in the sections of its call wherever the callee is cancelled.
@@ -2268,6 +2270,13 @@ static int release_ents(struct bpf_verifier_env *env, const struct bpf_pad_plan
 	return n;
 }
 
+/* The calls of the pad of @plan clobber the value that it has to pass on */
+static bool plan_saves_value(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+{
+	return bpf_site_has_value(env, plan->kind) &&
+	       (plan->nr_ents || plan->sections[BPF_PAD_RCU] || plan->sections[BPF_PAD_PREEMPT]);
+}
+
 /*
  * Emit the insns of the pad of @plan, a site in @subprog, except the last one, which leaves the
  * frame. The main pass does not see these insns, so the aux data that later passes look up for them
@@ -2276,9 +2285,12 @@ static int release_ents(struct bpf_verifier_env *env, const struct bpf_pad_plan
 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)
 {
-	int class, i, n;
+	int value_off = env->subprog_info[subprog].value_off;
+	int class, i, n = 0;
 
-	n = release_ents(env, plan, PAD_TURN_RCU_ITERS, buf, aux);
+	if (plan_saves_value(env, plan))
+		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_0, 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++)
 		for (i = 0; i < pad_leaves(plan, class); i++)
@@ -2288,7 +2300,10 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
 		for (i = 0; i < pad_enters(plan, class); i++)
 			buf[n++] = enter_call(class);
-	buf[n++] = BPF_MOV64_IMM(BPF_REG_0, bpf_cancelled_retval(env, subprog));
+	if (plan_saves_value(env, plan))
+		buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, 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));
 	if (bpf_ret_reg_pair(env, subprog))
 		buf[n++] = BPF_MOV64_IMM(BPF_REG_2, 0);
 	return n;
@@ -2682,6 +2697,7 @@ static int settle_slots(struct bpf_verifier_env *env)
 	for (s = 0; s < env->subprog_cnt; s++) {
 		env->subprog_info[s].slots = 0;
 		env->subprog_info[s].hidden_words = 0;
+		env->subprog_info[s].value_off = 0;
 		env->subprog_info[s].pend_off = 0;
 	}
 	for (s = 0; s < env->subprog_cnt; s++) {
@@ -3011,6 +3027,8 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 		[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",
+		[BPF_CONFLICT_NO_VALUE]		= "the value of unwind_exit is not a number",
+		[BPF_CONFLICT_NO_ROOM]		= "no room in the stack for the value",
 	};
 	int j;
 
@@ -3098,6 +3116,26 @@ static int skip_faults(struct bpf_verifier_env *env, int i, const struct bpf_pad
 	return 0;
 }
 
+/*
+ * The pads of @sub keep the value over their calls in a hidden word of the frame, below the
+ * hidden slots. Nothing else writes it. Returns the reason of a conflict.
+ */
+static int take_value_word(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
+{
+	int err;
+
+	if (sub->value_off)
+		return 0;
+	sub->hidden_words++;
+	err = bpf_hidden_slots_fit(env);
+	if (err <= 0) {
+		sub->hidden_words--;
+		return err ?: BPF_CONFLICT_NO_ROOM;
+	}
+	sub->value_off = -(int)bpf_stack_depth_with_slots(sub);
+	return 0;
+}
+
 /*
  * 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
@@ -3147,6 +3185,8 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 			if (!plan->used)
 				continue;
 			err = settle_plan(env, plan);
+			if (!err && plan_saves_value(env, plan))
+				err = take_value_word(env, bpf_find_containing_subprog(env, i));
 			if (err < 0)
 				return err;
 			plan->conflict = err;
diff --git a/kernel/bpf/precision.c b/kernel/bpf/precision.c
index feaab0485bdb..776fb82b11ec 100644
--- a/kernel/bpf/precision.c
+++ b/kernel/bpf/precision.c
@@ -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) {
diff --git a/kernel/bpf/states.c b/kernel/bpf/states.c
index 18f82546fa09..9201e3cbc448 100644
--- a/kernel/bpf/states.c
+++ b/kernel/bpf/states.c
@@ -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))
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 784810772b11..9b000754ae2f 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -3489,6 +3489,7 @@ static int check_unwind_insns(struct bpf_verifier_env *env)
 			bpf_find_containing_subprog(env, i)->can_unwind = true;
 			seen = true;
 		}
+		env->has_throw |= bpf_is_throw_kfunc(insn);
 		if (!bpf_is_unwind_goto(insn))
 			continue;
 		seen = true;
@@ -12329,6 +12330,10 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 			if (IS_ERR(branch))
 				return PTR_ERR(branch);
 			branch->unwound = true;
+			/* R0 has the value of the unwinding, also after a void function. */
+			if (env->has_throw)
+				mark_reg_unknown(env, branch->frame[branch->curframe]->regs,
+						 BPF_REG_0);
 		}
 
 		if (env->subprog_info[subprog].might_throw) {
@@ -20541,7 +20546,12 @@ static int check_global_subprog_return_code(struct bpf_verifier_env *env)
 	u32 i, nregs;
 	int err;
 
-	if (subprog_returns_void(env, subprog))
+	/*
+	 * R0 is checked at unwind_exit in a void function too: the landing pads of the callers
+	 * read it as a scalar, see check_func_call().
+	 */
+	if (subprog_returns_void(env, subprog) &&
+	    !bpf_is_unwind_exit(&env->prog->insnsi[env->insn_idx]))
 		return 0;
 
 	nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1;
@@ -20940,6 +20950,18 @@ static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type typ
 }
 
 
+/*
+ * The program starts to unwind with the value in R@regno. In a program with bpf_throw() the landing
+ * pads that the verifier emits pass the value on, and the main program returns it. Nobody
+ * looks at what an async callback returns.
+ */
+static int check_unwound_value(struct bpf_verifier_env *env, int regno, const char *reg_name)
+{
+	if (env->cur_state->frame[0]->in_async_callback_fn)
+		return 0;
+	return check_return_code(env, regno, reg_name);
+}
+
 static int process_bpf_exit_full(struct bpf_verifier_env *env,
 				 bool *do_print_state,
 				 bool exception_exit)
@@ -21297,6 +21319,11 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
 				env->insn_idx += insn->imm + 1;
 			return INSN_IDX_UPDATED;
 		} else if (opcode == BPF_EXIT) {
+			if (bpf_is_unwind_exit(insn) && env->has_throw) {
+				err = check_unwound_value(env, BPF_REG_0, "R0");
+				if (err)
+					return err;
+			}
 			return process_bpf_exit_full(env, do_print_state, false);
 		}
 		return check_cond_jmp_op(env, insn, &env->insn_idx);
@@ -21804,9 +21831,8 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge
 }
 
 /*
- * What @subprog returns when it is unwound, see unwind_frame(). No code of the program chooses that
- * value, so for the main program it is the one that refuses, drops or changes nothing. That is 0,
- * but:
+ * What the program returns when the verifier unwinds it, see unwind_frame(). No code of the program
+ * chooses that value, so it is the one that refuses, drops or changes nothing. That is 0, but:
  *
  *	tc					TC_ACT_SHOT, 0 is TC_ACT_OK
  *	lwt, flow dissector			BPF_DROP, 0 is BPF_OK
@@ -21814,20 +21840,19 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge
  *	lsm, the hook returns an errno		-EPERM, 0 lets the operation go on
  *	the range is [1, 1]			1, hooks that cannot refuse
  *
- * Each is a value that check_return_code() lets the program return.
+ * Each is a value that check_return_code() lets the program return: no state is checked there with
+ * it, see unwind_frame().
  * Two 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.
  * An extension returns into the program that it extends, with the value of that program.
- * The exception callback returns in place of the main program.
+ * A subprog is left with the same value: its callers may pass it on, see bpf_site_has_value().
  */
-int bpf_cancelled_retval(struct bpf_verifier_env *env, int subprog)
+int bpf_cancelled_retval(struct bpf_verifier_env *env)
 {
 	struct bpf_prog *prog = env->prog;
 	struct bpf_retval_range range;
 
-	if (subprog && subprog != env->exception_callback_subprog)
-		return 0;
 	switch (resolve_prog_type(prog)) {
 	case BPF_PROG_TYPE_SCHED_CLS:
 	case BPF_PROG_TYPE_SCHED_ACT:
@@ -22160,6 +22185,8 @@ static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_p
  * release_frame_resources(), the value in place of the result, then unwind_exit, or exit in a frame
  * that the kernel called. What is left of @st goes where the frame returns to, through the
  * worklist like every other state. @st is taken.
+ * The value was checked where it was made, see check_unwound_value(): on the way it is joined and
+ * widened like any other number, and what comes out of a global subprog is not known.
  *
  * With a conflict there is no pad: the site is an unproven insn in @st, which ends here. The pass
  * goes on, and a pass that keeps more apart may have no such state.
@@ -22192,6 +22219,9 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 			goto out;
 		if (!plan->conflict)
 			plan->conflict = frame_cannot_unwind(env, st);
+		if (!plan->conflict && bpf_site_has_value(env, kind) &&
+		    frame->regs[BPF_REG_0].type != SCALAR_VALUE)
+			plan->conflict = BPF_CONFLICT_NO_VALUE;
 		certain = site_is_certain(env, plan, insn_idx);
 		/* there is no other way out */
 		if (plan->conflict && bpf_pad_must_unwind(env, plan) && certain) {
@@ -22209,11 +22239,12 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	err = release_frame_resources(env, bpf_pad_plan(&env->insn_aux_data[insn_idx], kind));
 	if (err)
 		goto out;
-	bpf_mark_reg_known_scalar(&frame->regs[BPF_REG_0],
-				  bpf_cancelled_retval(env, frame->subprogno));
+	if (!bpf_site_has_value(env, kind)) {
+		bpf_mark_reg_known_scalar(&frame->regs[BPF_REG_0], bpf_cancelled_retval(env));
+		bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_0));
+	}
 	if (bpf_ret_reg_pair(env, frame->subprogno))
 		__mark_reg_const_zero(&frame->regs[BPF_REG_2]);
-	bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_0));
 	bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_2));
 
 	st->unwound = sub->bail_unwinds && !frame_is_top(st);
@@ -22232,7 +22263,9 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	if (env->log.level & BPF_LOG_LEVEL2)
 		verbose(env, "from %d to %s of func#%d\n", insn_idx,
 			st->unwound ? "unwind_exit" : "exit", frame->subprogno);
-	if (!st->curframe && st->instance_id) {
+	if (frame_is_top(st)) {
+		err = PROCESS_BPF_EXIT;
+	} else if (!st->curframe && st->instance_id) {
 		/*
 		 * The states that leave the function are compared as if they were at one exit, so
 		 * leave the loops first. A recursion is not left, see loop_stack_pop().
@@ -22243,7 +22276,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 			leave_loops(frame, cnt);
 			bpf_equations_clean(env, st);
 		}
-		err = exit_func_on_its_own(env, env->subprog_info[frame->subprogno].exit_idx);
+		err = exit_func_on_its_own(env, sub->exit_idx);
 	} else {
 		err = process_bpf_exit_full(env, &print_state, false);
 	}
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 41/73] bpf: Keep a reference of the caller that a function finds NULL
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (39 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 40/73] bpf: Let landing pads pass on the value of unwind_exit Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 42/73] bpf: Make bpf_throw() cancel the program through landing pads Kumar Kartikeya Dwivedi
                   ` (31 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  9 ++++-
 kernel/bpf/verifier.c        | 71 ++++++++++++++++++++++++++++++------
 2 files changed, 67 insertions(+), 13 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index e53a9f8618f6..4582dddd5e28 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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.
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 9b000754ae2f..6ede9f5d6aa1 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -12033,6 +12033,22 @@ static u32 returned_id(u32 id)
 	return bpf_id_is_xreg(id) ? BPF_RETURNED_ID(id) : id;
 }
 
+/*
+ * Did the function find a pointer to be NULL whose reference @caller holds? @caller waits at the
+ * call and does not know that yet, see ref_of_caller().
+ */
+static bool found_null_of_caller(const struct bpf_verifier_state *caller,
+				 const struct bpf_verifier_state *exit)
+{
+	u32 i;
+
+	for (i = 0; i < caller->acquired_refs; i++)
+		if (exit->refs[i].type == REF_TYPE_PTR && exit->refs[i].found_null &&
+		    !caller->refs[i].found_null)
+			return true;
+	return false;
+}
+
 /*
  * @caller waits at the call at @call_idx. @exit is the state at the exit of the
  * function. Make @caller the state after the call.
@@ -12044,23 +12060,28 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 	const struct bpf_func_state *callee = exit->frame[0];
 	u32 i, nregs, nheld = caller->acquired_refs;
 	struct bpf_reg_state *reg;
+	bool found_null;
 	int err;
 
 	caller->speculative |= exit->speculative;
 	/*
 	 * 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. The caller has non-owning references only under a lock, which
-	 * is one of what it holds.
+	 * instance of the caller. Do the same if the function invalidated non-owning references
+	 * and the caller holds anything: it has such references only under a lock. And do the
+	 * same if the function returns after it found a pointer of the caller to be NULL.
 	 */
+	found_null = callee->entry_refs == nheld && !exit->unwound &&
+		     found_null_of_caller(caller, exit);
 	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) {
+	    callee->entry_preempt_locks < caller->active_preempt_locks || found_null) {
 		if (exit->speculative)
 			return -EACCES;
 		if (env->log.level & BPF_LOG_LEVEL2)
-			verbose(env, "func#%d releases what its caller holds at insn %d\n",
-				callee->subprogno, call_idx);
+			verbose(env, "func#%d %s what its caller holds at insn %d\n",
+				callee->subprogno, found_null ? "finds NULL" : "releases",
+				call_idx);
 		env->subprog_info[callee->subprogno].releases_inherited = true;
 		return BPF_EXIT_NEEDS_CALLER;
 	}
@@ -13136,6 +13157,9 @@ static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exi
 	for (i = 0; i < state->acquired_refs; i++) {
 		if (state->refs[i].type != REF_TYPE_PTR)
 			continue;
+		/* found NULL on this path, see ref_of_caller(): a throw leaks nothing */
+		if (exception_exit && state->refs[i].found_null)
+			continue;
 		/* Allow struct_ops programs to return a referenced kptr back to
 		 * kernel. Type checks are performed later in check_return_code.
 		 */
@@ -19499,6 +19523,25 @@ static void mark_ptr_or_null_reg(struct bpf_func_state *state,
 	}
 }
 
+/*
+ * Returns the entry of the reference @id if the caller of frame 0 holds it.
+ *
+ * A function that is verified separately has the references of its caller in refs[], but not the
+ * caller's registers. When it finds such a pointer to be NULL, the reference stays, marked
+ * found_null. If the function returns, the call is verified once more in the frames of the caller,
+ * see bpf_flow_return(). If it is cancelled or unwinds, the caller holds the reference without the
+ * mark, and the landing pad after the call has to test the pointer for NULL.
+ */
+static struct bpf_reference_state *ref_of_caller(struct bpf_verifier_state *st, u32 id)
+{
+	u32 i;
+
+	for (i = 0; i < st->frame[0]->entry_refs; i++)
+		if (st->refs[i].type == REF_TYPE_PTR && st->refs[i].id == id)
+			return &st->refs[i];
+	return NULL;
+}
+
 /* The logic is similar to find_good_pkt_pointers(), both could eventually
  * be folded together at some point.
  */
@@ -19507,14 +19550,20 @@ static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno,
 {
 	struct bpf_func_state *state = vstate->frame[vstate->curframe];
 	struct bpf_reg_state *regs = state->regs, *reg;
+	struct bpf_reference_state *ref;
 	u32 id = regs[regno].id;
 
-	if (is_null && find_reference_state(vstate, id))
-		/* regs[regno] is in the " == NULL" branch.
-		 * No one could have freed the reference state before
-		 * doing the NULL check.
-		 */
-		WARN_ON_ONCE(__release_reference_nomark(vstate, id));
+	if (is_null && find_reference_state(vstate, id)) {
+		ref = ref_of_caller(vstate, id);
+		if (ref)
+			ref->found_null = true;
+		else
+			/* regs[regno] is in the " == NULL" branch.
+			 * No one could have freed the reference state before
+			 * doing the NULL check.
+			 */
+			WARN_ON_ONCE(__release_reference_nomark(vstate, id));
+	}
 
 	bpf_for_each_reg_in_vstate(vstate, state, reg, ({
 		mark_ptr_or_null_reg(state, reg, id, is_null);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 42/73] bpf: Make bpf_throw() cancel the program through landing pads
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (40 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 41/73] bpf: Keep a reference of the caller that a function finds NULL Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 43/73] bpf, x86: Remove the exception boundary Kumar Kartikeya Dwivedi
                   ` (30 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
index 447df36c380b..ed72a57ed27b 100644
--- a/Documentation/bpf/verifier.rst
+++ b/Documentation/bpf/verifier.rst
@@ -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:
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index e981d486a337..88dd179ff712 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -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;
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 4582dddd5e28..46cb7baa46bc 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/include/linux/filter.h b/include/linux/filter.h
index 3ce4609af05f..c2ebd258e275 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -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);
 }
 
diff --git a/kernel/bpf/failing_path.c b/kernel/bpf/failing_path.c
index 3c7dfb3270f9..1d5a5782835d 100644
--- a/kernel/bpf/failing_path.c
+++ b/kernel/bpf/failing_path.c
@@ -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))
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 233eca6e0df0..91aba7d99290 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -415,9 +415,7 @@ static bool patch_list_subprog_gone(const struct bpf_subprog_info *info, u32 cnt
 }
 
 /*
- * Remove the subprogs whose insns are all removed, with their func_info. The
- * passes that remove insns run before the hidden subprog, which has no
- * func_info, is added.
+ * Remove the subprogs whose insns are all removed, with their func_info.
  */
 static void patch_list_del_subprogs(struct bpf_verifier_env *env,
 				    const u32 *new_off)
@@ -608,14 +606,27 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
  * The landing pad of a site in subprog @s. The only exit of a pad is its last insn. Nothing in a
  * pad is hardened against a cpu that mispredicts: only a program that is loaded with CAP_PERFMON
  * gets one, see frame_cannot_unwind().
- * Returns the number of insns, BPF_PAD_MAX_INSNS + 1 at most.
+ * The main program returns what the exception callback makes of the value. The pad has no index
+ * yet: bpf_insert_sites() sets the offset of the call. The callback is not called a second time:
+ * its unwind_exit gets to the exit of the pad like its exit does. unwind_goto says so, to
+ * bpf_unwind_target(): a return address in a program without an entry is a lost unwind_exit.
+ * Only a callback that can leave with unwind_exit gets it, and such a program needs a JIT that
+ * knows both insns already. A pad of any other program is plain BPF: the interpreter and the other
+ * JITs run it. bpf_mark_subprogs_that_unwind() ran, so it is known which callback that is.
+ * Returns the number of insns, BPF_PAD_MAX_INSNS + 2 at most.
  */
 static int emit_pad(struct bpf_verifier_env *env, int s, const struct bpf_pad_plan *plan,
 		    struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
 {
+	int cb = env->exception_callback_subprog;
 	int n = 0;
 
 	n += bpf_pad_insns(env, plan, s, buf + n, aux + n);
+	if (!s && cb) {
+		buf[n++] = BPF_CALL_REL(0);
+		if (bpf_subprog_unwinds(&env->subprog_info[cb]))
+			buf[n++] = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0, 0);
+	}
 	buf[n++] = unwind_exit_insn(env, s);
 	return n;
 }
@@ -633,6 +644,8 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 		return env->insn_aux_data[i].loop_guard;
 	case BPF_SITE_RECURSION:
 		return bpf_find_containing_subprog(env, i)->recursive;
+	case BPF_SITE_THROW:
+		return true;
 	case BPF_SITE_CALL:
 		if (!plan->visited)
 			return false;
@@ -865,9 +878,9 @@ static int insert_slot_stores(struct bpf_verifier_env *env, struct bpf_insn *buf
 
 /*
  * Emit what the main pass decided about the sites: may_goto before the insns that it
- * marked, see check_loop_guard(), unwind_goto after calls and after accesses to arena, the landing
- * pads, and the stores to the hidden slots that the pads read. What a pad does it did to the states
- * that left the frame at the site, see unwind_frame().
+ * marked, see check_loop_guard(), unwind_goto after calls and after accesses to arena, a jump in
+ * place of a call of bpf_throw(), the landing pads, and the stores to the hidden slots that the pads
+ * read. What a pad does it did to the states that left the frame at the site, see unwind_frame().
  *
  *	may_goto pad		before an insn of a loop, see check_loop_guard(). A may_goto
  *	insn			of the program that is a site jumps to its pad too.
@@ -896,9 +909,9 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 
 	/* how many insns the pads after the subprog have */
 	added = kvzalloc_objs(int, env->subprog_cnt, BPF_VERIFIER_GFP);
-	new = kvzalloc_objs(*new, max(BPF_PAD_MAX_INSNS + 1, BPF_PAD_MAX_SLOT_INSNS),
+	new = kvzalloc_objs(*new, max(BPF_PAD_MAX_INSNS + 2, BPF_PAD_MAX_SLOT_INSNS),
 			    BPF_VERIFIER_GFP);
-	pad_aux = kvzalloc_objs(*pad_aux, BPF_PAD_MAX_INSNS + 1, BPF_VERIFIER_GFP);
+	pad_aux = kvzalloc_objs(*pad_aux, BPF_PAD_MAX_INSNS + 2, BPF_VERIFIER_GFP);
 	if (!added || !new || !pad_aux) {
 		err = -ENOMEM;
 		goto out;
@@ -952,8 +965,17 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 				emit_pad(env, s, plan, new, &aux[cnt]);
 				if (plan->kind == BPF_SITE_FAULT && aux[i].fault_unwinds)
 					sub->fault_pad = cnt;
+				/* no call is made, see check_kfunc_call() */
+				if (plan->kind == BPF_SITE_THROW)
+					env->prog->insnsi[i] = BPF_RAW_INSN(BPF_JMP32 | BPF_JA, 0, 0, 0,
+									    cnt - i - 1);
 			}
 		}
+		/* a pad calls no subprog but the exception callback, see emit_pad() */
+		for (insn = &env->prog->insnsi[i]; added[s] && i < sub[1].start; i++, insn++)
+			if (bpf_pseudo_call(insn))
+				insn->imm = env->subprog_info[env->exception_callback_subprog].start -
+					    i - 1;
 	}
 	err = insert_slot_stores(env, new, added);
 	err = err ?: insert_unwind_gotos(env, added);
@@ -1260,7 +1282,6 @@ void bpf_lower_cast_mov(struct bpf_verifier_env *env)
  *  - the main program takes a stack when it starts and returns it when it exits:
  *    the stack of the cpu when it's free, without a call.
  *    See struct bpf_arena_cpu_stack. So does a callback.
- *    bpf_throw() doesn't return it: the stack stays taken until the arena is freed.
  *  - a function that has a frame drops it before exit.
  *  - 'rX = r12' gives the address like user space sees it, as other addresses
  *    in arena are.
@@ -2120,15 +2141,11 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 		}
 		func[i]->aux->num_exentries = num_exentries;
 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
-		func[i]->aux->exception_cb = env->subprog_info[i].is_exception_cb;
-		func[i]->aux->might_throw = env->subprog_info[i].throws;
 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
 		func[i]->aux->can_unwind = env->subprog_info[i].can_unwind;
 		func[i]->aux->in_recursion = env->subprog_info[i].in_recursion;
 		func[i]->aux->token = prog->aux->token;
-		if (!i)
-			func[i]->aux->exception_boundary = env->seen_exception;
 		func[i] = bpf_int_jit_compile(env, func[i]);
 		if (!func[i]->jited) {
 			err = -ENOTSUPP;
@@ -2159,7 +2176,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 		 * the imm field of a call has the subprog id, an index for this list
 		 */
 		func[i]->aux->func = func;
-		func[i]->aux->func_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
+		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++) {
@@ -2220,11 +2237,9 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 	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->func_cnt = env->subprog_cnt;
 	prog->aux->real_func_cnt = env->subprog_cnt;
-	prog->aux->bpf_exception_cb = (void *)func[env->exception_callback_subprog]->bpf_func;
-	prog->aux->exception_boundary = func[0]->aux->exception_boundary;
-	prog->aux->stack_arg_sp_adjust = func[0]->aux->stack_arg_sp_adjust;
+	prog->aux->exception_callback_subprog = env->exception_callback_subprog;
 	bpf_prog_jit_attempt_done(prog);
 	return 0;
 out_free:
@@ -2415,31 +2430,6 @@ int bpf_fixup_call_args(struct bpf_verifier_env *env)
 	return err;
 }
 
-static int add_hidden_subprog(struct bpf_verifier_env *env, struct bpf_insn *patch, int len)
-{
-	struct bpf_subprog_info *info = env->subprog_info;
-	int err, cnt = env->subprog_cnt;
-	struct bpf_prog *prog;
-
-	/* We only reserve one slot for hidden subprogs in subprog_info. */
-	if (env->hidden_subprog_cnt) {
-		verifier_bug(env, "only one hidden subprog supported");
-		return -EFAULT;
-	}
-	err = bpf_patch_list_append(env, env->prog->len - 1, patch, len) ?:
-	      bpf_patch_list_commit(env);
-	if (err)
-		return err;
-	prog = env->prog;
-	info[cnt + 1].start = info[cnt].start;
-	info[cnt].start = prog->len - len;
-	/* The patch ends with the exit. */
-	info[cnt].exit_idx = prog->len - 1;
-	env->subprog_cnt++;
-	env->hidden_subprog_cnt++;
-	return 0;
-}
-
 /*
  * Timed may_goto. All may_goto of a prog use one count and one timestamp: per-cpu memory of the
  * prog, set in the first insns of the main prog, and by the callers of async callbacks.
@@ -2683,22 +2673,6 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 	bool timed_may_goto = prog->jit_requested && bpf_jit_supports_timed_may_goto();
 	struct bpf_timed_may_goto __percpu *tmg = NULL;
 
-	if (env->seen_exception && !env->exception_callback_subprog) {
-		struct bpf_insn *patch = insn_buf;
-
-		*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_1);
-		*patch++ = BPF_EXIT_INSN();
-		ret = add_hidden_subprog(env, insn_buf, patch - insn_buf);
-		if (ret < 0)
-			return ret;
-		prog = env->prog;
-		insn = prog->insnsi;
-
-		env->exception_callback_subprog = env->subprog_cnt - 1;
-		/* Don't update insn_cnt, as add_hidden_subprog always appends insns */
-		bpf_mark_subprog_exc_cb(env, env->exception_callback_subprog);
-	}
-
 	for (i = 0; i < insn_cnt;) {
 		if (is_addr_space_cast32(env->prog, insn)) {
 			/* convert to 32-bit mov that clears upper 32-bit */
diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index 1b55e9158332..d59b1d27324d 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -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
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index ba402a4e10e9..8f675995da71 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -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",
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 6ede9f5d6aa1..f5bc401bce87 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -483,13 +483,15 @@ const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog)
 	return btf_type_name(env->prog->aux->btf, info->type_id);
 }
 
-void bpf_mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
+static void mark_subprog_exc_cb(struct bpf_verifier_env *env, int subprog)
 {
 	struct bpf_subprog_info *info = subprog_info(env, subprog);
 
 	info->is_cb = true;
 	info->is_async_cb = true;
 	info->is_exception_cb = true;
+	/* The landing pads of the main program call it. */
+	info->is_called = true;
 }
 
 static bool subprog_is_exc_cb(struct bpf_verifier_env *env, int subprog)
@@ -3218,9 +3220,9 @@ static int add_subprogs(struct bpf_verifier_env *env)
 	if (ret < 0)
 		return ret;
 
-	/* + 2 for the fake and the hidden subprogs */
+	/* + 1 for the fake subprog */
 	cnt = bitmap_weight(starts, insn_cnt);
-	subprog = env->subprog_info = kvcalloc(cnt + 2, sizeof(*subprog), BPF_VERIFIER_GFP);
+	subprog = env->subprog_info = kvcalloc(cnt + 1, sizeof(*subprog), BPF_VERIFIER_GFP);
 	env->subprog_topo_order = kvcalloc(cnt, sizeof(int), BPF_VERIFIER_GFP);
 	if (!subprog || !env->subprog_topo_order)
 		return -ENOMEM;
@@ -3238,7 +3240,7 @@ static int add_subprogs(struct bpf_verifier_env *env)
 
 	if (ex_cb_insn) {
 		env->exception_callback_subprog = bpf_find_subprog(env, ex_cb_insn);
-		bpf_mark_subprog_exc_cb(env, env->exception_callback_subprog);
+		mark_subprog_exc_cb(env, env->exception_callback_subprog);
 	}
 
 	if (env->log.level & BPF_LOG_LEVEL2)
@@ -3489,7 +3491,11 @@ static int check_unwind_insns(struct bpf_verifier_env *env)
 			bpf_find_containing_subprog(env, i)->can_unwind = true;
 			seen = true;
 		}
-		env->has_throw |= bpf_is_throw_kfunc(insn);
+		/* bpf_throw() cancels the program through landing pads, see kernel/bpf/pads.c */
+		if (bpf_is_throw_kfunc(insn)) {
+			env->has_throw = true;
+			seen = true;
+		}
 		if (!bpf_is_unwind_goto(insn))
 			continue;
 		seen = true;
@@ -5600,7 +5606,7 @@ enum {
 	CG_ARENA_SP	= BIT(5), /* subprogs that get to r12 */
 	CG_CB		= BIT(6),
 	CG_GLOBAL	= BIT(7),
-	CG_THROW	= BIT(8), /* subprogs that get to bpf_throw() */
+	CG_IN_EXC_CB	= BIT(8), /* the exception callback and what it gets to */
 };
 
 #define for_each_marked_subprog(cg, s, mark) \
@@ -5641,16 +5647,15 @@ static int build_call_graph(struct bpf_verifier_env *env, struct bpf_call_graph
 	bpf_call_graph_mark_callees(cg, CG_LIVE);
 	for_each_marked_subprog(cg, s, CG_LIVE)
 		cg->marks[s] |= (si[s].is_cb ? CG_CB | CG_IN_CB : 0) |
+				(si[s].is_exception_cb ? CG_IN_EXC_CB : 0) |
 				(si[s].is_async_cb ? CG_IN_ASYNC_CB : 0) |
 				(bpf_call_graph_recursive(cg, s) ? CG_IN_RECURSION : 0) |
 				(si[s].has_tail_call ? CG_TAIL_CALL : 0) |
-				(si[s].throws ? CG_THROW : 0) |
 				(si[s].uses_arena_sp ? CG_ARENA_SP : 0) |
 				(bpf_subprog_is_global(env, s) ? CG_GLOBAL : 0);
-	bpf_call_graph_mark_callees(cg, CG_IN_CB | CG_IN_ASYNC_CB | CG_IN_RECURSION);
-	bpf_call_graph_mark_callers(cg, CG_TAIL_CALL | CG_THROW, 0);
-	for_each_marked_subprog(cg, s, CG_THROW)
-		si[s].throws = true;
+	bpf_call_graph_mark_callees(cg, CG_IN_CB | CG_IN_ASYNC_CB | CG_IN_RECURSION |
+					CG_IN_EXC_CB);
+	bpf_call_graph_mark_callers(cg, CG_TAIL_CALL, 0);
 	return 0;
 }
 
@@ -5681,18 +5686,33 @@ static int find_call_insn(struct bpf_verifier_env *env, int caller, int callee)
 	return i;
 }
 
-/* The exception callback is an async callback, so only a call is an edge to it */
+/*
+ * Only the landing pads of the main program call the exception callback: reject a call of it in the
+ * program. A value that is thrown in the callback, or in a function that it reaches, is what the
+ * program returns, and check_unwound_value() checks it only in the functions that were marked
+ * in_exception_cb before the main pass. So reject a function that the callback reaches only
+ * through an address that the main pass found.
+ */
 static int check_exception_cb(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
 {
 	int cb = env->exception_callback_subprog, s;
 
+	if (!cb)
+		return 0;
 	for_each_marked_subprog(cg, s, CG_LIVE) {
-		if (!cb || !subprog_calls(cg, s, cb))
+		if (!subprog_calls(cg, s, cb))
 			continue;
 		verbose(env, "insn %d cannot call exception cb directly\n",
 			find_call_insn(env, s, cb));
 		return -EINVAL;
 	}
+	for_each_marked_subprog(cg, s, CG_IN_EXC_CB) {
+		if (env->subprog_info[s].in_exception_cb)
+			continue;
+		verbose(env, "exception cb gets to %s(), whose address is taken elsewhere\n",
+			bpf_subprog_name(env, s));
+		return -EINVAL;
+	}
 	return 0;
 }
 
@@ -5756,22 +5776,13 @@ static int check_recursion(struct bpf_verifier_env *env, struct bpf_call_graph *
 static int check_callbacks(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
 {
 	struct bpf_subprog_info *si = env->subprog_info;
-	struct bpf_insn *insn = env->prog->insnsi;
-	int i, s;
+	int s;
 
 	for_each_marked_subprog(cg, s, CG_IN_CB) {
 		if (si[s].has_ld_abs) {
 			verbose(env, "cannot use BPF_LD_[ABS|IND] within callback\n");
 			return -EINVAL;
 		}
-		for (i = si[s].start; i < si[s + 1].start; i++) {
-			if (!bpf_is_throw_kfunc(insn + i) || !env->insn_aux_data[i].seen)
-				continue;
-			verbose(env,
-				"bpf_throw kfunc (insn %d) cannot be called from callback subprog %d\n",
-				i, s);
-			return -EINVAL;
-		}
 	}
 	return 0;
 }
@@ -5871,6 +5882,12 @@ static void compute_call_depth(struct bpf_verifier_env *env, struct bpf_call_gra
 	int frame;
 
 	memset(dinfo, 0, cg->cnt * sizeof(*dinfo));
+	/* A landing pad of the main program calls the exception callback. */
+	s = env->exception_callback_subprog;
+	if (s) {
+		dinfo[s].calls = 1;
+		dinfo[s].depth = subprog_stack_size(env, 0);
+	}
 	bpf_call_graph_sort(cg, 0);
 	for (end = cg->cnt; end; end = start) {
 		start = cg->cycle[cg->order[end - 1]];
@@ -6094,7 +6111,7 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 	int cnt = env->subprog_cnt, i, j, s, err;
 	struct bpf_call_graph cg;
 	/* CALLED: the program can call the subprog, with a call insn or through its address */
-	enum { CALLED = 1 };
+	enum { CALLED = 1, IN_EXC_CB = 2 };
 
 	/* callx calls node 'cnt', which calls each subprog whose address is taken */
 	err = bpf_call_graph_init(&cg, cnt + 1);
@@ -6146,6 +6163,15 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 
 	bpf_call_graph_sort(&cg, 0);
 
+	/* what the exception callback can reach, see check_unwound_value(), check_exception_cb() */
+	j = env->exception_callback_subprog;
+	if (j) {
+		cg.marks[j] |= IN_EXC_CB;
+		bpf_call_graph_mark_callees(&cg, IN_EXC_CB);
+	}
+	for (s = 1; s < cnt; s++)
+		si[s].in_exception_cb = cg.marks[s] & IN_EXC_CB;
+
 	/*
 	 * A function that the program calls can leave with unwind_exit or cancel_exit, if the JIT
 	 * supports them and the loader has CAP_PERFMON. A function that only the kernel calls, like
@@ -11829,8 +11855,6 @@ enum {
 	INSN_IDX_UPDATED = 2,
 };
 
-static int process_bpf_exit_full(struct bpf_verifier_env *env,
-				 bool *do_print_state, bool exception_exit);
 static void account_current_path(struct bpf_verifier_env *env);
 
 /*
@@ -12357,17 +12381,6 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 						 BPF_REG_0);
 		}
 
-		if (env->subprog_info[subprog].might_throw) {
-			struct bpf_verifier_state *branch;
-
-			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
-			if (IS_ERR(branch)) {
-				verbose(env, "failed to push state for global subprog exception path\n");
-				return PTR_ERR(branch);
-			}
-			return process_bpf_exit_full(env, NULL, true);
-		}
-
 		/* continue with next insn after call */
 		return 0;
 	}
@@ -12950,8 +12963,7 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 		print_verifier_state(env, state, caller->frameno, true);
 	}
 	account_processed_insns(env, callee, caller);
-	/* clear everything in the callee. In case of exceptional exits using
-	 * bpf_throw, this will be done by do_check_block() for extra frames. */
+	/* clear everything in the callee */
 	free_func_state(callee);
 	state->frame[state->curframe--] = NULL;
 	invalidate_outgoing_stack_args(env, caller);
@@ -13144,26 +13156,23 @@ static bool returns_to_kernel(const struct bpf_verifier_state *state)
 	return !frame->subprogno || frame->in_exception_callback_fn;
 }
 
-static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exit)
+static int check_reference_leak(struct bpf_verifier_env *env)
 {
 	struct bpf_verifier_state *state = env->cur_state;
 	struct bpf_reg_state *reg = reg_state(env, BPF_REG_0);
 	bool refs_lingering = false;
 	int i;
 
-	if (!exception_exit && cur_func(env)->frameno)
+	if (cur_func(env)->frameno)
 		return 0;
 
 	for (i = 0; i < state->acquired_refs; i++) {
 		if (state->refs[i].type != REF_TYPE_PTR)
 			continue;
-		/* found NULL on this path, see ref_of_caller(): a throw leaks nothing */
-		if (exception_exit && state->refs[i].found_null)
-			continue;
 		/* Allow struct_ops programs to return a referenced kptr back to
 		 * kernel. Type checks are performed later in check_return_code.
 		 */
-		if (!exception_exit && reg->id == state->refs[i].id &&
+		if (reg->id == state->refs[i].id &&
 		    env->prog->insnsi[env->insn_idx].code == (BPF_JMP | BPF_EXIT) &&
 		    st_ops_returns_ptr(env->prog) && returns_to_kernel(state))
 			continue;
@@ -13175,7 +13184,7 @@ static int check_reference_leak(struct bpf_verifier_env *env, bool exception_exi
 	return refs_lingering ? -EINVAL : 0;
 }
 
-static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit, bool check_lock, const char *prefix)
+static int check_resource_leak(struct bpf_verifier_env *env, bool check_lock, const char *prefix)
 {
 	int err;
 
@@ -13186,7 +13195,7 @@ static int check_resource_leak(struct bpf_verifier_env *env, bool exception_exit
 		return -EINVAL;
 	}
 
-	err = check_reference_leak(env, exception_exit);
+	err = check_reference_leak(env);
 	if (err) {
 		verbose(env, "%s would lead to reference leak\n", prefix);
 		return err;
@@ -13519,7 +13528,7 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 
 	switch (func_id) {
 	case BPF_FUNC_tail_call:
-		err = check_resource_leak(env, false, true, "tail_call");
+		err = check_resource_leak(env, true, "tail_call");
 		if (err)
 			return err;
 		break;
@@ -16224,7 +16233,8 @@ static int check_special_kfunc(struct bpf_verifier_env *env, struct bpf_call_arg
 	return 1;
 }
 
-static int check_return_code(struct bpf_verifier_env *env, int regno, const char *reg_name);
+static int check_unwound_value(struct bpf_verifier_env *env, int regno, const char *reg_name);
+static int push_unwind_edge(struct bpf_verifier_env *env, enum bpf_site_kind kind);
 
 /*
  * Does freeing an object of this type run code that a program may not call under a lock? The
@@ -16562,23 +16572,11 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		}
 	}
 
+	/* bpf_throw() is never called. The frame is cancelled here, see unwind_frame(). */
 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
-		if (!bpf_jit_supports_exceptions()) {
-			verbose(env, "JIT does not support calling kfunc %s#%d\n",
-				func_name, meta.func_id);
-			return -ENOTSUPP;
-		}
-		env->seen_exception = true;
-		env->subprog_info[cur_func(env)->subprogno].throws = true;
-
-		/* In the case of the default callback, the cookie value passed
-		 * to bpf_throw becomes the return value of the program.
-		 */
-		if (!env->exception_callback_subprog) {
-			err = check_return_code(env, BPF_REG_1, "R1");
-			if (err < 0)
-				return err;
-		}
+		err = check_unwound_value(env, BPF_REG_1, "R1");
+		err = err ?: push_unwind_edge(env, BPF_SITE_THROW);
+		return err ?: PROCESS_BPF_EXIT;
 	}
 
 	bpf_diag_record_caller_saved(env, regs);
@@ -16834,9 +16832,6 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	if (meta.func_id == special_kfunc_list[KF_bpf_session_cookie])
 		env->prog->call_session_cookie = true;
 
-	if (bpf_is_throw_kfunc(insn))
-		return process_bpf_exit_full(env, NULL, true);
-
 	return 0;
 }
 
@@ -20204,7 +20199,7 @@ static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
 	 * gen_ld_abs() may terminate the program at runtime, leading to
 	 * reference leak.
 	 */
-	err = check_resource_leak(env, false, true, "BPF_LD_[ABS|IND]");
+	err = check_resource_leak(env, true, "BPF_LD_[ABS|IND]");
 	if (err)
 		return err;
 
@@ -20899,8 +20894,7 @@ static void adjust_btf_func(struct bpf_verifier_env *env)
 	if (!aux->func_info)
 		return;
 
-	/* func_info is not available for hidden subprogs */
-	for (i = 0; i < env->subprog_cnt - env->hidden_subprog_cnt; i++)
+	for (i = 0; i < env->subprog_cnt; i++)
 		aux->func_info[i].insn_off = env->subprog_info[i].start;
 }
 
@@ -21001,23 +20995,26 @@ static int save_aux_ptr_type(struct bpf_verifier_env *env, enum bpf_reg_type typ
 
 /*
  * The program starts to unwind with the value in R@regno. In a program with bpf_throw() the landing
- * pads that the verifier emits pass the value on, and the main program returns it. Nobody
- * looks at what an async callback returns.
+ * pads pass it on and the main program returns it, so check it like R0 at the exit of the main
+ * program. Two cases are skipped: an async callback, whose return value nobody reads, and a
+ * program with an exception callback, which gets the value. The callback is not called a second
+ * time, so a value that is thrown in the callback or in a function that it reaches is checked.
  */
 static int check_unwound_value(struct bpf_verifier_env *env, int regno, const char *reg_name)
 {
 	if (env->cur_state->frame[0]->in_async_callback_fn)
 		return 0;
+	if (env->exception_callback_subprog &&
+	    !env->subprog_info[cur_func(env)->subprogno].in_exception_cb)
+		return 0;
 	return check_return_code(env, regno, reg_name);
 }
 
-static int process_bpf_exit_full(struct bpf_verifier_env *env,
-				 bool *do_print_state,
-				 bool exception_exit)
+static int process_bpf_exit_full(struct bpf_verifier_env *env, bool *do_print_state)
 {
 	struct bpf_func_state *cur_frame = cur_func(env);
 
-	if (!exception_exit && !env->cur_state->curframe && env->cur_state->instance_id)
+	if (!env->cur_state->curframe && env->cur_state->instance_id)
 		return exit_func_on_its_own(env, env->insn_idx);
 
 	/* We must do check_reference_leak here before
@@ -21026,25 +21023,11 @@ static int process_bpf_exit_full(struct bpf_verifier_env *env,
 	 * for which reference_state must match caller reference
 	 * state when it exits.
 	 */
-	int err = check_resource_leak(env, exception_exit,
-				      exception_exit || !env->cur_state->curframe,
-				      exception_exit ? "bpf_throw" :
+	int err = check_resource_leak(env, !env->cur_state->curframe,
 				      "BPF_EXIT instruction in main prog");
 	if (err)
 		return err;
 
-	/* The side effect of the prepare_func_exit which is
-	 * being skipped is that it frees bpf_func_state.
-	 * Typically, process_bpf_exit will only be hit with
-	 * outermost exit. do_check_block() frees the state with
-	 * any extra bpf_func_state left over
-	 * from not processing all nested function exits. We
-	 * also skip return code checks as they are not needed
-	 * for exceptional exits.
-	 */
-	if (exception_exit)
-		return PROCESS_BPF_EXIT;
-
 	if (env->cur_state->curframe) {
 		/* exit from nested function */
 		err = prepare_func_exit(env, &env->insn_idx);
@@ -21373,7 +21356,7 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
 				if (err)
 					return err;
 			}
-			return process_bpf_exit_full(env, do_print_state, false);
+			return process_bpf_exit_full(env, do_print_state);
 		}
 		return check_cond_jmp_op(env, insn, &env->insn_idx);
 	}
@@ -21880,8 +21863,8 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge
 }
 
 /*
- * What the program returns when the verifier unwinds it, see unwind_frame(). No code of the program
- * chooses that value, so it is the one that refuses, drops or changes nothing. That is 0, but:
+ * The value that a cancelled program returns to the kernel. No code of the program chose it, so it
+ * is the value that refuses, drops or changes nothing. That is 0, except for:
  *
  *	tc					TC_ACT_SHOT, 0 is TC_ACT_OK
  *	lwt, flow dissector			BPF_DROP, 0 is BPF_OK
@@ -21896,6 +21879,7 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge
  * is not complete.
  * An extension returns into the program that it extends, with the value of that program.
  * A subprog is left with the same value: its callers may pass it on, see bpf_site_has_value().
+ * The exception callback gets it and decides. A landing pad that the program has can replace it.
  */
 int bpf_cancelled_retval(struct bpf_verifier_env *env)
 {
@@ -21962,12 +21946,9 @@ static bool frame_holds_resources(const struct bpf_verifier_state *st)
 }
 
 /*
- * A loop or a recursion is out of budget in the current frame of @st, or what it called came back
- * with unwind_exit. What the program computed so far is not what it was meant to compute, so it's
- * better not to go on. The way to stop is to unwind: 'r0 = 0; unwind_exit'. The landing
- * pads that the callers have in the program are code like any other. They release what
- * the callers hold, or the program is rejected. Where a caller has none the verifier emits it.
- * There is no other way out. Returns why the frame cannot unwind, 0 if it can.
+ * Returns why the current frame of @st cannot be cancelled, or 0 if it can: its function has no
+ * exit, the program is loaded without CAP_PERFMON, or the frame has a caller in the program and
+ * its function cannot leave with cancel_exit.
  */
 static enum bpf_pad_conflict frame_cannot_unwind(struct bpf_verifier_env *env,
 						 const struct bpf_verifier_state *st)
@@ -22269,7 +22250,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		if (!plan->conflict)
 			plan->conflict = frame_cannot_unwind(env, st);
 		if (!plan->conflict && bpf_site_has_value(env, kind) &&
-		    frame->regs[BPF_REG_0].type != SCALAR_VALUE)
+		    frame->regs[bpf_site_value_reg(kind)].type != SCALAR_VALUE)
 			plan->conflict = BPF_CONFLICT_NO_VALUE;
 		certain = site_is_certain(env, plan, insn_idx);
 		/* there is no other way out */
@@ -22291,6 +22272,9 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	if (!bpf_site_has_value(env, kind)) {
 		bpf_mark_reg_known_scalar(&frame->regs[BPF_REG_0], bpf_cancelled_retval(env));
 		bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_0));
+	} else if (bpf_site_value_reg(kind) != BPF_REG_0) {
+		frame->regs[BPF_REG_0] = frame->regs[bpf_site_value_reg(kind)];
+		bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_0));
 	}
 	if (bpf_ret_reg_pair(env, frame->subprogno))
 		__mark_reg_const_zero(&frame->regs[BPF_REG_2]);
@@ -22327,7 +22311,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		}
 		err = exit_func_on_its_own(env, sub->exit_idx);
 	} else {
-		err = process_bpf_exit_full(env, &print_state, false);
+		err = process_bpf_exit_full(env, &print_state);
 	}
 	if (err == INSN_IDX_UPDATED)
 		err = bpf_flow_deliver(env, st, env->insn_idx, insn_idx, false);
@@ -24253,8 +24237,9 @@ static int do_check_subprogs(struct bpf_verifier_env *env)
 		return 0;
 
 	/*
-	 * Callbacks cannot throw, so the exception callback always runs in the
-	 * main program's context. It is presumed to be always called.
+	 * A landing pad of the main program calls the exception callback after its
+	 * releases, so the callback runs in the context of the main program. It is
+	 * presumed to be always called.
 	 */
 	if (env->exception_callback_subprog) {
 		sub_aux = subprog_aux(env, env->exception_callback_subprog);
@@ -24953,8 +24938,7 @@ static void add_insns_of_callees(struct bpf_verifier_env *env)
 
 static void print_verification_stats(struct bpf_verifier_env *env)
 {
-	/* Skip over hidden subprogs which are not verified. */
-	int i, subprog_cnt = env->subprog_cnt - env->hidden_subprog_cnt;
+	int i, subprog_cnt = env->subprog_cnt;
 
 	if (env->log.level & BPF_LOG_STATS) {
 		verbose(env, "verification time %lld usec\n",
@@ -25513,7 +25497,7 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,
 				BPF_REG_ARENA_SP);
 			return -EOPNOTSUPP;
 		}
-		if (aux->func && aux->func[subprog]->aux->exception_cb) {
+		if (subprog && subprog == aux->exception_callback_subprog) {
 			bpf_log(log,
 				"%s programs cannot attach to exception callback\n",
 				prog_extension ? "Extension" : "Tracing");
@@ -25530,12 +25514,6 @@ int bpf_check_attach_target(struct bpf_verifier_log *log,
 			bpf_log(log, "Only fentry can attach to %s, which can unwind\n", tname);
 			return -EINVAL;
 		}
-		/* bpf_throw() would have to skip the trampoline that called the target */
-		if (subprog && aux->func && aux->func[subprog]->aux->might_throw &&
-		    !prog_extension && prog->expected_attach_type != BPF_TRACE_FENTRY) {
-			bpf_log(log, "Only fentry can attach to %s, which can throw\n", tname);
-			return -EINVAL;
-		}
 		/* What it takes of the stack is not counted, see bpf_insert_recursion_checks() */
 		if (aux->func && aux->func[subprog]->aux->in_recursion) {
 			bpf_log(log, "Cannot attach to %s, which is called in a recursion\n", tname);
diff --git a/tools/testing/selftests/bpf/DENYLIST.s390x b/tools/testing/selftests/bpf/DENYLIST.s390x
index f7e1e5f5511c..92786c6a9071 100644
--- a/tools/testing/selftests/bpf/DENYLIST.s390x
+++ b/tools/testing/selftests/bpf/DENYLIST.s390x
@@ -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                   (?)
diff --git a/tools/testing/selftests/bpf/bpf_experimental.h b/tools/testing/selftests/bpf/bpf_experimental.h
index 2893bf06ff25..92ed34e8233f 100644
--- a/tools/testing/selftests/bpf/bpf_experimental.h
+++ b/tools/testing/selftests/bpf/bpf_experimental.h
@@ -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
diff --git a/tools/testing/selftests/bpf/prog_tests/arena_stack.c b/tools/testing/selftests/bpf/prog_tests/arena_stack.c
index 20950a8df3d8..d0d42b7a600f 100644
--- a/tools/testing/selftests/bpf/prog_tests/arena_stack.c
+++ b/tools/testing/selftests/bpf/prog_tests/arena_stack.c
@@ -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)
 {
diff --git a/tools/testing/selftests/bpf/prog_tests/exceptions.c b/tools/testing/selftests/bpf/prog_tests/exceptions.c
index fc36cd226fb1..b3997022bae7 100644
--- a/tools/testing/selftests/bpf/prog_tests/exceptions.c
+++ b/tools/testing/selftests/bpf/prog_tests/exceptions.c
@@ -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);
diff --git a/tools/testing/selftests/bpf/prog_tests/unwind_attach.c b/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
index 5ec96f478493..6e3733aef105 100644
--- a/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
+++ b/tools/testing/selftests/bpf/prog_tests/unwind_attach.c
@@ -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);
diff --git a/tools/testing/selftests/bpf/progs/arena_stack_throw.c b/tools/testing/selftests/bpf/progs/arena_stack_throw.c
index ac14139fb901..82a1fdb05c76 100644
--- a/tools/testing/selftests/bpf/progs/arena_stack_throw.c
+++ b/tools/testing/selftests/bpf/progs/arena_stack_throw.c
@@ -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)
diff --git a/tools/testing/selftests/bpf/progs/exceptions_fail.c b/tools/testing/selftests/bpf/progs/exceptions_fail.c
index 22503cf62e9f..9481ee97767d 100644
--- a/tools/testing/selftests/bpf/progs/exceptions_fail.c
+++ b/tools/testing/selftests/bpf/progs/exceptions_fail.c
@@ -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;
diff --git a/tools/testing/selftests/bpf/progs/res_spin_lock_fail.c b/tools/testing/selftests/bpf/progs/res_spin_lock_fail.c
index 8fd591bd1f6c..2f180c99590b 100644
--- a/tools/testing/selftests/bpf/progs/res_spin_lock_fail.c
+++ b/tools/testing/selftests/bpf/progs/res_spin_lock_fail.c
@@ -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)
 {
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
index 63697cbd5a92..ca7bdbd7e1ce 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
@@ -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)
diff --git a/tools/testing/selftests/bpf/progs/verifier_barrier.c b/tools/testing/selftests/bpf/progs/verifier_barrier.c
index cb6ae13141ae..0982873ed0c5 100644
--- a/tools/testing/selftests/bpf/progs/verifier_barrier.c
+++ b/tools/testing/selftests/bpf/progs/verifier_barrier.c
@@ -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
diff --git a/tools/testing/selftests/bpf/progs/verifier_jumps_ahead.c b/tools/testing/selftests/bpf/progs/verifier_jumps_ahead.c
index 7fc4a3c2acdc..1d49346f1466 100644
--- a/tools/testing/selftests/bpf/progs/verifier_jumps_ahead.c
+++ b/tools/testing/selftests/bpf/progs/verifier_jumps_ahead.c
@@ -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 (					\
diff --git a/tools/testing/selftests/bpf/progs/verifier_passes.c b/tools/testing/selftests/bpf/progs/verifier_passes.c
index 8b6db6898570..d17254990744 100644
--- a/tools/testing/selftests/bpf/progs/verifier_passes.c
+++ b/tools/testing/selftests/bpf/progs/verifier_passes.c
@@ -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)
 {
diff --git a/tools/testing/selftests/bpf/progs/verifier_private_stack.c b/tools/testing/selftests/bpf/progs/verifier_private_stack.c
index ed2a40475125..8f689ca69871 100644
--- a/tools/testing/selftests/bpf/progs/verifier_private_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_private_stack.c
@@ -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 ("				\
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 43/73] bpf, x86: Remove the exception boundary
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (41 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 42/73] bpf: Make bpf_throw() cancel the program through landing pads Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 44/73] bpf, arm64: " Kumar Kartikeya Dwivedi
                   ` (29 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 arch/x86/net/bpf_jit_comp.c | 95 +++++++------------------------------
 1 file changed, 17 insertions(+), 78 deletions(-)

diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index e91148abbfbb..aa0d760deeb5 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -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();
 
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 44/73] bpf, arm64: Remove the exception boundary
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (42 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 43/73] bpf, x86: Remove the exception boundary Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 45/73] s390/bpf: " Kumar Kartikeya Dwivedi
                   ` (28 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 arch/arm64/net/bpf_jit_comp.c | 128 ++++++++++------------------------
 1 file changed, 37 insertions(+), 91 deletions(-)

diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index 5e4e08a65ea3..475a7ae2c356 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -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);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 45/73] s390/bpf: Remove the exception boundary
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (43 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 44/73] bpf, arm64: " Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 46/73] powerpc64/bpf: " Kumar Kartikeya Dwivedi
                   ` (27 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 arch/s390/net/bpf_jit_comp.c | 38 +++++++++---------------------------
 1 file changed, 9 insertions(+), 29 deletions(-)

diff --git a/arch/s390/net/bpf_jit_comp.c b/arch/s390/net/bpf_jit_comp.c
index d6c3c4270a0b..5d3cfa3fe49e 100644
--- a/arch/s390/net/bpf_jit_comp.c
+++ b/arch/s390/net/bpf_jit_comp.c
@@ -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))
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 46/73] powerpc64/bpf: Remove the exception boundary
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (44 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 45/73] s390/bpf: " Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 47/73] bpf: Remove the stack walk of bpf_throw() Kumar Kartikeya Dwivedi
                   ` (26 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/arch/powerpc/net/bpf_jit.h b/arch/powerpc/net/bpf_jit.h
index 4da8bde92e1e..f65c06039ac5 100644
--- a/arch/powerpc/net/bpf_jit.h
+++ b/arch/powerpc/net/bpf_jit.h
@@ -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;
 };
diff --git a/arch/powerpc/net/bpf_jit_comp.c b/arch/powerpc/net/bpf_jit_comp.c
index c246709a15ce..b7147bb31ce3 100644
--- a/arch/powerpc/net/bpf_jit_comp.c
+++ b/arch/powerpc/net/bpf_jit_comp.c
@@ -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) {
diff --git a/arch/powerpc/net/bpf_jit_comp64.c b/arch/powerpc/net/bpf_jit_comp64.c
index c1e86fe0bd79..63606a123275 100644
--- a/arch/powerpc/net/bpf_jit_comp64.c
+++ b/arch/powerpc/net/bpf_jit_comp64.c
@@ -33,14 +33,10 @@
  *		[	prev sp		] <-------------
  *		[    tail_call_info	] 8		|
  *		[   nv gpr save area	] (6 * 8)	|
- *		[ addl. nv gpr save area] (12 * 8)	| <--- exception boundary/callback program
  *		[    local_tmp_var	] 24		|
  * fp (r31) -->	[   ebpf stack space	] upto 512	|
  *		[     frame header	] 32/112	|
  * sp (r1) --->	[    stack pointer	] --------------
- *
- * Additional (12 * 8) in 'nv gpr save area' only in case of
- * exception boundary/callback.
  */
 
 /* BPF non-volatile registers save area size */
@@ -48,11 +44,6 @@
 
 /* for bpf JIT code internal usage */
 #define BPF_PPC_STACK_LOCALS	24
-/*
- * for additional non volatile registers(r14-r25) to be saved
- * at exception boundary
- */
-#define BPF_PPC_EXC_STACK_SAVE (12 * 8)
 
 /* stack frame excluding BPF stack, ensure this is quadword aligned */
 #define BPF_PPC_STACKFRAME	(STACK_FRAME_MIN_SIZE + \
@@ -60,13 +51,6 @@
 				 BPF_PPC_STACK_SAVE   + \
 				 BPF_PPC_TAILCALL)
 
-/*
- * same as BPF_PPC_STACKFRAME with save area for additional
- * non volatile registers saved at exception boundary.
- * This is quad-word aligned.
- */
-#define BPF_PPC_EXC_STACKFRAME (BPF_PPC_STACKFRAME + BPF_PPC_EXC_STACK_SAVE)
-
 /* BPF register usage */
 #define TMP_REG_1	(MAX_BPF_JIT_REG + 0)
 #define TMP_REG_2	(MAX_BPF_JIT_REG + 1)
@@ -108,16 +92,8 @@ static inline bool bpf_has_stack_frame(struct codegen_context *ctx)
 	 * - we call other functions (kernel helpers), or
 	 * - the bpf program uses its stack area
 	 * The latter condition is deduced from the usage of BPF_REG_FP
-	 *
-	 * bpf_throw() leads to exception callback from a BPF (sub)program.
-	 * The (sub)program is always marked as SEEN_FUNC, creating a stack
-	 * frame. The exception callback uses the frame of the exception
-	 * boundary, so the exception boundary program must have a frame.
 	 */
-	return ctx->seen & SEEN_FUNC ||
-	       bpf_is_seen_register(ctx, bpf_to_ppc(BPF_REG_FP)) ||
-	       ctx->exception_cb ||
-	       ctx->exception_boundary;
+	return ctx->seen & SEEN_FUNC || bpf_is_seen_register(ctx, bpf_to_ppc(BPF_REG_FP));
 }
 
 /*
@@ -130,12 +106,8 @@ static inline bool bpf_has_stack_frame(struct codegen_context *ctx)
  * sp (r1) --->	[    stack pointer	] --------------
  *		[    tail_call_info	] 8
  *		[   nv gpr save area	] (6 * 8)
- *		[ addl. nv gpr save area] (12 * 8) <--- exception boundary/callback program
  *		[    local_tmp_var	] 24
  *		[   unused red zone	] 224
- *
- * Additional (12 * 8) in 'nv gpr save area' only in case of
- * exception boundary/callback.
  */
 static int bpf_jit_stack_local(struct codegen_context *ctx)
 {
@@ -144,12 +116,7 @@ static int bpf_jit_stack_local(struct codegen_context *ctx)
 		return STACK_FRAME_MIN_SIZE + ctx->stack_size;
 	} else {
 		/* Stack layout with redzone */
-		return -(BPF_PPC_TAILCALL
-			+BPF_PPC_STACK_SAVE
-			+(ctx->exception_boundary || ctx->exception_cb ?
-						BPF_PPC_EXC_STACK_SAVE : 0)
-			+BPF_PPC_STACK_LOCALS
-			);
+		return -(BPF_PPC_TAILCALL + BPF_PPC_STACK_SAVE + BPF_PPC_STACK_LOCALS);
 	}
 }
 
@@ -160,19 +127,9 @@ static int bpf_jit_stack_tailcallinfo_offset(struct codegen_context *ctx)
 
 static int bpf_jit_stack_offsetof(struct codegen_context *ctx, int reg)
 {
-	int min_valid_nvreg = BPF_PPC_NVR_MIN;
-	/* Default frame size for all cases except exception boundary */
-	int frame_nvr_size = BPF_PPC_STACKFRAME;
-
-	/* Consider all nv regs for handling exceptions */
-	if (ctx->exception_boundary || ctx->exception_cb) {
-		min_valid_nvreg = _R14;
-		frame_nvr_size = BPF_PPC_EXC_STACKFRAME;
-	}
-
-	if (reg >= min_valid_nvreg && reg < 32)
+	if (reg >= BPF_PPC_NVR_MIN && reg < 32)
 		return (bpf_has_stack_frame(ctx) ?
-			(frame_nvr_size + ctx->stack_size) : 0)
+			(BPF_PPC_STACKFRAME + ctx->stack_size) : 0)
 				- (8 * (32 - reg)) - BPF_PPC_TAILCALL;
 
 	pr_err("BPF JIT is asking about unknown registers");
@@ -226,17 +183,6 @@ static void emit_fp_priv_stack(u32 *image, struct codegen_context *ctx)
 			PRIV_STACK_GUARD_SZ + round_up(ctx->priv_stack_size, 16)));
 }
 
-/*
- * For exception boundary & exception_cb progs:
- *     return increased size to accommodate additional NVRs.
- */
-static int bpf_jit_stack_size(struct codegen_context *ctx)
-{
-	return ctx->exception_boundary || ctx->exception_cb ?
-					BPF_PPC_EXC_STACKFRAME :
-					BPF_PPC_STACKFRAME;
-}
-
 void bpf_jit_build_prologue(u32 *image, struct codegen_context *ctx)
 {
 	int i;
@@ -262,11 +208,8 @@ void bpf_jit_build_prologue(u32 *image, struct codegen_context *ctx)
 		EMIT(PPC_RAW_LI(bpf_to_ppc(TMP_REG_1), 0));
 		/* this goes in the redzone */
 		EMIT(PPC_RAW_STD(bpf_to_ppc(TMP_REG_1), _R1, -(BPF_PPC_TAILCALL)));
-	} else if (!ctx->exception_cb) {
+	} else {
 		/*
-		 * Tailcall jitting for non exception_cb progs only.
-		 * exception_cb won't require tail_call_info to be setup.
-		 *
 		 * tail_call_info interpretation logic:
 		 *
 		 * if tail_call_info < MAX_TAIL_CALL_CNT
@@ -283,7 +226,7 @@ void bpf_jit_build_prologue(u32 *image, struct codegen_context *ctx)
 		EMIT(PPC_RAW_STD(bpf_to_ppc(TMP_REG_1), _R1, -(BPF_PPC_TAILCALL)));
 	}
 
-	if (bpf_has_stack_frame(ctx) && !ctx->exception_cb) {
+	if (bpf_has_stack_frame(ctx)) {
 		/*
 		 * We need a stack frame, but we don't necessarily need to
 		 * save/restore LR unless we call other functions
@@ -293,63 +236,22 @@ void bpf_jit_build_prologue(u32 *image, struct codegen_context *ctx)
 			EMIT(PPC_RAW_STD(_R0, _R1, PPC_LR_STKOFF));
 		}
 
-		EMIT(PPC_RAW_STDU(_R1, _R1,
-				-(bpf_jit_stack_size(ctx) + ctx->stack_size)));
+		EMIT(PPC_RAW_STDU(_R1, _R1, -(BPF_PPC_STACKFRAME + ctx->stack_size)));
 	}
 
 	/*
-	 * Program acting as exception boundary pushes R14..R25 in addition to
-	 * BPF callee-saved non volatile registers. Exception callback uses
-	 * the boundary program's stack frame, recover additionally saved
-	 * registers in epilogue of exception callback.
+	 * Back up non-volatile regs -- BPF registers 6-10
+	 * If we haven't created our own stack frame, we save these
+	 * in the protected zone below the previous stack frame
 	 */
-	if (ctx->exception_boundary) {
-		for (i = _R14; i <= _R25; i++)
-			EMIT(PPC_RAW_STD(i, _R1, bpf_jit_stack_offsetof(ctx, i)));
-	}
-
-	if (!ctx->exception_cb) {
-		/*
-		 * Back up non-volatile regs -- BPF registers 6-10
-		 * If we haven't created our own stack frame, we save these
-		 * in the protected zone below the previous stack frame
-		 */
-		for (i = BPF_REG_6; i <= BPF_REG_10; i++)
-			if (ctx->exception_boundary || bpf_is_seen_register(ctx, bpf_to_ppc(i)))
-				EMIT(PPC_RAW_STD(bpf_to_ppc(i), _R1,
-					bpf_jit_stack_offsetof(ctx, bpf_to_ppc(i))));
+	for (i = BPF_REG_6; i <= BPF_REG_10; i++)
+		if (bpf_is_seen_register(ctx, bpf_to_ppc(i)))
+			EMIT(PPC_RAW_STD(bpf_to_ppc(i), _R1, bpf_jit_stack_offsetof(ctx, bpf_to_ppc(i))));
 
-		if (ctx->exception_boundary || ctx->arena_vm_start)
-			EMIT(PPC_RAW_STD(bpf_to_ppc(ARENA_VM_START), _R1,
+	if (ctx->arena_vm_start)
+		EMIT(PPC_RAW_STD(bpf_to_ppc(ARENA_VM_START), _R1,
 				 bpf_jit_stack_offsetof(ctx, bpf_to_ppc(ARENA_VM_START))));
-	} else {
-		/*
-		 * Exception callback receives Frame Pointer of boundary
-		 * program(main prog) as third arg
-		 */
-		EMIT(PPC_RAW_MR(_R1, _R5));
-		/*
-		 * Exception callback reuses the stack frame of exception boundary.
-		 * But BPF stack depth of exception callback and exception boundary
-		 * don't have to be same. If BPF stack depth is different, adjust the
-		 * stack frame size considering BPF stack depth of exception callback.
-		 * The non-volatile register save area remains unchanged. These non-
-		 * volatile registers are restored in exception callback's epilogue.
-		 */
-		EMIT(PPC_RAW_LD(bpf_to_ppc(TMP_REG_1), _R5, 0));
-		EMIT(PPC_RAW_SUB(bpf_to_ppc(TMP_REG_2), bpf_to_ppc(TMP_REG_1), _R1));
-		EMIT(PPC_RAW_ADDI(bpf_to_ppc(TMP_REG_2), bpf_to_ppc(TMP_REG_2),
-			-BPF_PPC_EXC_STACKFRAME));
-		EMIT(PPC_RAW_CMPLDI(bpf_to_ppc(TMP_REG_2), ctx->stack_size));
-		PPC_BCC_CONST_SHORT(COND_EQ, 12);
-		EMIT(PPC_RAW_MR(_R1, bpf_to_ppc(TMP_REG_1)));
-		EMIT(PPC_RAW_STDU(_R1, _R1, -(BPF_PPC_EXC_STACKFRAME + ctx->stack_size)));
-	}
 
-	/*
-	 * Exception_cb not restricted from using stack area or arena.
-	 * Setup frame pointer to point to the bpf stack area
-	 */
 	if (bpf_is_seen_register(ctx, bpf_to_ppc(BPF_REG_FP))) {
 		if (ctx->priv_sp) {
 			/* Set up fp in private stack */
@@ -371,27 +273,18 @@ static void bpf_jit_emit_common_epilogue(u32 *image, struct codegen_context *ctx
 
 	/* Restore NVRs */
 	for (i = BPF_REG_6; i <= BPF_REG_10; i++)
-		if (ctx->exception_cb || bpf_is_seen_register(ctx, bpf_to_ppc(i)))
+		if (bpf_is_seen_register(ctx, bpf_to_ppc(i)))
 			EMIT(PPC_RAW_LD(bpf_to_ppc(i), _R1, bpf_jit_stack_offsetof(ctx, bpf_to_ppc(i))));
 
-	if (ctx->exception_cb || ctx->arena_vm_start)
+	if (ctx->arena_vm_start)
 		EMIT(PPC_RAW_LD(bpf_to_ppc(ARENA_VM_START), _R1,
 				bpf_jit_stack_offsetof(ctx, bpf_to_ppc(ARENA_VM_START))));
 
-	if (ctx->exception_cb) {
-		/*
-		 * Recover additionally saved non volatile registers from stack
-		 * frame of exception boundary program.
-		 */
-		for (i = _R14; i <= _R25; i++)
-			EMIT(PPC_RAW_LD(i, _R1, bpf_jit_stack_offsetof(ctx, i)));
-	}
-
 	/* Tear down our stack frame */
 	if (bpf_has_stack_frame(ctx)) {
-		EMIT(PPC_RAW_ADDI(_R1, _R1, bpf_jit_stack_size(ctx) + ctx->stack_size));
+		EMIT(PPC_RAW_ADDI(_R1, _R1, BPF_PPC_STACKFRAME + ctx->stack_size));
 
-		if (ctx->seen & SEEN_FUNC || ctx->exception_cb) {
+		if (ctx->seen & SEEN_FUNC) {
 			EMIT(PPC_RAW_LD(_R0, _R1, PPC_LR_STKOFF));
 			EMIT(PPC_RAW_MTLR(_R0));
 		}
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 47/73] bpf: Remove the stack walk of bpf_throw()
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (45 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 46/73] powerpc64/bpf: " Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 48/73] bpf: Find at a site that a frame holds more than a landing pad releases Kumar Kartikeya Dwivedi
                   ` (25 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

From: Alexei Starovoitov <ast@kernel.org>

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.

Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index 475a7ae2c356..86f49bf96036 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -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;
diff --git a/arch/powerpc/net/bpf_jit_comp.c b/arch/powerpc/net/bpf_jit_comp.c
index b7147bb31ce3..df44afc79378 100644
--- a/arch/powerpc/net/bpf_jit_comp.c
+++ b/arch/powerpc/net/bpf_jit_comp.c
@@ -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);
diff --git a/arch/s390/net/bpf_jit_comp.c b/arch/s390/net/bpf_jit_comp.c
index 5d3cfa3fe49e..7f9e1c7b7b10 100644
--- a/arch/s390/net/bpf_jit_comp.c
+++ b/arch/s390/net/bpf_jit_comp.c
@@ -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)
 {
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index aa0d760deeb5..3a0143c4d212 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -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;
diff --git a/include/linux/bpf.h b/include/linux/bpf.h
index 88dd179ff712..a8e9d12dbe80 100644
--- a/include/linux/bpf.h
+++ b/include/linux/bpf.h
@@ -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;
diff --git a/include/linux/filter.h b/include/linux/filter.h
index c2ebd258e275..05a0bf8689a4 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -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 {
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 3582cde3cfe3..52fbca734d13 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -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;
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 91aba7d99290..97e147cc73ab 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -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;
diff --git a/kernel/bpf/helpers.c b/kernel/bpf/helpers.c
index d59b1d27324d..1c637c70b1da 100644
--- a/kernel/bpf/helpers.c
+++ b/kernel/bpf/helpers.c
@@ -3509,53 +3509,14 @@ __bpf_kfunc void bpf_rcu_read_unlock(void)
 	rcu_read_unlock();
 }
 
-struct bpf_throw_ctx {
-	struct bpf_prog_aux *aux;
-	u64 sp;
-	u64 bp;
-	int cnt;
-};
-
-static bool bpf_stack_walker(void *cookie, u64 ip, u64 sp, u64 bp)
+/*
+ * Never called: the verifier replaces each call with a jump to a landing pad, see
+ * kernel/bpf/pads.c. The function stays so that programs find it in BTF.
+ */
+__bpf_kfunc void bpf_throw(u64 cookie)
 {
-	struct bpf_throw_ctx *ctx = cookie;
-	struct bpf_prog *prog;
-
-	/*
-	 * The RCU read lock is held to safely traverse the latch tree, but we
-	 * don't need its protection when accessing the prog, since it has an
-	 * active stack frame on the current stack trace, and won't disappear.
-	 */
-	rcu_read_lock();
-	prog = bpf_prog_ksym_find(ip);
-	rcu_read_unlock();
-	if (!prog)
-		return !ctx->cnt;
-	ctx->cnt++;
-	if (bpf_is_subprog(prog))
-		return true;
-	ctx->aux = prog->aux;
-	ctx->sp = sp;
-	ctx->bp = bp;
-	return false;
-}
-
-/* It does not return. What a tracer keeps for the return would stay behind, redzones too. */
-__bpf_kfunc notrace __no_sanitize_address void bpf_throw(u64 cookie)
-{
-	struct bpf_throw_ctx ctx = {};
-
-	arch_bpf_stack_walk(bpf_stack_walker, &ctx);
-	WARN_ON_ONCE(!ctx.aux);
-	if (ctx.aux)
-		WARN_ON_ONCE(!ctx.aux->exception_boundary);
-	WARN_ON_ONCE(!ctx.bp);
-	WARN_ON_ONCE(!ctx.cnt);
-	/* arm64 drops one entry of the shadow call stack, don't move the call to a callee */
-	ctx.aux->bpf_exception_cb(cookie, ctx.sp + ctx.aux->stack_arg_sp_adjust, ctx.bp, 0, 0);
-	WARN(1, "A call to BPF exception callback should never return\n");
-}
-NOKPROBE_SYMBOL(bpf_throw);
+	WARN_ON_ONCE(1);
+}
 
 __bpf_kfunc int bpf_wq_init(struct bpf_wq *wq, void *p__const_map, unsigned int flags)
 {
diff --git a/kernel/bpf/syscall.c b/kernel/bpf/syscall.c
index 198438b95849..70112c2c1e40 100644
--- a/kernel/bpf/syscall.c
+++ b/kernel/bpf/syscall.c
@@ -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;
diff --git a/scripts/gdb/linux/bpf.py b/scripts/gdb/linux/bpf.py
index 1870534ef6f9..3a6d69d7ed5b 100644
--- a/scripts/gdb/linux/bpf.py
+++ b/scripts/gdb/linux/bpf.py
@@ -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
 
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 48/73] bpf: Find at a site that a frame holds more than a landing pad releases
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (46 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 47/73] bpf: Remove the stack walk of bpf_throw() Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 49/73] bpf: Cancel the program when the time of its own may_goto is up Kumar Kartikeya Dwivedi
                   ` (24 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  3 ++-
 kernel/bpf/pads.c            | 16 ++++++++++++++--
 2 files changed, 16 insertions(+), 3 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 46cb7baa46bc..1d4860542c42 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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,
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 8f675995da71..57cbeae78edb 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -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",
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 49/73] bpf: Cancel the program when the time of its own may_goto is up
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (47 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 48/73] bpf: Find at a site that a frame holds more than a landing pad releases Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:42   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 50/73] bpf: Reject a program that has no landing pad for a fault in arena Kumar Kartikeya Dwivedi
                   ` (23 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 1d4860542c42..e20df219d332 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 97e147cc73ab..f36e99814ab0 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -655,6 +655,8 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 		return false;
 	case BPF_SITE_FAULT:
 		return !env->insn_aux_data[i].fault_skips;
+	case BPF_SITE_MAY_GOTO:
+		return plan->visited && !bpf_find_containing_subprog(env, i)->stuck;
 	}
 	return false;
 }
@@ -817,6 +819,38 @@ static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added)
 	return bpf_patch_list_commit(env);
 }
 
+/*
+ * Make each may_goto of the program that is a site jump to its landing pad, see
+ * check_may_goto_site(). This has to run before dead code is hard wired. No state takes the jump
+ * of such a may_goto, so its old target can be dead code, and the insn would become 'goto +0',
+ * which stops no loop. @added is the number of insns that were appended to each subprog.
+ */
+static int retarget_may_gotos(struct bpf_verifier_env *env, const int *added)
+{
+	struct bpf_patch_list *pl = &env->patch_list;
+	const struct bpf_subprog_info *sub;
+	const struct bpf_pad_plan *plan;
+	struct bpf_insn *insn;
+	int i, s;
+
+	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++) {
+			plan = bpf_pad_plan(&env->insn_aux_data[i], BPF_SITE_MAY_GOTO);
+			if (!plan || !bpf_site_is_used(env, i, plan))
+				continue;
+			if (bpf_must_abort())
+				return -EINTR;
+			/* queue the insn as its own patch: the list sets the offset, however far */
+			insn = __bpf_patch_list_add(pl, env->prog, i, &env->prog->insnsi[i], 1);
+			if (IS_ERR(insn))
+				return PTR_ERR(insn);
+			bpf_patch_list_jump(pl, insn, sub[1].start - added[s] + plan->pad, 0);
+		}
+	}
+	return bpf_patch_list_commit(env);
+}
+
 /*
  * Add the stores that keep the hidden slots up to date, see kernel/bpf/pads.c. @buf has room for
  * BPF_PAD_MAX_SLOT_INSNS. @added is the number of insns that were appended to each subprog.
@@ -877,10 +911,9 @@ static int insert_slot_stores(struct bpf_verifier_env *env, struct bpf_insn *buf
 }
 
 /*
- * Emit what the main pass decided about the sites: may_goto before the insns that it
- * marked, see check_loop_guard(), unwind_goto after calls and after accesses to arena, a jump in
- * place of a call of bpf_throw(), the landing pads, and the stores to the hidden slots that the pads
- * read. What a pad does it did to the states that left the frame at the site, see unwind_frame().
+ * Emit the code for the sites that the main pass recorded. The landing pads of a subprog go after
+ * its last insn. They are not verified: unwind_frame() did to each state that left its frame at a
+ * site what the pad of the site does.
  *
  *	may_goto pad		before an insn of a loop, see check_loop_guard(). A may_goto
  *	insn			of the program that is a site jumps to its pad too.
@@ -979,6 +1012,7 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 	}
 	err = insert_slot_stores(env, new, added);
 	err = err ?: insert_unwind_gotos(env, added);
+	err = err ?: retarget_may_gotos(env, added);
 out:
 	kvfree(added);
 	kvfree(new);
@@ -1256,6 +1290,39 @@ static bool insn_is_nop(struct bpf_verifier_env *env, int i, int next)
 	       !memcmp(&insn, &MAY_GOTO_0, sizeof(MAY_GOTO_0));
 }
 
+/* Is @insn an addr_space_cast of a register into itself? bpf_lower_cast_mov() may remove it. */
+static bool cast_may_be_nop(const struct bpf_insn *insn)
+{
+	return insn->code == (BPF_ALU64 | BPF_MOV | BPF_X) &&
+	       insn->off == BPF_ADDR_SPACE_CAST && insn->dst_reg == insn->src_reg;
+}
+
+/*
+ * Mark each may_goto that jumps over nothing, or over nothing but insns like itself. clang emits
+ * them when it unrolls a loop with can_loop. bpf_opt_remove_nops() removes such an insn, so the
+ * main pass does not make it a site, see check_may_goto_site().
+ *
+ * A cast that may be removed counts as nothing too. If the cast stays, so does the may_goto that
+ * jumps over it. It then jumps where the program says, and the main pass has verified that jump.
+ */
+void bpf_mark_may_goto_nops(struct bpf_verifier_env *env)
+{
+	struct bpf_insn *insns = env->prog->insnsi, insn;
+	int i, next;
+
+	for (i = env->prog->len - 1, next = env->prog->len; i >= 0; i--) {
+		if (cast_may_be_nop(&insns[i]))
+			continue;
+		insn = insns[i];
+		insn.off = 0;
+		if (insns[i].off < 0 || i + 1 + insns[i].off > next ||
+		    (memcmp(&insn, &NOP, sizeof(NOP)) && memcmp(&insn, &MAY_GOTO_0, sizeof(insn))))
+			next = i;
+		else
+			env->insn_aux_data[i].may_goto_nop = bpf_is_may_goto_insn(&insn);
+	}
+}
+
 /* addr_space_cast of a pointer that is not in arena is a move, see is_cast_mov() */
 void bpf_lower_cast_mov(struct bpf_verifier_env *env)
 {
@@ -3516,6 +3583,14 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 				 * The time is up, but the helper would call the function again and
 				 * again. End its loop. The verifier has seen that: the loop can end
 				 * after each call.
+				 *
+				 * This check is not a site, unlike a may_goto of the program, see
+				 * check_may_goto_site(). When it ends the loop, the helper returns
+				 * the number of calls that it made, and the program continues
+				 * until its next may_goto. The main pass cannot make the check a
+				 * site: no insn of the program stands for it, and only after the
+				 * pass is it known that only loop helpers call the function and
+				 * that the program has a timed may_goto.
 				 */
 				insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_0, BPF_REG_0,
 							      count_off);
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 57cbeae78edb..36086dc5ee98 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -4,7 +4,8 @@
  *
  * The kernel can cancel a BPF program: it ends the program before the program's own code returns. A
  * SITE is an insn at which that can happen:
- *   - a may_goto that the verifier adds, when the time of the program is up (BPF_SITE_GUARD)
+ *   - a may_goto of the verifier or of the program, when the time of the program is up
+ *     (BPF_SITE_GUARD, BPF_SITE_MAY_GOTO)
  *   - 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)
@@ -2397,15 +2398,17 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 }
 
 /*
- * Is the pad the only way out of the site of @plan? An access to arena that faults can be skipped.
- * So can all of them below a call, unless a subprog comes back to the call that is left elsewhere.
+ * Is the pad the only way out of the site of @plan, whatever the subprog turns out to be? An access
+ * to arena that faults can be skipped. may_goto of the program can jump where the program says, as
+ * it does in a subprog that cannot unwind. So can all of them below a call, unless a subprog comes
+ * back to the call that is left elsewhere.
  */
 bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
 {
 	int s;
 
 	if (plan->kind != BPF_SITE_CALL)
-		return plan->kind != BPF_SITE_FAULT;
+		return plan->kind != BPF_SITE_FAULT && plan->kind != BPF_SITE_MAY_GOTO;
 	bpf_pad_for_each_callee(plan, s)
 		if (env->subprog_info[s].must_unwind)
 			return true;
@@ -2433,6 +2436,100 @@ void bpf_pads_must_unwind(struct bpf_verifier_env *env)
 	} while (changed);
 }
 
+/*
+ * At which kinds of site does the program leave each subprog? At its own, and at those of what
+ * comes back to its calls. Bits by enum bpf_site_kind in 'left_at'. The main pass notes them as
+ * the states leave, see bpf_pad_note_left(). This is what is left of that when the pass is over.
+ */
+static void sites_of_subprogs(struct bpf_verifier_env *env)
+{
+	const struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	const struct bpf_pad_plan *plan;
+	struct bpf_subprog_info *sub;
+	bool changed;
+	int i, s, c;
+	u8 kinds;
+
+	for (s = 0; s < env->subprog_cnt; s++) {
+		sub = &env->subprog_info[s];
+		sub->left_at = 0;
+	}
+	do {
+		changed = false;
+		for (s = 0; s < env->subprog_cnt; s++) {
+			sub = &env->subprog_info[s];
+			kinds = sub->left_at;
+			for (i = sub->start; i < sub[1].start; i++) {
+				if (aux[i].loop_guard)
+					kinds |= BIT(BPF_SITE_GUARD);
+				if (aux[i].fault_empty && !aux[i].fault_skips)
+					kinds |= BIT(BPF_SITE_FAULT);
+				for (plan = aux[i].pad_plans; plan; plan = plan->next) {
+					if (!plan->used)
+						continue;
+					if (plan->kind != BPF_SITE_CALL) {
+						kinds |= BIT(plan->kind);
+						continue;
+					}
+					bpf_pad_for_each_callee(plan, c)
+						kinds |= env->subprog_info[c].left_at;
+				}
+			}
+			changed |= kinds != sub->left_at;
+			sub->left_at = kinds;
+		}
+	} while (changed);
+}
+
+/* The kinds of site that the subprogs which come back to the call of @plan are left at */
+static u8 sites_below(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+{
+	u8 kinds = 0;
+	int s;
+
+	bpf_pad_for_each_callee(plan, s)
+		kinds |= env->subprog_info[s].left_at;
+	return kinds;
+}
+
+/* The frame at the site of @plan cannot be cancelled, so there is no pad to generate */
+static bool plan_is_stuck(const struct bpf_pad_plan *plan)
+{
+	return plan->conflict == BPF_CONFLICT_CANNOT_UNWIND ||
+	       plan->conflict == BPF_CONFLICT_NO_EXIT;
+}
+
+/*
+ * Does the site of @plan need a pad wherever its frame can unwind? If so a conflict there is an
+ * error, and hidden slots are worth their stores. All sites do, but for:
+ *   - an access to arena, and a call that has nothing but such accesses below it: they are
+ *     skipped, see skip_faults().
+ * may_goto of the program needs one, and so does a call above it: the jump that the program
+ * has there was not verified.
+ */
+static bool site_needs_pad(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+{
+	if (bpf_pad_must_unwind(env, plan))
+		return true;
+	if (plan->kind == BPF_SITE_FAULT)
+		return false;
+	return plan->kind != BPF_SITE_CALL || (sites_below(env, plan) & BIT(BPF_SITE_MAY_GOTO));
+}
+
+/*
+ * Is the conflict of @plan an error? Not where the frame cannot unwind and the site has another way
+ * out, see bpf_pad_must_unwind(): what comes back to a call there is made unable to unwind, see
+ * skip_faults().
+ */
+static bool plan_rejects(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+{
+	if (!plan->conflict)
+		return false;
+	if (bpf_pad_must_unwind(env, plan))
+		return true;
+	return !plan_is_stuck(plan) && site_needs_pad(env, plan);
+}
+
 /*
  * Does an insn of @sub acquire an iterator or a dynptr? If none does, a reference of its frame that
  * has no location is always a pointer, and the hidden slot of the call that returned it holds it.
@@ -2462,7 +2559,7 @@ static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_pl
 	u8 groups = plan->sections_differ;
 	int i, err;
 
-	if (!plan->used || plan->conflict || !bpf_pad_must_unwind(env, plan))
+	if (!plan->used || plan->conflict || !site_needs_pad(env, plan))
 		return 0;
 	if (plan->no_place && all_ptrs)
 		groups |= BIT(BPF_PAD_GROUP_REFS);
@@ -2670,7 +2767,7 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 	for (i = sub->start; i < sub[1].start; i++)
 		for (plan = aux[i].pad_plans; plan; plan = plan->next)
 			if (plan->used && plan_has_slots(plan) &&
-			    !plan_has_room(plan, group, slots) && bpf_pad_must_unwind(env, plan))
+			    !plan_has_room(plan, group, slots) && site_needs_pad(env, plan))
 				return 0;
 	sub->hidden_words += words;
 	err = bpf_hidden_slots_fit(env);
@@ -3030,6 +3127,7 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 		[BPF_SITE_CALL]			= "call",
 		[BPF_SITE_FAULT]		= "arena access",
 		[BPF_SITE_THROW]		= "bpf_throw",
+		[BPF_SITE_MAY_GOTO]		= "may_goto of the program",
 	};
 	static const char * const why[] = {
 		[BPF_CONFLICT_SECTIONS_DIFFER]	= "the number of sections differs",
@@ -3095,12 +3193,23 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pa
 	print_plan(env, insn_idx, plan);
 }
 
+/*
+ * A state leaves a frame of @sub at the site of @plan, which is of @kind. Record the kind in
+ * 'left_at', for the callers. bpf_pads_settle() computes it again for the sites that are kept.
+ */
+void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *sub,
+		       const struct bpf_pad_plan *plan, enum bpf_site_kind kind)
+{
+	sub->left_at |= kind == BPF_SITE_CALL ? sites_below(env, plan) : BIT(kind);
+}
+
 /*
  * The site of @plan, at insn @i, has no pad. An access to arena: it is skipped when it faults.
  * What follows the access was verified, and less unwinds than the main pass looked at.
- * Or it is a call, and only accesses to arena unwind below it. They are skipped: what came back to
- * the call cannot unwind, nor can what came back to the calls in there. The pass is done again,
- * and they cannot from its start, see check_funcs().
+ * Or it is a call, and below it only accesses to arena and may_goto of the program unwind. The
+ * accesses are skipped and may_goto jumps where the program says: what came back to the call cannot
+ * unwind, nor can what came back to the calls in there. The pass is done again, and they cannot
+ * from its start, see check_funcs().
  */
 static int skip_faults(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
 {
@@ -3125,6 +3234,7 @@ static int skip_faults(struct bpf_verifier_env *env, int i, const struct bpf_pad
 		if (!sub->bail_unwinds)
 			continue;
 		sub->bail_unwinds = false;
+		sub->stuck = true;
 		for (i = sub->start; i < sub[1].start; i++) {
 			plan = bpf_pad_plan(&aux[i], BPF_SITE_CALL);
 			if (plan)
@@ -3187,6 +3297,7 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 	int i, s, err;
 
 	bpf_pads_must_unwind(env);
+	sites_of_subprogs(env);
 	/* sort the releases first: hidden slots are inserted into that order */
 	for (i = 0; i < env->prog->len; i++) {
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next) {
@@ -3210,7 +3321,7 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 			if (err < 0)
 				return err;
 			plan->conflict = err;
-			if (plan->conflict && bpf_pad_must_unwind(env, plan)) {
+			if (plan_rejects(env, plan)) {
 				print_plan(env, i, plan);
 				return -EINVAL;
 			}
@@ -3237,7 +3348,7 @@ bool bpf_pads_conflict(struct bpf_verifier_env *env, const struct bpf_insn_aux_d
 	const struct bpf_pad_plan *plan;
 
 	for (plan = aux->pad_plans; plan; plan = plan->next)
-		if (plan->used && plan->conflict && bpf_pad_must_unwind(env, plan))
+		if (plan->used && plan_rejects(env, plan))
 			return true;
 	return false;
 }
@@ -3262,6 +3373,17 @@ static bool jump_leaves_loop(struct bpf_verifier_env *env, int h, int n)
 	       !loop_is_in(env, bpf_loop_at_index(env, n + 1), h);
 }
 
+/* The pass left a frame at the insn of @aux, may_goto of the program */
+static bool left_at_insn(const struct bpf_insn_aux_data *aux)
+{
+	const struct bpf_pad_plan *plan;
+
+	for (plan = aux->pad_plans; plan; plan = plan->next)
+		if (plan->visited && plan->kind == BPF_SITE_MAY_GOTO)
+			return true;
+	return false;
+}
+
 /*
  * The landing pad of the call of @plan has a conflict, and that is an error: what the call calls
  * is unwound. Where that is at may_goto that the verifier adds, it depends on the
@@ -3279,6 +3401,11 @@ static bool jump_leaves_loop(struct bpf_verifier_env *env, int h, int n)
  * Kept apart, neither call is cancelled. The calls do not say what to keep apart, because their
  * arguments are constants, so the causes are recorded in the callee.
  *
+ * may_goto of the program leaves a function as well. The dependencies of the next pass know exit,
+ * unwind_exit and bpf_throw() as the ways out of a function, and none of these stands for such an
+ * insn. Where only the calls together get to it, the jumps that can skip it are the cause: the insn
+ * is noted, and they are what controls it.
+ *
  * No pass that keeps more apart gives the frame of the call a place for a pointer that it passed
  * on and kept no copy of, or a way to tell whether the callee has released it. Where that is the
  * conflict, see conflict_of_ref(), and the callee is one that releases what the call could hand
@@ -3364,6 +3491,8 @@ static void note_causes_below(struct bpf_verifier_env *env)
 	for (s = 0; s < cnt; s++) {
 		guards = false;
 		for (i = sub[s].start; sub[s].below_conflict && i < sub[s + 1].start; i++) {
+			if (left_at_insn(&aux[i]))
+				bpf_note_controlled_cause(env, i);
 			if (!aux[i].loop_guard || bpf_flow_guard_is_guess(env, i))
 				continue;
 			h = bpf_loop_at_index(env, i);
@@ -3403,8 +3532,7 @@ void bpf_pads_note_causes(struct bpf_verifier_env *env)
 	env->ref_conflict = false;
 	for (i = 0; i < env->prog->len; i++)
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next)
-			if (plan->failed || (plan->used && plan->conflict &&
-					     bpf_pad_must_unwind(env, plan)))
+			if (plan->failed || (plan->used && plan_rejects(env, plan)))
 				note_causes(env, i, plan);
 	note_causes_below(env);
 	/* The caller checks the limits before the next pass. This is for a load that ends here. */
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index f5bc401bce87..2141cef41a88 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -225,6 +225,8 @@ static inline bool in_sleepable_context(struct bpf_verifier_env *env);
 static bool in_rcu_callback(struct bpf_verifier_env *env);
 static const char *non_sleepable_context_description(struct bpf_verifier_env *env);
 static int check_arena_site(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
+static int check_may_goto_site(struct bpf_verifier_env *env);
+static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog);
 
 static void bpf_map_ptr_store(struct bpf_insn_aux_data *aux,
 			      struct bpf_map *map,
@@ -3421,9 +3423,14 @@ static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)
 			env->insn_idx, bpf_subprog_name(env, subprog));
 		return -EINVAL;
 	}
-	/* It did at accesses to arena only. They are skipped, and the pass is done again. */
-	env->faults_late |= did_unwind;
+	/*
+	 * It did at accesses to arena, which are skipped, and at may_goto of the program, which
+	 * jumps where the program says, see check_may_goto_site(). The pass is done again.
+	 */
+	env->faults_late |= did_unwind ||
+			    ((sub->may_goto_unwinds || sub->made_calls) && !sub->stuck);
 	sub->bail_unwinds = false;
+	sub->stuck = true;
 	return 0;
 }
 
@@ -3468,6 +3475,51 @@ static void mark_unwind_above(struct bpf_verifier_env *env)
 	} while (changed);
 }
 
+/*
+ * A global subprog that has a may_goto of the program, or that calls a subprog which has one, is
+ * cancelled there when the time is up, see check_may_goto_site(). Its callers are verified before
+ * it. Mark it before the first pass, so that the pass does not have to start again to tell them.
+ */
+static int expect_may_goto_unwinds(struct bpf_verifier_env *env)
+{
+	struct bpf_subprog_info *si = env->subprog_info;
+	struct bpf_insn *insn = env->prog->insnsi;
+	int i, k, s, c, cnt = env->subprog_cnt, err = 0;
+	unsigned long *soft;
+	bool changed;
+
+	if (!env->prog->jit_requested || !bpf_jit_supports_timed_may_goto() ||
+	    bpf_prog_is_offloaded(env->prog->aux))
+		return 0;
+	soft = bitmap_zalloc(cnt, BPF_VERIFIER_GFP);
+	if (!soft)
+		return -ENOMEM;
+	for (i = 0; i < env->prog->len; i++)
+		if (bpf_is_may_goto_insn(&insn[i]) && !env->insn_aux_data[i].may_goto_nop)
+			__set_bit(bpf_find_containing_subprog(env, i) - si, soft);
+	/* Callees come first in the order, so only a cycle of calls needs a second round. */
+	do {
+		changed = false;
+		err = bpf_add_cost_and_check(env, env->prog->len, BPF_COST_SCAN);
+		for (k = 0; k < cnt && !err; k++) {
+			c = env->subprog_topo_order[k];
+			for (i = si[c].start; i < si[c + 1].start && !test_bit(c, soft); i++) {
+				if (!bpf_pseudo_call(&insn[i]))
+					continue;
+				s = bpf_find_subprog(env, i + insn[i].imm + 1);
+				if (s < 0 || !test_bit(s, soft))
+					continue;
+				__set_bit(c, soft);
+				changed = true;
+			}
+		}
+	} while (changed);
+	for_each_set_bit(s, soft, cnt)
+		si[s].did_unwind |= si[s].bail_unwinds && bpf_subprog_is_global(env, s);
+	bitmap_free(soft);
+	return err;
+}
+
 /*
  * 'call foo; unwind_goto pad' goes to the pad when foo left with unwind_exit.
  * JITs don't emit a branch for it. unwind_exit finds the pad by its return
@@ -11817,6 +11869,7 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 	err = record_callx_edge(env, caller->subprogno, subprog);
 	if (err)
 		return err;
+	stuck_frame_calls(env, subprog);
 
 	if (!bpf_pseudo_kfunc_call(insn) &&
 	    (insn->imm == BPF_FUNC_loop || insn->imm == BPF_FUNC_for_each_map_elem))
@@ -12286,6 +12339,7 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		return err;
 	if (err == -ENODATA)
 		return -EINVAL;
+	stuck_frame_calls(env, subprog);
 	if (bpf_subprog_is_global(env, subprog)) {
 		struct bpf_func_info_aux *sub_aux = subprog_aux(env, subprog);
 		const char *sub_name = bpf_subprog_name(env, subprog);
@@ -12418,6 +12472,7 @@ static int check_func_callx_one(struct bpf_verifier_env *env, int subprog, int *
 	err = record_callx_edge(env, cur_func(env)->subprogno, subprog);
 	if (err)
 		return err;
+	stuck_frame_calls(env, subprog);
 	env->subprog_info[subprog].via_callx = true;
 
 	return check_static_func_call(env, subprog, insn_idx);
@@ -19850,6 +19905,11 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 		struct bpf_verifier_state *queued_st;
 		int idx = *insn_idx;
 
+		/* At a site the frame is cancelled here, and no state takes the jump. */
+		err = check_may_goto_site(env);
+		if (err)
+			return min(err, 0);
+
 		/* branch out 'fallthrough' insn as a new state to explore */
 		queued_st = push_stack(env, idx + 1, idx, false);
 		if (IS_ERR(queued_st))
@@ -21967,6 +22027,39 @@ static enum bpf_pad_conflict frame_cannot_unwind(struct bpf_verifier_env *env,
 	return BPF_NO_CONFLICT;
 }
 
+/*
+ * An insn of the program enters @subprog from the current frame: a call, callx, a helper or a
+ * kfunc that has a landing pad for its callback. If the frame cannot unwind, or is a frame of a
+ * subprog whose may_goto stays and that has a caller in the program, then what comes back
+ * unwound to the call may have nowhere to go. So may_goto of @subprog stays too, see
+ * check_may_goto_site(): from this call on, before a state gets to its may_goto and makes a
+ * conflict there, or at another call of @subprog, that is none. That closes the answer over what
+ * a subprog that cannot unwind calls, call by call as the pass gets to them. If a state has left
+ * @subprog before, the pass is done again. The same if a frame of @subprog has made a call before:
+ * what it called was not told, and the function may not be walked again, since the call of a
+ * function on its own that an instance subsumes waits for the exits of that instance. A state that
+ * came back unwound from there can have ended in a conflict at the call, which leaves no other
+ * trace in @subprog.
+ * @subprog still unwinds where there is no other way out. A state that does so on the way from
+ * this call is an error at the call, see unwind_frame().
+ */
+static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog)
+{
+	struct bpf_subprog_info *caller = &env->subprog_info[cur_func(env)->subprogno];
+	struct bpf_subprog_info *sub = &env->subprog_info[subprog];
+	const struct bpf_verifier_state *st = env->cur_state;
+
+	if (sub->stuck)
+		return;
+	if (!frame_cannot_unwind(env, st) && (!caller->stuck || frame_is_top(st))) {
+		caller->made_calls = true;
+		return;
+	}
+	env->faults_late |= sub->may_goto_unwinds || sub->made_calls ||
+			    (sub->did_unwind && sub->bail_unwinds);
+	sub->stuck = true;
+}
+
 /* This insn is a site of @kind. Push a copy of the current state that leaves its frame here. */
 static int push_unwind_edge(struct bpf_verifier_env *env, enum bpf_site_kind kind)
 {
@@ -22028,6 +22121,37 @@ static int check_loop_guard(struct bpf_verifier_env *env)
 	return err;
 }
 
+/*
+ * The insn is a may_goto of the program (can_loop, cond_break). When its time is up, the kernel
+ * cancels the program here, as at a may_goto that the verifier adds: a copy of the state leaves the
+ * frame, see unwind_frame(), and no state takes the jump. The jump stays an edge of the control
+ * flow graph and of liveness, so what the program reads only at the target is live here.
+ *
+ * Returns 1 if the frame is cancelled here. Returns 0 if the insn stays a plain jump: it jumps
+ * over nothing, see bpf_mark_may_goto_nops(), no JIT runs the timed form (BPF_MAX_LOOPS trips are
+ * a bound of the loop, not a time-out), or its function cannot be cancelled ('stuck'). An insn is
+ * rewritten in one way, so the mark holds for all frames of the function, and the pass is repeated
+ * if the mark comes late.
+ */
+static int check_may_goto_site(struct bpf_verifier_env *env)
+{
+	struct bpf_subprog_info *sub = &env->subprog_info[cur_func(env)->subprogno];
+	int err;
+
+	if (cur_aux(env)->may_goto_nop || !env->prog->jit_requested ||
+	    !bpf_jit_supports_timed_may_goto() || bpf_prog_is_offloaded(env->prog->aux))
+		return 0;
+	if (sub->stuck || frame_cannot_unwind(env, env->cur_state)) {
+		env->faults_late |= (sub->may_goto_unwinds || sub->made_calls) &&
+				    !sub->stuck;
+		sub->stuck = true;
+		return 0;
+	}
+	sub->may_goto_unwinds = true;
+	err = push_unwind_edge(env, BPF_SITE_MAY_GOTO);
+	return err ?: 1;
+}
+
 /* Is all that the current frame of @st holds a pointer, which is NULL where nothing is held? */
 static bool frame_holds_pointers_only(const struct bpf_verifier_state *st)
 {
@@ -22220,9 +22344,11 @@ static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_p
  *
  * With a conflict there is no pad: the site is an unproven insn in @st, which ends here. The pass
  * goes on, and a pass that keeps more apart may have no such state.
- * A frame that cannot unwind is a conflict. At an access to arena check_arena_site() saw to both.
+ * A frame that cannot unwind is a conflict. At an access to arena check_arena_site() saw to both,
+ * and at may_goto of the program check_may_goto_site() saw to it: the jump is taken there.
  * At a call that has only such accesses below it a conflict is no error: @st is dropped, and
- * bpf_pads_settle() has the accesses skipped.
+ * bpf_pads_settle() has the accesses skipped. The same at a call in a frame that cannot unwind, if
+ * what comes back to it has another way out: the callees are made unable to unwind.
  * Nor is it one at a site that the program may not have in the end, see site_is_certain(): @st is
  * dropped, the plan keeps the conflict, and bpf_pads_settle() makes it an error of the pass if the
  * site is still there.
@@ -22235,7 +22361,8 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	struct bpf_verifier_state *cur = env->cur_state;
 	int cur_idx = env->insn_idx, err = 0;
 	struct bpf_pad_plan *plan = NULL;
-	bool print_state, certain = false;
+	bool print_state, certain = false, stuck;
+	enum bpf_pad_conflict conflict;
 	u32 cnt;
 
 	env->cur_state = st;
@@ -22247,14 +22374,25 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		err = PTR_ERR_OR_ZERO(plan);
 		if (err)
 			goto out;
-		if (!plan->conflict)
-			plan->conflict = frame_cannot_unwind(env, st);
+		conflict = frame_cannot_unwind(env, st);
+		/*
+		 * The frame cannot be cancelled. If the site can be skipped, that replaces any
+		 * other reason: no landing pad runs in this frame, see bpf_pads_settle().
+		 */
+		if (conflict && (!plan->conflict || !bpf_pad_must_unwind(env, plan)))
+			plan->conflict = conflict;
 		if (!plan->conflict && bpf_site_has_value(env, kind) &&
 		    frame->regs[bpf_site_value_reg(kind)].type != SCALAR_VALUE)
 			plan->conflict = BPF_CONFLICT_NO_VALUE;
 		certain = site_is_certain(env, plan, insn_idx);
-		/* there is no other way out */
-		if (plan->conflict && bpf_pad_must_unwind(env, plan) && certain) {
+		stuck = plan->conflict == BPF_CONFLICT_CANNOT_UNWIND ||
+			plan->conflict == BPF_CONFLICT_NO_EXIT;
+		/*
+		 * There is no other way out. Not for may_goto of the program and a call above it
+		 * either, but in a subprog that cannot unwind, and whether it is one may be found
+		 * later in the pass. Then this error was none, see do_check_all().
+		 */
+		if (plan->conflict && certain && (bpf_pad_must_unwind(env, plan) || !stuck)) {
 			bpf_pad_log(env, insn_idx, plan);
 			/* for bpf_pads_note_causes() */
 			plan->failed = true;
@@ -22291,8 +22429,10 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		env->pads_late = true;
 	}
 	sub->did_unwind |= st->unwound;
+	if (st->unwound)
+		bpf_pad_note_left(env, sub, plan, kind);
 	sub->must_unwind |= st->unwound && plan && bpf_pad_must_unwind(env, plan);
-	sub->unwinds_for_sure |= st->unwound && plan && bpf_pad_must_unwind(env, plan) && certain;
+	sub->unwinds_for_sure |= st->unwound && plan && certain;
 	if (env->log.level & BPF_LOG_LEVEL2)
 		verbose(env, "from %d to %s of func#%d\n", insn_idx,
 			st->unwound ? "unwind_exit" : "exit", frame->subprogno);
@@ -24487,7 +24627,7 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
 		if (bpf_subprog_is_global(env, i))
 			initial->subprogs[i].did_unwind |= env->subprog_info[i].did_unwind;
 		/*
-		 * The accesses to arena in it are skipped and the pass is done again, see
+		 * The accesses to arena in it are skipped, and the pass is done again, see
 		 * subprog_cannot_unwind() and skip_faults(). The second run has to know from its
 		 * start that the subprog cannot unwind, or it finds out late once more.
 		 * No other run knows: like all else about a subprog that is what one pass finds. A
@@ -24500,6 +24640,14 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
 				initial->subprogs[i].bail_unwinds_at_first;
 		else if (env->faults_late)
 			initial->subprogs[i].bail_unwinds &= env->subprog_info[i].bail_unwinds;
+		/*
+		 * Its may_goto jumps where the program says, see check_may_goto_site() and
+		 * stuck_frame_calls(). That is what it did before the verifier unwound programs
+		 * there, so it is safe to keep in every run that follows: a run that had to find
+		 * it again could end at an error which is none before it gets to the call that
+		 * tells.
+		 */
+		initial->subprogs[i].stuck |= env->subprog_info[i].stuck;
 		/* 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;
@@ -24794,6 +24942,20 @@ static int do_check_all(struct bpf_verifier_env *env)
 			err = ret;
 			break;
 		}
+		/*
+		 * The run has an error, and it found late what a run has to know from its start,
+		 * see check_arena_site(). Mostly that a subprog cannot unwind: its may_goto jumps
+		 * where the program says, and the states that left it there went where no run of
+		 * the program goes. A conflict at such a site or at a call above it was none, and
+		 * neither was what such a state ran into on its way. The run that follows knows
+		 * from its start.
+		 */
+		if (ret && env->faults_late && !env->over_limit) {
+			/* Drop the log of that error. */
+			restart_log(env, &log);
+			env->pass_again = true;
+			continue;
+		}
 		more = bpf_undo_precision(env);
 		if (more > 0)
 			continue;
@@ -26963,6 +27125,11 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (ret < 0)
 		goto skip_full_check;
 
+	bpf_mark_may_goto_nops(env);
+	ret = expect_may_goto_unwinds(env);
+	if (ret < 0)
+		goto skip_full_check;
+
 	ret = bpf_compute_live_registers(env);
 	if (ret < 0)
 		goto skip_full_check;
diff --git a/tools/testing/selftests/bpf/prog_tests/may_goto_far.c b/tools/testing/selftests/bpf/prog_tests/may_goto_far.c
index b6d262911a3e..201cda7cf34b 100644
--- a/tools/testing/selftests/bpf/prog_tests/may_goto_far.c
+++ b/tools/testing/selftests/bpf/prog_tests/may_goto_far.c
@@ -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);
 }
 
diff --git a/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c b/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c
index 3da3f33a2898..8f46e6a096ec 100644
--- a/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c
+++ b/tools/testing/selftests/bpf/prog_tests/timed_may_goto.c
@@ -42,7 +42,7 @@ static void wait_for(int *val, int expected, const char *name)
 
 static void test_async(struct timed_may_goto_user *skel)
 {
-	ASSERT_EQ(run_syscall(skel->progs.async_after_timeout), 0, "async_after_timeout");
+	ASSERT_EQ(run_syscall(skel->progs.async_after_timeout), -ECANCELED, "async_after_timeout");
 	wait_for(&skel->bss->timer_cnt, 1000, "timer_cnt");
 	wait_for(&skel->bss->wq_cnt, 1000, "wq_cnt");
 	wait_for(&skel->bss->tw_cnt, 1000, "tw_cnt");
@@ -50,10 +50,23 @@ static void test_async(struct timed_may_goto_user *skel)
 	wait_for(&skel->bss->rcu_trace_cnt, 1000, "rcu_trace_cnt");
 }
 
+static long now_ms(void)
+{
+	struct timespec ts;
+
+	clock_gettime(CLOCK_MONOTONIC, &ts);
+	return ts.tv_sec * 1000 + ts.tv_nsec / 1000000;
+}
+
 static void test_timer_on_top(struct timed_may_goto_user *skel)
 {
-	int ms = run_syscall(skel->progs.spin_under_timer);
-	int ticks = skel->bss->ticks;
+	long ms = now_ms();
+	int ticks;
+
+	/* the prog is unwound */
+	ASSERT_EQ(run_syscall(skel->progs.spin_under_timer), -ECANCELED, "spin_under_timer");
+	ms = now_ms() - ms;
+	ticks = skel->bss->ticks;
 
 	/* stop the timer */
 	skel->bss->ticks = 100;
@@ -68,21 +81,37 @@ static void test_freplace(struct timed_may_goto_user *skel)
 {
 	struct timed_may_goto_ext *ext;
 
-	ASSERT_EQ(run_tc(skel->progs.freplace_target), 1, "not replaced");
+	/* replaced_global() is unwound, and the prog with it */
+	ASSERT_EQ(run_tc(skel->progs.freplace_target), 2, "not replaced");
 
+	/* so it cannot be replaced */
 	ext = timed_may_goto_ext__open();
 	if (!ASSERT_OK_PTR(ext, "ext_open"))
 		return;
 	bpf_program__set_attach_target(ext->progs.replacement,
 				       bpf_program__fd(skel->progs.freplace_target),
 				       "replaced_global");
+	ASSERT_ERR(timed_may_goto_ext__load(ext), "ext_load of what can unwind");
+	timed_may_goto_ext__destroy(ext);
+
+	ASSERT_EQ(run_tc(skel->progs.freplace_plain_target), 10, "not replaced");
+	ext = timed_may_goto_ext__open();
+	if (!ASSERT_OK_PTR(ext, "ext_open"))
+		return;
+	bpf_program__set_attach_target(ext->progs.replacement,
+				       bpf_program__fd(skel->progs.freplace_plain_target),
+				       "plain_global");
 	if (!ASSERT_OK(timed_may_goto_ext__load(ext), "ext_load") ||
 	    !ASSERT_OK(timed_may_goto_ext__attach(ext), "ext_attach"))
 		goto out;
-	ASSERT_EQ(run_tc(skel->progs.freplace_target), TRIES, "replaced");
+	/* Each call of the extension spins, is unwound and returns 2 into the prog, which goes on */
+	ASSERT_EQ(run_tc(skel->progs.freplace_plain_target), 10 + TRIES * 2, "replaced");
+	/* and each call had its time: a short loop came to its end before the call used it up */
+	ASSERT_EQ(ext->bss->calls, TRIES, "calls of the extension");
+	ASSERT_EQ(ext->bss->counted_to_1000, TRIES, "a slice per call");
 out:
 	timed_may_goto_ext__destroy(ext);
-	ASSERT_EQ(run_tc(skel->progs.freplace_target), 1, "not replaced");
+	ASSERT_EQ(run_tc(skel->progs.freplace_plain_target), 10, "not replaced");
 }
 
 /* What a prog leaves behind when its time is up doesn't matter for the next one on the cpu. */
@@ -94,14 +123,29 @@ static void test_tail_call_and_throw(struct timed_may_goto_user *skel)
 	if (!ASSERT_OK(bpf_map_update_elem(map_fd, &key, &fd, 0), "update"))
 		return;
 
-	ASSERT_EQ(run_tc(skel->progs.normal_prog), 1, "normal_prog");
-	ASSERT_EQ(run_tc(skel->progs.normal_prog), 1, "normal_prog");
-
-	ASSERT_EQ(run_tc(skel->progs.tail_call_in_subprog), 1, "tail_call_in_subprog");
-	ASSERT_EQ(skel->bss->tail_callee_spun, 1, "tail_callee_spun");
-
-	ASSERT_EQ(run_tc(skel->progs.tail_call_after_timeout), 0, "tail_call_after_timeout");
-	ASSERT_EQ(skel->bss->tail_callee_spun, 1, "tail_callee_spun");
+	/*
+	 * Each run has its time: the loop counts to 1000, then the prog is unwound. With the count
+	 * that the run before left behind the prog would be unwound in the short loop, which 2
+	 * does not tell: the prog stores what it counted.
+	 */
+	skel->bss->normal_cnt = -1;
+	ASSERT_EQ(run_tc(skel->progs.normal_prog), 2, "normal_prog");
+	ASSERT_EQ(skel->bss->normal_cnt, 1000, "normal_cnt");
+	skel->bss->normal_cnt = -1;
+	ASSERT_EQ(run_tc(skel->progs.normal_prog), 2, "normal_prog");
+	ASSERT_EQ(skel->bss->normal_cnt, 1000, "normal_cnt, second run");
+
+	/* the callee is unwound and returns 2 into the subprog of its caller, which goes on */
+	skel->bss->tail_callee_cnt = -1;
+	ASSERT_EQ(run_tc(skel->progs.tail_call_in_subprog), 12, "tail_call_in_subprog");
+	ASSERT_EQ(skel->bss->tail_callee_runs, 1, "tail_callee_runs");
+	ASSERT_EQ(skel->bss->tail_callee_cnt, 1000, "tail_callee_cnt");
+
+	/* the callee has its time when its caller has none left: it counts, then it is unwound */
+	skel->bss->tail_callee_cnt = -1;
+	ASSERT_EQ(run_tc(skel->progs.tail_call_after_timeout), 2, "tail_call_after_timeout");
+	ASSERT_EQ(skel->bss->tail_callee_runs, 2, "tail_callee_runs");
+	ASSERT_EQ(skel->bss->tail_callee_cnt, 1000, "tail_callee_cnt, caller out of time");
 
 	ASSERT_EQ(run_tc(skel->progs.throw_after_timeout), 7, "throw_after_timeout");
 	ASSERT_EQ(run_tc(skel->progs.throw_after_timeout), 7, "throw_after_timeout");
@@ -122,8 +166,13 @@ static void test_user_ringbuf(struct timed_may_goto_user *skel)
 			goto out;
 		user_ring_buffer__submit(rb, sample);
 	}
-	/* The helper takes a sample out of the buffer for each call: all calls have to run. */
-	ASSERT_EQ(run_syscall(skel->progs.drain), TRIES * 10 + 1, "drain");
+	/*
+	 * The helper takes a sample out of the buffer for each call. The callback is unwound in
+	 * each run, and its sample is gone like one of a callback that returns.
+	 */
+	for (i = 0; i < TRIES; i++)
+		ASSERT_EQ(run_syscall(skel->progs.drain), -ECANCELED, "drain");
+	ASSERT_EQ(run_syscall(skel->progs.drain), 100, "drain of no samples");
 out:
 	user_ring_buffer__free(rb);
 }
@@ -137,9 +186,13 @@ static void test_priv_stack(struct timed_may_goto_user *skel)
 	link = bpf_program__attach(skel->progs.priv_stack);
 	if (!ASSERT_OK_PTR(link, "attach"))
 		return;
+	skel->bss->priv_stack_spun = skel->bss->priv_stack_cb_spun = -1;
+	/* unwound in the first call: the prog does not get to what follows its loop */
+	ASSERT_OK(bpf_prog_test_run_opts(fd, &opts), "test_run");
 	ASSERT_OK(bpf_prog_test_run_opts(fd, &opts), "test_run");
-	ASSERT_EQ(skel->bss->priv_stack_spun, 1, "priv_stack_spun");
-	ASSERT_EQ(skel->bss->priv_stack_cb_spun, 0, "priv_stack_cb_spun");
+	ASSERT_EQ(skel->bss->priv_stack_runs, 2, "priv_stack_runs");
+	ASSERT_EQ(skel->bss->priv_stack_spun, -1, "priv_stack_spun");
+	ASSERT_EQ(skel->bss->priv_stack_cb_spun, -1, "priv_stack_cb_spun");
 	bpf_link__destroy(link);
 }
 
diff --git a/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c b/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c
index 5c2aa0aa5055..d842cf5c966d 100644
--- a/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c
+++ b/tools/testing/selftests/bpf/progs/may_goto_priv_stack.c
@@ -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);						\
 }
 
diff --git a/tools/testing/selftests/bpf/progs/stream.c b/tools/testing/selftests/bpf/progs/stream.c
index 949c1b2fa6c0..68c2c80d7edf 100644
--- a/tools/testing/selftests/bpf/progs/stream.c
+++ b/tools/testing/selftests/bpf/progs/stream.c
@@ -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"
diff --git a/tools/testing/selftests/bpf/progs/timed_may_goto.c b/tools/testing/selftests/bpf/progs/timed_may_goto.c
index c1c48af808a9..e01b7e727707 100644
--- a/tools/testing/selftests/bpf/progs/timed_may_goto.c
+++ b/tools/testing/selftests/bpf/progs/timed_may_goto.c
@@ -3,8 +3,14 @@
  * There is one time slice of may_goto for an invocation of a prog: one call from the kernel into
  * the main prog, with the subprogs and sync callbacks that it reaches.
  *
- * Most tests call a function that spins until may_goto stops it, four times, each in a different
- * way. Only the first call can spin. With a time slice for each call all four do.
+ * When it is up may_goto ends the invocation: the prog is unwound, and returns what an unwound
+ * prog of its type returns. That is 2, TC_ACT_SHOT, for tc and 0 for a socket filter or a
+ * tracing prog. Most tests call a function that spins until may_goto stops it, four times, each
+ * in a different way. The first call ends the prog. With a time slice for each call the prog would
+ * go on for a second, or for ever.
+ *
+ * Where a subprog cannot unwind may_goto jumps where the program says and the prog goes on, see
+ * time_is_up(). The tests of what follows then use it.
  */
 #include <vmlinux.h>
 #include <bpf/bpf_helpers.h>
@@ -44,36 +50,124 @@ static __noinline int counts_to_1000(void)
 	return cnt;
 }
 
+/* The prog is unwound in the first call. If it went on it would return 11, or 14. */
 SEC("tc")
 __description("timed may_goto: call")
-__success __retval(1)
+__success __retval(2)
 int call_subprog(void *ctx)
 {
-	int i, n = 0;
+	int i, n = 10;
 
 	for (i = 0; i < TRIES; i++)
 		n += spins();
 	return n;
 }
 
+/*
+ * A subprog that cannot unwind: the comparator of bpf_rbtree_add() for a node that takes a lock
+ * when it is freed, and what the comparator calls. There may_goto jumps where the program says.
+ */
+struct item {
+	struct bpf_list_node link;
+};
+
+struct stuck_node {
+	struct bpf_rb_node rb;
+	struct bpf_spin_lock lock;
+	struct bpf_list_head items __contains(item, link);
+};
+
+#define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))
+private(S) struct bpf_spin_lock stuck_lock;
+private(S) struct bpf_rb_root stuck_root __contains(stuck_node, rb);
+
+/* No code has an item: this puts it in BTF, for __contains() above */
+void __item_btf_root(struct item *i)
+{
+}
+
+long stuck_ret;
+
+/* Add two nodes, so that @less runs one time, and take them out again. Returns 0. */
+static __always_inline int run_stuck(bool (less)(struct bpf_rb_node *a,
+						 const struct bpf_rb_node *b))
+{
+	struct bpf_rb_node *rb;
+	struct stuck_node *n;
+	int i;
+
+	for (i = 0; i < 2; i++) {
+		n = bpf_obj_new(typeof(*n));
+		if (!n)
+			return 100;
+		bpf_spin_lock(&stuck_lock);
+		bpf_rbtree_add(&stuck_root, &n->rb, less);
+		bpf_spin_unlock(&stuck_lock);
+	}
+	for (i = 0; i < 2; i++) {
+		bpf_spin_lock(&stuck_lock);
+		rb = bpf_rbtree_first(&stuck_root);
+		rb = rb ? bpf_rbtree_remove(&stuck_root, rb) : NULL;
+		bpf_spin_unlock(&stuck_lock);
+		if (!rb)
+			return 101;
+		bpf_obj_drop(container_of(rb, struct stuck_node, rb));
+	}
+	return 0;
+}
+
+/* no helpers under the lock: the loop counts its trips, a million of them take no 250 ms */
+static __always_inline int spin_stuck(void)
+{
+	long n = zero;
+
+	while (can_loop)
+		n++;
+	return n > 1000 * 1000;
+}
+
+static bool less_uses_up_time(struct bpf_rb_node *a, const struct bpf_rb_node *b)
+{
+	stuck_ret = spin_stuck();
+	return false;
+}
+
+/*
+ * Use up the time of the invocation where the prog is not unwound for it. The prog goes on, until
+ * the next may_goto in a subprog that can unwind. Returns 0.
+ */
+static __always_inline int time_is_up(void)
+{
+	return run_stuck(less_uses_up_time) ?: !stuck_ret;
+}
+
+static bool less_counts_after_timeout(struct bpf_rb_node *a, const struct bpf_rb_node *b)
+{
+	spin_stuck();
+	stuck_ret = counts_to_1000();
+	return false;
+}
+
+/* Both loops are in a subprog that cannot unwind */
 SEC("tc")
 __description("timed may_goto: a call after the time is up makes no iteration")
-__success __retval(0)
+__success __retval(10)
 int short_loop_after_timeout(void *ctx)
 {
-	spins();
-	return counts_to_1000();
+	stuck_ret = -1;
+	return run_stuck(less_counts_after_timeout) ?: 10 + stuck_ret;
 }
 
+/* The loop of the main prog can unwind: it does, in the trip after the time was used up */
 SEC("tc")
-__description("timed may_goto: the loop of the main prog stops when the time is up in a subprog")
-__success __retval(1)
+__description("timed may_goto: the loop of the main prog ends the prog when the time is up in a subprog that cannot unwind")
+__success __retval(2)
 int main_loop_after_timeout(void *ctx)
 {
-	int n = 0;
+	int n = 10;
 
-	while (can_loop && n < 2 * TRIES)
-		n += spins();
+	while (can_loop && n < 10 + 2 * TRIES)
+		n += time_is_up() + 1;
 	return n;
 }
 
@@ -84,10 +178,10 @@ static __noinline int passes(int i)
 
 SEC("tc")
 __description("timed may_goto: call through a function without a loop")
-__success __retval(1)
+__success __retval(2)
 int call_through(void *ctx)
 {
-	int i, n = 0;
+	int i, n = 10;
 
 	for (i = 0; i < TRIES; i++)
 		n += passes(zero);
@@ -101,10 +195,10 @@ __noinline int global_spins(void)
 
 SEC("tc")
 __description("timed may_goto: call of a global function")
-__success __retval(1)
+__success __retval(2)
 int call_global(void *ctx)
 {
-	int i, n = 0;
+	int i, n = 10;
 
 	for (i = 0; i < TRIES; i++)
 		n += global_spins();
@@ -113,11 +207,11 @@ int call_global(void *ctx)
 
 SEC("tc")
 __description("timed may_goto: callx")
-__success __retval(1)
+__success __retval(2)
 __naked void callx_subprog(void)
 {
 	asm volatile (
-		"r6 = 0;"
+		"r6 = 10;"
 		"r7 = 0;"
 	"1:"
 		"r3 = %[spins] ll;"
@@ -139,12 +233,13 @@ static int loop_cb(__u64 i, int *spun)
 	return *spun > 2 * TRIES;
 }
 
+/* The callback is unwound, and the helper and the prog with it */
 SEC("tc")
 __description("timed may_goto: bpf_loop() inlined")
-__success __retval(1)
+__success __retval(2)
 int loop_inlined(void *ctx)
 {
-	int spun = 0;
+	int spun = 10;
 
 	bpf_loop(1 << 20, loop_cb, &spun, 0);
 	return spun;
@@ -152,10 +247,10 @@ int loop_inlined(void *ctx)
 
 SEC("tc")
 __description("timed may_goto: bpf_loop() not inlined")
-__success __retval(1)
+__success __retval(2)
 int loop_not_inlined(void *ctx)
 {
-	int spun = 0;
+	int spun = 10;
 
 	bpf_loop(1 << 20, loop_cb, &spun, zero);
 	return spun;
@@ -167,7 +262,10 @@ static int count_cb(__u64 i, int *calls)
 	return 0;
 }
 
-/* The time is up: the helper calls the callback one more time. It returns 1 in its first insns. */
+/*
+ * The time is up: the helper calls the callback one more time. It returns 1 in its first insns.
+ * The callback has no may_goto and the prog has none after the time is up: nothing is unwound.
+ */
 #define LOOP_ENDS(name, flags)							\
 SEC("tc")									\
 __description("timed may_goto: bpf_loop() " #name " ends when the time is up")	\
@@ -176,7 +274,8 @@ int loop_ends_##name(void *ctx)							\
 {										\
 	int calls = 0;								\
 										\
-	spins();								\
+	if (time_is_up())							\
+		return 100;							\
 	return bpf_loop(1000, count_cb, &calls, flags) * 10 + calls;		\
 }
 
@@ -202,15 +301,16 @@ static int outer_cb(__u64 i, struct nested *n)
 	return bpf_ktime_get_ns() - n->t0 > 1000 * 1000 * 1000;
 }
 
+/* The inner callback is unwound through both helpers */
 SEC("tc")
 __description("timed may_goto: bpf_loop() in bpf_loop() ends when the time is up")
-__success __retval(1)
+__success __retval(2)
 int loop_in_loop(void *ctx)
 {
 	struct nested n = { .t0 = bpf_ktime_get_ns() };
 
 	bpf_loop(1 << 23, outer_cb, &n, 0);
-	return n.spun && bpf_ktime_get_ns() - n.t0 < 500 * 1000 * 1000;
+	return 10 + (n.spun && bpf_ktime_get_ns() - n.t0 < 500 * 1000 * 1000);
 }
 
 static __noinline int called_cb(__u64 i, int *calls)
@@ -227,7 +327,8 @@ int loop_and_call(void *ctx)
 {
 	int calls = 0;
 
-	spins();
+	if (time_is_up())
+		return 101;
 	if (called_cb(zero, &calls))
 		return 100;
 	return bpf_loop(TRIES, called_cb, &calls, 0) * 10 + calls;
@@ -244,38 +345,39 @@ static int short_cb(__u64 i, __u64 *t0)
 
 /*
  * The main prog has no may_goto. Each call of the callback ends before it reads the clock. The
- * iterations of all calls add up.
+ * iterations of all calls add up: a call finds that the time is up, and the next one is unwound.
+ * With a time slice for each call the callback gives up after a second, and the prog returns 10.
  */
 SEC("tc")
 __description("timed may_goto: bpf_loop() the callback makes 60000 iterations")
-__success __retval(1)
+__success __retval(2)
 int loop_short_cb(void *ctx)
 {
 	__u64 t0 = bpf_ktime_get_ns();
 
 	bpf_loop(1 << 20, short_cb, &t0, 0);
-	return bpf_ktime_get_ns() - t0 < 1000 * 1000 * 1000;
+	return 10 + (bpf_ktime_get_ns() - t0 < 1000 * 1000 * 1000);
 }
 
-/* spins() uses up the time. The loop that calls it ends at its next may_goto. */
-static __noinline int loops_around_spins(void)
+/* The comparator uses up the time. The loop that got there ends the prog at its next may_goto. */
+static __noinline int loops_around_time_is_up(void)
 {
 	int n = zero;
 
 	while (can_loop && n < 20000) {
-		if (n < 2 * TRIES)
-			spins();
+		if (n < 2 * TRIES && time_is_up())
+			return 100;
 		n++;
 	}
-	return n;
+	return 10 + n;
 }
 
 SEC("tc")
-__description("timed may_goto: a loop that is on the stack ends when the time is up")
-__success __retval(1)
+__description("timed may_goto: a loop that is on the stack ends the prog when the time is up")
+__success __retval(2)
 int rest_of_batch(void *ctx)
 {
-	return loops_around_spins();
+	return loops_around_time_is_up();
 }
 
 static __noinline int one_iteration(void)
@@ -308,7 +410,8 @@ static int call_many(__u64 i, __u64 *t0)
 
 /*
  * The iterations of all calls count: the prog reads the clock in each 65535th call. The call that
- * finds out that the time is up makes its iteration.
+ * finds out that the time is up makes its iteration. No may_goto runs after it: the helpers call
+ * their callbacks one more time, which return 1 in their first insns, and the prog goes on.
  */
 SEC("tc")
 __description("timed may_goto: 65535 calls that make one iteration read the clock")
@@ -334,7 +437,7 @@ struct {						\
 MAP(array, BPF_MAP_TYPE_ARRAY, 0);
 MAP(hash, BPF_MAP_TYPE_HASH, 0);
 
-/* The first call uses up the time. The second call ends the loop of the helper. */
+/* The first call uses up the time, and is unwound through the helper */
 static int elem_cb(void *map, int *key, int *val, int *spun)
 {
 	*spun += spin();
@@ -344,10 +447,10 @@ static int elem_cb(void *map, int *key, int *val, int *spun)
 #define FOR_EACH(name)								\
 SEC("tc")									\
 __description("timed may_goto: bpf_for_each_map_elem() " #name)			\
-__success __retval(21)								\
+__success __retval(2)								\
 int for_each_##name(void *ctx)							\
 {										\
-	int i, key, spun = 0;							\
+	int i, key, spun = 100;							\
 										\
 	for (i = 0; i < TRIES; i++) {						\
 		key = i;							\
@@ -365,14 +468,15 @@ static long vma_cb(struct task_struct *task, struct vm_area_struct *vma, int *sp
 	return 0;
 }
 
+/* An unwound tracing prog returns 0 */
 SEC("raw_tp")
 __description("timed may_goto: bpf_find_vma()")
-__success __retval(1)
+__success __retval(0)
 int find_vma(void *ctx)
 {
 	struct task_struct *task = bpf_get_current_task_btf();
 	__u64 addr = task->mm->arg_start;
-	int i, spun = 0;
+	int i, spun = 10;
 
 	for (i = 0; i < TRIES; i++)
 		if (bpf_find_vma(task, addr, vma_cb, &spun, 0))
@@ -385,7 +489,6 @@ struct tree_node {
 	int key;
 };
 
-#define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))
 private(A) struct bpf_spin_lock lock;
 private(A) struct bpf_rb_root root __contains(tree_node, rb);
 
@@ -404,9 +507,13 @@ static bool less(struct bpf_rb_node *a, const struct bpf_rb_node *b)
 	       container_of(b, struct tree_node, rb)->key;
 }
 
+/*
+ * The comparator is unwound: the kfunc drops the node, and the pad of the prog releases the lock.
+ * The node of the first trip stays in the tree.
+ */
 SEC("tc")
 __description("timed may_goto: bpf_rbtree_add()")
-__success __retval(1)
+__success __retval(2)
 int rbtree_add(void *ctx)
 {
 	struct bpf_rb_node *rb;
@@ -435,7 +542,7 @@ int rbtree_add(void *ctx)
 	}
 	if (less_calls < TRIES - 1)
 		return 102;
-	return less_spun;
+	return 10 + less_spun;
 }
 
 /*
@@ -619,7 +726,6 @@ static long live_fall_through(void)
 
 #define CALL_AND_ADD(f)	"call " #f ";" "r6 += r0;"
 #define CALL_ALL_LIVE						\
-		"r6 = 0;"					\
 		CALL_AND_ADD(live_r0_r0)			\
 		CALL_AND_ADD(live_r0_r1)			\
 		CALL_AND_ADD(live_r0_r2)			\
@@ -645,25 +751,15 @@ __success __retval(840180)
 __naked void dead_reg(void)
 {
 	asm volatile (
-		CALL_ALL_LIVE
-		::: __clobber_all);
-}
-
-/* No iteration: 165, then 6, 6 (the may_goto jumps) and 4 (R2 isn't stored). */
-SEC("tc")
-__description("timed may_goto: may_goto takes a register that is dead, the time is up")
-__success __retval(181)
-__naked void dead_reg_time_is_up(void)
-{
-	asm volatile (
-		"call spins_on_may_goto;"
+		"r6 = 0;"
 		CALL_ALL_LIVE
 		::: __clobber_all);
 }
 
 /*
- * The subprog uses up the time of the prog and returns. With a time slice for each call the caller
- * calls it 65535 times before it reads the clock.
+ * The subprog uses up the time of the prog. Where it can unwind that ends the prog. Where it
+ * cannot it returns: with a time slice for each call its caller would call it 65535 times before
+ * it reads the clock.
  */
 __naked __noinline __used
 static unsigned long spins_on_may_goto(void)
@@ -678,11 +774,37 @@ static unsigned long spins_on_may_goto(void)
 		::: __clobber_all);
 }
 
-/* The first may_goto of the function finds that the time is up */
+/* The time is up: each may_goto of these functions jumps in its first trip */
+__naked __noinline __used
+static long all_live_time_is_up(void)
+{
+	asm volatile (
+		"call spins_on_may_goto;"
+		"r6 = r0;"
+		CALL_ALL_LIVE
+		::: __clobber_all);
+}
+
+static bool less_all_live(struct bpf_rb_node *a, const struct bpf_rb_node *b)
+{
+	stuck_ret = all_live_time_is_up();
+	return false;
+}
+
+/*
+ * In a subprog that cannot unwind, where may_goto jumps. No iteration: 165, then 6, 6 (the
+ * may_goto jumps) and 4 (R2 isn't stored).
+ */
 SEC("tc")
-__description("timed may_goto: registers across may_goto when the time is up")
-__success __retval(46)
-__naked void regs_when_time_is_up(void)
+__description("timed may_goto: may_goto takes a register that is dead, the time is up")
+__success __retval(181)
+int dead_reg_time_is_up(void *ctx)
+{
+	return run_stuck(less_all_live) ?: stuck_ret;
+}
+
+__naked __noinline __used
+static long regs_time_is_up(void)
 {
 	asm volatile (
 		"call spins_on_may_goto;"
@@ -696,15 +818,33 @@ __naked void regs_when_time_is_up(void)
 		::: __clobber_all);
 }
 
-/* The first insn of the main prog is the target of a jump. It must not set the count again. */
+static bool less_regs(struct bpf_rb_node *a, const struct bpf_rb_node *b)
+{
+	stuck_ret = regs_time_is_up();
+	return false;
+}
+
+/* The same: the first may_goto of the function finds that the time is up */
+SEC("tc")
+__description("timed may_goto: registers across may_goto when the time is up")
+__success __retval(46)
+int regs_when_time_is_up(void *ctx)
+{
+	return run_stuck(less_regs) ?: stuck_ret;
+}
+
+/*
+ * The first insn of the main prog is the target of a jump. It must not set the count again: the
+ * subprog makes 60000 iterations in a call and would never read the clock.
+ */
 SEC("socket")
 __description("timed may_goto: 9 insns")
-__success __retval(1)
+__success __retval(0)
 __naked void loop_calls_subprog_with_may_goto(void)
 {
 	asm volatile (
 	"1:"
-		"call spins_on_may_goto;"
+		"call loops_60000;"
 		"may_goto 2f;"
 		"goto 1b;"
 	"2:"
@@ -716,7 +856,7 @@ __naked void loop_calls_subprog_with_may_goto(void)
 /*
  * These subprogs make 60000 iterations in each call. With a read of the clock after 65535
  * iterations of a call none of them reads it, and their caller does it after
- * 65535 * 60000 * 60000 iterations.
+ * 65535 * 60000 * 60000 iterations. The prog ends unwound, a socket filter returns 0 then.
  */
 __naked __noinline __used
 static unsigned long loops_60000(void)
@@ -751,7 +891,7 @@ static unsigned long calls_60000_times(void)
 
 SEC("socket")
 __description("timed may_goto: three levels of loops that end before they read the clock")
-__success __retval(1)
+__success __retval(0)
 __naked void three_levels_of_short_loops(void)
 {
 	asm volatile (
@@ -781,41 +921,57 @@ static unsigned long loops_65534(void)
 		::: __clobber_all);
 }
 
+/*
+ * The iterations of the callee count for the prog: it reads the clock in each 65535th of them, and
+ * is unwound when the time is up. With a count for each frame only the calls would count, the
+ * time would be up after 2^32 iterations, and the prog gives up after a second: 3.
+ * It gives up at the third round that finds the second over. Each round has one read of the clock
+ * by may_goto, so the round after a stall of the guest, however long, is one that unwinds the prog.
+ */
 SEC("socket")
 __description("timed may_goto: the subprog makes 65534 iterations")
-__success __retval(1)
+__success __retval(0)
 __naked void loop_calls_subprog_with_65534_iterations(void)
 {
 	asm volatile (
 		"call %[bpf_ktime_get_ns];"
 		"r6 = r0;"
+		"r7 = 0;"
 	"1:"
 		"call loops_65534;"
+		"call %[bpf_ktime_get_ns];"
+		"r0 -= r6;"
+		"if r0 <= 1000000000 goto +2;"
+		"r7 += 1;"
+		"if r7 > 2 goto 3f;"
 		"may_goto 2f;"
 		"goto 1b;"
 	"2:"
-		"call %[bpf_ktime_get_ns];"
-		"r0 -= r6;"
-		"r1 = r0;"
 		"r0 = 1;"
-		"if r1 < 1000000000 goto +1;"
-		"r0 = 0;"
+		"exit;"
+	"3:"
+		"r0 = 3;"
 		"exit;"
 		:
 		: __imm(bpf_ktime_get_ns)
 		: __clobber_all);
 }
 
-/* The subprog returns 16 bytes in R0 and R2. may_goto must not change them. */
+/*
+ * The subprog returns 16 bytes in R0 and R2. may_goto must not change them: the loop reads the
+ * clock one time and ends.
+ */
 __naked __noinline __used
 static unsigned __int128 returns_pair_after_may_goto(void)
 {
 	asm volatile (
 		"r0 = 1;"
 		"r2 = 2;"
+		"r1 = 70000;"
 	"1:"
 		"may_goto 2f;"
-		"goto 1b;"
+		"r1 += -1;"
+		"if r1 != 0 goto 1b;"
 	"2:"
 		"exit;"
 		::: __clobber_all);
@@ -863,26 +1019,32 @@ __naked void dead_may_goto(void)
 		::: __clobber_all);
 }
 
-static __noinline int throws_after_spin(void)
+static __noinline int throws_after_time_is_up(void)
 {
-	spin();
+	if (time_is_up())
+		return 100;
 	bpf_throw(0);
 	return 0;
 }
 
 __noinline int exception_cb_loops(u64 cookie)
 {
-	return counts_to_1000();
+	return 20 + counts_to_1000();
 }
 
-/* The exception callback belongs to the invocation that throws. */
+/*
+ * The exception callback belongs to the invocation that throws. The time is up before the prog
+ * throws, in a subprog that cannot unwind, so the prog does get to bpf_throw(). The loop of the
+ * callback has no time of its own: it ends the prog in its first trip. With a new slice the
+ * callback would count to 1000 and return 1020.
+ */
 SEC("tc")
 __description("timed may_goto: bpf_throw() the exception callback has a loop")
 __exception_cb(exception_cb_loops)
-__success __retval(0)
+__success __retval(2)
 int throw_after_timeout(void *ctx)
 {
-	return throws_after_spin();
+	return throws_after_time_is_up();
 }
 
 #else
diff --git a/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c b/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c
index 969ca58b6eed..d6cd5f370fd8 100644
--- a/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c
+++ b/tools/testing/selftests/bpf/progs/timed_may_goto_ext.c
@@ -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;
 }
diff --git a/tools/testing/selftests/bpf/progs/timed_may_goto_user.c b/tools/testing/selftests/bpf/progs/timed_may_goto_user.c
index 8b85815d45d2..aed7a2354c41 100644
--- a/tools/testing/selftests/bpf/progs/timed_may_goto_user.c
+++ b/tools/testing/selftests/bpf/progs/timed_may_goto_user.c
@@ -1,5 +1,8 @@
 // SPDX-License-Identifier: GPL-2.0
-/* The tests of timed_may_goto.c that need help from user space. */
+/*
+ * The tests of timed_may_goto.c that need help from user space. A prog whose time is up is
+ * unwound: tc returns 2, TC_ACT_SHOT, then, and a syscall prog -ECANCELED.
+ */
 #include <vmlinux.h>
 #include <bpf/bpf_helpers.h>
 #include <bpf/bpf_tracing.h>
@@ -37,19 +40,88 @@ static __noinline int counts_to_1000(void)
 	return cnt;
 }
 
-/* Nothing special: the loops go on, then the time is up one time. */
+/* What a short loop counts before the time is up: user space sees that it got to its end */
+int normal_cnt, tail_callee_cnt;
+
+/* Nothing special: the loops go on, then the time is up and the prog is unwound. */
 SEC("tc")
 int normal_prog(void *ctx)
 {
-	int i, n = 0;
+	int i, n = 10;
 
-	if (counts_to_1000() != 1000)
+	normal_cnt = counts_to_1000();
+	if (normal_cnt != 1000)
 		return 100;
 	for (i = 0; i < TRIES; i++)
 		n += spins();
 	return n;
 }
 
+/*
+ * A subprog that cannot unwind: the comparator of bpf_rbtree_add() for a node that takes a lock
+ * when it is freed. There may_goto jumps where the program says when the time is up, and the prog
+ * goes on, see timed_may_goto.c.
+ */
+struct item {
+	struct bpf_list_node link;
+};
+
+struct stuck_node {
+	struct bpf_rb_node rb;
+	struct bpf_spin_lock lock;
+	struct bpf_list_head items __contains(item, link);
+};
+
+#define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))
+private(S) struct bpf_spin_lock stuck_lock;
+private(S) struct bpf_rb_root stuck_root __contains(stuck_node, rb);
+
+/* No code has an item: this puts it in BTF, for __contains() above */
+void __item_btf_root(struct item *i)
+{
+}
+
+long stuck_spun;
+
+static bool less_uses_up_time(struct bpf_rb_node *a, const struct bpf_rb_node *b)
+{
+	long n = zero;
+
+	/* no helpers under the lock */
+	while (can_loop)
+		n++;
+	stuck_spun = n > 1000 * 1000;
+	return false;
+}
+
+/* Use up the time of the invocation, the prog goes on. Returns 0. */
+static __always_inline int time_is_up(void)
+{
+	struct bpf_rb_node *rb;
+	struct stuck_node *n;
+	int i;
+
+	stuck_spun = 0;
+	for (i = 0; i < 2; i++) {
+		n = bpf_obj_new(typeof(*n));
+		if (!n)
+			return 100;
+		bpf_spin_lock(&stuck_lock);
+		bpf_rbtree_add(&stuck_root, &n->rb, less_uses_up_time);
+		bpf_spin_unlock(&stuck_lock);
+	}
+	for (i = 0; i < 2; i++) {
+		bpf_spin_lock(&stuck_lock);
+		rb = bpf_rbtree_first(&stuck_root);
+		rb = rb ? bpf_rbtree_remove(&stuck_root, rb) : NULL;
+		bpf_spin_unlock(&stuck_lock);
+		if (!rb)
+			return 101;
+		bpf_obj_drop(container_of(rb, struct stuck_node, rb));
+	}
+	return !stuck_spun;
+}
+
 /*
  * Async callbacks
  */
@@ -100,8 +172,9 @@ static int rcu_trace_cb(struct bpf_map *map, void *key, void *val)
 }
 
 /*
- * The time of this prog is up when it starts the callbacks. User space keeps the task on the cpu,
- * so the callbacks find what it has left. Each call of a callback is an invocation of its own.
+ * The time of this prog is up when it starts the callbacks: a comparator has used it. User space
+ * keeps the task on the cpu, so the callbacks find what it has left. Each call of a callback is an
+ * invocation of its own.
  */
 SEC("syscall")
 int async_after_timeout(void *ctx)
@@ -119,11 +192,8 @@ int async_after_timeout(void *ctx)
 		return 101;
 	if (bpf_wq_init(&e->wq, &async, 0) || bpf_wq_set_callback(&e->wq, wq_cb, 0))
 		return 102;
-	if (!spins())
+	if (time_is_up())
 		return 103;
-	/* control: the time is up */
-	if (counts_to_1000())
-		return 109;
 	if (bpf_timer_start(&e->timer, 0, BPF_F_TIMER_CPU_PIN))
 		return 104;
 	if (bpf_wq_start(&e->wq, 0))
@@ -134,7 +204,8 @@ int async_after_timeout(void *ctx)
 		return 107;
 	if (bpf_call_rcu_tasks_trace(&e1->rcu, &async, rcu_trace_cb))
 		return 108;
-	return 0;
+	/* control: the time is up, the prog is unwound here and returns -ECANCELED */
+	return 109 + counts_to_1000();
 }
 
 int ticks;
@@ -150,30 +221,30 @@ static int tick_cb(void *map, int *key, struct elem *e)
 
 /*
  * A callback of the prog interrupts it, on the same cpu, each 20 ms. It has its own time. That
- * doesn't give more time to the prog. Return how long the loop went on, in ms.
+ * doesn't give more time to the prog: it is unwound when its own time is up. User space sees how
+ * long that took.
  */
 SEC("syscall")
 int spin_under_timer(void *ctx)
 {
 	struct elem *e;
 	int key = 1;
-	__u64 t0;
 
 	e = bpf_map_lookup_elem(&async, &key);
 	if (!e)
-		return 0;
+		return 100;
 	if (bpf_timer_init(&e->timer, &async, CLOCK_MONOTONIC) ||
 	    bpf_timer_set_callback(&e->timer, tick_cb) ||
 	    bpf_timer_start(&e->timer, 20 * 1000 * 1000, BPF_F_TIMER_CPU_PIN))
-		return 0;
-	t0 = bpf_ktime_get_ns();
+		return 101;
 	while (can_loop)
 		;
-	return (bpf_ktime_get_ns() - t0) / 1000000;
+	return 102;
 }
 
 /*
- * Extension prog
+ * Extension prog. A function that can unwind cannot be replaced: an extension ends in its main
+ * prog. With a loop that may_goto stops that is replaced_global(). plain_global() cannot unwind.
  */
 __noinline int replaced_global(int i)
 {
@@ -183,13 +254,32 @@ __noinline int replaced_global(int i)
 SEC("tc")
 int freplace_target(void *ctx)
 {
-	int i, n = 0;
+	int i, n = 10;
 
 	for (i = 0; i < TRIES; i++)
 		n += replaced_global(zero);
 	return n;
 }
 
+int plain_global_calls;
+
+/* It counts its calls: the compiler must not make one call of the calls in a loop */
+__noinline int plain_global(int i)
+{
+	plain_global_calls++;
+	return i + zero;
+}
+
+SEC("tc")
+int freplace_plain_target(void *ctx)
+{
+	int i, n = 10;
+
+	for (i = 0; i < TRIES; i++)
+		n += plain_global(zero);
+	return n;
+}
+
 /*
  * Tail calls
  */
@@ -200,17 +290,21 @@ struct {
 	__uint(value_size, sizeof(int));
 } jmp_table SEC(".maps");
 
-int tail_callee_spun;
+int tail_callee_runs;
 
+/* It has its own time: the prog that makes the tail call may have none left */
 SEC("tc")
 int tail_callee(struct __sk_buff *skb)
 {
-	int i;
+	int i, n = 10;
 
-	tail_callee_spun = 0;
+	tail_callee_runs++;
+	tail_callee_cnt = counts_to_1000();
+	if (tail_callee_cnt != 1000)
+		return 100;
 	for (i = 0; i < TRIES; i++)
-		tail_callee_spun += spins();
-	return 0;
+		n += spins();
+	return n;
 }
 
 static __noinline int tail_calls(struct __sk_buff *skb)
@@ -219,31 +313,32 @@ static __noinline int tail_calls(struct __sk_buff *skb)
 	return zero + 100;
 }
 
-/* The target of the tail call is another prog. It returns to this function. */
+/*
+ * The target of the tail call is another prog. It is unwound when its time is up, and that ends
+ * at its own exit: it returns 2 to this function, which goes on with the time that it has.
+ */
 SEC("tc")
 int tail_call_in_subprog(struct __sk_buff *skb)
 {
-	int i, n;
+	int n;
 
 	n = tail_calls(skb);
 	if (counts_to_1000() != 1000)
 		return 101;
-	for (i = 0; i < TRIES; i++)
-		n += spins();
-	return n;
+	return 10 + n;
 }
 
 SEC("tc")
 int tail_call_after_timeout(struct __sk_buff *skb)
 {
-	spins();
+	if (time_is_up())
+		return 101;
 	bpf_tail_call(skb, &jmp_table, 0);
 	return 100;
 }
 
 static __noinline int throws(void)
 {
-	spin();
 	bpf_throw(7);
 	return 0;
 }
@@ -251,6 +346,8 @@ static __noinline int throws(void)
 SEC("tc")
 int throw_after_timeout(void *ctx)
 {
+	if (time_is_up())
+		return 101;
 	return throws();
 }
 
@@ -268,18 +365,22 @@ static long drain_cb(struct bpf_dynptr *dynptr, int *spun)
 	return 0;
 }
 
+/*
+ * The callback is unwound, and the helper and the prog with it: -ECANCELED. The helper has taken
+ * the sample of that call out of the buffer. With no sample left the prog returns 100.
+ */
 SEC("syscall")
 int drain(void *ctx)
 {
 	int spun = 0;
 
-	return bpf_user_ringbuf_drain(&user_ringbuf, drain_cb, &spun, 0) * 10 + spun;
+	return 100 + bpf_user_ringbuf_drain(&user_ringbuf, drain_cb, &spun, 0) * 10 + spun;
 }
 
 /*
  * A tracing prog with large frames: they are in a private stack.
  */
-int priv_stack_spun, priv_stack_cb_spun;
+int priv_stack_runs, priv_stack_spun, priv_stack_cb_spun;
 
 static __noinline int spins_with_stack(void)
 {
@@ -302,6 +403,8 @@ int BPF_PROG(priv_stack)
 	volatile char buf[128] = {};
 	int i, n = buf[zero & 127], spun = 0;
 
+	/* the first call is unwound in each run: the frames in the private stack are left */
+	priv_stack_runs++;
 	for (i = 0; i < TRIES; i++)
 		n += spins_with_stack();
 	bpf_loop(TRIES, priv_stack_cb, &spun, zero);
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
index ca7bdbd7e1ce..5d22dfc6fdcb 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
@@ -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;"
diff --git a/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c b/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
index 2120f4e71fb8..8a69d6b7874f 100644
--- a/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
+++ b/tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c
@@ -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)
 {
diff --git a/tools/testing/selftests/bpf/progs/verifier_equations.c b/tools/testing/selftests/bpf/progs/verifier_equations.c
index 66786aae3664..21a30e6c9b3f 100644
--- a/tools/testing/selftests/bpf/progs/verifier_equations.c
+++ b/tools/testing/selftests/bpf/progs/verifier_equations.c
@@ -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;"
diff --git a/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c b/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c
index 1dfeb13b4382..c4a0c3f303b4 100644
--- a/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c
+++ b/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c
@@ -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
diff --git a/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c b/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c
index f61a07424834..4995b3116691 100644
--- a/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c
+++ b/tools/testing/selftests/bpf/progs/verifier_linked_scalars.c
@@ -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;"						\
diff --git a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
index 8d231fb2a317..f8861ad046ce 100644
--- a/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
+++ b/tools/testing/selftests/bpf/progs/verifier_may_goto_1.c
@@ -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);
 }
 
diff --git a/tools/testing/selftests/bpf/progs/verifier_passes.c b/tools/testing/selftests/bpf/progs/verifier_passes.c
index d17254990744..48c59e7935e2 100644
--- a/tools/testing/selftests/bpf/progs/verifier_passes.c
+++ b/tools/testing/selftests/bpf/progs/verifier_passes.c
@@ -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];"
diff --git a/tools/testing/selftests/bpf/progs/verifier_patch_list.c b/tools/testing/selftests/bpf/progs/verifier_patch_list.c
index 80d08d93b625..5516100dd2b0 100644
--- a/tools/testing/selftests/bpf/progs/verifier_patch_list.c
+++ b/tools/testing/selftests/bpf/progs/verifier_patch_list.c
@@ -85,7 +85,10 @@ __naked void patch_list_backward(void)
 	: __clobber_all);
 }
 
-/* The jump of may_goto leaves its own patch and crosses another one. */
+/*
+ * The jump of may_goto leaves its own patch and crosses another one, on the way to the landing pad
+ * that follows the prog.
+ */
 SEC("raw_tp")
 __description("patch list: may_goto between patched insns")
 __arch_x86_64
@@ -104,13 +107,15 @@ __xlated("11: r0 /= r1")
 __xlated("12: r2 = ")
 __xlated("14: r2 = &(void __percpu *)(r2)")
 __xlated("15: r13 = *(u64 *)(r2 +0)")
-__xlated("16: if r13 == 0x0 goto pc+9")
+__xlated("16: if r13 == 0x0 goto pc+10")
 __xlated("...")
 __xlated("22: if r1 != 0x0 goto pc+2")
 __xlated("23: w0 ^= w0")
 __xlated("24: goto pc+1")
 __xlated("25: r0 /= r1")
 __xlated("26: exit")
+__xlated("27: r0 = 0")
+__xlated("28: exit")
 __naked void patch_list_may_goto(void)
 {
 	asm volatile (
@@ -311,42 +316,38 @@ int patch_list_indirect(void)
 #endif
 
 /*
- * may_goto jumps back by 8195 insns, by 32768 once each of the 8191
- * divisions is guarded by a patch of 4 insns. That still fits the 16 bits of
- * may_goto, but not the jump it expands to, which has to become gotol. Once
- * the budget runs out, may_goto jumps back with r6 set and the program exits.
+ * When the time is up may_goto goes to the landing pad, which follows the prog: over 8191
+ * divisions, 32764 insns once each of them is guarded by a patch of 4 insns. That does not fit
+ * the 16 bits of the jump that may_goto expands to, which has to become gotol.
  */
 SEC("raw_tp")
-__description("patch list: backward may_goto expanded to gotol")
+__description("patch list: far may_goto expanded to gotol")
 __arch_x86_64
 __arch_arm64
 __success
-__xlated("12: if r6 != 0x0 goto pc-3")
+__xlated("12: r13 = *(u64 *)(r2 +0)")
+__xlated("13: if r13 == 0x0 goto pc+1")
+__xlated("14: goto pc+1")
+__xlated("15: gotol pc+32771")
 __xlated("...")
-__xlated("32783: if r13 == 0x0 goto pc+1")
-__xlated("32784: goto pc+1")
-__xlated("32785: gotol pc-32774")
+__xlated("32786: exit")
+__xlated("32787: r0 = 0")
+__xlated("32788: exit")
 __naked void patch_list_may_goto_gotol(void)
 {
 	asm volatile ("					\
 	call %[bpf_get_prandom_u32];			\
 	r1 = r0;					\
 	r6 = 0;						\
-	goto 0f;					\
-1:	r0 = 0;						\
-	exit;						\
-0:	if r6 != 0 goto 1b;				\
+	.8byte %[may_goto];				\
 	.rept 8191;					\
 	r0 /= r1;					\
 	.endr;						\
-	r2 = 0;						\
-	r6 = 1;						\
-	.8byte %[may_goto];				\
 	r0 = 0;						\
 	exit;						\
 "	:
 	: __imm(bpf_get_prandom_u32),
-	  __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, -8195 /* offset */, 0))
+	  __imm_insn(may_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 8191 /* offset */, 0))
 	: __clobber_all);
 }
 
@@ -388,17 +389,60 @@ static unsigned long patch_list_loop_at_start(void)
 	: __clobber_all);
 }
 
+#define INSERT_IN_FRONT					\
+	asm volatile (					\
+	"r1 = 3;"					\
+	"r2 = %[patch_list_loop_at_start] ll;"		\
+	"r3 = 0;"					\
+	"r4 = 0;"					\
+	"call %[bpf_loop];"				\
+	"exit;"						\
+	:						\
+	: __imm_addr(patch_list_loop_at_start),		\
+	  __imm(bpf_loop)				\
+	: __clobber_all)
+
 /*
  * The check of the may_goto count goes in front of the callback of bpf_loop().
  * The call of the inlined bpf_loop() lands on the check, the jump to the first
  * insn of the callback behind it.
- * This is the code for the JITs that support the timed may_goto.
+ * This is the code for the JITs that support the timed may_goto and unwind programs: the callback
+ * can unwind at its may_goto, so the inlined bpf_loop() has a landing pad, and the callback has
+ * one after its last insn.
  */
 SEC("raw_tp")
 __description("patch list: call of and jump to an insn with insns inserted in front")
 __arch_x86_64
-__arch_s390x
 __arch_arm64
+__success
+__xlated("27: call pc+10")
+__xlated("28: unwind_goto pc-15")
+__xlated("...")
+__xlated("37: exit")
+__xlated("38: r0 = ")
+__xlated("40: r0 = &(void __percpu *)(r0)")
+__xlated("41: r0 = *(u64 *)(r0 +0)")
+__xlated("42: if r0 != 0x0 goto pc+2")
+__xlated("43: r0 = 1")
+__xlated("44: exit")
+__xlated("45: r1 += -1")
+__xlated("...")
+__xlated("50: if r13 == 0x0 goto pc+8")
+__xlated("...")
+__xlated("56: if r1 != 0x0 goto pc-12")
+__xlated("57: r0 = 0")
+__xlated("58: exit")
+__xlated("59: r0 = 0")
+__xlated("60: unwind_exit")
+__naked void patch_list_insert_in_front(void)
+{
+	INSERT_IN_FRONT;
+}
+
+/* The JITs that do not unwind programs: the callback cannot unwind, and its may_goto jumps */
+SEC("raw_tp")
+__description("patch list: call of and jump to an insn with insns inserted in front, no pads")
+__arch_s390x
 __arch_riscv64
 __arch_loongarch
 __success
@@ -416,19 +460,9 @@ __xlated("...")
 __xlated("49: if r1 != 0x0 goto pc-12")
 __xlated("50: r0 = 0")
 __xlated("51: exit")
-__naked void patch_list_insert_in_front(void)
+__naked void patch_list_insert_in_front_no_pads(void)
 {
-	asm volatile (
-	"r1 = 3;"
-	"r2 = %[patch_list_loop_at_start] ll;"
-	"r3 = 0;"
-	"r4 = 0;"
-	"call %[bpf_loop];"
-	"exit;"
-	:
-	: __imm_addr(patch_list_loop_at_start),
-	  __imm(bpf_loop)
-	: __clobber_all);
+	INSERT_IN_FRONT;
 }
 
 __naked __noinline __used
diff --git a/tools/testing/selftests/bpf/progs/verifier_stack_arg.c b/tools/testing/selftests/bpf/progs/verifier_stack_arg.c
index 16afc69af947..91357043fdf4 100644
--- a/tools/testing/selftests/bpf/progs/verifier_stack_arg.c
+++ b/tools/testing/selftests/bpf/progs/verifier_stack_arg.c
@@ -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 (
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 50/73] bpf: Reject a program that has no landing pad for a fault in arena
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (48 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 49/73] bpf: Cancel the program when the time of its own may_goto is up Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:26   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 51/73] bpf: Log why a call is a site and which functions cannot be cancelled Kumar Kartikeya Dwivedi
                   ` (22 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index e20df219d332..12b93e15f7a4 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 36086dc5ee98..a6a328d8548a 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -381,8 +381,9 @@ static void charge_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 	plan->bytes = bytes;
 }
 
-/* @callee came back to the call of @plan: it takes its place in the list */
-static int plan_add_callee(struct bpf_verifier_env *env, struct bpf_pad_plan *plan, u32 callee)
+/* Add @callee, which came back to the call at @call_idx, to the sorted list of @plan */
+static int plan_add_callee(struct bpf_verifier_env *env, struct bpf_pad_plan *plan, int call_idx,
+			   u32 callee)
 {
 	u32 n = plan->nr_callees, mid, lo = 0, hi = n, *list;
 
@@ -407,6 +408,9 @@ static int plan_add_callee(struct bpf_verifier_env *env, struct bpf_pad_plan *pl
 	memmove(&plan->callee[lo + 1], &plan->callee[lo], (n - lo) * sizeof(*list));
 	plan->callee[lo] = callee;
 	plan->nr_callees++;
+	/* what bpf_pad_skip_faults() found below the function of the call is no longer all */
+	if (bpf_find_containing_subprog(env, call_idx)->skip_gen)
+		env->pad_skip_gen++;
 	charge_plan(env, plan);
 	return 0;
 }
@@ -439,7 +443,7 @@ int bpf_pad_note_callee(struct bpf_verifier_env *env, int call_idx, int callee)
 
 	if (!plan)
 		return -ENOMEM;
-	return plan_add_callee(env, plan, callee);
+	return plan_add_callee(env, plan, call_idx, callee);
 }
 
 /* Free a list of records. Returns the bytes that they had charged to env->mem. */
@@ -488,6 +492,7 @@ void bpf_pads_new_round(struct bpf_verifier_env *env)
 	int i;
 
 	env->pads_late = false;
+	env->pad_skip_gen++;
 	for (i = 0; i < env->prog->len; i++, aux++) {
 		env->mem -= bpf_pad_plans_free(aux);
 		env->mem -= bpf_pad_note_free(aux->pad_note);
@@ -505,6 +510,7 @@ void bpf_pads_move(struct bpf_verifier_env *env, struct bpf_pads_moved *moved, b
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	int i;
 
+	env->pad_skip_gen++;
 	for (i = 0; i < env->prog->len; i++, aux++, moved++) {
 		if (save) {
 			env->mem -= free_plans(moved->plans);
@@ -2398,10 +2404,11 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 }
 
 /*
- * Is the pad the only way out of the site of @plan, whatever the subprog turns out to be? An access
- * to arena that faults can be skipped. may_goto of the program can jump where the program says, as
- * it does in a subprog that cannot unwind. So can all of them below a call, unless a subprog comes
- * back to the call that is left elsewhere.
+ * Is the pad the only way to continue at the site of @plan? It is not at an access to arena, which
+ * can be skipped when it faults, nor at a may_goto of the program, which can jump where the program
+ * says. That is what they do in a function whose frames cannot be cancelled, which is marked
+ * 'stuck': for example the callback of a helper that has no unwind label. A call has another way
+ * too if its callees were cancelled at such insns only.
  */
 bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
 {
@@ -2500,34 +2507,14 @@ static bool plan_is_stuck(const struct bpf_pad_plan *plan)
 }
 
 /*
- * Does the site of @plan need a pad wherever its frame can unwind? If so a conflict there is an
- * error, and hidden slots are worth their stores. All sites do, but for:
- *   - an access to arena, and a call that has nothing but such accesses below it: they are
- *     skipped, see skip_faults().
- * may_goto of the program needs one, and so does a call above it: the jump that the program
- * has there was not verified.
- */
-static bool site_needs_pad(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
-{
-	if (bpf_pad_must_unwind(env, plan))
-		return true;
-	if (plan->kind == BPF_SITE_FAULT)
-		return false;
-	return plan->kind != BPF_SITE_CALL || (sites_below(env, plan) & BIT(BPF_SITE_MAY_GOTO));
-}
-
-/*
- * Is the conflict of @plan an error? Not where the frame cannot unwind and the site has another way
- * out, see bpf_pad_must_unwind(): what comes back to a call there is made unable to unwind, see
- * skip_faults().
+ * Is the conflict of @plan an error? It is one at every site: a prog that goes on from a loop that
+ * was out of time, or from an access that faulted, was not verified. But not where the frame cannot
+ * unwind and the site has another way out, see bpf_pad_must_unwind(): what comes back to a call
+ * there is stuck, see bpf_pad_skip_faults().
  */
 static bool plan_rejects(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
 {
-	if (!plan->conflict)
-		return false;
-	if (bpf_pad_must_unwind(env, plan))
-		return true;
-	return !plan_is_stuck(plan) && site_needs_pad(env, plan);
+	return plan->conflict && (bpf_pad_must_unwind(env, plan) || !plan_is_stuck(plan));
 }
 
 /*
@@ -2548,10 +2535,9 @@ static bool acquires_stack_obj(struct bpf_verifier_env *env, const struct bpf_su
 }
 
 /*
- * The groups of which @plan has something that its pad cannot tell whether it is held, or where.
- * Slots are stores on the normal path: none where there is another way out, and none for a site
- * that the program does not have.
- * @all_ptrs: no insn of the function acquires an iterator or a dynptr.
+ * Returns the groups for which the pad of @plan needs hidden slots: it cannot tell whether a
+ * resource is held, or it has no location for it. Slots are stores on the normal path, so a site
+ * that the program does not keep asks for none. @all_ptrs: see acquires_stack_obj().
  */
 static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 			   bool all_ptrs)
@@ -2559,7 +2545,7 @@ static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_pl
 	u8 groups = plan->sections_differ;
 	int i, err;
 
-	if (!plan->used || plan->conflict || !site_needs_pad(env, plan))
+	if (!plan->used || plan->conflict)
 		return 0;
 	if (plan->no_place && all_ptrs)
 		groups |= BIT(BPF_PAD_GROUP_REFS);
@@ -2767,7 +2753,7 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 	for (i = sub->start; i < sub[1].start; i++)
 		for (plan = aux[i].pad_plans; plan; plan = plan->next)
 			if (plan->used && plan_has_slots(plan) &&
-			    !plan_has_room(plan, group, slots) && site_needs_pad(env, plan))
+			    !plan_has_room(plan, group, slots))
 				return 0;
 	sub->hidden_words += words;
 	err = bpf_hidden_slots_fit(env);
@@ -2779,7 +2765,7 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 		sub->pend_off = pend_off;
 	for (i = sub->start; i < sub[1].start; i++) {
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
-			/* it has another way out */
+			/* the program does not have its site */
 			if (plan_has_slots(plan) && !plan_has_room(plan, group, slots))
 				plan->conflict = BPF_CONFLICT_SLOTS_FULL;
 			err = plan_has_slots(plan) ?
@@ -3203,37 +3189,59 @@ void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *su
 	sub->left_at |= kind == BPF_SITE_CALL ? sites_below(env, plan) : BIT(kind);
 }
 
+/* Did bpf_pad_skip_faults() walk @sub, and has no call in or below it got a new callee since? */
+static bool skip_walked(const struct bpf_verifier_env *env, const struct bpf_subprog_info *sub)
+{
+	return sub->skip_gen && sub->skip_gen == env->pad_skip_gen;
+}
+
 /*
- * The site of @plan, at insn @i, has no pad. An access to arena: it is skipped when it faults.
- * What follows the access was verified, and less unwinds than the main pass looked at.
- * Or it is a call, and below it only accesses to arena and may_goto of the program unwind. The
- * accesses are skipped and may_goto jumps where the program says: what came back to the call cannot
- * unwind, nor can what came back to the calls in there. The pass is done again, and they cannot
- * from its start, see check_funcs().
+ * The frame of the call of @plan, at @insn_idx, cannot be cancelled, and the callees that came back
+ * to the call were cancelled only at accesses to arena and at may_gotos of the program. Mark those
+ * callees as stuck, see bpf_pad_must_unwind(), and the callees of their calls in turn. The main
+ * pass does most of this where a call is made, see stuck_frame_calls() in verifier.c. This is for a
+ * state that left its function before that. If a subprog is marked here for the first time, the
+ * pass is repeated, see check_funcs().
  */
-static int skip_faults(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
+int bpf_pad_skip_faults(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
 {
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
-	int s, c, cnt = env->subprog_cnt;
+	int i, s, c, err = 0, cnt = env->subprog_cnt;
 	struct bpf_subprog_info *sub;
-	unsigned long *todo;
+	unsigned long *todo, *done;
+	bool walked = true;
 
-	if (plan->kind == BPF_SITE_FAULT) {
-		aux[i].fault_skips = true;
+	if (verifier_bug_if(plan->kind != BPF_SITE_CALL, env,
+			    "a site that is no call has a frame that cannot unwind"))
+		return -EFAULT;
+	/*
+	 * Many states can come back to calls of the same subprogs. What was walked is not walked
+	 * again while no call in it got a new callee, see plan_add_callee().
+	 */
+	bpf_pad_for_each_callee(plan, c)
+		walked &= skip_walked(env, &env->subprog_info[c]);
+	if (walked)
 		return 0;
-	}
 	todo = bitmap_zalloc(cnt, BPF_VERIFIER_GFP);
-	if (!todo)
+	done = bitmap_zalloc(cnt, BPF_VERIFIER_GFP);
+	if (!todo || !done) {
+		bitmap_free(todo);
+		bitmap_free(done);
 		return -ENOMEM;
-	env->faults_late = true;
+	}
 	bpf_pad_for_each_callee(plan, c)
 		__set_bit(c, todo);
 	while ((s = find_first_bit(todo, cnt)) < cnt) {
 		__clear_bit(s, todo);
 		sub = &env->subprog_info[s];
-		if (!sub->bail_unwinds)
+		if (skip_walked(env, sub) || __test_and_set_bit(s, done))
 			continue;
-		sub->bail_unwinds = false;
+		/* the search in the bitmap, and each insn of the subprog */
+		err = bpf_add_cost_and_check(env, cnt / BITS_PER_LONG + sub[1].start - sub->start,
+					     BPF_COST_SCAN);
+		if (err)
+			break;
+		env->faults_late |= !sub->stuck;
 		sub->stuck = true;
 		for (i = sub->start; i < sub[1].start; i++) {
 			plan = bpf_pad_plan(&aux[i], BPF_SITE_CALL);
@@ -3242,8 +3250,13 @@ static int skip_faults(struct bpf_verifier_env *env, int i, const struct bpf_pad
 					__set_bit(c, todo);
 		}
 	}
+	/* a walk that got to its end has all that is below what it walked */
+	if (!err)
+		for_each_set_bit(s, done, cnt)
+			env->subprog_info[s].skip_gen = env->pad_skip_gen;
 	bitmap_free(todo);
-	return 0;
+	bitmap_free(done);
+	return err;
 }
 
 /*
@@ -3325,9 +3338,20 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 				print_plan(env, i, plan);
 				return -EINVAL;
 			}
-			err = plan->conflict ? skip_faults(env, i, plan) : 0;
+			if (!plan->conflict)
+				continue;
+			/*
+			 * The frame cannot unwind and the site has another way out. The main pass
+			 * made what came back stuck, and no run that finds a subprog stuck late
+			 * gets here. So the program still has the site, and no pad.
+			 */
+			err = bpf_pad_skip_faults(env, plan);
 			if (err)
 				return err;
+			if (!env->faults_late) {
+				bpf_pad_log(env, i, plan);
+				return -EINVAL;
+			}
 		}
 	}
 	/* all accesses of the program to its stack are known: the hidden words go below them */
@@ -3373,13 +3397,21 @@ static bool jump_leaves_loop(struct bpf_verifier_env *env, int h, int n)
 	       !loop_is_in(env, bpf_loop_at_index(env, n + 1), h);
 }
 
-/* The pass left a frame at the insn of @aux, may_goto of the program */
+/*
+ * Did the pass cancel a frame at the insn of @aux, an access to arena or a may_goto of the program?
+ * An access at which no frame holds anything has no record, see check_arena_site().
+ */
 static bool left_at_insn(const struct bpf_insn_aux_data *aux)
 {
 	const struct bpf_pad_plan *plan;
 
+	if (aux->fault_skips)
+		return false;
+	if (aux->fault_empty)
+		return true;
 	for (plan = aux->pad_plans; plan; plan = plan->next)
-		if (plan->visited && plan->kind == BPF_SITE_MAY_GOTO)
+		if (plan->visited &&
+		    (plan->kind == BPF_SITE_FAULT || plan->kind == BPF_SITE_MAY_GOTO))
 			return true;
 	return false;
 }
@@ -3401,10 +3433,10 @@ static bool left_at_insn(const struct bpf_insn_aux_data *aux)
  * Kept apart, neither call is cancelled. The calls do not say what to keep apart, because their
  * arguments are constants, so the causes are recorded in the callee.
  *
- * may_goto of the program leaves a function as well. The dependencies of the next pass know exit,
- * unwind_exit and bpf_throw() as the ways out of a function, and none of these stands for such an
- * insn. Where only the calls together get to it, the jumps that can skip it are the cause: the insn
- * is noted, and they are what controls it.
+ * An access to arena that faults leaves a function as well, and so does may_goto of the program.
+ * The dependencies of the next pass know exit, unwind_exit and bpf_throw() as the ways out of a
+ * function, and none of these stands for such an insn. Where only the calls together get to it,
+ * the jumps that can skip it are the cause: the insn is noted, and they are what controls it.
  *
  * No pass that keeps more apart gives the frame of the call a place for a pointer that it passed
  * on and kept no copy of, or a way to tell whether the callee has released it. Where that is the
@@ -3518,7 +3550,8 @@ static void note_causes_below(struct bpf_verifier_env *env)
 
 /*
  * The pass is over and has an error. Note the causes of the conflicts that are one: those that a
- * state made an error where it visited, see unwind_frame(), and those that bpf_pads_settle() found.
+ * state made an error where it visited, see unwind_frame() and check_arena_site(), and those that
+ * bpf_pads_settle() found.
  */
 void bpf_pads_note_causes(struct bpf_verifier_env *env)
 {
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 2141cef41a88..22da9e990f5f 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -3423,12 +3423,8 @@ static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)
 			env->insn_idx, bpf_subprog_name(env, subprog));
 		return -EINVAL;
 	}
-	/*
-	 * It did at accesses to arena, which are skipped, and at may_goto of the program, which
-	 * jumps where the program says, see check_may_goto_site(). The pass is done again.
-	 */
-	env->faults_late |= did_unwind ||
-			    ((sub->may_goto_unwinds || sub->made_calls) && !sub->stuck);
+	/* 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;
 	return 0;
@@ -22028,20 +22024,11 @@ static enum bpf_pad_conflict frame_cannot_unwind(struct bpf_verifier_env *env,
 }
 
 /*
- * An insn of the program enters @subprog from the current frame: a call, callx, a helper or a
- * kfunc that has a landing pad for its callback. If the frame cannot unwind, or is a frame of a
- * subprog whose may_goto stays and that has a caller in the program, then what comes back
- * unwound to the call may have nowhere to go. So may_goto of @subprog stays too, see
- * check_may_goto_site(): from this call on, before a state gets to its may_goto and makes a
- * conflict there, or at another call of @subprog, that is none. That closes the answer over what
- * a subprog that cannot unwind calls, call by call as the pass gets to them. If a state has left
- * @subprog before, the pass is done again. The same if a frame of @subprog has made a call before:
- * what it called was not told, and the function may not be walked again, since the call of a
- * function on its own that an instance subsumes waits for the exits of that instance. A state that
- * came back unwound from there can have ended in a conflict at the call, which leaves no other
- * trace in @subprog.
- * @subprog still unwinds where there is no other way out. A state that does so on the way from
- * this call is an error at the call, see unwind_frame().
+ * The current frame calls @subprog, with a call, callx or a helper that has an unwind label. If the
+ * frame cannot be cancelled, or its function is 'stuck' and has a caller in the program, a
+ * cancellation of @subprog would have nowhere to go. So mark @subprog 'stuck' too, see
+ * check_may_goto_site(). If a state has left @subprog before, or a frame of @subprog has made a
+ * call before, the pass is repeated with the mark set from its start.
  */
 static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog)
 {
@@ -22055,7 +22042,7 @@ static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog)
 		caller->made_calls = true;
 		return;
 	}
-	env->faults_late |= sub->may_goto_unwinds || sub->made_calls ||
+	env->faults_late |= sub->soft_unwinds || sub->made_calls ||
 			    (sub->did_unwind && sub->bail_unwinds);
 	sub->stuck = true;
 }
@@ -22142,83 +22129,67 @@ static int check_may_goto_site(struct bpf_verifier_env *env)
 	    !bpf_jit_supports_timed_may_goto() || bpf_prog_is_offloaded(env->prog->aux))
 		return 0;
 	if (sub->stuck || frame_cannot_unwind(env, env->cur_state)) {
-		env->faults_late |= (sub->may_goto_unwinds || sub->made_calls) &&
-				    !sub->stuck;
+		env->faults_late |= (sub->soft_unwinds || sub->made_calls) && !sub->stuck;
 		sub->stuck = true;
 		return 0;
 	}
-	sub->may_goto_unwinds = true;
+	sub->soft_unwinds = true;
 	err = push_unwind_edge(env, BPF_SITE_MAY_GOTO);
 	return err ?: 1;
 }
 
-/* Is all that the current frame of @st holds a pointer, which is NULL where nothing is held? */
-static bool frame_holds_pointers_only(const struct bpf_verifier_state *st)
-{
-	const struct bpf_func_state *frame = st->frame[st->curframe];
-	int i;
-
-	for (i = frame->entry_refs; i < st->acquired_refs; i++)
-		if (st->refs[i].type != REF_TYPE_PTR)
-			return false;
-	return st->active_rcu_locks == frame->entry_rcu_locks &&
-	       st->active_preempt_locks == frame->entry_preempt_locks;
-}
-
 /*
- * An access through an arena pointer, @reg, faults when the page is not mapped. Then the program
- * is unwound. The site is the access itself, with the state before it takes effect, since the
- * fault precedes any write of its result.
- *
- * This site has another way out, which costs nothing: the access is skipped, a load reads 0. It
- * is taken where the frame cannot unwind and where no pad serves all states: a conflict here does
- * not reject the program. There are many of them. The normal path pays nothing, the main pass little:
- *
- *   The frame holds nothing, in all states that get here: there is no plan and no visit.
- *
- *   It holds something: each state visits the plan, as it is. If states went by without a visit
- *   the plan does not know what is NULL where nothing is held, see visit_refs(). All is done again,
- *   and then all states visit. Unless what is held is no pointer: no test tells.
+ * An access through @reg faults when @reg points to arena and the page is not mapped, and the
+ * kernel cancels the program there. The site is the access itself, with the state before the insn:
+ * the fault comes before the insn writes anything. The fault is skipped, and a load reads 0, where
+ * the JIT has no unwind_exit and in a function that is 'stuck', as for check_may_goto_site().
  *
- *   A copy of the state leaves the frame, see unwind_frame(), once per stretch of insns
- *   without a call and without a store to the stack of a caller. They alone change what gets to the
- *   caller: what the frame holds is dropped, R0 is set. See 'fault_edge', and bpf_states_join().
+ * A program can have thousands of such accesses. So nothing is recorded where no state holds
+ * anything: the landing pad releases nothing. If a state that holds something comes after states
+ * that passed without a record, the pass is repeated and all states record, see bpf_pad_visit().
+ * And one cancelled copy of the state serves a stretch of insns without a call or a store to the
+ * stack of a caller ('fault_edge'), because only those change what the caller gets.
  */
 static int check_arena_site(struct bpf_verifier_env *env, const struct bpf_reg_state *reg)
 {
 	struct bpf_insn_aux_data *aux = cur_aux(env);
 	struct bpf_verifier_state *st = env->cur_state;
 	struct bpf_func_state *frame = cur_func(env);
+	struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
 	struct bpf_pad_plan *plan;
 	bool visits;
 
 	/* frame_cannot_unwind() does not ask the JIT about a frame that the kernel called. */
-	if (reg->type != PTR_TO_ARENA || aux->fault_skips ||
-	    !bpf_jit_supports_unwind())
+	if (reg->type != PTR_TO_ARENA || !bpf_jit_supports_unwind())
+		return 0;
+	if (sub->stuck || frame_cannot_unwind(env, st)) {
+		env->faults_late |= (sub->soft_unwinds || sub->made_calls) && !sub->stuck;
+		sub->stuck = true;
+		aux->fault_skips = true;
 		return 0;
+	}
+	sub->soft_unwinds = true;
 	visits = frame_holds_resources(st) || aux->fault_full || bpf_pad_plan(aux, BPF_SITE_FAULT);
 	if (!visits) {
 		aux->fault_empty = true;
 		if (frame->fault_edge)
 			return 0;
-	}
-	if (frame_cannot_unwind(env, st)) {
-		aux->fault_skips = true;
-		return 0;
-	}
-	if (visits) {
+	} else {
 		if (aux->fault_empty && !aux->fault_full) {
-			if (!frame_holds_pointers_only(st)) {
-				aux->fault_skips = true;
-				return 0;
-			}
 			aux->fault_full = true;
 			env->faults_late = true;
 		}
 		plan = bpf_pad_visit(env, st, env->insn_idx, BPF_SITE_FAULT);
 		if (IS_ERR(plan))
 			return PTR_ERR(plan);
-		if (plan->conflict || frame->fault_edge)
+		/* No error if the function turns out to be 'stuck', see do_check_all(). */
+		if (plan->conflict) {
+			bpf_pad_log(env, env->insn_idx, plan);
+			/* for bpf_pads_note_causes() */
+			plan->failed = true;
+			return -EINVAL;
+		}
+		if (frame->fault_edge)
 			return 0;
 	}
 	frame->fault_edge = true;
@@ -22345,13 +22316,13 @@ static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_p
  * With a conflict there is no pad: the site is an unproven insn in @st, which ends here. The pass
  * goes on, and a pass that keeps more apart may have no such state.
  * A frame that cannot unwind is a conflict. At an access to arena check_arena_site() saw to both,
- * and at may_goto of the program check_may_goto_site() saw to it: the jump is taken there.
- * At a call that has only such accesses below it a conflict is no error: @st is dropped, and
- * bpf_pads_settle() has the accesses skipped. The same at a call in a frame that cannot unwind, if
- * what comes back to it has another way out: the callees are made unable to unwind.
- * Nor is it one at a site that the program may not have in the end, see site_is_certain(): @st is
- * dropped, the plan keeps the conflict, and bpf_pads_settle() makes it an error of the pass if the
- * site is still there.
+ * and at may_goto of the program check_may_goto_site() saw to it: the access is skipped there,
+ * the jump is taken. At a call in such a frame that is no error if what comes back to the call
+ * was left at such sites only: @st is dropped, and what came back is stuck from now on, see
+ * stuck_frame_calls() and bpf_pad_skip_faults().
+ * Nor is a conflict an error at a site that the program may not have in the end, see
+ * site_is_certain(): @st is dropped, the plan keeps the conflict, and bpf_pads_settle() makes it
+ * an error of the pass if the site is still there.
  */
 static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int insn_idx,
 			enum bpf_site_kind kind)
@@ -22361,7 +22332,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	struct bpf_verifier_state *cur = env->cur_state;
 	int cur_idx = env->insn_idx, err = 0;
 	struct bpf_pad_plan *plan = NULL;
-	bool print_state, certain = false, stuck;
+	bool print_state, certain = true, stuck;
 	enum bpf_pad_conflict conflict;
 	u32 cnt;
 
@@ -22388,9 +22359,10 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		stuck = plan->conflict == BPF_CONFLICT_CANNOT_UNWIND ||
 			plan->conflict == BPF_CONFLICT_NO_EXIT;
 		/*
-		 * There is no other way out. Not for may_goto of the program and a call above it
-		 * either, but in a subprog that cannot unwind, and whether it is one may be found
-		 * later in the pass. Then this error was none, see do_check_all().
+		 * There is no other way out. Not for may_goto of the program, an access to arena
+		 * and a call above them either, but in a subprog that cannot unwind, and whether
+		 * it is one may be found later in the pass. Then this error was none, see
+		 * do_check_all().
 		 */
 		if (plan->conflict && certain && (bpf_pad_must_unwind(env, plan) || !stuck)) {
 			bpf_pad_log(env, insn_idx, plan);
@@ -22399,6 +22371,12 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 			err = -EINVAL;
 			goto unproven;
 		}
+		/*
+		 * The frame of the call cannot be cancelled, and its callees were cancelled only at
+		 * 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);
 		if (plan->conflict)
 			goto out;
 	}
@@ -22432,7 +22410,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	if (st->unwound)
 		bpf_pad_note_left(env, sub, plan, kind);
 	sub->must_unwind |= st->unwound && plan && bpf_pad_must_unwind(env, plan);
-	sub->unwinds_for_sure |= st->unwound && plan && certain;
+	sub->unwinds_for_sure |= st->unwound && certain;
 	if (env->log.level & BPF_LOG_LEVEL2)
 		verbose(env, "from %d to %s of func#%d\n", insn_idx,
 			st->unwound ? "unwind_exit" : "exit", frame->subprogno);
@@ -24627,13 +24605,8 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
 		if (bpf_subprog_is_global(env, i))
 			initial->subprogs[i].did_unwind |= env->subprog_info[i].did_unwind;
 		/*
-		 * The accesses to arena in it are skipped, and the pass is done again, see
-		 * subprog_cannot_unwind() and skip_faults(). The second run has to know from its
-		 * start that the subprog cannot unwind, or it finds out late once more.
-		 * No other run knows: like all else about a subprog that is what one pass finds. A
-		 * pass that keeps more apart, and a path-sensitive run, may not get to the call
-		 * that has no landing pad for the subprog, or may have no conflict at its
-		 * caller. Then the subprog is left where it has to unwind, and it can.
+		 * A repeated run starts with bail_unwinds as subprog_cannot_unwind() left it. Any
+		 * other run starts from the first value: it may not get to the call that clears it.
 		 */
 		if (!env->pass_again)
 			initial->subprogs[i].bail_unwinds =
@@ -24641,11 +24614,8 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
 		else if (env->faults_late)
 			initial->subprogs[i].bail_unwinds &= env->subprog_info[i].bail_unwinds;
 		/*
-		 * Its may_goto jumps where the program says, see check_may_goto_site() and
-		 * stuck_frame_calls(). That is what it did before the verifier unwound programs
-		 * there, so it is safe to keep in every run that follows: a run that had to find
-		 * it again could end at an error which is none before it gets to the call that
-		 * tells.
+		 * '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;
 		/* releases_args adds up. asks_args is that of the last pass with an error. */
@@ -24687,7 +24657,7 @@ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial
 	 */
 	mark_used_sites(env, initial);
 	ret = bpf_pads_settle(env);
-	/* accesses to arena are skipped after all, see skip_faults() */
+	/* bpf_pads_settle() found what a pass has to know from its start: repeat the pass. */
 	if (!ret && pass_needs_restart(env))
 		return 0;
 	ret = ret ?: check_after_pass(env);
@@ -24943,12 +24913,9 @@ static int do_check_all(struct bpf_verifier_env *env)
 			break;
 		}
 		/*
-		 * The run has an error, and it found late what a run has to know from its start,
-		 * see check_arena_site(). Mostly that a subprog cannot unwind: its may_goto jumps
-		 * where the program says, and the states that left it there went where no run of
-		 * the program goes. A conflict at such a site or at a call above it was none, and
-		 * neither was what such a state ran into on its way. The run that follows knows
-		 * from its start.
+		 * The pass has an error, and it found late what a pass has to know from its start,
+		 * mostly that a function cannot be cancelled, see check_arena_site(). The error can
+		 * be false, so repeat the pass.
 		 */
 		if (ret && env->faults_late && !env->over_limit) {
 			/* Drop the log of that error. */
diff --git a/tools/testing/selftests/bpf/progs/arena_atomics.c b/tools/testing/selftests/bpf/progs/arena_atomics.c
index c12f7e6894e9..869742da1524 100644
--- a/tools/testing/selftests/bpf/progs/arena_atomics.c
+++ b/tools/testing/selftests/bpf/progs/arena_atomics.c
@@ -3,12 +3,12 @@
 #include <linux/bpf.h>
 #include <bpf/bpf_helpers.h>
 #include <bpf/bpf_tracing.h>
+#include <bpf/bpf_core_read.h>
 #include <stdbool.h>
 #include <stdatomic.h>
 #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);
@@ -276,30 +276,53 @@ __u64 __arena_global uaf_r0_after_src_r0;
 /* What reading the faulted address again gives, see the end of uaf() */
 __u64 __arena_global uaf_reread;
 
-SEC("syscall")
-int uaf(const void *ctx)
-{
-	if (pid != (bpf_get_current_pid_tgid() >> 32))
-		return 0;
 /*
  * __BPF_FEATURE_ADDR_SPACE_CAST is required by the asm below, which spells
  * addr_space_cast textually. That and the mnemonic both arrived in LLVM 19.
  */
 #if defined(ENABLE_ATOMICS_TESTS) && !defined(__TARGET_ARCH_arm64) && \
 	defined(__BPF_FEATURE_ADDR_SPACE_CAST)
+/*
+ * An access to the arena that faults ends the prog where its subprog can unwind. Where it cannot
+ * the access is skipped, and the registers of an atomic insn are what they have to be: that is what
+ * this test looks at. A subprog that cannot unwind is the comparator of bpf_rbtree_add() for a node
+ * that takes a lock when it is freed. No helper may be called there.
+ */
+#define __contains(name, node) __attribute__((btf_decl_tag("contains:" #name ":" #node)))
+#define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))
+
+extern void *bpf_obj_new(__u64 local_type_id__k) __ksym;
+extern void bpf_obj_drop(void *p__alloc) __ksym;
+extern long bpf_rbtree_add(struct bpf_rb_root *root, struct bpf_rb_node *node,
+			   bool (*less)(struct bpf_rb_node *, const struct bpf_rb_node *)) __ksym;
+extern struct bpf_rb_node *bpf_rbtree_first(struct bpf_rb_root *root) __ksym;
+extern struct bpf_rb_node *bpf_rbtree_remove(struct bpf_rb_root *root,
+					      struct bpf_rb_node *node) __ksym;
+
+struct uaf_leaf {
+	struct bpf_rb_node node;
+};
+
+struct uaf_node {
+	struct bpf_rb_node node;
+	struct bpf_spin_lock lock;
+	struct bpf_rb_root root __contains(uaf_leaf, node);
+};
+
+private(U) struct bpf_spin_lock uaf_lock;
+private(U) struct bpf_rb_root uaf_root __contains(uaf_node, node);
+
+/* No code has a leaf: this puts it in BTF, for __contains() above */
+struct uaf_leaf *__uaf_leaf_btf_root SEC(".data.uaf_leaf");
+
+void __arena *uaf_page;
+
+static bool uaf_less(struct bpf_rb_node *a, const struct bpf_rb_node *b)
+{
+	void __arena *page = uaf_page;
 	__u32 __arena *page32;
 	__u64 __arena *page64;
-	void __arena *page;
 
-	page = bpf_arena_alloc_pages(&arena, NULL, 1, NUMA_NO_NODE, 0);
-	bpf_arena_free_pages(&arena, page, 1);
-	uaf_recovery_fails = 26;
-	uaf_r1_after_dst_r0 = 1;
-	uaf_r0_after_dst_r0 = 1;
-	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;
@@ -419,7 +442,49 @@ int uaf(const void *ctx)
 	: : [page]"r"(page64),
 	    __imm_addr(uaf_reread)
 	: "r1", "r2", "r3", "memory");
-	unwind_faults();
+	return false;
+}
+#endif
+
+SEC("syscall")
+int uaf(const void *ctx)
+{
+	if (pid != (bpf_get_current_pid_tgid() >> 32))
+		return 0;
+#if defined(ENABLE_ATOMICS_TESTS) && !defined(__TARGET_ARCH_arm64) && \
+	defined(__BPF_FEATURE_ADDR_SPACE_CAST)
+	struct bpf_rb_node *node;
+	struct uaf_node *n;
+	void __arena *page;
+	int i;
+
+	page = bpf_arena_alloc_pages(&arena, NULL, 1, NUMA_NO_NODE, 0);
+	bpf_arena_free_pages(&arena, page, 1);
+	uaf_recovery_fails = 26;
+	uaf_r1_after_dst_r0 = 1;
+	uaf_r0_after_dst_r0 = 1;
+	uaf_r0_after_src_r0 = 1;
+	uaf_reread = 1;
+	uaf_page = page;
+
+	/* two nodes, so that the comparator runs, one time */
+	for (i = 0; i < 2; i++) {
+		n = bpf_obj_new(bpf_core_type_id_local(struct uaf_node));
+		if (!n)
+			return 1;
+		bpf_spin_lock(&uaf_lock);
+		bpf_rbtree_add(&uaf_root, &n->node, uaf_less);
+		bpf_spin_unlock(&uaf_lock);
+	}
+	for (i = 0; i < 2; i++) {
+		bpf_spin_lock(&uaf_lock);
+		node = bpf_rbtree_first(&uaf_root);
+		node = node ? bpf_rbtree_remove(&uaf_root, node) : NULL;
+		bpf_spin_unlock(&uaf_lock);
+		if (!node)
+			return 2;
+		bpf_obj_drop(container_of(node, struct uaf_node, node));
+	}
 #endif
 
 	return 0;
diff --git a/tools/testing/selftests/bpf/progs/arena_skipped.h b/tools/testing/selftests/bpf/progs/arena_skipped.h
deleted file mode 100644
index 8b0a265ec6aa..000000000000
--- a/tools/testing/selftests/bpf/progs/arena_skipped.h
+++ /dev/null
@@ -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; })
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena.c b/tools/testing/selftests/bpf/progs/verifier_arena.c
index e46ce213c34d..b9b34c526671 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena.c
@@ -9,7 +9,6 @@
 #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)))
 
@@ -81,8 +80,6 @@ int basic_alloc1(void *ctx)
 	bpf_arena_free_pages(&arena, (void __arena *)page2, 1);
 	if (*page1 != 1)
 		return 6;
-	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)
 		return 8;
@@ -127,35 +124,27 @@ __success __retval(0)
 __skip_without_arena
 int basic_alloc2_nosleep(void *ctx)
 {
-	volatile char __arena *page1, *page2, *page3, *page4;
+	volatile char __arena *page1, *page2;
 
 	page1 = bpf_arena_alloc_pages(&arena, NULL, 2, NUMA_NO_NODE, 0);
 	if (!page1)
 		return 1;
 	page2 = page1 + __PAGE_SIZE;
-	page3 = page1 + __PAGE_SIZE * 2;
-	page4 = page1 - __PAGE_SIZE;
 	*page1 = 1;
 	*page2 = 2;
-	skipped(*page3 = 3);
-	skipped(*page4 = 4);
 	if (*page1 != 1)
 		return 1;
 	if (*page2 != 2)
 		return 2;
-	if (skipped(*page3) != 0)
-		return 3;
-	if (skipped(*page4) != 0)
-		return 4;
 	bpf_arena_free_pages(&arena, (void __arena *)page1, 2);
-	if (skipped(*page1) != 0 && skipped(*page1) != 1)
+	/*
+	 * The pages may be there still: 1 and 2. If not, the prog ends here, with 0, or the
+	 * load is skipped and reads 0 where the JIT cannot unwind.
+	 */
+	if (*page1 != 0 && *page1 != 1)
 		return 5;
-	if (skipped(*page2) != 0 && skipped(*page2) != 2)
+	if (*page2 != 0 && *page2 != 2)
 		return 6;
-	if (skipped(*page3) != 0)
-		return 7;
-	if (skipped(*page4) != 0)
-		return 8;
 	return 0;
 }
 
@@ -164,35 +153,19 @@ __success __retval(0)
 __skip_without_arena
 int basic_alloc2(void *ctx)
 {
-	volatile char __arena *page1, *page2, *page3, *page4;
+	volatile char __arena *page1, *page2;
 
 	page1 = bpf_arena_alloc_pages(&arena, NULL, 2, NUMA_NO_NODE, 0);
 	if (!page1)
 		return 1;
 	page2 = page1 + __PAGE_SIZE;
-	page3 = page1 + __PAGE_SIZE * 2;
-	page4 = page1 - __PAGE_SIZE;
 	*page1 = 1;
 	*page2 = 2;
-	skipped(*page3 = 3);
-	skipped(*page4 = 4);
 	if (*page1 != 1)
 		return 1;
 	if (*page2 != 2)
 		return 2;
-	if (skipped(*page3) != 0)
-		return 3;
-	if (skipped(*page4) != 0)
-		return 4;
 	bpf_arena_free_pages(&arena, (void __arena *)page1, 2);
-	if (skipped(*page1) != 0)
-		return 5;
-	if (skipped(*page2) != 0)
-		return 6;
-	if (skipped(*page3) != 0)
-		return 7;
-	if (skipped(*page4) != 0)
-		return 8;
 	return 0;
 }
 
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena_large.c b/tools/testing/selftests/bpf/progs/verifier_arena_large.c
index 73dc5ac69a82..30b730929e62 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena_large.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena_large.c
@@ -8,7 +8,6 @@
 #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
@@ -62,8 +61,6 @@ int big_alloc1(void *ctx)
 	bpf_arena_free_pages(&arena, (void __arena *)page1, 1);
 	if (*page2 != 2)
 		return 6;
-	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)
 		return 8;
@@ -72,52 +69,13 @@ int big_alloc1(void *ctx)
 		return 9;
 	if (*page2 != 2)
 		return 10;
-	if (skipped(*(page1 + PAGE_SIZE)) != 0)
-		return 11;
-	if (skipped(*(page1 - PAGE_SIZE)) != 0)
-		return 12;
-	if (skipped(*(page2 + PAGE_SIZE)) != 0)
+	/*
+	 * The page behind page2 is the last one of the arena. It is no page that is missing:
+	 * libbpf puts the globals that the object has in the arena at its end, page[] below.
+	 * So bpf_arena_alloc_pages() refuses it above, and the load reads 0 that is there.
+	 */
+	if (*(page2 + PAGE_SIZE) != 0)
 		return 13;
-	if (skipped(*(page2 - PAGE_SIZE)) != 0)
-		return 14;
-	return 0;
-}
-
-/* Try to access a reserved page. Behavior should be identical with accessing unallocated pages. */
-SEC("syscall")
-__success __retval(0)
-__skip_without_arena
-int access_reserved(void *ctx)
-{
-	volatile char __arena *page;
-	char __arena *base;
-	const size_t len = 4;
-	int ret, i;
-
-	/* Get a separate region of the arena. */
-	page = base = arena_base(&arena) + 16384 * PAGE_SIZE;
-
-	ret = bpf_arena_reserve_pages(&arena, base, len);
-	if (ret)
-		return 1;
-
-	/* Try to dirty reserved memory. */
-	for (i = 0; i < len && can_loop; i++)
-		skipped(*page = 0x5a);
-
-	for (i = 0; i < len && can_loop; i++) {
-		page = (volatile char __arena *)(base + i * PAGE_SIZE);
-
-		/*
-		 * Error out in case either the write went through,
-		 * or the address has random garbage.
-		 */
-		if (skipped(*page) == 0x5a)
-			return 2 + 2 * i;
-
-		if (skipped(*page))
-			return 2 + 2 * i + 1;
-	}
 	return 0;
 }
 
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 51/73] bpf: Log why a call is a site and which functions cannot be cancelled
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (49 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 50/73] bpf: Reject a program that has no landing pad for a fault in arena Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 52/73] bpf: Add cancel_goto and cancel_exit, which only the verifier emits Kumar Kartikeya Dwivedi
                   ` (21 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  27 +++++++-
 kernel/bpf/pads.c            | 120 +++++++++++++++++++++++++++++------
 kernel/bpf/verifier.c        |  16 +++--
 3 files changed, 138 insertions(+), 25 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 12b93e15f7a4..a143c7685cc2 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -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);
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index a6a328d8548a..ffdae8ba5c35 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -2443,6 +2443,18 @@ void bpf_pads_must_unwind(struct bpf_verifier_env *env)
 	} while (changed);
 }
 
+static const char * const site_kind[] = {
+	[BPF_SITE_GUARD]		= "may_goto",
+	[BPF_SITE_RECURSION]		= "recursion check",
+	[BPF_SITE_CALL]			= "call",
+	[BPF_SITE_FAULT]		= "arena access",
+	[BPF_SITE_THROW]		= "bpf_throw",
+	[BPF_SITE_MAY_GOTO]		= "may_goto of the program",
+};
+
+/* The program has unwind_exit in the subprog. No site: a bit that follows those of the kinds. */
+#define LEFT_AT_UNWIND_EXIT	BIT(BPF_SITE_MAY_GOTO + 1)
+
 /*
  * At which kinds of site does the program leave each subprog? At its own, and at those of what
  * comes back to its calls. Bits by enum bpf_site_kind in 'left_at'. The main pass notes them as
@@ -2459,7 +2471,7 @@ static void sites_of_subprogs(struct bpf_verifier_env *env)
 
 	for (s = 0; s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
-		sub->left_at = 0;
+		sub->left_at = sub->can_unwind && s ? LEFT_AT_UNWIND_EXIT : 0;
 	}
 	do {
 		changed = false;
@@ -2488,17 +2500,44 @@ static void sites_of_subprogs(struct bpf_verifier_env *env)
 	} while (changed);
 }
 
-/* The kinds of site that the subprogs which come back to the call of @plan are left at */
+/*
+ * Returns the kinds of site at which the callees that came back to the call of @plan leave. The
+ * main pass asks before sites_of_subprogs() has run, so the program's unwind_exit is added here.
+ */
 static u8 sites_below(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
 {
 	u8 kinds = 0;
 	int s;
 
-	bpf_pad_for_each_callee(plan, s)
+	bpf_pad_for_each_callee(plan, s) {
 		kinds |= env->subprog_info[s].left_at;
+		if (env->subprog_info[s].can_unwind)
+			kinds |= LEFT_AT_UNWIND_EXIT;
+	}
 	return kinds;
 }
 
+/*
+ * Log why the call of @plan at insn @i is a site: the kinds of site at which its callees leave. The
+ * line goes before the line of the error, which ends the log.
+ */
+static void print_sites_below(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
+{
+	u8 kinds;
+	int k;
+
+	if (plan->kind != BPF_SITE_CALL)
+		return;
+	kinds = sites_below(env, plan);
+	verbose(env, "what the call at %d calls is left at:", i);
+	for (k = 0; k <= BPF_SITE_MAY_GOTO; k++)
+		if (kinds & BIT(k))
+			verbose(env, " %s%s", site_kind[k], kinds >> (k + 1) ? "," : "");
+	if (kinds & LEFT_AT_UNWIND_EXIT)
+		verbose(env, " unwind_exit");
+	verbose(env, "\n");
+}
+
 /* The frame at the site of @plan cannot be cancelled, so there is no pad to generate */
 static bool plan_is_stuck(const struct bpf_pad_plan *plan)
 {
@@ -3107,14 +3146,6 @@ static void print_ent(struct bpf_verifier_env *env, const struct bpf_pad_ent *en
 /* Print what the pad of the site at insn @i releases, or why it cannot be generated */
 static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
 {
-	static const char * const kind[] = {
-		[BPF_SITE_GUARD]		= "may_goto",
-		[BPF_SITE_RECURSION]		= "recursion check",
-		[BPF_SITE_CALL]			= "call",
-		[BPF_SITE_FAULT]		= "arena access",
-		[BPF_SITE_THROW]		= "bpf_throw",
-		[BPF_SITE_MAY_GOTO]		= "may_goto of the program",
-	};
 	static const char * const why[] = {
 		[BPF_CONFLICT_SECTIONS_DIFFER]	= "the number of sections differs",
 		[BPF_CONFLICT_TOO_MUCH]		= "too much is held",
@@ -3136,7 +3167,7 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 	};
 	int j;
 
-	verbose(env, "landing pad of %s at %d: ", kind[plan->kind], i);
+	verbose(env, "landing pad of %s at %d: ", site_kind[plan->kind], i);
 	for (j = plan->nr_ents - 1; !plan->conflict && j >= 0; j--)
 		print_ent(env, &plan->ents[j]);
 	if (plan->conflict)
@@ -3171,6 +3202,7 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pa
 	const struct bpf_subprog_info *sub = bpf_find_containing_subprog(env, insn_idx);
 
 	if (plan->conflict) {
+		print_sites_below(env, insn_idx, plan);
 		/* a release that the pad may not make is one of a pointer or of an object */
 		if (sub->owns_args && (plan->conflict == BPF_CONFLICT_NO_RELEASE ||
 				       conflict_of_ref(env, plan)))
@@ -3203,7 +3235,8 @@ static bool skip_walked(const struct bpf_verifier_env *env, const struct bpf_sub
  * state that left its function before that. If a subprog is marked here for the first time, the
  * pass is repeated, see check_funcs().
  */
-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)
 {
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	int i, s, c, err = 0, cnt = env->subprog_cnt;
@@ -3242,7 +3275,8 @@ int bpf_pad_skip_faults(struct bpf_verifier_env *env, const struct bpf_pad_plan
 		if (err)
 			break;
 		env->faults_late |= !sub->stuck;
-		sub->stuck = true;
+		/* the log names the call at @insn_idx also for a subprog further down */
+		bpf_subprog_set_stuck(sub, BPF_STUCK_CAME_BACK, insn_idx);
 		for (i = sub->start; i < sub[1].start; i++) {
 			plan = bpf_pad_plan(&aux[i], BPF_SITE_CALL);
 			if (plan)
@@ -3335,7 +3369,7 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 				return err;
 			plan->conflict = err;
 			if (plan_rejects(env, plan)) {
-				print_plan(env, i, plan);
+				bpf_pad_log(env, i, plan);
 				return -EINVAL;
 			}
 			if (!plan->conflict)
@@ -3345,7 +3379,7 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 			 * made what came back stuck, and no run that finds a subprog stuck late
 			 * gets here. So the program still has the site, and no pad.
 			 */
-			err = bpf_pad_skip_faults(env, plan);
+			err = bpf_pad_skip_faults(env, plan, i);
 			if (err)
 				return err;
 			if (!env->faults_late) {
@@ -3572,11 +3606,49 @@ void bpf_pads_note_causes(struct bpf_verifier_env *env)
 	bpf_check_limits(env);
 }
 
-/* The plans of the sites that the program has */
+/*
+ * Log that subprog @s cannot be cancelled, and the insn at which it was marked. The mark is kept
+ * for later passes, see check_funcs(), and the pass that is loaded may not reach that insn.
+ */
+static void print_stuck(struct bpf_verifier_env *env, int s)
+{
+	const struct bpf_subprog_info *sub = &env->subprog_info[s];
+	int by = bpf_find_containing_subprog(env, sub->stuck_insn) - env->subprog_info;
+
+	verbose(env, "func#%d cannot unwind", s);
+	switch (sub->stuck_by) {
+	case BPF_STUCK_NO_PAD:
+		verbose(env, ", the call at %u has no landing pad for it", sub->stuck_insn);
+		break;
+	case BPF_STUCK_CALLED:
+		verbose(env, ", func#%d calls it at %u and cannot unwind", by, sub->stuck_insn);
+		break;
+	case BPF_STUCK_CAME_BACK:
+		verbose(env, ", it came back to the call at %u in func#%d, which cannot unwind",
+			sub->stuck_insn, by);
+		break;
+	default:
+		verbose(env, " at %u", sub->stuck_insn);
+		break;
+	}
+	verbose(env, ": its may_goto jumps, its arena accesses are skipped\n");
+}
+
+/*
+ * Log at level 2 the pads of the sites that the program keeps, the functions that cannot be
+ * cancelled, and the functions that have hidden slots
+ */
 void bpf_pads_log(struct bpf_verifier_env *env)
 {
+	static const char * const group[] = {
+		[BPF_PAD_GROUP_RCU]	= "rcu",
+		[BPF_PAD_GROUP_PREEMPT]	= "preempt",
+		[BPF_PAD_GROUP_LOCKS]	= "locks",
+		[BPF_PAD_GROUP_REFS]	= "refs",
+	};
+	const struct bpf_subprog_info *sub;
 	const struct bpf_pad_plan *plan;
-	int i;
+	int i, s, g;
 
 	if (!(env->log.level & BPF_LOG_LEVEL2))
 		return;
@@ -3584,4 +3656,16 @@ void bpf_pads_log(struct bpf_verifier_env *env)
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next)
 			if (plan->used)
 				print_plan(env, i, plan);
+	for (s = 0; s < env->subprog_cnt; s++) {
+		sub = &env->subprog_info[s];
+		if (sub->stuck)
+			print_stuck(env, s);
+		if (!sub->slots)
+			continue;
+		verbose(env, "func#%d has hidden slots for:", s);
+		for (g = 0; g < BPF_PAD_NR_GROUPS; g++)
+			if (sub->slots & BIT(g))
+				verbose(env, " %s", group[g]);
+		verbose(env, "\n");
+	}
 }
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 22da9e990f5f..7036baf1efe7 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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;
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 52/73] bpf: Add cancel_goto and cancel_exit, which only the verifier emits
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (50 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 51/73] bpf: Log why a call is a site and which functions cannot be cancelled Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 53/73] bpf: Give the unwind label of a helper a second way in Kumar Kartikeya Dwivedi
                   ` (20 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 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(-)

diff --git a/include/linux/filter.h b/include/linux/filter.h
index 05a0bf8689a4..74e61ef02285 100644
--- a/include/linux/filter.h
+++ b/include/linux/filter.h
@@ -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);
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 52fbca734d13..25fd3213d000 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -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
diff --git a/kernel/bpf/disasm.c b/kernel/bpf/disasm.c
index 43aa0656a588..8426c6c04610 100644
--- a/kernel/bpf/disasm.c
+++ b/kernel/bpf/disasm.c
@@ -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",
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index f36e99814ab0..1ce65bc8ca46 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -1193,10 +1193,11 @@ 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 + bpf_jmp_offset(insn)].seen;
+		unwinds = bpf_is_pad_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.
+		 * The callee never exits. Its unwind_exit needs unwind_goto all the same, and
+		 * its cancel_exit needs cancel_goto.
 		 * The cpu predicts that it returns to what follows, or speculates to an exit.
 		 * Don't let the removal of dead code put something else there.
 		 */
@@ -1208,9 +1209,10 @@ void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
 		if (unwinds || !aux_data[i].seen || !bpf_insn_is_cond_jump(insn->code))
 			continue;
 
+		/* the 32 bit form of unwind_goto has its offset in imm */
 		if (!aux_data[i + 1].seen)
 			ja.off = insn->off;
-		else if (!aux_data[i + 1 + insn->off].seen)
+		else if (!aux_data[i + 1 + bpf_jmp_offset(insn)].seen)
 			ja.off = 0;
 		else
 			continue;
@@ -1558,7 +1560,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, err, patch_len, len = env->prog->len;
+	int i, err, patch_len, gotos, len = env->prog->len;
 	struct bpf_insn *insns = env->prog->insnsi;
 	bool rnd_hi32;
 
@@ -1634,11 +1636,14 @@ int bpf_opt_subreg_zext_lo32_rnd_hi32(struct bpf_verifier_env *env,
 		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.
+		 * Nothing may stand between an insn and its unwind_goto or cancel_goto, so the
+		 * zero extension goes after them. The landing pad does not need it: on that path
+		 * 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);
+		gotos = bpf_is_pad_goto(&insns[i + 1]);
+		gotos += gotos && bpf_is_pad_goto(&insns[i + 2]);
+		if (gotos) {
+			err = bpf_patch_list_insert(env, i + 1 + gotos, patch + 1, patch_len - 1);
 			if (err)
 				return err;
 			continue;
@@ -1813,7 +1818,7 @@ 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)) {
+		} else if (bpf_is_pad_goto(insn)) {
 			/* jit_subprogs() counts them too, but only for a prog with subprogs */
 			env->prog->aux->num_exentries++;
 			continue;
@@ -2203,7 +2208,7 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 			if (BPF_CLASS(insn->code) == BPF_STX &&
 			     BPF_MODE(insn->code) == BPF_PROBE_ATOMIC)
 				num_exentries++;
-			if (bpf_is_unwind_goto(insn))
+			if (bpf_is_pad_goto(insn))
 				num_exentries++;
 		}
 		func[i]->aux->num_exentries = num_exentries;
@@ -2398,10 +2403,16 @@ static bool is_arena_access(const struct bpf_insn *insn)
 	return class == BPF_STX && (mode == BPF_PROBE_MEM32 || mode == BPF_PROBE_ATOMIC);
 }
 
+/* Is @insn a call of any kind? Its callee returns to the insn after it. */
+static bool is_call(const struct bpf_insn *insn)
+{
+	return insn->code == (BPF_JMP | BPF_CALL) || bpf_is_callx(insn);
+}
+
 /* A call or an access to arena: the exception table can have an entry for the end of the insn */
 static bool can_have_unwind_goto(const struct bpf_insn *insn)
 {
-	return insn->code == (BPF_JMP | BPF_CALL) || bpf_is_callx(insn) || is_arena_access(insn);
+	return is_call(insn) || is_arena_access(insn);
 }
 
 /*
@@ -2414,6 +2425,9 @@ static bool can_have_unwind_goto(const struct bpf_insn *insn)
  * front, and such an insn that the verifier gave unwind_goto still has it behind. An insn that a
  * pass has replaced by other code is no site any more: the inlined bpf_loop() has unwind_goto of
  * its own, see inline_bpf_loop().
+ * cancel_goto is the same for cancel_exit. It stands behind a call, or behind unwind_goto of a
+ * call. Not behind an access to arena: the handler of a fault looks for unwind_goto there.
+ * cancel_exit is in no frame that the kernel calls: the main program leaves with exit.
  */
 int bpf_check_unwind_gotos(struct bpf_verifier_env *env)
 {
@@ -2426,6 +2440,16 @@ int bpf_check_unwind_gotos(struct bpf_verifier_env *env)
 				    "unwind_goto at insn %d follows no call and no access to arena",
 				    i))
 			return -EFAULT;
+		if (bpf_is_cancel_goto(insn) &&
+		    verifier_bug_if(!i || !(is_call(insn - 1) ||
+					    (i > 1 && bpf_is_unwind_goto(insn - 1) &&
+					     is_call(insn - 2))), env,
+				    "cancel_goto at insn %d follows no call", i))
+			return -EFAULT;
+		if (bpf_is_cancel_exit(insn) &&
+		    verifier_bug_if(i < env->subprog_info[1].start, env,
+				    "cancel_exit at insn %d of the main program", i))
+			return -EFAULT;
 		if (env->insn_aux_data[i].unwind_goto_follows && can_have_unwind_goto(insn) &&
 		    verifier_bug_if(i + 1 == len || !bpf_is_unwind_goto(insn + 1), env,
 				    "insn %d has lost its unwind_goto", i))
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 7036baf1efe7..ed73f660d5ce 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -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);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 53/73] bpf: Give the unwind label of a helper a second way in
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (51 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 52/73] bpf: Add cancel_goto and cancel_exit, which only the verifier emits Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:26   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 54/73] bpf, x86: Put the landing of unwind_goto after the function Kumar Kartikeya Dwivedi
                   ` (19 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_unwind.h | 103 +++++++++++++++++++++++++++----------
 kernel/bpf/arraymap.c      |   8 +--
 kernel/bpf/bpf_iter.c      |  15 +++---
 kernel/bpf/hashtab.c       |  17 +++---
 kernel/bpf/helpers.c       |  11 ++--
 kernel/bpf/ringbuf.c       |  17 +++---
 kernel/bpf/task_iter.c     |  10 ++--
 7 files changed, 114 insertions(+), 67 deletions(-)

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


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 54/73] bpf, x86: Put the landing of unwind_goto after the function
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (52 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 53/73] bpf: Give the unwind label of a helper a second way in Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 55/73] bpf, x86: Return to cancel_goto at cancel_exit Kumar Kartikeya Dwivedi
                   ` (18 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

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

Three points need care:

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

private_stack_unwinds of verifier_unwind.c expects the new layout.

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 arch/x86/net/bpf_jit_comp.c                   | 101 ++++++++++++++----
 .../selftests/bpf/progs/verifier_unwind.c     |   7 +-
 2 files changed, 87 insertions(+), 21 deletions(-)

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


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 55/73] bpf, x86: Return to cancel_goto at cancel_exit
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (53 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 54/73] bpf, x86: Put the landing of unwind_goto after the function Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 56/73] bpf, arm64: " Kumar Kartikeya Dwivedi
                   ` (17 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

These cases need care:

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 arch/x86/net/bpf_jit_comp.c | 221 ++++++++++++++++++++++++++----------
 include/linux/bpf_unwind.h  |  14 ++-
 2 files changed, 168 insertions(+), 67 deletions(-)

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


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 56/73] bpf, arm64: Return to cancel_goto at cancel_exit
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (54 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 55/73] bpf, x86: Return to cancel_goto at cancel_exit Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 57/73] bpf: Use cancel_exit to leave a frame that the kernel cancels Kumar Kartikeya Dwivedi
                   ` (16 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

Three cases need care:

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 arch/arm64/net/bpf_jit_comp.c | 175 +++++++++++++++++++++++++---------
 1 file changed, 132 insertions(+), 43 deletions(-)

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


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 57/73] bpf: Use cancel_exit to leave a frame that the kernel cancels
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (55 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 56/73] bpf, arm64: " Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:42   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 58/73] bpf: Check that a helper whose callback may unwind has an unwind label Kumar Kartikeya Dwivedi
                   ` (15 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

Emit cancel_exit and cancel_goto instead:

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

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

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

What changes for programs that load today:

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

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

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

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

These cases need care:

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 Documentation/bpf/verifier.rst                |  92 ++++-
 include/linux/bpf_verifier.h                  | 149 ++++++-
 kernel/bpf/const_fold.c                       |  11 +-
 kernel/bpf/core.c                             |  20 +-
 kernel/bpf/fixups.c                           | 374 +++++++++++++-----
 kernel/bpf/pads.c                             | 235 +++++++----
 kernel/bpf/verifier.c                         | 372 +++++++++++------
 .../bpf/progs/pro_epilogue_arena_stack.c      |   2 +-
 .../bpf/progs/verifier_arena_stack.c          |  27 +-
 .../selftests/bpf/progs/verifier_budget.c     |  75 ++--
 .../selftests/bpf/progs/verifier_patch_list.c |   5 +-
 11 files changed, 956 insertions(+), 406 deletions(-)

diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
index ed72a57ed27b..8555d023dbaf 100644
--- a/Documentation/bpf/verifier.rst
+++ b/Documentation/bpf/verifier.rst
@@ -749,7 +749,7 @@ if                                     the loop ends because
 =====================================  =========================================
 k of s is at most 2^32                 k grows in each trip and has a bound;
                                        the largest k + 1 is the *trip count*
-each trip runs ``may_goto``            it leaves the loop after some time or
+each trip runs ``may_goto``            it stops the loop after some time or
                                        some number of trips
 each trip takes from an iterator       an iterator has an end
 none of these holds                    the verifier adds ``may_goto``
@@ -915,10 +915,10 @@ Cancellation
 ============
 
 The kernel *cancels* a program when it has to end the program before the
-program returns by itself: a ``may_goto`` of the verifier is taken, the stack
-check of a recursive function fails, an access to arena faults, or the program
-calls ``bpf_throw()``. Each frame of the program then releases what it holds,
-and the program returns a value that the kernel chooses.
+program returns by itself: a ``may_goto`` is taken, the stack check of a
+recursive function fails, an access to arena faults, or the program calls
+``bpf_throw()``. Each frame of the program then releases what it holds, and the
+program returns a value that the kernel chooses.
 
 An insn at which the kernel can cancel the program is a *site*: one of these
 four insns, or a call whose callee can be cancelled. For each site the verifier
@@ -937,7 +937,9 @@ what the frame holds at the site and leaves the frame::
                                              exit
 
 When the time is up, ``may_goto`` jumps to the pad, and the program ends without
-getting to ``*p``.
+getting to ``*p``. A ``may_goto`` of the program is a site too, where a JIT
+gives it a time limit: when the time is up, the code at its target does not
+run. Where it counts trips, it stays a plain jump.
 
 The pad of a function that the kernel called ends in ``exit``. The main
 function returns the value that the kernel chooses for the program type, see
@@ -947,21 +949,22 @@ errno. It is 0 in the listings here. After ``bpf_throw()`` it is the argument
 of ``bpf_throw()``. If the program has an exception callback, the pad of the
 main function calls it with the value and returns what the callback returns.
 
-The pad of a function that the program called ends in ``unwind_exit``. That
-insn returns to the ``unwind_goto`` after the call, which jumps to the landing
+The pad of a function that the program called ends in ``cancel_exit``. That
+insn returns to the ``cancel_goto`` after the call, which jumps to the landing
 pad of the call in the caller. So the frames are cancelled one by one. When a
-callback is cancelled, its helper returns to the ``unwind_goto`` after its own
-call. The verifier adds the ``unwind_goto`` where the program has none.
+callback is cancelled, its helper returns to the ``cancel_goto`` after its own
+call. Only the verifier emits these two insns. ``cancel_goto`` is an entry of
+the exception table and no code, so a call that returns pays nothing for it.
 
 A function *cannot be cancelled* if it has neither ``exit`` nor a call of
 ``bpf_throw()``, or if the program is loaded without ``CAP_PERFMON``. A
-function that the program calls cannot be cancelled either if the JIT lacks
-``unwind_exit``, which only the JITs of x86-64 and arm64 have, or if its caller
-is a helper that cannot pass a cancellation on. In such a function a loop that
-needs a ``may_goto`` of the verifier, a recursion and ``bpf_throw()`` reject
-the program. An access to arena that faults is skipped there, in every function
-on a JIT without ``unwind_exit``, and where the verifier cannot generate a
-landing pad for it.
+function that the program calls cannot be cancelled either if the JIT lacks the
+two insns, which only the JITs of x86-64 and arm64 have, if its caller is a
+helper that cannot pass a cancellation on, or if its caller cannot be
+cancelled. In such a function a loop that needs a ``may_goto`` of the verifier,
+a recursion and ``bpf_throw()`` reject the program, and a ``may_goto`` of the
+program is a plain jump. An access to arena that faults is skipped there, and
+in every function on a JIT without the two insns.
 
 Landing pads
 ------------
@@ -1022,7 +1025,8 @@ callee returns with it, the caller holds it again, see ``hand_over_refs()``::
                                       pad: r1 = r6
                                            call bpf_task_release
                                            r0 = 0
-                                           unwind_exit
+                                           r2 = 0
+                                           cancel_exit
 
 The landing pad of the call releases nothing, and nothing is added at run time.
 A call hands over a pointer in one of ``R1`` - ``R5`` that the callee reads and
@@ -1078,6 +1082,55 @@ landing pad needs them, in these cases:
 Both are tried only where the program would be rejected without them, see
 `All passes`_.
 
+The program's own unwinding
+---------------------------
+
+A program can unwind by itself, as C++ and Rust do. ``unwind_exit`` leaves a
+function, and the ``unwind_goto`` after the call jumps to a landing pad that
+the program has. "Landing pad" alone is always one that the verifier generates.
+The program's landing pad is code like any other: it can catch and continue
+running. A cancelled program must not continue. So ``cancel_exit`` returns to a
+``cancel_goto`` only, and ``unwind_exit`` to an ``unwind_goto`` only. Where the
+program has an ``unwind_goto`` after a call, the ``cancel_goto`` follows it::
+
+  try {                       call wait
+          v = wait();         unwind_goto catch  <- wait() threw on its own
+  } catch (...) {             cancel_goto pad    <- wait() was cancelled
+          v = 0;              ...
+  }                    catch: ...
+                              exit
+                         pad: r0 = 0
+                              exit
+
+A cancellation enters no landing pad of the program, so the program cannot
+catch it.
+
+Where a callee leaves with ``unwind_exit`` and the caller has no
+``unwind_goto`` after the call, the verifier adds one, with a landing pad that
+releases what the frame holds and leaves with ``unwind_exit`` in turn. What a
+landing pad of the program further up reads depends on the functions in
+between:
+
+=====================================  =========================================
+the function in between                what gets through it
+=====================================  =========================================
+a static function                      ``R0`` as ``unwind_exit`` left it, a
+                                       pointer as well as a number, and ``R2``
+                                       if the function returns two registers
+a global function that has a landing   what that pad leaves at its
+pad of its own at the call             ``unwind_exit``: a number, or a pointer
+                                       to arena
+a global function without one          nothing: ``R0`` is the value that the
+                                       kernel chooses, see
+                                       ``bpf_cancelled_retval()``, and ``R2``
+                                       is 0 if the function returns two
+                                       registers
+=====================================  =========================================
+
+A global function is different because its callers are checked without it and
+only see a number as its return value. A compiler that wants an object to get
+through a global function gives the call there a landing pad of its own.
+
 After an error
 ==============
 
@@ -1451,7 +1504,8 @@ A landing pad has no barrier, and no speculative state is checked on the way to
 one. So only a program that is loaded with ``CAP_PERFMON`` gets landing pads
 and can have ``unwind_exit``, ``unwind_goto`` and ``bpf_throw()``. Without it
 no function can be cancelled, see `Cancellation`_: a loop that needs a
-``may_goto`` of the verifier and a recursion are rejected.
+``may_goto`` of the verifier and a recursion are rejected, and a ``may_goto``
+of the program is a plain jump.
 
 Some mechanisms depend on a capability. The last line is there because the cpu
 can go past the jump that a proof needs:
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index a143c7685cc2..c500504cbfe1 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -454,7 +454,11 @@ static inline u64 bpf_xreg(u32 frameno, u32 xregno)
  */
 /* 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. */
+/*
+ * The kinds of site. An insn has at most one site of a kind. At BPF_SITE_CALL the frame is on the
+ * way of the program's own unwinding. At every other kind the kernel cancels the frame, see
+ * bpf_site_is_cancel(). A call can be a site of both kinds, with a landing pad for each.
+ */
 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 */
@@ -463,8 +467,22 @@ enum bpf_site_kind {
 	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() */
+	/* a call whose callee was cancelled, with or without an unwind_goto of the program */
+	BPF_SITE_CANCEL_CALL,
 };
 
+/* The site is a call whose callee did not return: it left with unwind_exit or was cancelled */
+static inline bool bpf_site_is_call(enum bpf_site_kind kind)
+{
+	return kind == BPF_SITE_CALL || kind == BPF_SITE_CANCEL_CALL;
+}
+
+/* The kernel cancels the frame at a site of @kind */
+static inline bool bpf_site_is_cancel(enum bpf_site_kind kind)
+{
+	return kind != BPF_SITE_CALL;
+}
+
 /* The classes of resources that a landing pad releases */
 enum bpf_pad_class {
 	/* Sections. A state only counts them. */
@@ -513,7 +531,8 @@ enum bpf_stuck_by {
 
 /*
  * The limits of a landing pad. BPF_PAD_MAX_INSNS: a release is two insns per argument, a test and
- * the call. The 5 are one insn that saves the value and four that leave the frame.
+ * the call. The 5 are two insns that save the value, two that load the value, and 'r2 = 0'.
+ * emit_pad() adds the insn that leaves the frame, or the call of the exception callback.
  */
 #define BPF_PAD_MAX_SECTIONS	8
 #define BPF_PAD_MAX_ENTS	8
@@ -602,7 +621,7 @@ struct bpf_pad_plan {
 	/* 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 */
+	/* the subprogs that came back to the call in the way of 'kind', 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 */
@@ -875,8 +894,32 @@ enum {
 	BPF_UNWOUND = 1,
 	/* The same out of a callback. The next insn is the call of its helper once more. */
 	BPF_UNWOUND_CB,
+	/*
+	 * It was cancelled and left with cancel_exit. The state takes no unwind_goto of the
+	 * program: the verifier adds a cancel_goto, see check_unwound_arrival().
+	 */
+	BPF_CANCELLED,
+	BPF_CANCELLED_CB,	/* the same out of a callback */
 };
 
+static inline bool bpf_unwound_cancelled(u8 unwound)
+{
+	return unwound == BPF_CANCELLED || unwound == BPF_CANCELLED_CB;
+}
+
+static inline bool bpf_unwound_cb(u8 unwound)
+{
+	return unwound == BPF_UNWOUND_CB || unwound == BPF_CANCELLED_CB;
+}
+
+/* The mark of a state whose callee was cancelled (@kernel) or left with unwind_exit */
+static inline u8 bpf_unwound_mark(bool kernel, bool cb)
+{
+	if (kernel)
+		return cb ? BPF_CANCELLED_CB : BPF_CANCELLED;
+	return cb ? BPF_UNWOUND_CB : BPF_UNWOUND;
+}
+
 struct bpf_verifier_state {
 	struct bpf_equations equations;
 	/* call stack tracking */
@@ -909,7 +952,7 @@ struct bpf_verifier_state {
 	);
 	u32 curframe;
 	bool in_sleepable;
-	u8 unwound;	/* BPF_UNWOUND or BPF_UNWOUND_CB: the callee did not return */
+	u8 unwound;	/* BPF_UNWOUND, BPF_CANCELLED or a _CB form: 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().
@@ -1310,6 +1353,7 @@ struct bpf_insn_aux_data {
 	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 */
+	u64 cancel_goto_follows:1; /* the verifier added a cancel_goto after the insn */
 	);
 
 	/* what one pass gives to the next pass, see bpf_flow_new_pass() */
@@ -1505,6 +1549,8 @@ struct bpf_subprog_info {
 	 * bpf_mark_subprogs_that_unwind(). Subprog 0 has the bit for such a site, for freplace.
 	 */
 	bool can_unwind: 1;
+	/* the same for cancel_exit: it has a site at which the kernel cancels it */
+	bool can_cancel: 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 */
@@ -1548,8 +1594,8 @@ struct bpf_subprog_info {
 	/* 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: the verifier adds the unwind_goto that its calls lack. Not
-	 * if a helper without an unwind label calls it, see subprog_cannot_unwind().
+	 * It can leave with unwind_exit and cancel_exit: the verifier adds the gotos that its calls
+	 * lack. Not 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() */
@@ -1559,14 +1605,18 @@ struct bpf_subprog_info {
 	 * to, see mark_unwind_above(). For a global subprog the bit goes to the next pass.
 	 */
 	bool did_unwind: 1;
+	/* the same for a cancellation of one of its frames, in this pass or expected */
+	bool did_cancel: 1;
 	/*
 	 * It did so at a site with no other way out, see bpf_pads_must_unwind(). A fault in arena
 	 * 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;
+	bool must_cancel: 1;
 	/* it did so at a site that the program keeps for sure, see site_is_certain() */
 	bool unwinds_for_sure: 1;
+	bool cancels_for_sure: 1;
 	/*
 	 * soft_unwinds: in this pass a frame of it was cancelled at a may_goto of the program or at
 	 * an access to arena.
@@ -1596,7 +1646,7 @@ struct bpf_subprog_info {
 	 */
 	bool arg_refs_differ: 1;
 	/* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */
-	u8 left_at;
+	u16 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. */
@@ -1621,13 +1671,22 @@ struct bpf_subprog_info {
 };
 
 /*
- * 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.
+ * The subprog can leave with cancel_exit: at a landing pad, or at the stack check that a recursive
+ * subprog gets, see bpf_insert_recursion_checks(). Each call of it needs a cancel_goto.
+ */
+static inline bool bpf_subprog_cancels(const struct bpf_subprog_info *sub)
+{
+	return sub->can_cancel || (sub->recursive && sub->bail_unwinds);
+}
+
+/*
+ * The subprog can leave with unwind_exit or with cancel_exit, so a helper that calls it needs an
+ * unwind label, see check_cb_unwind(). A recursive subprog counts before it has such an 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);
+	return sub->can_unwind || bpf_subprog_cancels(sub);
 }
 
 /* Mark @sub as stuck. The log names the first insn that marked it, see bpf_pads_log(). */
@@ -1726,6 +1785,8 @@ struct bpf_insn_patch {
 	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;
+	u32 jmp3;		/* and a third one */
+	u32 jmp3_to;
 	struct bpf_insn orig;	/* the replaced insn when the patch was queued */
 };
 
@@ -2322,7 +2383,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);
+int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass);
 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);
@@ -2330,14 +2391,53 @@ int bpf_insert_recursion_checks(struct bpf_verifier_env *env);
 
 /* pads.c */
 
+bool bpf_subprog_is_global(const struct bpf_verifier_env *env, int subprog);
+
+/*
+ * The landing pad of a site of @kind in @subprog continues the program's own unwinding and leaves
+ * with unwind_exit. In a function that only the kernel calls, it ends the program with exit.
+ */
+static inline bool bpf_pad_rethrows(const struct bpf_verifier_env *env, int subprog,
+				    enum bpf_site_kind kind)
+{
+	const struct bpf_subprog_info *sub = &env->subprog_info[subprog];
+
+	return kind == BPF_SITE_CALL && subprog && !sub->is_exception_cb && sub->bail_unwinds;
+}
+
+/*
+ * Such a pad passes on the R0 that the callee left with, a pointer as well as a number, for a
+ * landing pad of the program in a caller. A global subprog is different: its callers only see a
+ * scalar return value, so its pad leaves with bpf_cancelled_retval().
+ */
+static inline bool bpf_pad_passes_on(const struct bpf_verifier_env *env, int subprog,
+				     enum bpf_site_kind kind)
+{
+	return bpf_pad_rethrows(env, subprog, kind) && !bpf_subprog_is_global(env, subprog);
+}
+
+/*
+ * Is the landing pad of a site of @kind in @subprog entered with the value that the program is to
+ * return? Only in a program with bpf_throw(): at the call of bpf_throw(), and after a call whose
+ * callee did not return. A pad that continues the program's own unwinding has none, see
+ * bpf_pad_passes_on().
+ */
+static inline bool bpf_site_has_value(const struct bpf_verifier_env *env, int subprog,
+				      enum bpf_site_kind kind)
+{
+	if (bpf_pad_rethrows(env, subprog, kind))
+		return false;
+	return env->has_throw && (bpf_site_is_call(kind) || kind == BPF_SITE_THROW);
+}
+
 /*
- * 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(): at the call of bpf_throw(), and after a call whose callee
- * did not return.
+ * The landing pad of a site of @kind in @subprog leaves with cancel_exit. In a function that only
+ * the kernel calls, such as the main program, it leaves with exit.
  */
-static inline bool bpf_site_has_value(const struct bpf_verifier_env *env, enum bpf_site_kind kind)
+static inline bool bpf_pad_cancel_exits(const struct bpf_verifier_env *env, int subprog,
+					enum bpf_site_kind kind)
 {
-	return env->has_throw && (kind == BPF_SITE_CALL || kind == BPF_SITE_THROW);
+	return bpf_site_is_cancel(kind) && subprog && env->subprog_info[subprog].bail_unwinds;
 }
 
 /* The register that has the value when the landing pad of a site of @kind is entered */
@@ -2349,7 +2449,9 @@ static inline int bpf_site_value_reg(enum bpf_site_kind kind)
 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);
+int bpf_pad_note_callee(struct bpf_verifier_env *env, int call_idx, int callee,
+			enum bpf_site_kind kind);
+bool bpf_pad_passes_r2(struct bpf_verifier_env *env, int subprog, enum bpf_site_kind kind);
 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);
@@ -2379,7 +2481,7 @@ 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);
+int 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 insn_idx);
@@ -2454,15 +2556,20 @@ static inline u32 bpf_frame_insn_idx(const struct bpf_verifier_state *st, u32 fr
 
 /*
  * 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().
+ * a landing pad that is not in the program yet and that reads R0, or R0 and R2: see
+ * bpf_site_has_value() and bpf_pad_passes_on().
  */
 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)
+	if (!st->unwound || frame != st->curframe)
+		return live;
+	if (env->has_throw)
 		live |= BIT(BPF_REG_0);
+	if (!bpf_unwound_cancelled(st->unwound))
+		live |= BIT(BPF_REG_0) | BIT(BPF_REG_2);
 	return live;
 }
 
diff --git a/kernel/bpf/const_fold.c b/kernel/bpf/const_fold.c
index 17d208f1ed0e..2a5f15d22474 100644
--- a/kernel/bpf/const_fold.c
+++ b/kernel/bpf/const_fold.c
@@ -300,13 +300,12 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 			struct const_arg_info *c = &ci[r];
 
 			/*
-			 * The revisit of a call with a callback that unwound
-			 * carries the r0 of the callback, see check_helper_call():
-			 * r0 is no constant of that insn.
+			 * A callback that unwinds goes back to the call of its helper with its own
+			 * R0, see check_helper_call(), so R0 is no constant before such a call. An
+			 * unwind_goto of the program need not follow: a generated pad passes R0 on
+			 * too, see bpf_pad_passes_on().
 			 */
-			if (r == BPF_REG_0 && i + 1 < insn_cnt &&
-			    bpf_is_sync_callback_calling_insn(&insns[i]) &&
-			    (bpf_is_unwind_goto(&insns[i + 1]) || env->has_throw))
+			if (r == BPF_REG_0 && bpf_is_sync_callback_calling_insn(&insns[i]))
 				continue;
 			switch (c->state) {
 			case CONST_ARG_CONST: {
diff --git a/kernel/bpf/core.c b/kernel/bpf/core.c
index 25fd3213d000..288963919afd 100644
--- a/kernel/bpf/core.c
+++ b/kernel/bpf/core.c
@@ -437,6 +437,8 @@ static int patch_insn_target(const struct bpf_patch_image *img, const struct bpf
 		tgt = p->jmp_to;
 	} else if (idx + 1 == p->jmp2) {
 		tgt = p->jmp2_to;
+	} else if (idx + 1 == p->jmp3) {
+		tgt = p->jmp3_to;
 	} else if (idx == p->self) {
 		tgt = p->off + rel + 1;
 	} else {
@@ -561,6 +563,7 @@ int __bpf_patch_list_insert(struct bpf_patch_list *pl, const struct bpf_prog *pr
 		p->self += cnt;
 		p->jmp += p->jmp ? cnt : 0;
 		p->jmp2 += p->jmp2 ? cnt : 0;
+		p->jmp3 += p->jmp3 ? cnt : 0;
 	}
 	memcpy(insn, insns, cnt * sizeof(*insns));
 	p->len += cnt;
@@ -571,7 +574,7 @@ int __bpf_patch_list_insert(struct bpf_patch_list *pl, const struct bpf_prog *pr
 /*
  * 'insn' of the last patch goes to insn 'to' of the old image, however far that is.
  * With 'back' it goes to the last insns of the patch of insn 'to - 1'.
- * A patch has two such jumps at most, and the second one has no 'back'.
+ * A patch has three such jumps at most, and only the first one has 'back'.
  */
 void bpf_patch_list_jump(struct bpf_patch_list *pl, const struct bpf_insn *insn, u32 to, u32 back)
 {
@@ -580,13 +583,18 @@ void bpf_patch_list_jump(struct bpf_patch_list *pl, const struct bpf_insn *insn,
 
 	if (p->jmp) {
 		/*
-		 * There is no room for a third one, nor for 'back' of the second one. Such a jump
-		 * goes out of the program: bpf_patch_list_build() fails for it.
+		 * A patch has no room for a fourth jump, nor for 'back' of a later one. Make such a
+		 * jump lead out of the program, so that bpf_patch_list_build() fails.
 		 */
-		if (WARN_ON_ONCE(p->jmp2 || back))
+		if (WARN_ON_ONCE(p->jmp3 || back))
 			to = U32_MAX;
-		p->jmp2 = jmp;
-		p->jmp2_to = to;
+		if (p->jmp2) {
+			p->jmp3 = jmp;
+			p->jmp3_to = to;
+		} else {
+			p->jmp2 = jmp;
+			p->jmp2_to = to;
+		}
 		return;
 	}
 	p->jmp = jmp;
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 1ce65bc8ca46..7a913f5b5df6 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -576,13 +576,22 @@ int bpf_patch_list_commit(struct bpf_verifier_env *env)
 	return err;
 }
 
-/* The insn that subprog @s leaves with when it has to stop: unwind_exit if it can do that */
-static struct bpf_insn unwind_exit_insn(struct bpf_verifier_env *env, int s)
+/*
+ * The insn that ends a landing pad of subprog @s at a site of @kind. A cancelled frame leaves with
+ * cancel_exit. A frame that the program's own unwinding passes through (BPF_SITE_CALL) leaves with
+ * unwind_exit. A function that cannot leave that way leaves with exit: the kernel called it.
+ */
+static struct bpf_insn unwind_exit_insn(struct bpf_verifier_env *env, int s,
+					enum bpf_site_kind kind)
 {
 	struct bpf_subprog_info *sub = &env->subprog_info[s];
 	struct bpf_insn insn = BPF_EXIT_INSN();
 
-	if (sub->bail_unwinds) {
+	if (bpf_pad_cancel_exits(env, s, kind)) {
+		insn.src_reg = BPF_CANCEL_EXIT;
+		sub->can_cancel = true;
+		env->prog->jit_required = 1;
+	} else if (!bpf_site_is_cancel(kind) && sub->bail_unwinds) {
 		insn.src_reg = BPF_UNWIND_EXIT;
 		sub->can_unwind = true;
 		env->prog->jit_required = 1;
@@ -590,15 +599,16 @@ static struct bpf_insn unwind_exit_insn(struct bpf_verifier_env *env, int s)
 	return insn;
 }
 
-/* How subprog @s leaves when it has to stop, see unwind_frame(). Returns the length. */
+/* Emit how subprog @s leaves when its recursion check fails. Returns the number of insns. */
 static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn *buf)
 {
 	int n = 0;
 
 	buf[n++] = BPF_MOV64_IMM(BPF_REG_0, bpf_cancelled_retval(env));
-	if (bpf_ret_reg_pair(env, s))
+	/* R2 is 0 as at the end of a landing pad, see bpf_pad_insns() */
+	if (bpf_pad_cancel_exits(env, s, BPF_SITE_RECURSION) || bpf_ret_reg_pair(env, s))
 		buf[n++] = BPF_MOV64_IMM(BPF_REG_2, 0);
-	buf[n++] = unwind_exit_insn(env, s);
+	buf[n++] = unwind_exit_insn(env, s, BPF_SITE_RECURSION);
 	return n;
 }
 
@@ -608,11 +618,12 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
  * gets one, see frame_cannot_unwind().
  * The main program returns what the exception callback makes of the value. The pad has no index
  * yet: bpf_insert_sites() sets the offset of the call. The callback is not called a second time:
- * its unwind_exit gets to the exit of the pad like its exit does. unwind_goto says so, to
- * bpf_unwind_target(): a return address in a program without an entry is a lost unwind_exit.
- * Only a callback that can leave with unwind_exit gets it, and such a program needs a JIT that
- * knows both insns already. A pad of any other program is plain BPF: the interpreter and the other
- * JITs run it. bpf_mark_subprogs_that_unwind() ran, so it is known which callback that is.
+ * its unwind_exit gets to the exit of the pad like its exit does, and so does its cancel_exit.
+ * unwind_goto and cancel_goto say so, to bpf_unwind_target() and bpf_cancel_target(): a return
+ * address in a program without an entry is a lost unwind_exit or cancel_exit. Only a callback that
+ * can leave that way gets the insn, and such a program needs a JIT that knows it already. A pad of
+ * any other program is plain BPF: the interpreter and the other JITs run it.
+ * bpf_mark_subprogs_that_unwind() ran, so it is known which callback that is.
  * Returns the number of insns, BPF_PAD_MAX_INSNS + 2 at most.
  */
 static int emit_pad(struct bpf_verifier_env *env, int s, const struct bpf_pad_plan *plan,
@@ -623,11 +634,20 @@ static int emit_pad(struct bpf_verifier_env *env, int s, const struct bpf_pad_pl
 
 	n += bpf_pad_insns(env, plan, s, buf + n, aux + n);
 	if (!s && cb) {
+		bool cancels = bpf_subprog_cancels(&env->subprog_info[cb]);
+
 		buf[n++] = BPF_CALL_REL(0);
-		if (bpf_subprog_unwinds(&env->subprog_info[cb]))
-			buf[n++] = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0, 0);
+		/*
+		 * Both lead to the exit, so the callback is not called a second time. No jump may
+		 * lead to a cancel_goto after an unwind_goto, so the unwind_goto skips it.
+		 */
+		if (env->subprog_info[cb].can_unwind)
+			buf[n++] = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0,
+						cancels);
+		if (cancels)
+			buf[n++] = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_CANCEL_GOTO, 0, 0);
 	}
-	buf[n++] = unwind_exit_insn(env, s);
+	buf[n++] = unwind_exit_insn(env, s, plan->kind);
 	return n;
 }
 
@@ -653,6 +673,13 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 			if (env->subprog_info[s].can_unwind)
 				return true;
 		return false;
+	case BPF_SITE_CANCEL_CALL:
+		if (!plan->visited)
+			return false;
+		bpf_pad_for_each_callee(plan, s)
+			if (env->subprog_info[s].can_cancel)
+				return true;
+		return false;
 	case BPF_SITE_FAULT:
 		return !env->insn_aux_data[i].fault_skips;
 	case BPF_SITE_MAY_GOTO:
@@ -663,34 +690,53 @@ 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(). The main program leaves with exit: it is
- * marked for bpf_check_attach_target(), see bpf_insert_sites().
+ * trip count after all has no may_goto. Find the subprogs that get cancel_exit: those that are left
+ * at a site where the kernel unwinds. And those that get unwind_exit: they have a call with no
+ * unwind_goto, to which unwind_exit of the program comes back. A call is a site if it calls one of
+ * them: of one kind, of the other, or of both. The main pass asks the same when a global subprog
+ * unwinds, see settle_late_unwinds(). The main program leaves with exit: it is marked for
+ * bpf_check_attach_target(), see bpf_insert_sites().
  */
-void bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env)
+int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)
 {
 	const struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	const struct bpf_pad_plan *plan;
 	struct bpf_subprog_info *sub;
-	bool changed;
-	int i, s;
+	bool changed, unwinds, cancels;
+	int i, k, s, err;
 
 	do {
 		changed = false;
-		for (s = 0; s < env->subprog_cnt; s++) {
+		/* callees come first: only callx and a cycle of calls take more than one round */
+		err = in_pass ? bpf_add_cost_and_check(env, env->prog->len, BPF_COST_SCAN) :
+		      bpf_must_abort() ? -EINTR : 0;
+		if (err)
+			return err;
+		for (k = 0; k < env->subprog_cnt; k++) {
+			s = env->subprog_topo_order[k];
 			sub = &env->subprog_info[s];
-			if (sub->can_unwind || (s && !sub->bail_unwinds))
+			if ((sub->can_unwind && sub->can_cancel) || (s && !sub->bail_unwinds))
 				continue;
-			for (i = sub->start; i < sub[1].start && !sub->can_unwind; i++) {
-				sub->can_unwind = aux[i].loop_guard ||
-						  (aux[i].fault_empty && !aux[i].fault_skips);
-				for (plan = aux[i].pad_plans; plan; plan = plan->next)
-					sub->can_unwind |= bpf_site_is_used(env, i, plan);
+			unwinds = sub->can_unwind;
+			cancels = sub->can_cancel;
+			for (i = sub->start; i < sub[1].start && !(unwinds && cancels); i++) {
+				cancels |= aux[i].loop_guard ||
+					   (aux[i].fault_empty && !aux[i].fault_skips);
+				for (plan = aux[i].pad_plans; plan; plan = plan->next) {
+					if (!bpf_site_is_used(env, i, plan))
+						continue;
+					if (bpf_site_is_cancel(plan->kind))
+						cancels = true;
+					else
+						unwinds = true;
+				}
 			}
-			changed |= sub->can_unwind;
+			changed |= unwinds != sub->can_unwind || cancels != sub->can_cancel;
+			sub->can_unwind = unwinds;
+			sub->can_cancel = cancels;
 		}
 	} while (changed);
+	return 0;
 }
 
 /* Does the site of @plan at insn @i get a landing pad after its subprog? */
@@ -770,50 +816,93 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 	return cnt;
 }
 
-/* The plan of insn @i if it is a site that has unwind_goto after it: a call, an access to arena */
-static const struct bpf_pad_plan *unwind_goto_plan(struct bpf_verifier_env *env, int i)
+/* The plan of the site of @kind at insn @i if it has unwind_goto or cancel_goto after it */
+static const struct bpf_pad_plan *goto_plan(struct bpf_verifier_env *env, int i,
+					    enum bpf_site_kind kind)
 {
 	const struct bpf_insn_aux_data *aux = &env->insn_aux_data[i];
-	const struct bpf_pad_plan *plan;
+	const struct bpf_pad_plan *plan = bpf_pad_plan(aux, kind);
 
-	plan = bpf_pad_plan(aux, BPF_SITE_CALL) ?: bpf_pad_plan(aux, BPF_SITE_FAULT);
 	return plan && bpf_site_is_used(env, i, plan) && !aux->fault_unwinds ? plan : NULL;
 }
 
 /*
- * Add unwind_goto after the calls that are sites, see check_unwound_arrival(), and after the
- * accesses to arena that are, see check_arena_site(). Nothing stands between such an insn and its
- * unwind_goto, and jumps to the insn that follows it go past unwind_goto.
- * 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.
+ * Add unwind_goto and cancel_goto after the sites, now that the pads are in the program. @added is
+ * the number of insns appended to each subprog, @stubbed the number of its unwind_gotos with a
+ * stub. An access to arena that is a site gets an unwind_goto, and so does a call without one to
+ * which unwind_exit of a callee comes back. A call whose callee can be cancelled gets a
+ * cancel_goto, after its unwind_goto:
  *
- * 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.
+ *	call foo		call foo		call foo
+ *	cancel_goto cancel_pad	unwind_goto pad		unwind_goto P	of the program
+ *				cancel_goto cancel_pad	cancel_goto cancel_pad
+ *
+ * unwind_goto of the program takes the form that has 32 bits there: a jump that is taken around
+ * its target would put two insns between it and cancel_goto. Where no state got to that unwind_goto
+ * it is dead code, and a trap is going to stand in its place, or nothing at all: cancel_goto goes
+ * in front of it, behind the call.
  */
 static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added)
 {
 	struct bpf_insn unwind_goto = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0, 0);
+	struct bpf_insn cancel_goto = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_CANCEL_GOTO, 0, 0);
 	struct bpf_patch_list *pl = &env->patch_list;
+	const struct bpf_pad_plan *plan, *cancel_plan;
 	const struct bpf_subprog_info *sub;
-	const struct bpf_pad_plan *plan;
 	const struct bpf_insn_patch *p;
-	int i, s, err;
+	struct bpf_insn *insn;
+	int i, s, pads, err;
 
 	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++) {
-			plan = unwind_goto_plan(env, i);
-			if (!plan)
+		pads = sub[1].start - added[s];
+		for (i = sub->start; added[s] && i < pads; i++) {
+			plan = goto_plan(env, i, BPF_SITE_CALL) ?: goto_plan(env, i, BPF_SITE_FAULT);
+			cancel_plan = goto_plan(env, i, BPF_SITE_CANCEL_CALL);
+			if (!plan && !cancel_plan)
+				continue;
+			if (bpf_must_abort())
+				return -EINTR;
+			insn = &env->prog->insnsi[i + 1];
+			if (cancel_plan && bpf_is_unwind_goto(insn) &&
+			    env->insn_aux_data[i + 1].seen) {
+				/* the program has unwind_goto there: no plan for unwind_exit */
+				unwind_goto.imm = 0;
+				insn = __bpf_patch_list_add(pl, env->prog, i + 1, &unwind_goto, 1);
+				if (IS_ERR(insn))
+					return PTR_ERR(insn);
+				bpf_patch_list_jump(pl, insn,
+						    i + 2 + bpf_jmp_offset(&env->prog->insnsi[i + 1]),
+						    0);
+				err = bpf_patch_list_append(env, i + 1, &cancel_goto, 1);
+				if (err)
+					return err;
+				p = &pl->patches[pl->cnt - 1];
+				bpf_patch_list_jump(pl, &pl->insns[p->start + p->len - 1],
+						    pads + cancel_plan->pad, 0);
+				env->insn_aux_data[i].cancel_goto_follows = true;
 				continue;
+			}
 			/* what is appended to the site is not dead code, the next insn may be */
-			err = bpf_patch_list_append(env, i, &unwind_goto, 1);
-			if (err)
-				return err;
-			/* for bpf_check_unwind_gotos() */
-			env->insn_aux_data[i].unwind_goto_follows = true;
-			p = &pl->patches[pl->cnt - 1];
-			bpf_patch_list_jump(pl, &pl->insns[p->start + p->len - 1],
-					    sub[1].start - added[s] + plan->pad, 0);
+			if (plan) {
+				err = bpf_patch_list_append(env, i, &unwind_goto, 1);
+				if (err)
+					return err;
+				/* for bpf_check_unwind_gotos() */
+				env->insn_aux_data[i].unwind_goto_follows = true;
+				p = &pl->patches[pl->cnt - 1];
+				bpf_patch_list_jump(pl, &pl->insns[p->start + p->len - 1],
+						    pads + plan->pad, 0);
+			}
+			if (cancel_plan) {
+				err = bpf_patch_list_append(env, i, &cancel_goto, 1);
+				if (err)
+					return err;
+				env->insn_aux_data[i].cancel_goto_follows = true;
+				p = &pl->patches[pl->cnt - 1];
+				bpf_patch_list_jump(pl, &pl->insns[p->start + p->len - 1],
+						    pads + cancel_plan->pad, 0);
+			}
 		}
 	}
 	return bpf_patch_list_commit(env);
@@ -949,8 +1038,11 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 		err = -ENOMEM;
 		goto out;
 	}
-	bpf_mark_subprogs_that_unwind(env);
-	env->prog->aux->can_unwind = env->subprog_info[0].can_unwind;
+	err = bpf_mark_subprogs_that_unwind(env, false);
+	if (err)
+		goto out;
+	env->prog->aux->can_unwind = env->subprog_info[0].can_unwind ||
+				     env->subprog_info[0].can_cancel;
 	for (s = 0; s < env->subprog_cnt && !err; s++) {
 		sub = &env->subprog_info[s];
 		cnt = collect_pads(env, s, new, pad_aux, &pads);
@@ -1455,7 +1547,7 @@ int bpf_insert_arena_stack(struct bpf_verifier_env *env)
 	struct bpf_insn *insn_buf = env->insn_buf, *patch, *insn;
 	struct bpf_prog_aux *aux = env->prog->aux;
 	struct bpf_insn ld_aux[2] = { BPF_LD_IMM64(BPF_REG_1, (long)aux) };
-	int i, cur = 0, err;
+	int i, cur = 0, err, reg;
 
 	if (!env->uses_arena_sp)
 		return 0;
@@ -1486,11 +1578,15 @@ int bpf_insert_arena_stack(struct bpf_verifier_env *env)
 				*patch++ = BPF_ALU32_IMM(BPF_ADD, BPF_REG_ARENA_SP,
 							 -(int)subprogs[cur].arena_stack_depth);
 			if (!cur || subprogs[cur].arena_stack_entry) {
-				/* r1-r5 are free */
+				/*
+				 * r1-r5 are free, except R2 before cancel_exit: it is 0 there, see
+				 * bpf_pad_insns(), and stays 0 on both paths.
+				 */
+				reg = bpf_is_cancel_exit(insn) ? BPF_REG_1 : BPF_REG_2;
 				*patch++ = BPF_JMP32_IMM(BPF_JSET, BPF_REG_ARENA_SP,
 							 BPF_ARENA_STACK_SLOW, 5);
-				patch = emit_arena_stack_percpu(env, patch, BPF_REG_2);
-				*patch++ = BPF_ST_MEM(BPF_DW, BPF_REG_2, CPU_STACK_OFF(busy), 0);
+				patch = emit_arena_stack_percpu(env, patch, reg);
+				*patch++ = BPF_ST_MEM(BPF_DW, reg, CPU_STACK_OFF(busy), 0);
 				*patch++ = *insn;
 				*patch++ = BPF_MOV64_REG(BPF_REG_6, BPF_REG_0);
 				*patch++ = ld_aux[0];
@@ -1498,6 +1594,8 @@ int bpf_insert_arena_stack(struct bpf_verifier_env *env)
 				*patch++ = BPF_MOV64_REG(BPF_REG_2, BPF_REG_ARENA_SP);
 				*patch++ = BPF_EMIT_KERNEL_CALL(bpf_arena_stack_put);
 				*patch++ = BPF_MOV64_REG(BPF_REG_0, BPF_REG_6);
+				if (bpf_is_cancel_exit(insn))
+					*patch++ = BPF_MOV64_IMM(BPF_REG_2, 0);
 			}
 			if (patch != insn_buf)
 				*patch++ = *insn;
@@ -2215,7 +2313,9 @@ static int jit_subprogs(struct bpf_verifier_env *env)
 		func[i]->aux->tail_call_reachable = env->subprog_info[i].tail_call_reachable;
 		func[i]->aux->changes_pkt_data = env->subprog_info[i].changes_pkt_data;
 		func[i]->aux->might_sleep = env->subprog_info[i].might_sleep;
-		func[i]->aux->can_unwind = env->subprog_info[i].can_unwind;
+		/* bpf_check_attach_target() asks whether it can unwind, not with which insn */
+		func[i]->aux->can_unwind = env->subprog_info[i].can_unwind ||
+					   env->subprog_info[i].can_cancel;
 		func[i]->aux->in_recursion = env->subprog_info[i].in_recursion;
 		func[i]->aux->token = prog->aux->token;
 		func[i] = bpf_int_jit_compile(env, func[i]);
@@ -2416,25 +2516,53 @@ static bool can_have_unwind_goto(const struct bpf_insn *insn)
 }
 
 /*
- * unwind_goto is no code. It is an entry of the exception table, which a JIT keys at the end of
- * the insn in front: a call, or an access to arena. No pass may put anything between the two.
- * After a call that would be a lost unwind_exit, which bpf_unwind_target() warns about when it
- * happens. After an access nothing would tell: a fault finds no entry, see
- * bpf_fault_unwind_target(), and the access is skipped as if no pad had been planned for it.
- * So look at the insns once they are final, from both sides: unwind_goto has such an insn in
- * front, and such an insn that the verifier gave unwind_goto still has it behind. An insn that a
- * pass has replaced by other code is no site any more: the inlined bpf_loop() has unwind_goto of
- * its own, see inline_bpf_loop().
- * cancel_goto is the same for cancel_exit. It stands behind a call, or behind unwind_goto of a
- * call. Not behind an access to arena: the handler of a fault looks for unwind_goto there.
- * cancel_exit is in no frame that the kernel calls: the main program leaves with exit.
+ * Is @insn a jump with an offset, see bpf_jmp_offset()? That includes may_goto, unwind_goto and
+ * cancel_goto, but not gotox and the tail call insn of bpf_do_misc_fixups(), which have none.
+ */
+static bool insn_goes_to(const struct bpf_insn *insn)
+{
+	u8 class = BPF_CLASS(insn->code), op = BPF_OP(insn->code);
+
+	if (class != BPF_JMP && class != BPF_JMP32)
+		return false;
+	return op != BPF_CALL && op != BPF_EXIT && op != BPF_TAIL_CALL &&
+	       !(op == BPF_JA && BPF_SRC(insn->code) == BPF_X);
+}
+
+/*
+ * Check unwind_goto and cancel_goto once the insns are final. A JIT makes each an exception table
+ * entry that is keyed at the end of the insn before it. If a pass put an insn between the two,
+ * unwind_exit or cancel_exit of a callee would find no entry, and a fault in an access to arena
+ * would be skipped without a warning. So it is a verifier bug unless:
+ *   - unwind_goto follows a call or an access to arena, and cancel_goto follows a call or the
+ *     unwind_goto of a call.
+ *   - A call or an access that the verifier gave one of the two still has it. An insn that a pass
+ *     replaced is not checked: the inlined bpf_loop() has gotos of its own.
+ *   - cancel_exit is not in the main program, which the kernel calls.
+ *   - No unwind_goto or cancel_goto jumps to one of the two, and no jump leads to a cancel_goto
+ *     after an unwind_goto. A JIT may emit a landing where the insn is, which redoes the code
+ *     after the native call, and a jump to it would run that code twice.
  */
 int bpf_check_unwind_gotos(struct bpf_verifier_env *env)
 {
-	const struct bpf_insn *insn = env->prog->insnsi;
-	int i, len = env->prog->len;
+	const struct bpf_insn *insns = env->prog->insnsi, *insn = insns;
+	int i, to, len = env->prog->len;
+	bool bad;
 
 	for (i = 0; i < len; i++, insn++) {
+		if (insn_goes_to(insn)) {
+			to = i + 1 + bpf_jmp_offset(insn);
+			bad = to < 0 || to >= len;
+			if (!bad && bpf_is_pad_goto(insn))
+				bad = bpf_is_pad_goto(&insns[to]);
+			else if (!bad)
+				bad = to && bpf_is_cancel_goto(&insns[to]) &&
+				      bpf_is_unwind_goto(&insns[to - 1]);
+			if (verifier_bug_if(bad, env,
+					    "insn %d goes to unwind_goto or cancel_goto at insn %d",
+					    i, to))
+				return -EFAULT;
+		}
 		if (bpf_is_unwind_goto(insn) &&
 		    verifier_bug_if(!i || !can_have_unwind_goto(insn - 1), env,
 				    "unwind_goto at insn %d follows no call and no access to arena",
@@ -2454,6 +2582,13 @@ int bpf_check_unwind_gotos(struct bpf_verifier_env *env)
 		    verifier_bug_if(i + 1 == len || !bpf_is_unwind_goto(insn + 1), env,
 				    "insn %d has lost its unwind_goto", i))
 			return -EFAULT;
+		if (env->insn_aux_data[i].cancel_goto_follows && is_call(insn) &&
+		    verifier_bug_if(i + 1 == len ||
+				    !(bpf_is_cancel_goto(insn + 1) ||
+				      (bpf_is_unwind_goto(insn + 1) && i + 2 < len &&
+				       bpf_is_cancel_goto(insn + 2))), env,
+				    "insn %d has lost its cancel_goto", i))
+			return -EFAULT;
 	}
 	return 0;
 }
@@ -3659,40 +3794,59 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 }
 
 /*
- * When the callback can unwind and unwind_goto follows the call of bpf_loop,
- * unwind_goto follows the call of the callback, and the pad restores r6-r8 and
- * jumps to the pad after the call of bpf_loop with the r0 of the callback, which
- * the verifier has checked with the state of that r0. The callback may have no
- * unwind_exit yet: bpf_insert_recursion_checks() adds the one of the check of a
- * recursive callback when the loop is inlined already. That pad has to be one the
- * verifier saw: a loop of no rounds never runs its callback, and an unwind_exit
- * may sit on a path never taken, so the pad can be dead, and dead code is
- * removed after the inlining, which sends a jump into it to whatever follows.
- * The unwind_goto that followed the call of bpf_loop doesn't follow a call
- * anymore and becomes a no-op jump either way. A loop of no rounds may have no
- * unwind_goto at all, since the verifier asked for none, and then the insn after
- * the call is some other insn.
+ * Inline the call of bpf_loop() at @position. The inlined loop has no helper that passes on a
+ * callback that unwinds or is cancelled, so it does that itself. '+' marks what unwind_exit needs:
+ *
+ *		if r1 <= BPF_MAX_LOOPS goto 1f
+ *		r0 = -E2BIG
+ *		goto end
+ * +	pad:	fill r6 - r8
+ * +		gotol <target of the unwind_goto after the call of bpf_loop>
+ *	1:	spill r6 - r8
+ *		...
+ *		call cb
+ * +		unwind_goto pad
+ *		...
+ *		fill r6 - r8
+ *	end:
+ *
+ * The pad restores R6-R8, which hold the variables of the loop, and keeps R0 as the callback left
+ * it. A cancel_goto after the call of bpf_loop() gives a second pad and a cancel_goto after the
+ * call of the callback. The pad for unwind_goto is added only if a state reached its target: a
+ * target that is dead code is removed after the inlining. bpf_subprog_cancels() is asked because
+ * a recursive callback gets its cancel_exit later, in bpf_insert_recursion_checks().
  */
 static int inline_bpf_loop(struct bpf_verifier_env *env, int position,
 			   s32 stack_base, u32 callback_subprogno)
 {
+	const struct bpf_subprog_info *cb = &env->subprog_info[callback_subprogno];
 	s32 r6_offset = stack_base + 0 * BPF_REG_SIZE;
 	s32 r7_offset = stack_base + 1 * BPF_REG_SIZE;
 	s32 r8_offset = stack_base + 2 * BPF_REG_SIZE;
 	int reg_loop_max = BPF_REG_6;
 	int reg_loop_cnt = BPF_REG_7;
 	int reg_loop_ctx = BPF_REG_8;
-	struct bpf_insn *unwind_goto = &env->prog->insnsi[position + 1];
+	struct bpf_insn *unwind_goto = &env->prog->insnsi[position + 1], *cancel_goto;
 	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]) &&
+	bool pad = has_unwind_goto && cb->can_unwind &&
 		   env->insn_aux_data[position + 2 + pad_off].seen;
+	bool has_cancel_goto, cancel_pad;
+	/* the target of each pad, an insn of the old image */
+	int to[2], npads = 0, i, off;
 
 	struct bpf_insn *insn_buf = env->insn_buf;
 	struct bpf_insn *last;
 	u32 cnt = 0, call;
 
+	cancel_goto = unwind_goto + has_unwind_goto;
+	has_cancel_goto = bpf_is_cancel_goto(cancel_goto);
+	cancel_pad = has_cancel_goto && bpf_subprog_cancels(cb);
+	if (pad)
+		to[npads++] = position + 2 + pad_off;
+	if (cancel_pad)
+		to[npads++] = cancel_goto - env->prog->insnsi + 1 + bpf_jmp_offset(cancel_goto);
+
 	/* This represents an inlined version of bpf_iter.c:bpf_loop,
 	 * be careful to modify this code in sync.
 	 */
@@ -3700,14 +3854,11 @@ static int inline_bpf_loop(struct bpf_verifier_env *env, int position,
 	/* Return error and jump to the end of the patch if
 	 * expected number of iterations is too big.
 	 */
-	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, pad ? 6 : 2);
+	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JLE, BPF_REG_1, BPF_MAX_LOOPS, 2 + 4 * npads);
 	insn_buf[cnt++] = BPF_MOV64_IMM(BPF_REG_0, -E2BIG);
-	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, pad ? 21 : 16);
-	if (pad) {
-		/*
-		 * The pad: r0 is what the callback unwound with. Nothing falls through to this
-		 * place, so no jump around the pad is needed.
-		 */
+	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JA, 0, 0, 16 + 5 * npads);
+	for (i = 0; i < npads; i++) {
+		/* A pad keeps R0 as the callback left it. No insn falls through to a pad. */
 		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_6, BPF_REG_10, r6_offset);
 		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_7, BPF_REG_10, r7_offset);
 		insn_buf[cnt++] = BPF_LDX_MEM(BPF_DW, BPF_REG_8, BPF_REG_10, r8_offset);
@@ -3725,19 +3876,25 @@ static int inline_bpf_loop(struct bpf_verifier_env *env, int position,
 	/* loop header,
 	 * if reg_loop_cnt >= reg_loop_max skip the loop body
 	 */
-	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, pad ? 6 : 5);
+	insn_buf[cnt++] = BPF_JMP_REG(BPF_JGE, reg_loop_cnt, reg_loop_max, 5 + npads);
 	/* callback call, the offset is set below */
 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_1, reg_loop_cnt);
 	insn_buf[cnt++] = BPF_MOV64_REG(BPF_REG_2, reg_loop_ctx);
 	call = cnt;
 	insn_buf[cnt++] = BPF_CALL_REL(0);
-	if (pad)
-		/* to the pad above when the callback left with unwind_exit */
-		insn_buf[cnt++] = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, BPF_UNWIND_GOTO, -15, 0);
+	/* The gotos to the pads above: the first pad is insn 3 of the patch, each has 4 insns */
+	if (pad) {
+		off = 3 - (int)cnt - 1;
+		insn_buf[cnt++] = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, BPF_UNWIND_GOTO, off, 0);
+	}
+	if (cancel_pad) {
+		off = 3 + 4 * (npads - 1) - (int)cnt - 1;
+		insn_buf[cnt++] = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_CANCEL_GOTO, 0, off);
+	}
 	/* increment loop counter */
 	insn_buf[cnt++] = BPF_ALU64_IMM(BPF_ADD, reg_loop_cnt, 1);
 	/* jump to loop header if callback returned 0 */
-	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, pad ? -7 : -6);
+	insn_buf[cnt++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_0, 0, -6 - npads);
 	/* return value of bpf_loop,
 	 * set R0 to the number of iterations
 	 */
@@ -3754,15 +3911,16 @@ static int inline_bpf_loop(struct bpf_verifier_env *env, int position,
 	bpf_patch_list_jump(&env->patch_list, last - (cnt - 1 - call),
 			    env->subprog_info[callback_subprogno].start, 0);
 	/*
-	 * insn_buf[6] goes where the unwind_goto after the call of bpf_loop goes, whichever side
-	 * of the call that is. A long jump, since an unwind_goto may jump as far as a jump can.
+	 * The last insn of each pad jumps where the unwind_goto or the cancel_goto after the call
+	 * of bpf_loop() jumps. It is a gotol, because that target can be far.
 	 */
-	if (pad)
-		bpf_patch_list_jump(&env->patch_list, last - (cnt - 1 - 6),
-				    position + 2 + pad_off, 0);
-	/* The unwind_goto after the call of bpf_loop follows no call anymore. */
+	for (i = 0; i < npads; i++)
+		bpf_patch_list_jump(&env->patch_list, last - (cnt - 1 - (6 + 4 * i)), to[i], 0);
+	/* The unwind_goto and the cancel_goto after the call of bpf_loop follow no call anymore. */
 	if (has_unwind_goto)
 		*unwind_goto = BPF_JMP_A(0);
+	if (has_cancel_goto)
+		*cancel_goto = BPF_JMP_A(0);
 	return 0;
 }
 
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index ffdae8ba5c35..4ab3df74b97a 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -9,7 +9,7 @@
  *   - 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 call whose callee was cancelled (BPF_SITE_CANCEL_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
  * time is up, and the program ends without reading '*p'. '+' marks what the verifier adds:
@@ -65,7 +65,7 @@
  *	if (!t)					   +	   *(u64 *)(r10 - 8) = r0
  *		t = bpf_get_current_task_btf();		   ...
  *	v = wait(t);					   call wait
- *	if (own)				   +	   unwind_goto pad
+ *	if (own)				   +	   cancel_goto pad
  *		bpf_task_release(t);			   ...
  *						   +	   ax = *(u64 *)(r10 - 8)
  *						   +	   if ax != r1 goto +1
@@ -85,25 +85,31 @@
  * pads then release that group through the slots alone.
  *
  * The frames of a program are cancelled one at a time. The pad of a function that the program calls
- * ends in unwind_exit. That returns to the unwind_goto after the call, which leads to the pad of
- * the caller. The verifier adds the unwind_goto, which is an exception table entry and no code:
+ * ends in cancel_exit. That returns to the cancel_goto after the call, which leads to the pad of
+ * the caller. Like unwind_goto, cancel_goto is an exception table entry and no code:
  *
  *       wait:                                   main:
  *         1: ...                                        call bpf_rcu_read_lock
  *    +       may_goto pad ------.                       call wait
- *            if r0 == 0 goto 1b |          .---> +      unwind_goto pad -----------.
+ *            if r0 == 0 goto 1b |          .---> +      cancel_goto pad -----------.
  *            ...                |          |            ...                        |
  *            exit               |          |            exit                       |
- *    + pad:  r0 = 0 <-----------'          |     + pad: call bpf_rcu_read_unlock <-'
- *    +       unwind_exit ------------------'     +      r0 = 0; exit
+ *    + pad:  r0 = 0; r2 = 0 <---'          |     + pad: call bpf_rcu_read_unlock <-'
+ *    +       cancel_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().
+ * cancellation on from its unwind label to the cancel_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, 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 program has its own insns for unwinding, in C++ or Rust: unwind_exit returns to the unwind_goto
+ * after the call, where the program has a landing pad of its own. cancel_exit never returns to an
+ * unwind_goto, so no landing pad of the program can catch a cancellation and continue running.
+ * Where a callee leaves with unwind_exit and the call has no unwind_goto (BPF_SITE_CALL), the
+ * verifier adds one, with a pad that leaves with unwind_exit in turn.
+ *
  * A frame can be in fewer sections than it was called in. Its pad enters the sections that the
  * frame left, so that the caller is in the sections of its call wherever the callee is cancelled.
  * Here grow() is called with preemption disabled, and its load from arena can fault. The fault
@@ -117,7 +123,7 @@
  *		lock(pool);				   call bpf_preempt_disable
  *		return p;				   exit
  *	}					   + pad:  call bpf_preempt_disable
- *						   +	   r0 = 0; unwind_exit
+ *						   +	   r0 = 0; r2 = 0; cancel_exit
  *
  * A subprog can acquire or release for its caller, as lock() and unlock() functions do. Where the
  * caller has hidden slots, the call stands for what the subprog does, like the call of a kfunc. The
@@ -436,10 +442,11 @@ struct bpf_pad_plan *bpf_pad_plan_get(struct bpf_verifier_env *env, int insn_idx
 	return plan;
 }
 
-/* @callee was left with unwind_exit and comes back to the call at @call_idx, which is a site */
-int bpf_pad_note_callee(struct bpf_verifier_env *env, int call_idx, int callee)
+/* Record that @callee came back to the call at @call_idx, a site of @kind, without returning */
+int bpf_pad_note_callee(struct bpf_verifier_env *env, int call_idx, int callee,
+			enum bpf_site_kind kind)
 {
-	struct bpf_pad_plan *plan = bpf_pad_plan_get(env, call_idx, BPF_SITE_CALL);
+	struct bpf_pad_plan *plan = bpf_pad_plan_get(env, call_idx, kind);
 
 	if (!plan)
 		return -ENOMEM;
@@ -1246,7 +1253,7 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 	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;
+	insn_idx += bpf_site_is_call(plan->kind);
 	for (i = 0; i < plan->nr_ents; i++)
 		plan->ents[i].ref = -1;
 	/*
@@ -2288,13 +2295,25 @@ static int release_ents(struct bpf_verifier_env *env, const struct bpf_pad_plan
 	return n;
 }
 
-/* The calls of the pad of @plan clobber the value that it has to pass on */
-static bool plan_saves_value(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+/*
+ * Does the pad of a site of @kind in @subprog pass R2 on with R0, see bpf_pad_passes_on()? Only in
+ * a subprog that returns two registers. Its other pads leave with 0 in R2.
+ */
+bool bpf_pad_passes_r2(struct bpf_verifier_env *env, int subprog, enum bpf_site_kind kind)
+{
+	return bpf_pad_passes_on(env, subprog, kind) && bpf_ret_reg_pair(env, subprog);
+}
+
+/* Does the pad of @plan keep the value in the value word, because its calls clobber R0? */
+static bool plan_saves_value(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
+			     int subprog)
 {
-	return bpf_site_has_value(env, plan->kind) &&
+	return (bpf_site_has_value(env, subprog, plan->kind) ||
+		bpf_pad_passes_on(env, subprog, plan->kind)) &&
 	       (plan->nr_ents || plan->sections[BPF_PAD_RCU] || plan->sections[BPF_PAD_PREEMPT]);
 }
 
+
 /*
  * Emit the insns of the pad of @plan, a site in @subprog, except the last one, which leaves the
  * frame. The main pass does not see these insns, so the aux data that later passes look up for them
@@ -2305,13 +2324,19 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 {
 	int value_off = env->subprog_info[subprog].value_off;
 	int src = bpf_site_value_reg(plan->kind), dst = BPF_REG_0;
+	bool passes_on = bpf_pad_passes_on(env, subprog, plan->kind);
+	bool pair = bpf_pad_passes_r2(env, subprog, plan->kind);
 	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))
+	if (plan_saves_value(env, plan, subprog)) {
 		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, src, value_off);
+		if (pair)
+			buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_2,
+					       value_off + BPF_REG_SIZE);
+	}
 	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++)
@@ -2322,13 +2347,25 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
 		for (i = 0; i < pad_enters(plan, class); i++)
 			buf[n++] = enter_call(class);
-	if (plan_saves_value(env, plan))
+	if (plan_saves_value(env, plan, subprog)) {
 		buf[n++] = BPF_LDX_MEM(BPF_DW, dst, BPF_REG_FP, value_off);
-	else if (!bpf_site_has_value(env, plan->kind))
+		if (pair)
+			buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_2, BPF_REG_FP,
+					       value_off + BPF_REG_SIZE);
+	} else if (passes_on) {
+		/* no call: R0 and R2 are what unwind_exit left */
+	} else if (!bpf_site_has_value(env, subprog, plan->kind)) {
 		buf[n++] = BPF_MOV64_IMM(dst, bpf_cancelled_retval(env));
-	else if (src != dst)
+	} else if (src != dst) {
 		buf[n++] = BPF_MOV64_REG(dst, src);
-	if (bpf_ret_reg_pair(env, subprog))
+	}
+	/*
+	 * R2 is 0 at every cancel_exit, so that the code after a cancel_goto reads nothing of the
+	 * cancelled frame. Every other pad of a subprog that returns two registers also clears R2,
+	 * unless it passes R2 on.
+	 */
+	if (bpf_pad_cancel_exits(env, subprog, plan->kind) ||
+	    (!pair && bpf_ret_reg_pair(env, subprog)))
 		buf[n++] = BPF_MOV64_IMM(BPF_REG_2, 0);
 	return n;
 }
@@ -2412,35 +2449,58 @@ static int settle_plan(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
  */
 bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
 {
+	const struct bpf_subprog_info *sub;
 	int s;
 
-	if (plan->kind != BPF_SITE_CALL)
+	if (!bpf_site_is_call(plan->kind))
 		return plan->kind != BPF_SITE_FAULT && plan->kind != BPF_SITE_MAY_GOTO;
-	bpf_pad_for_each_callee(plan, s)
-		if (env->subprog_info[s].must_unwind)
+	/* the callees came back cancelled or with unwind_exit, by the kind of the site */
+	bpf_pad_for_each_callee(plan, s) {
+		sub = &env->subprog_info[s];
+		if (bpf_site_is_cancel(plan->kind) ? sub->must_cancel : sub->must_unwind)
 			return true;
+	}
 	return false;
 }
 
-/* What a subprog is left for may be found after its callers were unwound: look at them again */
-void bpf_pads_must_unwind(struct bpf_verifier_env *env)
+/*
+ * Compute 'must_unwind' and 'must_cancel' of the subprogs again from the records of their calls:
+ * the main pass can find a site in a callee after it has cancelled the callers. Callees come first,
+ * and callx and a cycle of calls need more rounds.
+ */
+int bpf_pads_must_unwind(struct bpf_verifier_env *env)
 {
 	struct bpf_subprog_info *sub;
 	const struct bpf_pad_plan *plan;
-	bool changed;
-	int i, s;
+	bool changed, must, must_cancel;
+	int i, k, err;
 
 	do {
 		changed = false;
-		for (s = 0; s < env->subprog_cnt; s++) {
-			sub = &env->subprog_info[s];
-			for (i = sub->start; i < sub[1].start && !sub->must_unwind; i++) {
-				plan = bpf_pad_plan(&env->insn_aux_data[i], BPF_SITE_CALL);
-				sub->must_unwind = plan && bpf_pad_must_unwind(env, plan);
-				changed |= sub->must_unwind;
+		err = bpf_add_cost_and_check(env, env->prog->len, BPF_COST_SCAN);
+		if (err)
+			return err;
+		for (k = 0; k < env->subprog_cnt; k++) {
+			sub = &env->subprog_info[env->subprog_topo_order[k]];
+			must = sub->must_unwind;
+			must_cancel = sub->must_cancel;
+			for (i = sub->start; i < sub[1].start && !(must && must_cancel); i++) {
+				for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next) {
+					if (!bpf_site_is_call(plan->kind) ||
+					    !bpf_pad_must_unwind(env, plan))
+						continue;
+					if (bpf_site_is_cancel(plan->kind))
+						must_cancel = true;
+					else
+						must = true;
+				}
 			}
+			changed |= must != sub->must_unwind || must_cancel != sub->must_cancel;
+			sub->must_unwind = must;
+			sub->must_cancel = must_cancel;
 		}
 	} while (changed);
+	return 0;
 }
 
 static const char * const site_kind[] = {
@@ -2450,24 +2510,36 @@ static const char * const site_kind[] = {
 	[BPF_SITE_FAULT]		= "arena access",
 	[BPF_SITE_THROW]		= "bpf_throw",
 	[BPF_SITE_MAY_GOTO]		= "may_goto of the program",
+	[BPF_SITE_CANCEL_CALL]		= "call",
 };
 
-/* The program has unwind_exit in the subprog. No site: a bit that follows those of the kinds. */
-#define LEFT_AT_UNWIND_EXIT	BIT(BPF_SITE_MAY_GOTO + 1)
+/* A bit of 'left_at' that is no kind of site: the subprog has an unwind_exit of the program */
+#define LEFT_AT_UNWIND_EXIT	BIT(15)
+
+/*
+ * Returns the bits of @kinds, 'left_at' of a callee, that count at the call of @plan: the sites of
+ * a cancellation, or LEFT_AT_UNWIND_EXIT if the record is for the program's own unwinding
+ */
+static u16 kinds_of_plan(const struct bpf_pad_plan *plan, u16 kinds)
+{
+	return plan->kind == BPF_SITE_CANCEL_CALL ? kinds & ~LEFT_AT_UNWIND_EXIT
+						  : kinds & LEFT_AT_UNWIND_EXIT;
+}
 
 /*
- * At which kinds of site does the program leave each subprog? At its own, and at those of what
- * comes back to its calls. Bits by enum bpf_site_kind in 'left_at'. The main pass notes them as
- * the states leave, see bpf_pad_note_left(). This is what is left of that when the pass is over.
+ * Compute 'left_at' of each subprog: the kinds of site at which the program leaves it, in the
+ * subprog itself and in the callees that come back to its calls, as bits by enum bpf_site_kind. The
+ * main pass records them as states leave, see bpf_pad_note_left(). This computes them again from
+ * the sites that the program keeps. Callees come first, as in bpf_pads_must_unwind().
  */
-static void sites_of_subprogs(struct bpf_verifier_env *env)
+static int sites_of_subprogs(struct bpf_verifier_env *env)
 {
 	const struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	const struct bpf_pad_plan *plan;
 	struct bpf_subprog_info *sub;
+	int i, k, s, c, err;
 	bool changed;
-	int i, s, c;
-	u8 kinds;
+	u16 kinds;
 
 	for (s = 0; s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
@@ -2475,8 +2547,11 @@ static void sites_of_subprogs(struct bpf_verifier_env *env)
 	}
 	do {
 		changed = false;
-		for (s = 0; s < env->subprog_cnt; s++) {
-			sub = &env->subprog_info[s];
+		err = bpf_add_cost_and_check(env, env->prog->len, BPF_COST_SCAN);
+		if (err)
+			return err;
+		for (k = 0; k < env->subprog_cnt; k++) {
+			sub = &env->subprog_info[env->subprog_topo_order[k]];
 			kinds = sub->left_at;
 			for (i = sub->start; i < sub[1].start; i++) {
 				if (aux[i].loop_guard)
@@ -2486,27 +2561,29 @@ static void sites_of_subprogs(struct bpf_verifier_env *env)
 				for (plan = aux[i].pad_plans; plan; plan = plan->next) {
 					if (!plan->used)
 						continue;
-					if (plan->kind != BPF_SITE_CALL) {
+					if (!bpf_site_is_call(plan->kind)) {
 						kinds |= BIT(plan->kind);
 						continue;
 					}
 					bpf_pad_for_each_callee(plan, c)
-						kinds |= env->subprog_info[c].left_at;
+						kinds |= kinds_of_plan(plan,
+								       env->subprog_info[c].left_at);
 				}
 			}
 			changed |= kinds != sub->left_at;
 			sub->left_at = kinds;
 		}
 	} while (changed);
+	return 0;
 }
 
 /*
  * Returns the kinds of site at which the callees that came back to the call of @plan leave. The
  * main pass asks before sites_of_subprogs() has run, so the program's unwind_exit is added here.
  */
-static u8 sites_below(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+static u16 sites_below(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
 {
-	u8 kinds = 0;
+	u16 kinds = 0;
 	int s;
 
 	bpf_pad_for_each_callee(plan, s) {
@@ -2514,7 +2591,7 @@ static u8 sites_below(struct bpf_verifier_env *env, const struct bpf_pad_plan *p
 		if (env->subprog_info[s].can_unwind)
 			kinds |= LEFT_AT_UNWIND_EXIT;
 	}
-	return kinds;
+	return kinds_of_plan(plan, kinds);
 }
 
 /*
@@ -2523,10 +2600,10 @@ static u8 sites_below(struct bpf_verifier_env *env, const struct bpf_pad_plan *p
  */
 static void print_sites_below(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
 {
-	u8 kinds;
+	u16 kinds;
 	int k;
 
-	if (plan->kind != BPF_SITE_CALL)
+	if (!bpf_site_is_call(plan->kind))
 		return;
 	kinds = sites_below(env, plan);
 	verbose(env, "what the call at %d calls is left at:", i);
@@ -3167,7 +3244,9 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 	};
 	int j;
 
-	verbose(env, "landing pad of %s at %d: ", site_kind[plan->kind], i);
+	/* a call has one for what the kernel unwinds, and one for unwind_exit of the program */
+	verbose(env, "landing pad of %s at %d%s: ", site_kind[plan->kind], i,
+		plan->kind == BPF_SITE_CALL ? " for unwind_exit" : "");
 	for (j = plan->nr_ents - 1; !plan->conflict && j >= 0; j--)
 		print_ent(env, &plan->ents[j]);
 	if (plan->conflict)
@@ -3218,7 +3297,7 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pa
 void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *sub,
 		       const struct bpf_pad_plan *plan, enum bpf_site_kind kind)
 {
-	sub->left_at |= kind == BPF_SITE_CALL ? sites_below(env, plan) : BIT(kind);
+	sub->left_at |= bpf_site_is_call(kind) ? sites_below(env, plan) : BIT(kind);
 }
 
 /* Did bpf_pad_skip_faults() walk @sub, and has no call in or below it got a new callee since? */
@@ -3244,7 +3323,7 @@ int bpf_pad_skip_faults(struct bpf_verifier_env *env, const struct bpf_pad_plan
 	unsigned long *todo, *done;
 	bool walked = true;
 
-	if (verifier_bug_if(plan->kind != BPF_SITE_CALL, env,
+	if (verifier_bug_if(!bpf_site_is_call(plan->kind), env,
 			    "a site that is no call has a frame that cannot unwind"))
 		return -EFAULT;
 	/*
@@ -3277,12 +3356,11 @@ int bpf_pad_skip_faults(struct bpf_verifier_env *env, const struct bpf_pad_plan
 		env->faults_late |= !sub->stuck;
 		/* the log names the call at @insn_idx also for a subprog further down */
 		bpf_subprog_set_stuck(sub, BPF_STUCK_CAME_BACK, insn_idx);
-		for (i = sub->start; i < sub[1].start; i++) {
-			plan = bpf_pad_plan(&aux[i], BPF_SITE_CALL);
-			if (plan)
-				bpf_pad_for_each_callee(plan, c)
-					__set_bit(c, todo);
-		}
+		for (i = sub->start; i < sub[1].start; i++)
+			for (plan = aux[i].pad_plans; plan; plan = plan->next)
+				if (bpf_site_is_call(plan->kind))
+					bpf_pad_for_each_callee(plan, c)
+						__set_bit(c, todo);
 	}
 	/* a walk that got to its end has all that is below what it walked */
 	if (!err)
@@ -3295,18 +3373,20 @@ int bpf_pad_skip_faults(struct bpf_verifier_env *env, const struct bpf_pad_plan
 
 /*
  * The pads of @sub keep the value over their calls in a hidden word of the frame, below the
- * hidden slots. Nothing else writes it. Returns the reason of a conflict.
+ * hidden slots. Nothing else writes it. A subprog whose pads pass on R2 has a second word above
+ * it, see bpf_pad_passes_r2(). Returns the reason of a conflict.
  */
 static int take_value_word(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
 {
+	int words = 1 + bpf_pad_passes_r2(env, sub - env->subprog_info, BPF_SITE_CALL);
 	int err;
 
 	if (sub->value_off)
 		return 0;
-	sub->hidden_words++;
+	sub->hidden_words += words;
 	err = bpf_hidden_slots_fit(env);
 	if (err <= 0) {
-		sub->hidden_words--;
+		sub->hidden_words -= words;
 		return err ?: BPF_CONFLICT_NO_ROOM;
 	}
 	sub->value_off = -(int)bpf_stack_depth_with_slots(sub);
@@ -3343,8 +3423,9 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 	struct bpf_pad_plan *plan;
 	int i, s, err;
 
-	bpf_pads_must_unwind(env);
-	sites_of_subprogs(env);
+	err = bpf_pads_must_unwind(env) ?: sites_of_subprogs(env);
+	if (err)
+		return err;
 	/* sort the releases first: hidden slots are inserted into that order */
 	for (i = 0; i < env->prog->len; i++) {
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next) {
@@ -3363,8 +3444,9 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 			if (!plan->used)
 				continue;
 			err = settle_plan(env, plan);
-			if (!err && plan_saves_value(env, plan))
-				err = take_value_word(env, bpf_find_containing_subprog(env, i));
+			sub = bpf_find_containing_subprog(env, i);
+			if (!err && plan_saves_value(env, plan, sub - env->subprog_info))
+				err = take_value_word(env, sub);
 			if (err < 0)
 				return err;
 			plan->conflict = err;
@@ -3451,11 +3533,13 @@ static bool left_at_insn(const struct bpf_insn_aux_data *aux)
 }
 
 /*
- * The landing pad of the call of @plan has a conflict, and that is an error: what the call calls
- * is unwound. Where that is at may_goto that the verifier adds, it depends on the
- * values that got to the loop: may_goto is there because a state went around without a trip
- * count. A function is verified for its calls together, and two calls of which each has a trip
- * count can make such a state between them:
+ * The pad of @plan, the record of a site at @insn_idx, cannot be generated, and that is an error of
+ * the pass. Mark what can make the next pass succeed.
+ *
+ * The callees that were cancelled at the call are marked for note_causes_below(). 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. The loop then gets a may_goto, and the calls become
+ * sites:
  *
  *	static long count(long step, long end)		count(1, 1000000);
  *	{						count(-1, -999993);
@@ -3486,11 +3570,12 @@ static void note_causes(struct bpf_verifier_env *env, int insn_idx, const struct
 	/* what try_more() in verifier.c is for, see 'ref_conflict' */
 	env->ref_conflict |= conflict_of_ref(env, plan) ||
 			     plan->conflict == BPF_CONFLICT_NO_RELEASE;
-	if (plan->kind == BPF_SITE_CALL && conflict_of_ref(env, plan)) {
+	if ((plan->kind == BPF_SITE_CALL || plan->kind == BPF_SITE_CANCEL_CALL) &&
+	    conflict_of_ref(env, plan)) {
 		bpf_pad_for_each_callee(plan, s)
 			sub[s].asks_args |= sub[s].releases_args;
 	}
-	if (plan->kind != BPF_SITE_CALL)
+	if (plan->kind != BPF_SITE_CANCEL_CALL)
 		return;
 	bpf_pad_for_each_callee(plan, s)
 		sub[s].below_conflict = true;
@@ -3536,7 +3621,7 @@ static void note_causes_below(struct bpf_verifier_env *env)
 			break;
 		for (i = sub[s].start; i < sub[s + 1].start; i++) {
 			for (below = aux[i].pad_plans; below; below = below->next) {
-				if (below->kind != BPF_SITE_CALL || !below->visited)
+				if (below->kind != BPF_SITE_CANCEL_CALL || !below->visited)
 					continue;
 				/*
 				 * The frame is left at this call, whatever what it calls
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index ed73f660d5ce..3cade295dd8d 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -3414,11 +3414,13 @@ static bool is_indirect_call(const struct bpf_insn *insn)
 static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)
 {
 	struct bpf_subprog_info *sub = &env->subprog_info[subprog];
-	bool did_unwind = sub->did_unwind && sub->bail_unwinds;
+	bool did_unwind = (sub->did_unwind || sub->did_cancel) && sub->bail_unwinds;
+	int err;
 
-	if (did_unwind)
-		bpf_pads_must_unwind(env);
-	if (did_unwind && sub->must_unwind) {
+	err = did_unwind ? bpf_pads_must_unwind(env) : 0;
+	if (err)
+		return err;
+	if (did_unwind && (sub->must_unwind || sub->must_cancel)) {
 		verbose(env, "callback cannot unwind at insn %d: %s() does\n",
 			env->insn_idx, bpf_subprog_name(env, subprog));
 		return -EINVAL;
@@ -3430,45 +3432,95 @@ static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)
 	return 0;
 }
 
-static bool callee_did_unwind(struct bpf_verifier_env *env, int insn_idx)
+/*
+ * Did a callee of an indirect call of @caller leave with cancel_exit (@kernel) or with unwind_exit?
+ * Only the callees that the pass has recorded so far are known.
+ */
+static bool callx_did_unwind(struct bpf_verifier_env *env, const struct bpf_subprog_info *caller,
+			     bool kernel)
 {
-	const struct bpf_insn *insn = &env->prog->insnsi[insn_idx];
-	struct bpf_subprog_info *si = env->subprog_info;
+	const struct bpf_subprog_info *sub;
 	u32 e;
 
-	if (bpf_pseudo_call(insn))
-		return si[bpf_find_subprog(env, insn_idx + insn->imm + 1)].did_unwind;
-	if (!is_indirect_call(insn))
-		return false;
-	/* the edges that the pass has so far */
-	for (e = bpf_find_containing_subprog(env, insn_idx)->callx_edge; e;
-	     e = env->callx_edges[e - 1].next)
-		if (si[env->callx_edges[e - 1].callee].did_unwind)
+	for (e = caller->callx_edge; e; e = env->callx_edges[e - 1].next) {
+		sub = &env->subprog_info[env->callx_edges[e - 1].callee];
+		if (kernel ? sub->did_cancel : sub->did_unwind)
 			return true;
+	}
 	return false;
 }
 
 /*
- * A subprog unwinds. What calls it without unwind_goto is unwound in turn, and so on. The callers
- * of a global subprog among them have to know, see unwind_frame(): one more round will do for all.
+ * Pass did_unwind and did_cancel on from callees to callers. A caller unwinds in turn if it has no
+ * unwind_goto after the call. A cancellation goes through every caller, because it never takes an
+ * unwind_goto of the program. All callers are marked at once, so a chain of global subprogs costs
+ * one more pass and not one per subprog, see unwind_frame().
  */
-static void mark_unwind_above(struct bpf_verifier_env *env)
+static int mark_unwind_above(struct bpf_verifier_env *env)
 {
+	bool changed, unwinds, cancels, did, did_cancel, xdid, xdid_cancel, asked;
+	struct bpf_subprog_info *si = env->subprog_info, *caller;
 	const struct bpf_insn *insn = env->prog->insnsi;
-	struct bpf_subprog_info *caller;
-	bool changed;
-	int i;
+	/* the first insns of the subprogs with did_unwind, and of those with did_cancel */
+	unsigned long *starts, *cancel_starts;
+	int i, k, err = 0;
 
+	starts = bitmap_zalloc(env->prog->len, BPF_VERIFIER_GFP);
+	cancel_starts = bitmap_zalloc(env->prog->len, BPF_VERIFIER_GFP);
+	if (!starts || !cancel_starts) {
+		err = -ENOMEM;
+		goto out;
+	}
+	for (k = 0; k < env->subprog_cnt; k++) {
+		if (si[k].did_unwind)
+			__set_bit(si[k].start, starts);
+		if (si[k].did_cancel)
+			__set_bit(si[k].start, cancel_starts);
+	}
 	do {
 		changed = false;
-		for (i = 0; i < env->prog->len; i++) {
-			if (!callee_did_unwind(env, i) || bpf_is_unwind_goto(&insn[i + 1]))
+		err = bpf_add_cost_and_check(env, env->prog->len + env->callx_index.cnt,
+					     BPF_COST_SCAN);
+		if (err)
+			break;
+		for (k = 0; k < env->subprog_cnt; k++) {
+			caller = &si[env->subprog_topo_order[k]];
+			unwinds = caller->did_unwind;
+			cancels = caller->did_cancel;
+			xdid = xdid_cancel = asked = false;
+			for (i = caller->start; i < caller[1].start && !(unwinds && cancels); i++) {
+				if (bpf_pseudo_call(&insn[i])) {
+					did = test_bit(i + insn[i].imm + 1, starts);
+					did_cancel = test_bit(i + insn[i].imm + 1, cancel_starts);
+				} else if (is_indirect_call(&insn[i])) {
+					if (!asked) {
+						xdid = callx_did_unwind(env, caller, false);
+						xdid_cancel = callx_did_unwind(env, caller, true);
+						asked = true;
+					}
+					did = xdid;
+					did_cancel = xdid_cancel;
+				} else {
+					continue;
+				}
+				unwinds |= did && !bpf_is_unwind_goto(&insn[i + 1]);
+				cancels |= did_cancel;
+			}
+			if (unwinds == caller->did_unwind && cancels == caller->did_cancel)
 				continue;
-			caller = bpf_find_containing_subprog(env, i);
-			changed |= !caller->did_unwind;
-			caller->did_unwind = true;
+			changed = true;
+			caller->did_unwind = unwinds;
+			caller->did_cancel = cancels;
+			if (unwinds)
+				__set_bit(caller->start, starts);
+			if (cancels)
+				__set_bit(caller->start, cancel_starts);
 		}
 	} while (changed);
+out:
+	bitmap_free(starts);
+	bitmap_free(cancel_starts);
+	return err;
 }
 
 /*
@@ -3511,7 +3563,7 @@ static int expect_may_goto_unwinds(struct bpf_verifier_env *env)
 		}
 	} while (changed);
 	for_each_set_bit(s, soft, cnt)
-		si[s].did_unwind |= si[s].bail_unwinds && bpf_subprog_is_global(env, s);
+		si[s].did_cancel |= si[s].bail_unwinds && bpf_subprog_is_global(env, s);
 	bitmap_free(soft);
 	return err;
 }
@@ -6231,14 +6283,16 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
 				      !bpf_prog_is_offloaded(env->prog->aux) && bpf_may_unwind(env) &&
 				      (cg.marks[s] & CALLED));
 		si[s].bail_unwinds_at_first = si[s].bail_unwinds;
+		/* An unwind_exit insn makes these certain. The main pass finds the cancel bits. */
 		si[s].must_unwind = si[s].unwinds_for_sure = si[s].can_unwind;
+		si[s].must_cancel = si[s].cancels_for_sure = false;
 		/*
-		 * The callers of a global subprog are verified ahead of it, see unwind_frame().
-		 * Where there is an arena expect it to unwind, that saves a pass.
+		 * The callers of a global subprog are verified before it. In a program with an
+		 * arena expect the subprog to be cancelled, which saves starting the pass again.
 		 */
-		si[s].did_unwind = si[s].can_unwind ||
-				   (env->prog->aux->arena && si[s].bail_unwinds &&
-				    bpf_subprog_is_global(env, s));
+		si[s].did_unwind = si[s].can_unwind;
+		si[s].did_cancel = env->prog->aux->arena && si[s].bail_unwinds &&
+				   bpf_subprog_is_global(env, s);
 	}
 
 	for (s = 0; s < cnt; s++) {
@@ -12071,7 +12125,9 @@ static int exit_func_on_its_own(struct bpf_verifier_env *env, int exit_idx)
 
 	hide_returned_stack_ptrs(env, bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1,
 				 callee->regs);
-	state->unwound |= bpf_is_unwind_exit(&env->prog->insnsi[env->insn_idx]);
+	/* unwind_frame() has already marked a state that it brings here. */
+	if (!state->unwound && bpf_is_unwind_exit(&env->prog->insnsi[env->insn_idx]))
+		state->unwound = BPF_UNWOUND;
 
 	/* Invalidate callee-local dynptrs and their slices before the frame goes away. */
 	err = destroy_dynptrs_in_stack_slots(env, callee, 0,
@@ -12088,15 +12144,18 @@ static int exit_func_on_its_own(struct bpf_verifier_env *env, int exit_idx)
 }
 
 /*
- * @callee was left with unwind_exit and comes back to the call at @call_idx. From there the program
- * goes to unwind_goto that follows the call. If it has none the verifier adds it, see
- * check_unwound_arrival().
+ * @callee did not return to the call at @call_idx: it left with unwind_exit, or with cancel_exit if
+ * @kernel. Record @callee at the site that the call becomes, see check_unwound_arrival(). There is
+ * no site if @callee left with unwind_exit and the program has an unwind_goto after the call.
  */
-static int check_unwound_return(struct bpf_verifier_env *env, int call_idx, int callee)
+static int check_unwound_return(struct bpf_verifier_env *env, int call_idx, int callee,
+				bool kernel)
 {
+	if (kernel)
+		return bpf_pad_note_callee(env, call_idx, callee, BPF_SITE_CANCEL_CALL);
 	if (bpf_is_unwind_goto(&env->prog->insnsi[call_idx + 1]))
 		return 0;
-	return bpf_pad_note_callee(env, call_idx, callee);
+	return bpf_pad_note_callee(env, call_idx, callee, BPF_SITE_CALL);
 }
 
 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, bool is_null);
@@ -12159,7 +12218,8 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 		return BPF_EXIT_NEEDS_CALLER;
 	}
 	if (exit->unwound) {
-		err = check_unwound_return(env, call_idx, callee->subprogno);
+		err = check_unwound_return(env, call_idx, callee->subprogno,
+					   bpf_unwound_cancelled(exit->unwound));
 		if (err)
 			return err;
 	}
@@ -12413,18 +12473,24 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 			}
 		}
 
-		/* No state comes out of a global subprog, see unwind_frame() */
-		if (env->subprog_info[subprog].did_unwind &&
-		    env->subprog_info[subprog].bail_unwinds) {
+		/*
+		 * No state comes back from a global subprog. Push one for each way in which it is
+		 * known to leave without returning: with unwind_exit and with cancel_exit.
+		 */
+		for (i = 0; i < 2; i++) {
+			const struct bpf_subprog_info *sub = &env->subprog_info[subprog];
 			struct bpf_verifier_state *branch;
+			bool kernel = i;
 
-			err = check_unwound_return(env, *insn_idx, subprog);
+			if (!(kernel ? sub->did_cancel : sub->did_unwind) || !sub->bail_unwinds)
+				continue;
+			err = check_unwound_return(env, *insn_idx, subprog, kernel);
 			if (err)
 				return err;
 			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
 			if (IS_ERR(branch))
 				return PTR_ERR(branch);
-			branch->unwound = true;
+			branch->unwound = bpf_unwound_mark(kernel, false);
 			/* R0 has the value of the unwinding, also after a void function. */
 			if (env->has_throw)
 				mark_reg_unknown(env, branch->frame[branch->curframe]->regs,
@@ -12918,18 +12984,13 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 	caller = state->frame[state->curframe - 1];
 	unwinds = bpf_is_unwind_exit(&env->prog->insnsi[*insn_idx]) || state->unwound;
 	if (unwinds) {
-		/*
-		 * A callback returns into the helper that called it, and to the
-		 * pad of the helper when the helper has one. check_cb_unwind()
-		 * has seen to that. From there the helper leaves right away to
-		 * the unwind_goto after its call, with the r0 of the callback
-		 * as it is: the pad gets its state, as the pad after a subprog
-		 * call does.
-		 */
-		err = check_unwound_return(env, callee->callsite, callee->subprogno);
+		/* unwind_frame() has already marked a state that it brings here. */
+		bool kernel = bpf_unwound_cancelled(state->unwound);
+
+		err = check_unwound_return(env, callee->callsite, callee->subprogno, kernel);
 		if (err)
 			return err;
-		state->unwound = callee->in_callback_fn ? BPF_UNWOUND_CB : BPF_UNWOUND;
+		state->unwound = bpf_unwound_mark(kernel, callee->in_callback_fn);
 	}
 	bpf_pad_note_return(env, state, caller, callee->callsite,
 			    !unwinds && !callee->in_callback_fn);
@@ -19892,6 +19953,10 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 	if (bpf_is_unwind_goto(insn)) {
 		if (!env->cur_state->unwound)
 			return 0;
+		/* what the kernel unwinds does not get here, see check_unwound_arrival() */
+		if (verifier_bug_if(env->cur_state->unwound != BPF_UNWOUND, env,
+				    "unwind_goto at insn %d is taken for cancel_exit", *insn_idx))
+			return -EFAULT;
 		env->cur_state->unwound = false;
 		*insn_idx += insn->off;
 		return 0;
@@ -21865,6 +21930,19 @@ int bpf_flow_start_leftover(struct bpf_verifier_env *env)
 	return enter_callback(env, false, NULL);
 }
 
+/*
+ * @st came back from a call unwound and is at the insn behind the call. It does not go on there:
+ * the frame is unwound in turn, at the call, see check_unwound_arrival(). What the kernel unwound
+ * always, whatever the insn is. What left with unwind_exit of the program unless the program has
+ * unwind_goto there, which is a jump for it.
+ */
+static bool unwound_in_turn(const struct bpf_verifier_env *env, const struct bpf_verifier_state *st)
+{
+	if (st->unwound == BPF_CANCELLED)
+		return true;
+	return st->unwound == BPF_UNWOUND && !bpf_is_unwind_goto(&env->prog->insnsi[env->insn_idx]);
+}
+
 /*
  * The current state gets to env->insn_idx. Leave the loops that the insn is not in. Enter
  * the loops that it is in. Returns 1 if the state ends here.
@@ -21882,9 +21960,8 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge
 	if (infeasible_state_ends(env))
 		return 1;
 
-	/* what comes back from a call with unwind_exit goes to a landing pad, not to the insn */
-	if (env->cur_state->unwound == BPF_UNWOUND &&
-	    !bpf_is_unwind_goto(&env->prog->insnsi[env->insn_idx]))
+	/* The state does not run this insn: its frame leaves at the call before it. */
+	if (unwound_in_turn(env, env->cur_state))
 		return 0;
 
 	/* The callback came back to the helper that calls it, in the same trip. */
@@ -21928,14 +22005,13 @@ int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge
  *	lsm, the hook returns an errno		-EPERM, 0 lets the operation go on
  *	the range is [1, 1]			1, hooks that cannot refuse
  *
- * Each is a value that check_return_code() lets the program return: no state is checked there with
- * it, see unwind_frame().
+ * Each is a value that check_return_code() accepts. It has to be, because no state is checked with
+ * it. An extension returns the value for the type of the program that it extends. If the program
+ * has an exception callback, the callback gets the value and chooses what the program returns.
+ *
  * Two 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.
- * An extension returns into the program that it extends, with the value of that program.
- * A subprog is left with the same value: its callers may pass it on, see bpf_site_has_value().
- * The exception callback gets it and decides. A landing pad that the program has can replace it.
+ * in direct-action mode takes 2 for a class, and a stream parser of sk_skb takes 0 for a message
+ * that is not complete.
  */
 int bpf_cancelled_retval(struct bpf_verifier_env *env)
 {
@@ -22043,7 +22119,7 @@ static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog)
 		return;
 	}
 	env->faults_late |= sub->soft_unwinds || sub->made_calls ||
-			    (sub->did_unwind && sub->bail_unwinds);
+			    ((sub->did_unwind || sub->did_cancel) && sub->bail_unwinds);
 	bpf_subprog_set_stuck(sub, BPF_STUCK_CALLED, env->insn_idx);
 }
 
@@ -22278,11 +22354,10 @@ static int release_frame_resources(struct bpf_verifier_env *env, const struct bp
 }
 
 /*
- * Does the program have the site of @plan at @insn_idx for sure? Pass 0 takes the edge of may_goto
- * in every loop that nothing stops, a later pass in every loop that had no trip count before, and
- * a loop that turns out to have a trip count gets no may_goto, see bpf_flow_drop_guards() and
- * bpf_flow_guard_is_guess(). A call is a site only if a callee is left at one.
- * bpf_pads_settle() knows them all. Until then a conflict at a site that may go is no error.
+ * Is it certain that the program keeps the site of @plan at @insn_idx? A pass takes the edge of
+ * may_goto also in a loop that turns out to have a trip count and gets no may_goto, and a call is
+ * a site only as long as a callee leaves at one. Until bpf_pads_settle() knows all sites, a
+ * missing landing pad is an error only at a site that is certain.
  */
 static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 			    int insn_idx)
@@ -22297,32 +22372,28 @@ static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_p
 			if (env->subprog_info[s].unwinds_for_sure)
 				return true;
 		return false;
+	case BPF_SITE_CANCEL_CALL:
+		bpf_pad_for_each_callee(plan, s)
+			if (env->subprog_info[s].cancels_for_sure)
+				return true;
+		return false;
 	default:
 		return true;
 	}
 }
 
 /*
- * The current frame of @st is left at @insn_idx, a site of @kind. The program has no code for
- * that: the verifier emits a landing pad after the main pass, see kernel/bpf/pads.c. No insn
- * stands for it in the main pass. @st visits the plan of the site, which notes what the pad has to
- * do. Then what the pad does to a state is done to @st: the releases, see
- * release_frame_resources(), the value in place of the result, then unwind_exit, or exit in a frame
- * that the kernel called. What is left of @st goes where the frame returns to, through the
- * worklist like every other state. @st is taken.
- * The value was checked where it was made, see check_unwound_value(): on the way it is joined and
- * widened like any other number, and what comes out of a global subprog is not known.
+ * The current frame of @st leaves at @insn_idx, a site of @kind, and @st is consumed. No insn
+ * stands for the landing pad in the main pass: the verifier generates it afterwards, see
+ * kernel/bpf/pads.c. So record what the frame holds, see bpf_pad_visit(), and do to @st what the
+ * pad will do: release what the frame holds, put the value of the cancellation into R0 and leave
+ * the frame as an exit does, marked as cancelled. At BPF_SITE_CALL the program unwinds instead:
+ * the pad ends in unwind_exit and can pass R0 on, see bpf_pad_passes_on().
  *
- * With a conflict there is no pad: the site is an unproven insn in @st, which ends here. The pass
- * goes on, and a pass that keeps more apart may have no such state.
- * A frame that cannot unwind is a conflict. At an access to arena check_arena_site() saw to both,
- * and at may_goto of the program check_may_goto_site() saw to it: the access is skipped there,
- * the jump is taken. At a call in such a frame that is no error if what comes back to the call
- * was left at such sites only: @st is dropped, and what came back is stuck from now on, see
- * stuck_frame_calls() and bpf_pad_skip_faults().
- * Nor is a conflict an error at a site that the program may not have in the end, see
- * site_is_certain(): @st is dropped, the plan keeps the conflict, and bpf_pads_settle() makes it
- * an error of the pass if the site is still there.
+ * If the verifier cannot generate the pad, @st ends here. That is an error of the pass, recorded
+ * as an unproven insn, only at a site that the program is certain to keep, see site_is_certain().
+ * Otherwise bpf_pads_settle() raises it if the site is still there. A call in a frame that cannot
+ * be cancelled is no error if its callees can skip their sites, see bpf_pad_skip_faults().
  */
 static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int insn_idx,
 			enum bpf_site_kind kind)
@@ -22331,6 +22402,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
 	struct bpf_verifier_state *cur = env->cur_state;
 	int cur_idx = env->insn_idx, err = 0;
+	bool kernel = bpf_site_is_cancel(kind), passes_on, late;
 	struct bpf_pad_plan *plan = NULL;
 	bool print_state, certain = true, stuck;
 	enum bpf_pad_conflict conflict;
@@ -22338,6 +22410,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 
 	env->cur_state = st;
 	env->insn_idx = insn_idx;
+	passes_on = bpf_pad_passes_on(env, frame->subprogno, kind);
 	if (kind != BPF_SITE_FAULT) {
 		/* Keep the suspects for an error that only bpf_pads_settle() raises. */
 		env->insn_aux_data[insn_idx].suspect_loops |= st->suspect_loops;
@@ -22352,7 +22425,9 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		 */
 		if (conflict && (!plan->conflict || !bpf_pad_must_unwind(env, plan)))
 			plan->conflict = conflict;
-		if (!plan->conflict && bpf_site_has_value(env, kind) &&
+		/* The value becomes the return value of the program, so it has to be a scalar. */
+		if (!plan->conflict && !passes_on &&
+		    bpf_site_has_value(env, frame->subprogno, kind) &&
 		    frame->regs[bpf_site_value_reg(kind)].type != SCALAR_VALUE)
 			plan->conflict = BPF_CONFLICT_NO_VALUE;
 		certain = site_is_certain(env, plan, insn_idx);
@@ -22375,7 +22450,7 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		 * The frame of the call cannot be cancelled, and its callees were cancelled only at
 		 * 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))
+		if (stuck && bpf_site_is_call(kind) && !bpf_pad_must_unwind(env, plan))
 			err = bpf_pad_skip_faults(env, plan, insn_idx);
 		if (plan->conflict)
 			goto out;
@@ -22385,35 +22460,55 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	err = release_frame_resources(env, bpf_pad_plan(&env->insn_aux_data[insn_idx], kind));
 	if (err)
 		goto out;
-	if (!bpf_site_has_value(env, kind)) {
+	if (passes_on) {
+		/* R0 stays as the callee left it, unless a release invalidated it. */
+	} else if (!bpf_site_has_value(env, frame->subprogno, kind)) {
 		bpf_mark_reg_known_scalar(&frame->regs[BPF_REG_0], bpf_cancelled_retval(env));
 		bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_0));
 	} else if (bpf_site_value_reg(kind) != BPF_REG_0) {
 		frame->regs[BPF_REG_0] = frame->regs[bpf_site_value_reg(kind)];
 		bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_0));
 	}
-	if (bpf_ret_reg_pair(env, frame->subprogno))
-		__mark_reg_const_zero(&frame->regs[BPF_REG_2]);
-	bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_2));
+	/* A pad that does not pass R2 on clears it. R2 matters only for a returned pair. */
+	if (!bpf_pad_passes_r2(env, frame->subprogno, kind)) {
+		if (bpf_ret_reg_pair(env, frame->subprogno))
+			__mark_reg_const_zero(&frame->regs[BPF_REG_2]);
+		bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_2));
+	}
 
-	st->unwound = sub->bail_unwinds && !frame_is_top(st);
+	st->unwound = 0;
+	if (sub->bail_unwinds && !frame_is_top(st))
+		st->unwound = bpf_unwound_mark(kernel, false);
 	/*
 	 * The callers of a global subprog were verified before it. Mark them, and start the pass
 	 * again if the subprog still unwinds when the pass ends, see settle_late_unwinds().
 	 */
-	if (st->unwound && !sub->did_unwind && bpf_subprog_is_global(env, frame->subprogno)) {
+	late = st->unwound && bpf_subprog_is_global(env, frame->subprogno) &&
+	       !(kernel ? sub->did_cancel : sub->did_unwind);
+	if (st->unwound && kernel)
+		sub->did_cancel = true;
+	else if (st->unwound)
 		sub->did_unwind = true;
-		mark_unwind_above(env);
+	if (late) {
+		err = mark_unwind_above(env);
+		if (err)
+			goto out;
 		env->pads_late = true;
 	}
-	sub->did_unwind |= st->unwound;
 	if (st->unwound)
 		bpf_pad_note_left(env, sub, plan, kind);
-	sub->must_unwind |= st->unwound && plan && bpf_pad_must_unwind(env, plan);
-	sub->unwinds_for_sure |= st->unwound && certain;
+	/* Recorded per way of leaving: a caller asks about cancel_exit or about unwind_exit. */
+	if (st->unwound && kernel) {
+		sub->must_cancel |= plan && bpf_pad_must_unwind(env, plan);
+		sub->cancels_for_sure |= certain;
+	} else if (st->unwound) {
+		sub->must_unwind |= plan && bpf_pad_must_unwind(env, plan);
+		sub->unwinds_for_sure |= certain;
+	}
 	if (env->log.level & BPF_LOG_LEVEL2)
 		verbose(env, "from %d to %s of func#%d\n", insn_idx,
-			st->unwound ? "unwind_exit" : "exit", frame->subprogno);
+			!st->unwound ? "exit" : kernel ? "cancel_exit" : "unwind_exit",
+			frame->subprogno);
 	if (frame_is_top(st)) {
 		err = PROCESS_BPF_EXIT;
 	} else if (!st->curframe && st->instance_id) {
@@ -22448,14 +22543,19 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 }
 
 /*
- * The call before this insn came back with unwind_exit, and the program has no unwind_goto
- * there. The verifier adds it: the call is a site of the current frame, which is unwound in turn.
- * The current state is taken.
+ * The callee of the call before this insn did not return, and the current frame leaves in turn, at
+ * the call. If the callee left with unwind_exit, the program has no unwind_goto after the call and
+ * the verifier adds one. If the callee was cancelled, the verifier adds a cancel_goto, whether the
+ * program has an unwind_goto there or not: a landing pad of the program could continue running, and
+ * a cancellation ends only in the frame that the kernel called. The current state is consumed.
  */
 static int check_unwound_arrival(struct bpf_verifier_env *env)
 {
+	bool kernel = bpf_unwound_cancelled(env->cur_state->unwound);
+
 	env->cur_state->unwound = false;
-	return unwind_frame(env, env->cur_state, env->insn_idx - 1, BPF_SITE_CALL);
+	return unwind_frame(env, env->cur_state, env->insn_idx - 1,
+			    kernel ? BPF_SITE_CANCEL_CALL : BPF_SITE_CALL);
 }
 
 /* Deliver the states that the insn pushed: to their next insn, or out of their frame at a site. */
@@ -22758,9 +22858,10 @@ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
 		insn_aux = &env->insn_aux_data[env->insn_idx];
 
 		/* A callback unwound: the call of its helper is visited once more. */
-		if (state->unwound == BPF_UNWOUND_CB) {
-			state->unwound = BPF_UNWOUND;
-		} else if (state->unwound && !bpf_is_unwind_goto(insn)) {
+		if (bpf_unwound_cb(state->unwound)) {
+			state->unwound = bpf_unwound_mark(bpf_unwound_cancelled(state->unwound),
+							  false);
+		} else if (unwound_in_turn(env, state)) {
 			err = check_unwound_arrival(env);
 			if (err)
 				return err;
@@ -24560,24 +24661,32 @@ static int check_after_pass(struct bpf_verifier_env *env)
  * the subprog still leaves that way after the pass, as bpf_insert_sites() will see it, did_unwind
  * and did_cancel go to the next pass, in which the callers expect it.
  */
-static void settle_late_unwinds(struct bpf_verifier_env *env, const struct bpf_snapshot *initial)
+static int settle_late_unwinds(struct bpf_verifier_env *env, const struct bpf_snapshot *initial)
 {
 	struct bpf_subprog_info *sub = env->subprog_info;
-	bool unwinds, late = false;
-	int s;
+	bool unwinds, cancels, late = false;
+	int s, err;
 
 	bpf_flow_drop_guards(env);
-	bpf_mark_subprogs_that_unwind(env);
+	err = bpf_mark_subprogs_that_unwind(env, true);
 	for (s = 0; s < env->subprog_cnt; s++, sub++) {
 		unwinds = sub->can_unwind;
+		cancels = sub->can_cancel;
 		sub->can_unwind = initial->subprogs[s].can_unwind;
-		late |= unwinds && !initial->subprogs[s].did_unwind &&
-			bpf_subprog_is_global(env, s);
+		sub->can_cancel = initial->subprogs[s].can_cancel;
+		/* The walk did not finish: keep what the states of the pass found. */
+		if (err)
+			continue;
+		late |= bpf_subprog_is_global(env, s) &&
+			((unwinds && !initial->subprogs[s].did_unwind) ||
+			 (cancels && !initial->subprogs[s].did_cancel));
 		sub->did_unwind = unwinds;
+		sub->did_cancel = cancels;
 	}
-	if (late)
-		mark_unwind_above(env);
+	if (err)
+		return err;
 	env->pads_late = late;
+	return late ? mark_unwind_above(env) : 0;
 }
 
 /*
@@ -24585,27 +24694,32 @@ static void settle_late_unwinds(struct bpf_verifier_env *env, const struct bpf_s
  * see them: a loop that turned out to have a trip count has no may_goto, and a call is no site if
  * its callees leave at no site. can_unwind and can_cancel are restored afterwards.
  */
-static void mark_used_sites(struct bpf_verifier_env *env, const struct bpf_snapshot *initial)
+static int mark_used_sites(struct bpf_verifier_env *env, const struct bpf_snapshot *initial)
 {
-	int s;
+	int s, err;
 
 	bpf_flow_drop_guards(env);
-	bpf_mark_subprogs_that_unwind(env);
+	err = bpf_mark_subprogs_that_unwind(env, true);
 	bpf_pads_mark_used(env);
-	for (s = 0; s < env->subprog_cnt; s++)
+	for (s = 0; s < env->subprog_cnt; s++) {
 		env->subprog_info[s].can_unwind = initial->subprogs[s].can_unwind;
+		env->subprog_info[s].can_cancel = initial->subprogs[s].can_cancel;
+	}
+	return err;
 }
 
 /* Returns the first error */
 static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initial)
 {
 	u32 level = env->log.level;
-	int i, ret;
+	int i, ret, err;
 
 	for (i = 1; i < env->subprog_cnt; i++) {
 		/* did_unwind and did_cancel of a global subprog go to the next pass. */
-		if (bpf_subprog_is_global(env, i))
+		if (bpf_subprog_is_global(env, i)) {
 			initial->subprogs[i].did_unwind |= env->subprog_info[i].did_unwind;
+			initial->subprogs[i].did_cancel |= env->subprog_info[i].did_cancel;
+		}
 		/*
 		 * A repeated run starts with bail_unwinds as subprog_cannot_unwind() left it. Any
 		 * other run starts from the first value: it may not get to the call that clears it.
@@ -24637,8 +24751,10 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
 	bpf_flow_new_pass(env);
 	bpf_pads_new_round(env);
 	ret = do_check_main(env) ?: do_check_subprogs(env) ?: bpf_check_limits(env);
-	if (env->pads_late)
-		settle_late_unwinds(env, initial);
+	if (env->pads_late) {
+		err = settle_late_unwinds(env, initial);
+		ret = ret ?: err;
+	}
 	env->log.level = level;
 	env->pass_max_cost = U64_MAX;
 	return ret == -EINTR ? ret : env->err ?: ret;
@@ -24661,8 +24777,10 @@ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial
 	 * Only the sites that the program keeps count. Hidden slots add to the stack of a
 	 * function, so the landing pads are settled before the stack is checked.
 	 */
-	mark_used_sites(env, initial);
-	ret = bpf_pads_settle(env);
+	ret = mark_used_sites(env, initial) ?: bpf_pads_settle(env);
+	/* The limit on cost or a signal is no error of the program, see do_check_all(). */
+	if (ret == -EINTR || (ret && env->over_limit))
+		return ret;
 	/* bpf_pads_settle() found what a pass has to know from its start: repeat the pass. */
 	if (!ret && pass_needs_restart(env))
 		return 0;
diff --git a/tools/testing/selftests/bpf/progs/pro_epilogue_arena_stack.c b/tools/testing/selftests/bpf/progs/pro_epilogue_arena_stack.c
index e901282c53a3..2bb4261229dd 100644
--- a/tools/testing/selftests/bpf/progs/pro_epilogue_arena_stack.c
+++ b/tools/testing/selftests/bpf/progs/pro_epilogue_arena_stack.c
@@ -83,7 +83,7 @@ __xlated("*(u64 *)(r12 -8) = 10")
 __xlated("...")
 __xlated("call pc+")
 /* a fault in the stack of the subprog unwinds */
-__xlated("unwind_goto pc+")
+__xlated("cancel_goto pc+")
 /* give the stack back, then the epilogue */
 __xlated("w12 += -16")
 __xlated("if w12 & 0x10 goto pc+5")
diff --git a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
index 5d22dfc6fdcb..2a3210a50678 100644
--- a/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
+++ b/tools/testing/selftests/bpf/progs/verifier_arena_stack.c
@@ -5,6 +5,8 @@
 #include "../../../include/linux/filter.h"
 #include "bpf_misc.h"
 
+#define __exception_cb(name) __attribute__((btf_decl_tag("exception_callback:" #name)))
+
 #if defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64)
 
 struct {
@@ -218,10 +220,22 @@ static __naked __noinline __used long goes_down(void)
 	: __clobber_all);
 }
 
+/*
+ * The kernel unwinds the prog, and no code of the prog runs behind the call: what the prog returns
+ * is up to the exception callback, which runs when the frames are gone.
+ */
+__noinline int used_between_8k_and_32k(__u64 cookie)
+{
+	unsigned long used = last_r12 - first_r12;
+
+	return used >= 8192 && used <= 32736;
+}
+
 /* The check of a recursion looks at the kernel stack. It fails before 32K of arena are used. */
 SEC("syscall")
 __description("arena stack: recursion ends in the stack")
 __success __retval(1)
+__exception_cb(used_between_8k_and_32k)
 __naked void recursion(void)
 {
 	asm volatile (
@@ -230,23 +244,12 @@ __naked void recursion(void)
 	"r2 = %[first_r12] ll;"
 	"*(u64 *)(r2 + 0) = r1;"
 	"call goes_down;"
-	".8byte %[unwind_goto];"
-	"r1 = %[last_r12] ll;"
-	"r1 = *(u64 *)(r1 + 0);"
-	"r2 = %[first_r12] ll;"
-	"r2 = *(u64 *)(r2 + 0);"
-	"r1 -= r2;"
 	"r0 = 0;"
-	"if r1 < 8192 goto +2;"
-	"if r1 > 32736 goto +1;"
-	"r0 = 1;"
 	"exit;"
 	:
 	: __imm_addr(first_r12),
-	  __imm_addr(last_r12),
 	  __imm_insn(adj, ADJ(32)),
-	  __imm_insn(mov, MOV(BPF_REG_1)),
-	  __imm_insn(unwind_goto, BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0, 0))
+	  __imm_insn(mov, MOV(BPF_REG_1))
 	: __clobber_all);
 }
 
diff --git a/tools/testing/selftests/bpf/progs/verifier_budget.c b/tools/testing/selftests/bpf/progs/verifier_budget.c
index ddf5f9168c53..8fac2763239e 100644
--- a/tools/testing/selftests/bpf/progs/verifier_budget.c
+++ b/tools/testing/selftests/bpf/progs/verifier_budget.c
@@ -7,9 +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.
+ * it unwinds, frame by frame, up to the main prog or an async callback, which end. No landing
+ * pad that a caller has in the program is on that way: the kernel unwinds with cancel_exit, and the
+ * verifier adds cancel_goto after each 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
@@ -24,6 +25,7 @@
 #define __imm_unwind_exit \
 	__imm_insn(insn_unwind_exit, \
 		   BPF_RAW_INSN(BPF_JMP | BPF_EXIT, 0, BPF_UNWIND_EXIT, 0, 0))
+#define __exception_cb(name) __attribute__((btf_decl_tag("exception_callback:" #name)))
 
 extern void bpf_rcu_read_lock(void) __ksym;
 extern void bpf_rcu_read_unlock(void) __ksym;
@@ -187,13 +189,13 @@ static unsigned long spins_caught(void)
 }
 
 SEC("socket")
-__description("budget: a loop in a subprog unwinds, the verifier adds unwind_goto")
+__description("budget: a loop in a subprog unwinds, the verifier adds cancel_goto")
 __arch_x86_64
 __arch_arm64
 __success __retval(0)
 __xlated("...")
 __xlated("call pc+4")
-__xlated("unwind_goto pc+1")
+__xlated("cancel_goto pc+1")
 __xlated("exit")
 __xlated("r0 = 0")
 __xlated("exit")
@@ -201,7 +203,8 @@ __xlated("...")
 __xlated("r0 = 7")
 __xlated("exit")
 __xlated("r0 = 0")
-__xlated("unwind_exit")
+__xlated("r2 = 0")
+__xlated("cancel_exit")
 __naked void loop_in_subprog(void)
 {
 	asm volatile (
@@ -211,11 +214,22 @@ __naked void loop_in_subprog(void)
 	);
 }
 
+/*
+ * unwind_goto of the prog is for unwind_exit, which the prog has. The kernel unwinds with
+ * cancel_exit: the landing pad of the prog is not entered, and the prog returns what the kernel
+ * says, not 42. Nothing gets to that unwind_goto: it is dead code, and so is the pad.
+ */
 SEC("socket")
-__description("budget: a loop in a subprog unwinds when there is unwind_goto")
+__description("budget: a loop in a subprog unwinds past unwind_goto of the prog")
 __arch_x86_64
 __arch_arm64
-__success __retval(42)
+__success __retval(0)
+__xlated("...")
+__xlated("call pc+")
+__xlated("cancel_goto pc+")
+__xlated("...")
+__xlated("r0 = 0")
+__xlated("exit")
 __naked void loop_in_subprog_caught(void)
 {
 	asm volatile (
@@ -245,12 +259,16 @@ static unsigned long spins_caught3(void)
 	);
 }
 
-/* Nothing in the subprog unwinds. The pad is looked at because of may_goto that is added. */
+/*
+ * Nothing in the subprog leaves with unwind_exit, and may_goto that is added does not lead to the
+ * pad of the prog, which would forget the section: the pad of the verifier leaves it. The loop
+ * ends at once here.
+ */
 SEC("socket")
-__description("budget: the pad forgets what the caller holds")
+__description("budget: the pad of the prog forgets what the caller holds, it is not entered")
 __arch_x86_64
 __arch_arm64
-__failure __msg("cannot be used inside bpf_rcu_read_lock-ed region")
+__success __retval(7)
 __naked void pad_forgets(void)
 {
 	asm volatile (
@@ -292,10 +310,10 @@ static unsigned long spins_locked(void)
 }
 
 SEC("socket")
-__description("budget: a loop in a subprog leaves the section and unwinds to the pad of the prog")
+__description("budget: a loop in a subprog leaves the section and unwinds past the pad of the prog")
 __arch_x86_64
 __arch_arm64
-__success __retval(42)
+__success __retval(0)
 __naked void loop_in_subprog_locked(void)
 {
 	asm volatile (
@@ -345,7 +363,7 @@ __naked void recursion(void)
 
 /* The one that is called too deep unwinds them all */
 SEC("socket")
-__description("budget: recursion that is too deep unwinds, the verifier adds unwind_goto")
+__description("budget: recursion that is too deep unwinds, the verifier adds cancel_goto")
 __arch_x86_64
 __arch_arm64
 __success __retval(0)
@@ -376,32 +394,30 @@ static unsigned long goes_down(void)
 	);
 }
 
+/* What the prog returns is up to the exception callback, which runs when the frames are gone */
+__noinline int lowest_is_in_the_middle(__u64 cookie)
+{
+	return ((lowest_r10 + 64) & 8191) < 256;
+}
+
 /*
  * The stack of a task is aligned to its size, 16K at least. r10 of the last frame whose body
- * runs is right above the middle.
+ * runs is right above the middle. No code of the prog runs behind the call once the kernel
+ * unwinds.
  */
 SEC("socket")
 __description("budget: recursion ends in the middle of the kernel stack")
 __arch_x86_64
 __arch_arm64
 __success __retval(1)
+__exception_cb(lowest_is_in_the_middle)
 __naked void recursion_ends_in_the_middle(void)
 {
 	asm volatile (
 		"call goes_down;"
-		unwind_goto(0)
-		"r1 = %[lowest_r10] ll;"
-		"r1 = *(u64 *)(r1 + 0);"
-		"r1 += 64;"
-		"r1 &= 8191;"
-		"r0 = 1;"
-		"if r1 < 256 goto +1;"
 		"r0 = 0;"
 		"exit;"
-		:
-		: __imm_addr(lowest_r10),
-		  __imm_unwind_goto(0)
-		: __clobber_all
+		::: __clobber_all
 	);
 }
 
@@ -475,11 +491,12 @@ __naked void recursion_caught(void)
 	);
 }
 
+/* Each frame has a landing pad of the prog, and so has the prog. The kernel unwinds past them. */
 SEC("socket")
-__description("budget: recursion that is too deep unwinds")
+__description("budget: recursion that is too deep unwinds past the pads of the prog")
 __arch_x86_64
 __arch_arm64
-__success __retval(42)
+__success __retval(0)
 __naked void recursion_too_deep_caught(void)
 {
 	asm volatile (
@@ -1083,7 +1100,7 @@ SEC("socket")
 __description("budget: a subprog is in a section on some paths")
 __arch_x86_64
 __arch_arm64
-__success __retval(42)
+__success __retval(0)
 __naked void unwinds_then_cannot(void)
 {
 	asm volatile (
diff --git a/tools/testing/selftests/bpf/progs/verifier_patch_list.c b/tools/testing/selftests/bpf/progs/verifier_patch_list.c
index 5516100dd2b0..5631df29d111 100644
--- a/tools/testing/selftests/bpf/progs/verifier_patch_list.c
+++ b/tools/testing/selftests/bpf/progs/verifier_patch_list.c
@@ -416,7 +416,7 @@ __arch_x86_64
 __arch_arm64
 __success
 __xlated("27: call pc+10")
-__xlated("28: unwind_goto pc-15")
+__xlated("28: cancel_goto pc-15")
 __xlated("...")
 __xlated("37: exit")
 __xlated("38: r0 = ")
@@ -433,7 +433,8 @@ __xlated("56: if r1 != 0x0 goto pc-12")
 __xlated("57: r0 = 0")
 __xlated("58: exit")
 __xlated("59: r0 = 0")
-__xlated("60: unwind_exit")
+__xlated("60: r2 = 0")
+__xlated("61: cancel_exit")
 __naked void patch_list_insert_in_front(void)
 {
 	INSERT_IN_FRONT;
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 58/73] bpf: Check that a helper whose callback may unwind has an unwind label
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (56 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 57/73] bpf: Use cancel_exit to leave a frame that the kernel cancels Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:26   ` bot+bpf-ci
  2026-12-01  5:47   ` sashiko-bot
  2026-12-01  4:39 ` [PATCH bpf-next v1 59/73] bpf: Find the landing pads of a program that can only clean up Kumar Kartikeya Dwivedi
                   ` (14 subsequent siblings)
  72 siblings, 2 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

  verifier bug: bpf_find_vma has no landing pad for its callback

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

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

The lists are trusted without a check in two cases:

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 arch/arm64/net/bpf_jit_comp.c | 13 +++---
 arch/x86/net/bpf_jit_comp.c   | 13 +++---
 include/linux/bpf_verifier.h  |  3 ++
 kernel/bpf/verifier.c         | 77 +++++++++++++++++++++++++++++++++--
 4 files changed, 88 insertions(+), 18 deletions(-)

diff --git a/arch/arm64/net/bpf_jit_comp.c b/arch/arm64/net/bpf_jit_comp.c
index 18ec626762f6..c41e649c735f 100644
--- a/arch/arm64/net/bpf_jit_comp.c
+++ b/arch/arm64/net/bpf_jit_comp.c
@@ -1807,13 +1807,12 @@ static u64 unwind_target(u64 ret_addr, int key)
 		return (unsigned long)&e->fixup + e->fixup +
 		       (key == CANCEL_EXKEY ? BPF_CB_CANCEL_OFF : BPF_CB_PAD_OFF);
 	/*
-	 * No pad. That is how it ends when the kernel called an async callback
-	 * or the main prog of an extension: it's exit. A call in a prog of what
-	 * can unwind has unwind_goto behind it, which is an entry also when the
-	 * pad is the next insn, and cancel_goto behind a call of what has
-	 * cancel_exit. So a return address in a prog without an entry is an
-	 * unwind_exit or a cancel_exit that gets lost: the verifier sent it to
-	 * a pad.
+	 * No entry: the kernel called the frame, as it calls an async callback
+	 * or the main prog of an extension, and the frame returns like exit.
+	 * In a prog, unwind_goto or cancel_goto follows every call whose callee
+	 * can leave this way, so a return address in a prog is a bug here. A
+	 * helper without an unwind label would not show: the verifier checks
+	 * for that at load time, see check_cb_pad().
 	 */
 	scoped_guard(rcu)
 		WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
diff --git a/arch/x86/net/bpf_jit_comp.c b/arch/x86/net/bpf_jit_comp.c
index 1c7bc301784f..fc57ab6a238c 100644
--- a/arch/x86/net/bpf_jit_comp.c
+++ b/arch/x86/net/bpf_jit_comp.c
@@ -2440,13 +2440,12 @@ static u64 unwind_target(u64 ret_addr, int key)
 		return (unsigned long)&e->fixup + e->fixup +
 		       (key == CANCEL_EXKEY ? BPF_CB_CANCEL_OFF : BPF_CB_PAD_OFF);
 	/*
-	 * No pad. That is how it ends when the kernel called an async callback
-	 * or the main prog of an extension: it's exit. A call in a prog of what
-	 * can unwind has unwind_goto behind it, which is an entry also when the
-	 * pad is the next insn, and cancel_goto behind a call of what has
-	 * cancel_exit. So a return address in a prog without an entry is an
-	 * unwind_exit or a cancel_exit that gets lost: the verifier sent it to
-	 * a pad.
+	 * No entry: the kernel called the frame, as it calls an async callback
+	 * or the main prog of an extension, and the frame returns like exit.
+	 * In a prog, unwind_goto or cancel_goto follows every call whose callee
+	 * can leave this way, so a return address in a prog is a bug here. A
+	 * helper without an unwind label would not show: the verifier checks
+	 * for that at load time, see check_cb_pad().
 	 */
 	scoped_guard(rcu)
 		WARN_ON_ONCE(bpf_prog_ksym_find(ret_addr - 1));
diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index c500504cbfe1..6efe11f458b7 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -1902,6 +1902,9 @@ struct bpf_verifier_env {
 	bool run_over_budget;		/* in one of its functions, see find_failing_path() */
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
 	bool guards_late;		/* see bpf_flow_needs_guard() */
+	/* the helpers and kfuncs whose unwind label was found, see check_cb_pad() */
+	unsigned long cb_pads[8];
+	u8 cb_pad_cnt;
 	bool pads_late;			/* a global subprog unwinds: see settle_late_unwinds() */
 	bool faults_late;		/* a site is not what it seemed: see check_arena_site() */
 	bool pad_releases;		/* see release_frame_resources() */
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 3cade295dd8d..76ba16991a24 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -11807,6 +11807,64 @@ static bool insn_has_cb_pad(const struct bpf_insn *insn)
 		(bpf_pseudo_kfunc_call(insn) && kfunc_has_cb_pad(insn->imm)));
 }
 
+extern struct exception_table_entry __start___ex_table[];
+extern struct exception_table_entry __stop___ex_table[];
+
+/*
+ * Does the function at @addr call a callback with bpf_call_cb()? Such a call has an exception
+ * table entry whose key is its return address.
+ */
+static bool func_has_cb_pad(unsigned long addr)
+{
+#ifdef ARCH_HAS_RELATIVE_EXTABLE
+	const struct exception_table_entry *e = __start___ex_table, *end = __stop___ex_table;
+	unsigned long size, off, key;
+	struct module *mod;
+
+	/* Only a JIT that unwinds can recognize such an entry. Without one, trust the lists. */
+	if (!bpf_jit_supports_unwind())
+		return true;
+	/* Without kallsyms the size of the function is not known, and the lists are trusted. */
+	if (!kallsyms_lookup_size_offset(addr, &size, &off))
+		return true;
+	addr -= off;
+	guard(rcu)();
+	mod = __module_address(addr);
+	if (mod) {
+		e = mod->extable;
+		end = e + mod->num_exentries;
+	}
+	for (; e < end; e++) {
+		key = (unsigned long)&e->insn + e->insn;
+		/* bpf_unwind_target() returns the key itself for an entry of any other kind */
+		if (key > addr && key - addr <= size && bpf_unwind_target(key) != key)
+			return true;
+	}
+#endif
+	return false;
+}
+
+/*
+ * The lists above say that the function @name at @addr has an unwind label. They are kept by hand,
+ * so check it. If a listed function had no label, unwind_exit or cancel_exit of its callback would
+ * find no exception table entry and return to the function like exit, and nothing would warn.
+ * Each function is checked once per load.
+ */
+static int check_cb_pad(struct bpf_verifier_env *env, unsigned long addr, const char *name)
+{
+	int i;
+
+	for (i = 0; i < env->cb_pad_cnt; i++)
+		if (env->cb_pads[i] == addr)
+			return 0;
+	if (verifier_bug_if(!func_has_cb_pad(addr), env,
+			    "%s has no landing pad for its callback", name))
+		return -EFAULT;
+	if (env->cb_pad_cnt < ARRAY_SIZE(env->cb_pads))
+		env->cb_pads[env->cb_pad_cnt++] = addr;
+	return 0;
+}
+
 /*
  * A helper or a kfunc is a C frame between its callback and the BPF code that called it. When the
  * callback unwinds, a helper with an unwind label releases what it holds and leaves to the
@@ -13628,6 +13686,12 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 	if (err)
 		return err;
 
+	if (insn_has_cb_pad(insn)) {
+		err = check_cb_pad(env, (unsigned long)fn->func, func_id_name(func_id));
+		if (err)
+			return err;
+	}
+
 	if (meta.release_regno) {
 		struct bpf_reg_state *reg = &regs[meta.release_regno];
 		bool convert_rcu = (func_id == BPF_FUNC_kptr_xchg) && in_rcu_cs(env) &&
@@ -13654,8 +13718,12 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 		}
 		break;
 	case BPF_FUNC_for_each_map_elem:
-		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
-					 set_map_elem_callback_state);
+		/* The helper calls the op of the map, which calls the callback: check the op. */
+		err = BPF_HAS_CB_PADS ?
+		      check_cb_pad(env, (unsigned long)meta.map.ptr->ops->map_for_each_callback,
+				   "map_for_each_callback()") : 0;
+		err = err ?: push_callback_call(env, insn, insn_idx, meta.subprogno,
+						set_map_elem_callback_state);
 		break;
 	case BPF_FUNC_timer_set_callback:
 		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
@@ -16538,8 +16606,9 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 			if (err)
 				return err;
 		}
-		err = push_callback_call(env, insn, insn_idx, meta.subprogno,
-					 set_rbtree_add_callback_state);
+		err = insn_has_cb_pad(insn) ? check_cb_pad(env, desc->addr, func_name) : 0;
+		err = err ?: push_callback_call(env, insn, insn_idx, meta.subprogno,
+						set_rbtree_add_callback_state);
 		if (err) {
 			verbose(env, "kfunc %s#%d failed callback verification\n",
 				func_name, meta.func_id);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 59/73] bpf: Find the landing pads of a program that can only clean up
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (57 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 58/73] bpf: Check that a helper whose callback may unwind has an unwind label Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 60/73] bpf: Don't let hidden stack words turn on the private stack Kumar Kartikeya Dwivedi
                   ` (13 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

  what the program has      what the verifier makes of it

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

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

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

Some landing pads of the program need care:

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |   3 +
 kernel/bpf/pads.c            | 114 +++++++++++++++++++++++++++++++++++
 2 files changed, 117 insertions(+)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 6efe11f458b7..66771c403f95 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -1373,6 +1373,8 @@ struct bpf_insn_aux_data {
 	u32 calls_callback:1;
 	/* true if some jump or call instruction targets this instruction */
 	u32 jump_target:1;
+	/* an unwind_goto of the program that leads to a cleanup pad, see bpf_find_cleanup_pads() */
+	u32 cleanup_pad:1;
 	/* it can read or write the frame of a caller, in a call with a known callee */
 	u32 reads_outer:1;
 	u32 writes_outer:1;
@@ -2500,6 +2502,7 @@ int bpf_pad_insns_before(const struct bpf_subprog_info *sub, const struct bpf_pa
 int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
 			int nr, const struct bpf_pad_note *note, struct bpf_insn *buf);
 void bpf_pads_log(struct bpf_verifier_env *env);
+int bpf_find_cleanup_pads(struct bpf_verifier_env *env);
 
 int bpf_copy_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *dst_state,
 			    const struct bpf_verifier_state *src);
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 4ab3df74b97a..e4a9f9600822 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -110,6 +110,9 @@
  * Where a callee leaves with unwind_exit and the call has no unwind_goto (BPF_SITE_CALL), the
  * verifier adds one, with a pad that leaves with unwind_exit in turn.
  *
+ * A landing pad of the program is a CLEANUP PAD if it can only clean up and continue unwinding,
+ * like a C++ destructor or Rust drop glue, see bpf_find_cleanup_pads().
+ *
  * A frame can be in fewer sections than it was called in. Its pad enters the sections that the
  * frame left, so that the caller is in the sections of its call wherever the callee is cancelled.
  * Here grow() is called with preemption disabled, and its load from arena can fault. The fault
@@ -3754,3 +3757,114 @@ void bpf_pads_log(struct bpf_verifier_env *env)
 		verbose(env, "\n");
 	}
 }
+
+/*
+ * Does @insn return to the caller? exit does, and so do a tail call that is taken and an LD_ABS or
+ * LD_IND that fails. unwind_exit does not: the caller is unwound in turn.
+ */
+static bool insn_returns(const struct bpf_insn *insn)
+{
+	if (insn->code == (BPF_JMP | BPF_EXIT))
+		return !bpf_is_unwind_exit(insn);
+	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_tail_call)
+		return true;
+	return BPF_CLASS(insn->code) == BPF_LD &&
+	       (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND);
+}
+
+/*
+ * Find the cleanup pads of the program on the control flow graph, before the main pass. The landing
+ * pad of an unwind_goto is a cleanup pad ('cleanup_pad' in the aux data of the unwind_goto) if,
+ * from its first insn, no path in the function reaches an insn that returns to the caller, see
+ * insn_returns(), and some path reaches unwind_exit:
+ *
+ *	   ~Guard()		   try { } catch (...)	   noexcept
+ *
+ *	   call foo		   call foo		   call foo
+ *	   unwind_goto pad	   unwind_goto pad	   unwind_goto pad
+ *	   ...			   ...			   ...
+ *    pad: r6 = r0		   call begin_catch	   call terminate
+ *	   call dtor		   ...			   goto -1
+ *	   r0 = r6		   r0 = 0
+ *	   unwind_exit		   exit
+ *
+ *	   a cleanup pad	   returns		   no unwind_exit
+ *
+ *	only resumes		returns			no unwind_exit
+ *
+ * A typed catch gets to its handler by a branch on what the personality routine of the program
+ * says, which is a value like any other: the pad returns. Pads that share their last insns, as the
+ * pads of one function of C++ do, are judged one by one, each from its first insn.
+ *
+ * The answer is a property of the insns, the same in every pass: 'cleanup_pad' of unwind_goto.
+ * Dead branches are gone from the graph, see bpf_prune_dead_branches().
+ */
+int bpf_find_cleanup_pads(struct bpf_verifier_env *env)
+{
+	const struct bpf_insn *insns = env->prog->insnsi, *insn;
+	int i, p, t, pad, cnt, len = env->prog->len, err = 0;
+	unsigned long *returns, *resumes;
+	struct bpf_iarray *succ;
+	bool changed, ret, res;
+
+	for (i = 0; i < len && !bpf_is_unwind_goto(&insns[i]); i++)
+		;
+	if (i == len)
+		return 0;
+	returns = bitmap_zalloc(len, BPF_VERIFIER_GFP);
+	resumes = bitmap_zalloc(len, BPF_VERIFIER_GFP);
+	if (!returns || !resumes) {
+		err = -ENOMEM;
+		goto out;
+	}
+	for (i = 0; i < len; i++) {
+		if (insn_returns(&insns[i]))
+			__set_bit(i, returns);
+		if (bpf_is_unwind_exit(&insns[i]))
+			__set_bit(i, resumes);
+	}
+	/* an insn reaches what its successors reach, and those come first in the postorder */
+	do {
+		changed = false;
+		err = bpf_add_cost_and_check(env, env->cfg.cur_postorder, BPF_COST_SCAN);
+		if (err)
+			goto out;
+		for (p = 0; p < env->cfg.cur_postorder; p++) {
+			i = env->cfg.insn_postorder[p];
+			insn = &insns[i];
+			ret = test_bit(i, returns);
+			res = test_bit(i, resumes);
+			succ = bpf_insn_successors(env, i);
+			/*
+			 * The edge of a tail call or LD_ABS to the exit insn that stands for its
+			 * return is not followed: the insn returns, whatever that exit is.
+			 */
+			cnt = insn_returns(insn) ? min(succ->cnt, 1) : succ->cnt;
+			for (t = 0; t < cnt; t++) {
+				ret |= test_bit(succ->items[t], returns);
+				res |= test_bit(succ->items[t], resumes);
+			}
+			if (ret && !__test_and_set_bit(i, returns))
+				changed = true;
+			if (res && !__test_and_set_bit(i, resumes))
+				changed = true;
+		}
+	} while (changed);
+	for (i = 0; i < len; i++) {
+		insn = &insns[i];
+		if (!bpf_is_unwind_goto(insn))
+			continue;
+		pad = i + 1 + bpf_jmp_offset(insn);
+		ret = test_bit(pad, returns);
+		res = test_bit(pad, resumes);
+		env->insn_aux_data[i].cleanup_pad = !ret && res;
+		if (!(env->log.level & BPF_LOG_LEVEL2))
+			continue;
+		verbose(env, "landing pad at %d of the call at %d %s\n", pad, i - 1,
+			ret ? "returns" : res ? "only resumes" : "has no unwind_exit");
+	}
+out:
+	bitmap_free(returns);
+	bitmap_free(resumes);
+	return err;
+}
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 60/73] bpf: Don't let hidden stack words turn on the private stack
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (58 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 59/73] bpf: Find the landing pads of a program that can only clean up Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 61/73] bpf: Add a landing pad per site for frames that are cancelled already Kumar Kartikeya Dwivedi
                   ` (12 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h | 30 ++++++++++++++++++++++++++++++
 kernel/bpf/pads.c            |  7 ++-----
 kernel/bpf/verifier.c        | 29 ++++++++++++++++++++---------
 3 files changed, 52 insertions(+), 14 deletions(-)

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


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 61/73] bpf: Add a landing pad per site for frames that are cancelled already
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (59 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 60/73] bpf: Don't let hidden stack words turn on the private stack Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 62/73] bpf: Verify a cleanup pad for a frame that is cancelled Kumar Kartikeya Dwivedi
                   ` (11 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  25 ++++++-
 kernel/bpf/fixups.c          | 122 +++++++++++++++++++++++++++--------
 kernel/bpf/pads.c            |  36 +++++++----
 kernel/bpf/verifier.c        |   3 +
 4 files changed, 143 insertions(+), 43 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index e578977518fb..9dd68c7a29fd 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -469,15 +469,33 @@ enum bpf_site_kind {
 	BPF_SITE_MAY_GOTO,	/* a may_goto of the program, see check_may_goto_site() */
 	/* a call whose callee was cancelled, with or without an unwind_goto of the program */
 	BPF_SITE_CANCEL_CALL,
+	/*
+	 * A flag on top of a kind: the frame that reaches the site is cancelled already. Such
+	 * frames have a plan and a landing pad of their own at the site.
+	 */
+	BPF_SITE_CANCELLED = 0x10,
 };
 
+static inline enum bpf_site_kind bpf_site_base(enum bpf_site_kind kind)
+{
+	return kind & ~BPF_SITE_CANCELLED;
+}
+
+static inline bool bpf_site_is_cancelled(enum bpf_site_kind kind)
+{
+	return kind & BPF_SITE_CANCELLED;
+}
+
 /* The site is a call whose callee did not return: it left with unwind_exit or was cancelled */
 static inline bool bpf_site_is_call(enum bpf_site_kind kind)
 {
-	return kind == BPF_SITE_CALL || kind == BPF_SITE_CANCEL_CALL;
+	return bpf_site_base(kind) == BPF_SITE_CALL || bpf_site_base(kind) == BPF_SITE_CANCEL_CALL;
 }
 
-/* The kernel cancels the frame at a site of @kind */
+/*
+ * The kernel cancels the frame at a site of @kind. That includes a call in a frame that is
+ * cancelled already whose callee left with unwind_exit.
+ */
 static inline bool bpf_site_is_cancel(enum bpf_site_kind kind)
 {
 	return kind != BPF_SITE_CALL;
@@ -2460,7 +2478,8 @@ static inline bool bpf_pad_passes_on(const struct bpf_verifier_env *env, int sub
 static inline bool bpf_site_has_value(const struct bpf_verifier_env *env, int subprog,
 				      enum bpf_site_kind kind)
 {
-	if (bpf_pad_rethrows(env, subprog, kind))
+	/* a frame that is cancelled already has the value in its value word */
+	if (bpf_site_is_cancelled(kind) || bpf_pad_rethrows(env, subprog, kind))
 		return false;
 	return env->has_throw && (bpf_site_is_call(kind) || kind == BPF_SITE_THROW);
 }
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 7a913f5b5df6..e3f7e5b37bc5 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -659,7 +659,7 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 {
 	int s;
 
-	switch (plan->kind) {
+	switch (bpf_site_base(plan->kind)) {
 	case BPF_SITE_GUARD:
 		return env->insn_aux_data[i].loop_guard;
 	case BPF_SITE_RECURSION:
@@ -684,8 +684,9 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 		return !env->insn_aux_data[i].fault_skips;
 	case BPF_SITE_MAY_GOTO:
 		return plan->visited && !bpf_find_containing_subprog(env, i)->stuck;
+	default:
+		return false;
 	}
-	return false;
 }
 
 /*
@@ -743,7 +744,7 @@ int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)
 static bool plan_has_pad(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
 {
 	/* bpf_insert_recursion_checks() emits the pad of the check */
-	return plan->kind != BPF_SITE_RECURSION && bpf_site_is_used(env, i, plan);
+	return bpf_site_base(plan->kind) != BPF_SITE_RECURSION && bpf_site_is_used(env, i, plan);
 }
 
 /* The record of the site of @kind at insn @i. An empty one is made if no state reached the site. */
@@ -760,19 +761,93 @@ static struct bpf_pad_plan *unvisited_plan(struct bpf_verifier_env *env, int i,
 	return plan;
 }
 
+/* The landing pads that go after a subprog: their insns, and where each pad ends */
+struct pad_buf {
+	struct bpf_insn *insns;
+	int *ends;
+	/* maps the hash of the insns of a pad to the pad, so that add_pad() can share it */
+	struct bpf_index index;
+	u64 seed;
+	int max_nr;	/* the room of 'ends' */
+	int max_cnt;	/* the room of 'insns' */
+	int nr;		/* pads */
+	int cnt;	/* insns */
+};
+
+/* Make room in @pads for @n more insns. The buffer is kept from one subprog to the next. */
+static int reserve_pad_insns(struct pad_buf *pads, int n)
+{
+	int max = max3(2 * pads->max_cnt, pads->cnt + n, 64);
+	void *mem;
+
+	if (pads->cnt + n <= pads->max_cnt)
+		return 0;
+	mem = kvrealloc(pads->insns, array_size(max, sizeof(*pads->insns)), BPF_VERIFIER_GFP);
+	if (!mem)
+		return -ENOMEM;
+	pads->insns = mem;
+	pads->max_cnt = max;
+	return 0;
+}
+
+/*
+ * Add the pad @new of @n insns to @pads. With @share, reuse a pad of the subprog that has the same
+ * insns. It is found by a hash of the insns, with a random seed so that a program cannot make pads
+ * collide. Returns where the pad starts in @pads, or a negative error.
+ */
+static int add_pad(struct pad_buf *pads, const struct bpf_insn *new, int n, bool share)
+{
+	int k, start = 0;
+	void *mem;
+	u64 key = 0;
+
+	if (bpf_must_abort())
+		return -EINTR;
+	/* the first pad of a subprog: drop the index of the subprog before it */
+	if (!pads->nr) {
+		kvfree(pads->index.slots);
+		pads->index = (struct bpf_index){};
+		pads->seed = get_random_u64();
+	}
+	if (share)
+		key = bpf_hash64(new, n * sizeof(*new), pads->seed);
+	/* pads with the same hash have consecutive keys */
+	for (; share && (k = bpf_index_find(&pads->index, key)) >= 0; key++) {
+		const struct bpf_insn *pad = &pads->insns[k ? pads->ends[k - 1] : start];
+
+		if (&pads->insns[pads->ends[k]] - pad == n && !memcmp(pad, new, n * sizeof(*new)))
+			return pad - pads->insns;
+	}
+	if (pads->nr == pads->max_nr) {
+		k = max(2 * pads->max_nr, 16);
+		mem = kvrealloc(pads->ends, array_size(k, sizeof(*pads->ends)), BPF_VERIFIER_GFP);
+		if (!mem)
+			return -ENOMEM;
+		pads->ends = mem;
+		pads->max_nr = k;
+	}
+	if (reserve_pad_insns(pads, n) || (share && bpf_index_add(&pads->index, key, pads->nr)))
+		return -ENOMEM;
+	memcpy(&pads->insns[pads->cnt], new, n * sizeof(*new));
+	start = pads->cnt;
+	pads->cnt += n;
+	pads->ends[pads->nr++] = pads->cnt;
+	return start;
+}
+
 /*
  * The landing pads of the sites of subprog @s go after its last insn. Sites whose pads have the
- * same insns share one. @new and @new_aux have room for a pad. Returns the insns in @pads and
- * their number.
+ * same insns share one. @new and @new_aux have room for a pad. Returns the pads in @pads, which
+ * has the memory of the subprog before, and the number of their insns.
  */
 static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *new,
-			struct bpf_insn_aux_data *new_aux, struct bpf_insn **pads)
+			struct bpf_insn_aux_data *new_aux, struct pad_buf *pads)
 {
-	int last = env->subprog_info[s + 1].start - 1, cnt = 0, i, n, pad, len;
+	int last = env->subprog_info[s + 1].start - 1, i, n, pad;
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
-	struct bpf_insn *buf = *pads, *insn;
 	struct bpf_pad_plan *plan, *shared = NULL;
 
+	pads->nr = pads->cnt = 0;
 	for (i = env->subprog_info[s].start; i <= last; i++) {
 		if (aux[i].loop_guard && !unvisited_plan(env, i, BPF_SITE_GUARD))
 			return -ENOMEM;
@@ -795,25 +870,13 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 					    "the landing pad of insn %d was not settled", i))
 				return -EFAULT;
 			n = emit_pad(env, s, plan, new, new_aux);
-			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++)
-					;
-				if (len == n && !memcmp(&buf[pad], new, n * sizeof(*buf)))
-					break;
-			}
+			pad = add_pad(pads, new, n, bpf_pad_can_be_shared(plan));
+			if (pad < 0)
+				return pad;
 			plan->pad = pad;
-			if (pad < cnt)
-				continue;
-			insn = kvrealloc(buf, (cnt + n) * sizeof(*buf), BPF_VERIFIER_GFP);
-			if (!insn)
-				return -ENOMEM;
-			*pads = buf = insn;
-			memcpy(&buf[cnt], new, n * sizeof(*buf));
-			cnt += n;
 		}
 	}
-	return cnt;
+	return pads->cnt;
 }
 
 /* The plan of the site of @kind at insn @i if it has unwind_goto or cancel_goto after it */
@@ -1023,8 +1086,9 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 {
 	struct bpf_insn patch[2] = { BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0) };
 	struct bpf_insn_aux_data *aux = env->insn_aux_data, *pad_aux;
-	struct bpf_insn *pads = NULL, *new, *insn;
+	struct bpf_insn *new, *insn;
 	const struct bpf_pad_plan *plan;
+	struct pad_buf pads = {};
 	struct bpf_subprog_info *sub;
 	int i, s, cnt, err = 0;
 	int *added;
@@ -1073,7 +1137,7 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 					    cnt - plan->pad);
 		}
 		if (cnt)
-			err = bpf_patch_list_append(env, i - 1, pads, cnt);
+			err = bpf_patch_list_append(env, i - 1, pads.insns, cnt);
 	}
 	err = err ?: bpf_patch_list_commit(env);
 	if (err)
@@ -1091,7 +1155,7 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 				if (plan->kind == BPF_SITE_FAULT && aux[i].fault_unwinds)
 					sub->fault_pad = cnt;
 				/* no call is made, see check_kfunc_call() */
-				if (plan->kind == BPF_SITE_THROW)
+				if (bpf_site_base(plan->kind) == BPF_SITE_THROW)
 					env->prog->insnsi[i] = BPF_RAW_INSN(BPF_JMP32 | BPF_JA, 0, 0, 0,
 									    cnt - i - 1);
 			}
@@ -1109,7 +1173,9 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 	kvfree(added);
 	kvfree(new);
 	kvfree(pad_aux);
-	kvfree(pads);
+	kvfree(pads.insns);
+	kvfree(pads.ends);
+	kvfree(pads.index.slots);
 	return err;
 }
 
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index e84867527b71..6969abb66250 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -2350,7 +2350,10 @@ int bpf_pad_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
 	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++)
 		for (i = 0; i < pad_enters(plan, class); i++)
 			buf[n++] = enter_call(class);
-	if (plan_saves_value(env, plan, subprog)) {
+	if (bpf_site_is_cancelled(plan->kind) && env->has_throw) {
+		/* the value of the first cancellation, which the entry of the cleanup pad stored */
+		buf[n++] = BPF_LDX_MEM(BPF_DW, dst, BPF_REG_FP, value_off);
+	} else if (plan_saves_value(env, plan, subprog)) {
 		buf[n++] = BPF_LDX_MEM(BPF_DW, dst, BPF_REG_FP, value_off);
 		if (pair)
 			buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_2, BPF_REG_FP,
@@ -2455,6 +2458,9 @@ bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan
 	const struct bpf_subprog_info *sub;
 	int s;
 
+	/* the frame was being unwound when it got to the site: what began that is asked */
+	if (bpf_site_is_cancelled(plan->kind))
+		return false;
 	if (!bpf_site_is_call(plan->kind))
 		return plan->kind != BPF_SITE_FAULT && plan->kind != BPF_SITE_MAY_GOTO;
 	/* the callees came back cancelled or with unwind_exit, by the kind of the site */
@@ -2525,8 +2531,8 @@ static const char * const site_kind[] = {
  */
 static u16 kinds_of_plan(const struct bpf_pad_plan *plan, u16 kinds)
 {
-	return plan->kind == BPF_SITE_CANCEL_CALL ? kinds & ~LEFT_AT_UNWIND_EXIT
-						  : kinds & LEFT_AT_UNWIND_EXIT;
+	return bpf_site_base(plan->kind) == BPF_SITE_CANCEL_CALL ? kinds & ~LEFT_AT_UNWIND_EXIT
+								 : kinds & LEFT_AT_UNWIND_EXIT;
 }
 
 /*
@@ -2565,7 +2571,7 @@ static int sites_of_subprogs(struct bpf_verifier_env *env)
 					if (!plan->used)
 						continue;
 					if (!bpf_site_is_call(plan->kind)) {
-						kinds |= BIT(plan->kind);
+						kinds |= BIT(bpf_site_base(plan->kind));
 						continue;
 					}
 					bpf_pad_for_each_callee(plan, c)
@@ -2713,7 +2719,7 @@ static int slot_words(const struct bpf_pad_note *note)
 /* Does the pad of @plan run in a frame that has set up its hidden slots? */
 static bool plan_has_slots(const struct bpf_pad_plan *plan)
 {
-	return plan->kind != BPF_SITE_RECURSION && !plan->conflict;
+	return bpf_site_base(plan->kind) != BPF_SITE_RECURSION && !plan->conflict;
 }
 
 /* Does @plan have room for @slots releases instead of those that it has of @group? */
@@ -3247,9 +3253,13 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 	};
 	int j;
 
-	/* a call has one for what the kernel unwinds, and one for unwind_exit of the program */
-	verbose(env, "landing pad of %s at %d%s: ", site_kind[plan->kind], i,
-		plan->kind == BPF_SITE_CALL ? " for unwind_exit" : "");
+	/*
+	 * A call can have a pad for a cancellation and one for the program's unwind_exit. Every
+	 * site can have one more for the frames that are cancelled already.
+	 */
+	verbose(env, "landing pad of %s at %d%s%s: ", site_kind[bpf_site_base(plan->kind)], i,
+		bpf_site_base(plan->kind) == BPF_SITE_CALL ? " for unwind_exit" : "",
+		bpf_site_is_cancelled(plan->kind) ? " in a frame that the kernel unwinds" : "");
 	for (j = plan->nr_ents - 1; !plan->conflict && j >= 0; j--)
 		print_ent(env, &plan->ents[j]);
 	if (plan->conflict)
@@ -3300,7 +3310,7 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pa
 void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *sub,
 		       const struct bpf_pad_plan *plan, enum bpf_site_kind kind)
 {
-	sub->left_at |= bpf_site_is_call(kind) ? sites_below(env, plan) : BIT(kind);
+	sub->left_at |= bpf_site_is_call(kind) ? sites_below(env, plan) : BIT(bpf_site_base(kind));
 }
 
 /* Did bpf_pad_skip_faults() walk @sub, and has no call in or below it got a new callee since? */
@@ -3448,7 +3458,8 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 				continue;
 			err = settle_plan(env, plan);
 			sub = bpf_find_containing_subprog(env, i);
-			if (!err && plan_saves_value(env, plan, sub - env->subprog_info))
+			if (!err && (plan_saves_value(env, plan, sub - env->subprog_info) ||
+				     (bpf_site_is_cancelled(plan->kind) && env->has_throw)))
 				err = take_value_word(env, sub);
 			if (err < 0)
 				return err;
@@ -3575,7 +3586,7 @@ static void note_causes(struct bpf_verifier_env *env, int insn_idx, const struct
 		bpf_pad_for_each_callee(plan, s)
 			sub[s].asks_args |= sub[s].releases_args;
 	}
-	if (plan->kind != BPF_SITE_CANCEL_CALL)
+	if (bpf_site_base(plan->kind) != BPF_SITE_CANCEL_CALL)
 		return;
 	bpf_pad_for_each_callee(plan, s)
 		sub[s].below_conflict = true;
@@ -3621,7 +3632,8 @@ static void note_causes_below(struct bpf_verifier_env *env)
 			break;
 		for (i = sub[s].start; i < sub[s + 1].start; i++) {
 			for (below = aux[i].pad_plans; below; below = below->next) {
-				if (below->kind != BPF_SITE_CANCEL_CALL || !below->visited)
+				if (bpf_site_base(below->kind) != BPF_SITE_CANCEL_CALL ||
+				    !below->visited)
 					continue;
 				/*
 				 * The frame is left at this call, whatever what it calls
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 99c7c1370211..5b0700660bcf 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -22444,6 +22444,9 @@ static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_p
 {
 	int s;
 
+	/* A cancelled frame came through an entry, which the program may not keep. */
+	if (bpf_site_is_cancelled(plan->kind))
+		return false;
 	switch (plan->kind) {
 	case BPF_SITE_GUARD:
 		return !bpf_flow_guard_is_guess(env, insn_idx);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 62/73] bpf: Verify a cleanup pad for a frame that is cancelled
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (60 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 61/73] bpf: Add a landing pad per site for frames that are cancelled already Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 63/73] bpf: Reject a program whose cleanup pad a cancellation cannot enter Kumar Kartikeya Dwivedi
                   ` (10 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

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

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

Some cases need care:

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  43 ++++-
 kernel/bpf/fixups.c          |  36 +++-
 kernel/bpf/pads.c            | 321 +++++++++++++++++++++++++++--------
 kernel/bpf/verifier.c        | 229 ++++++++++++++++++++++---
 4 files changed, 521 insertions(+), 108 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 9dd68c7a29fd..1e87200119bc 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -469,6 +469,13 @@ enum bpf_site_kind {
 	BPF_SITE_MAY_GOTO,	/* a may_goto of the program, see check_may_goto_site() */
 	/* a call whose callee was cancelled, with or without an unwind_goto of the program */
 	BPF_SITE_CANCEL_CALL,
+	/*
+	 * Such a call whose unwind_goto leads to a cleanup pad. The frame does not leave: its
+	 * cancel_goto leads to the entry of the cleanup pad, see enter_cleanup_pad().
+	 */
+	BPF_SITE_CANCEL_ENTRY,
+	/* an unwind_exit of the program in a cancelled frame: the remainder replaces it */
+	BPF_SITE_REMAINDER,
 	/*
 	 * A flag on top of a kind: the frame that reaches the site is cancelled already. Such
 	 * frames have a plan and a landing pad of their own at the site.
@@ -481,15 +488,17 @@ static inline enum bpf_site_kind bpf_site_base(enum bpf_site_kind kind)
 	return kind & ~BPF_SITE_CANCELLED;
 }
 
+/* The frame that reaches the site is cancelled already */
 static inline bool bpf_site_is_cancelled(enum bpf_site_kind kind)
 {
-	return kind & BPF_SITE_CANCELLED;
+	return (kind & BPF_SITE_CANCELLED) || kind == BPF_SITE_REMAINDER;
 }
 
 /* The site is a call whose callee did not return: it left with unwind_exit or was cancelled */
 static inline bool bpf_site_is_call(enum bpf_site_kind kind)
 {
-	return bpf_site_base(kind) == BPF_SITE_CALL || bpf_site_base(kind) == BPF_SITE_CANCEL_CALL;
+	return bpf_site_base(kind) == BPF_SITE_CALL || bpf_site_base(kind) == BPF_SITE_CANCEL_CALL ||
+	       kind == BPF_SITE_CANCEL_ENTRY;
 }
 
 /*
@@ -807,6 +816,7 @@ struct bpf_func_state {
 	bool in_rcu_callback_fn;
 	/* parent_id of the args that are gone when this frame returns */
 	u32 frame_id;
+	u32 cancelled;	/* the marks BPF_FRAME_CANCELLED and BPF_FRAME_BELOW */
 	/*
 	 * Bit f: the frame, or a subprog that returned to it, released a lock or irq flags of
 	 * frame f. If the frame returns, a store after its call clears the hidden slot. If not,
@@ -903,6 +913,22 @@ struct bpf_equations {
 	u32 clean_sym_cnt;	/* after the last bpf_equations_clean() */
 };
 
+/* The marks in 'cancelled' of struct bpf_func_state */
+enum {
+	/* The frame is cancelled and runs a cleanup pad, see enter_cleanup_pad(). Never cleared. */
+	BPF_FRAME_CANCELLED = 1,
+	/*
+	 * The first frame of a function that is verified separately, for a call out of a frame
+	 * that has a mark. It only keeps the function apart from its other calls.
+	 */
+	BPF_FRAME_BELOW = 2,
+};
+
+static inline bool bpf_frame_is_cancelled(const struct bpf_func_state *frame)
+{
+	return frame->cancelled & BPF_FRAME_CANCELLED;
+}
+
 /* 'unwound' of struct bpf_verifier_state: how the callee left when it did not return */
 enum {
 	/*
@@ -1665,11 +1691,20 @@ struct bpf_subprog_info {
 	bool made_calls: 1;
 	/* scratch of bpf_pads_note_causes(): its insns are searched for causes of the error */
 	bool below_conflict: 1;
+	/*
+	 * scratch of bpf_pads_note_causes(): a cancelled frame of it got no landing pad because
+	 * of a reference, see ask_below_cleanup_pads()
+	 */
+	bool cleanup_pad_ref_conflict: 1;
 	/*
 	 * In this pass the verifier merged states in a callee of it that differ in which
 	 * references the arguments of the call had, see bpf_pad_states_meet()
 	 */
 	bool arg_refs_differ: 1;
+	/* it has an unwind_goto that leads to a cleanup pad, see bpf_find_cleanup_pads() */
+	bool has_cleanup_pads: 1;
+	/* a cancellation enters one of its cleanup pads, see bpf_mark_subprogs_that_unwind() */
+	bool enters_cleanup_pads: 1;
 	/* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */
 	u16 left_at;
 	/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */
@@ -1688,6 +1723,8 @@ struct bpf_subprog_info {
 	u8 owns_args;
 	/* its hidden slots and words take that many words of 8 bytes below its stack */
 	u8 hidden_words;
+	/* take_value_word() found no room for the value word, in this bpf_pads_settle() */
+	bool no_value_word: 1;
 	/* stack_depth includes the hidden words, see bpf_stack_take_hidden_words() */
 	bool hidden_in_depth: 1;
 	u8 code_stack_args;
@@ -2525,6 +2562,8 @@ size_t bpf_pad_plans_free(struct bpf_insn_aux_data *aux);
 void bpf_pads_new_round(struct bpf_verifier_env *env);
 void bpf_pads_move(struct bpf_verifier_env *env, struct bpf_pads_moved *moved, bool save);
 size_t bpf_pads_free_moved(struct bpf_pads_moved *moved, u32 cnt);
+struct bpf_pad_plan *bpf_pad_enter(struct bpf_verifier_env *env,
+				   const struct bpf_verifier_state *st, int call_idx);
 struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 				   const struct bpf_verifier_state *st, int insn_idx,
 				   enum bpf_site_kind kind);
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index e3f7e5b37bc5..b00a011fa66c 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -659,6 +659,10 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 {
 	int s;
 
+	/* without 'enters_cleanup_pads' no frame of the function is cancelled already */
+	if (bpf_site_is_cancelled(plan->kind) &&
+	    !bpf_find_containing_subprog(env, i)->enters_cleanup_pads)
+		return false;
 	switch (bpf_site_base(plan->kind)) {
 	case BPF_SITE_GUARD:
 		return env->insn_aux_data[i].loop_guard;
@@ -674,12 +678,15 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 				return true;
 		return false;
 	case BPF_SITE_CANCEL_CALL:
+	case BPF_SITE_CANCEL_ENTRY:
 		if (!plan->visited)
 			return false;
 		bpf_pad_for_each_callee(plan, s)
 			if (env->subprog_info[s].can_cancel)
 				return true;
 		return false;
+	case BPF_SITE_REMAINDER:
+		return plan->visited;
 	case BPF_SITE_FAULT:
 		return !env->insn_aux_data[i].fault_skips;
 	case BPF_SITE_MAY_GOTO:
@@ -690,13 +697,16 @@ bool bpf_site_is_used(struct bpf_verifier_env *env, int i, const struct bpf_pad_
 }
 
 /*
- * The main pass looked at more ways to unwind than the program has in the end: a loop that has a
- * trip count after all has no may_goto. Find the subprogs that get cancel_exit: those that are left
- * at a site where the kernel unwinds. And those that get unwind_exit: they have a call with no
- * unwind_goto, to which unwind_exit of the program comes back. A call is a site if it calls one of
- * them: of one kind, of the other, or of both. The main pass asks the same when a global subprog
- * unwinds, see settle_late_unwinds(). The main program leaves with exit: it is marked for
- * bpf_check_attach_target(), see bpf_insert_sites().
+ * Decide how each subprog can be left, from the sites that the program keeps:
+ *
+ *   can_cancel           the kernel can cancel it at a site: it gets cancel_exit
+ *   can_unwind           unwind_exit of a callee comes back to a call of it that has no
+ *                        unwind_goto: it gets unwind_exit
+ *   enters_cleanup_pads  a cancellation enters one of its cleanup pads
+ *
+ * A call is a site only if a callee has the matching bit, so the walk repeats until nothing
+ * changes. The main program leaves with exit but is marked too, for bpf_check_attach_target().
+ * With @in_pass the main pass asks the same question and is charged for the walk.
  */
 int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)
 {
@@ -706,6 +716,8 @@ int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)
 	bool changed, unwinds, cancels;
 	int i, k, s, err;
 
+	for (s = 0; s < env->subprog_cnt; s++)
+		env->subprog_info[s].enters_cleanup_pads = false;
 	do {
 		changed = false;
 		/* callees come first: only callx and a cycle of calls take more than one round */
@@ -716,6 +728,12 @@ int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)
 		for (k = 0; k < env->subprog_cnt; k++) {
 			s = env->subprog_topo_order[k];
 			sub = &env->subprog_info[s];
+			for (i = sub->start; sub->has_cleanup_pads && !sub->enters_cleanup_pads &&
+			     i < sub[1].start; i++) {
+				plan = bpf_pad_plan(&aux[i], BPF_SITE_CANCEL_ENTRY);
+				if (plan && bpf_site_is_used(env, i, plan))
+					sub->enters_cleanup_pads = changed = true;
+			}
 			if ((sub->can_unwind && sub->can_cancel) || (s && !sub->bail_unwinds))
 				continue;
 			unwinds = sub->can_unwind;
@@ -724,7 +742,9 @@ int bpf_mark_subprogs_that_unwind(struct bpf_verifier_env *env, bool in_pass)
 				cancels |= aux[i].loop_guard ||
 					   (aux[i].fault_empty && !aux[i].fault_skips);
 				for (plan = aux[i].pad_plans; plan; plan = plan->next) {
-					if (!bpf_site_is_used(env, i, plan))
+					/* at an entry the frame continues in its cleanup pad */
+					if (plan->kind == BPF_SITE_CANCEL_ENTRY ||
+					    !bpf_site_is_used(env, i, plan))
 						continue;
 					if (bpf_site_is_cancel(plan->kind))
 						cancels = true;
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 6969abb66250..8bcde2582519 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -111,7 +111,15 @@
  * verifier adds one, with a pad that leaves with unwind_exit in turn.
  *
  * A landing pad of the program is a CLEANUP PAD if it can only clean up and continue unwinding,
- * like a C++ destructor or Rust drop glue, see bpf_find_cleanup_pads().
+ * like a C++ destructor or Rust drop glue, see bpf_find_cleanup_pads(). A cancellation runs the
+ * cleanup pads of the frames that it leaves.
+ *
+ * In the main pass, enter_cleanup_pad() in verifier.c marks the frame as cancelled and verifies the
+ * cleanup pad a second time for it, with 0 in R0. A cancelled frame never returns to its caller. It
+ * leaves at the unwind_exit of the pad, which is a site for it (BPF_SITE_REMAINDER), or at
+ * a site inside the pad, where its states have a record and a pad of their own
+ * (BPF_SITE_CANCELLED). A cleanup pad that a cancellation can reach is entered, or the program is
+ * rejected.
  *
  * A frame can be in fewer sections than it was called in. Its pad enters the sections that the
  * frame left, so that the caller is in the sections of its call wherever the callee is cancelled.
@@ -1454,6 +1462,32 @@ static bool same_release(const struct bpf_pad_ent *a, const struct bpf_pad_ent *
 	       !memcmp(&a->release, &b->release, sizeof(a->release));
 }
 
+/*
+ * The kernel unwound what the call at @call_idx called, and the current frame of @st goes on in
+ * the landing pad that the program has behind the call, see enter_cleanup_pad() in verifier.c. The
+ * plan of the entry is no plan of a pad: the frame is not left, and nothing is released. It says
+ * that the call has an entry, and what the entry has to find: in a program with bpf_throw() the
+ * value of the kernel is in R0, a number, and goes to the hidden word of the frame.
+ * With a conflict the state ends here, and bpf_pads_settle() rejects the program.
+ * Returns the plan.
+ */
+struct bpf_pad_plan *bpf_pad_enter(struct bpf_verifier_env *env,
+				   const struct bpf_verifier_state *st, int call_idx)
+{
+	const struct bpf_func_state *frame = st->frame[st->curframe];
+	struct bpf_pad_plan *plan;
+
+	plan = bpf_pad_plan_get(env, call_idx, BPF_SITE_CANCEL_ENTRY);
+	if (!plan)
+		return ERR_PTR(-ENOMEM);
+	plan->visited = true;
+	if (plan->conflict)
+		return plan;
+	if (env->has_throw && frame->regs[BPF_REG_0].type != SCALAR_VALUE)
+		plan->conflict = BPF_CONFLICT_NO_VALUE;
+	return plan;
+}
+
 static int class_group(int class)
 {
 	if (class < BPF_PAD_NR_SECTIONS)
@@ -2458,7 +2492,10 @@ bool bpf_pad_must_unwind(struct bpf_verifier_env *env, const struct bpf_pad_plan
 	const struct bpf_subprog_info *sub;
 	int s;
 
-	/* the frame was being unwound when it got to the site: what began that is asked */
+	/*
+	 * The frame was cancelled already when it got to the site. The answer is that of the call
+	 * at which the cancellation entered the cleanup pad, BPF_SITE_CANCEL_ENTRY.
+	 */
 	if (bpf_site_is_cancelled(plan->kind))
 		return false;
 	if (!bpf_site_is_call(plan->kind))
@@ -2520,6 +2557,8 @@ static const char * const site_kind[] = {
 	[BPF_SITE_THROW]		= "bpf_throw",
 	[BPF_SITE_MAY_GOTO]		= "may_goto of the program",
 	[BPF_SITE_CANCEL_CALL]		= "call",
+	[BPF_SITE_CANCEL_ENTRY]		= "call",
+	[BPF_SITE_REMAINDER]		= "unwind_exit",
 };
 
 /* A bit of 'left_at' that is no kind of site: the subprog has an unwind_exit of the program */
@@ -2531,8 +2570,8 @@ static const char * const site_kind[] = {
  */
 static u16 kinds_of_plan(const struct bpf_pad_plan *plan, u16 kinds)
 {
-	return bpf_site_base(plan->kind) == BPF_SITE_CANCEL_CALL ? kinds & ~LEFT_AT_UNWIND_EXIT
-								 : kinds & LEFT_AT_UNWIND_EXIT;
+	return bpf_site_is_cancel(bpf_site_base(plan->kind)) ? kinds & ~LEFT_AT_UNWIND_EXIT
+							     : kinds & LEFT_AT_UNWIND_EXIT;
 }
 
 /*
@@ -2568,10 +2607,16 @@ static int sites_of_subprogs(struct bpf_verifier_env *env)
 				if (aux[i].fault_empty && !aux[i].fault_skips)
 					kinds |= BIT(BPF_SITE_FAULT);
 				for (plan = aux[i].pad_plans; plan; plan = plan->next) {
-					if (!plan->used)
+					/* the frame does not leave at the entry of a cleanup pad */
+					if (!plan->used || plan->kind == BPF_SITE_CANCEL_ENTRY)
 						continue;
+					/* a cancelled frame, wherever it leaves */
+					if (bpf_site_is_cancelled(plan->kind)) {
+						kinds |= BIT(BPF_SITE_REMAINDER);
+						continue;
+					}
 					if (!bpf_site_is_call(plan->kind)) {
-						kinds |= BIT(bpf_site_base(plan->kind));
+						kinds |= BIT(plan->kind);
 						continue;
 					}
 					bpf_pad_for_each_callee(plan, c)
@@ -2619,6 +2664,8 @@ static void print_sites_below(struct bpf_verifier_env *env, int i, const struct
 	for (k = 0; k <= BPF_SITE_MAY_GOTO; k++)
 		if (kinds & BIT(k))
 			verbose(env, " %s%s", site_kind[k], kinds >> (k + 1) ? "," : "");
+	if (kinds & BIT(BPF_SITE_REMAINDER))
+		verbose(env, " a landing pad of the program");
 	if (kinds & LEFT_AT_UNWIND_EXIT)
 		verbose(env, " unwind_exit");
 	verbose(env, "\n");
@@ -2632,13 +2679,16 @@ static bool plan_is_stuck(const struct bpf_pad_plan *plan)
 }
 
 /*
- * Is the conflict of @plan an error? It is one at every site: a prog that goes on from a loop that
- * was out of time, or from an access that faulted, was not verified. But not where the frame cannot
- * unwind and the site has another way out, see bpf_pad_must_unwind(): what comes back to a call
- * there is stuck, see bpf_pad_skip_faults().
+ * Does @plan reject the program? A site without a pad is an error: a program that continues after a
+ * loop that ran out of time, or after an access that faulted, was not verified. The exception is a
+ * frame that cannot be cancelled, at a site that has another way to continue, see
+ * bpf_pad_must_unwind(). A cancelled frame and the entry of a cleanup pad have no other way: the
+ * cleanup pad is entered, or the program is rejected.
  */
 static bool plan_rejects(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
 {
+	if (plan->kind == BPF_SITE_CANCEL_ENTRY || bpf_site_is_cancelled(plan->kind))
+		return plan->conflict;
 	return plan->conflict && (bpf_pad_must_unwind(env, plan) || !plan_is_stuck(plan));
 }
 
@@ -2923,6 +2973,7 @@ static int settle_slots(struct bpf_verifier_env *env)
 		env->subprog_info[s].slots = 0;
 		env->subprog_info[s].hidden_words = 0;
 		env->subprog_info[s].value_off = 0;
+		env->subprog_info[s].no_value_word = false;
 		env->subprog_info[s].pend_off = 0;
 	}
 	for (s = 0; s < env->subprog_cnt; s++) {
@@ -3229,30 +3280,36 @@ static void print_ent(struct bpf_verifier_env *env, const struct bpf_pad_ent *en
 	verbose(env, ")%s ", ent_is_tested(ent) ? " if not 0" : "");
 }
 
+static const char * const conflict_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",
+	[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 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",
+	[BPF_CONFLICT_NO_VALUE]		= "the value of unwind_exit is not a number",
+	[BPF_CONFLICT_NO_ROOM]		= "no room in the stack for the value",
+};
+
 /* Print what the pad of the site at insn @i releases, or why it cannot be generated */
 static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad_plan *plan)
 {
-	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",
-		[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 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",
-		[BPF_CONFLICT_NO_VALUE]		= "the value of unwind_exit is not a number",
-		[BPF_CONFLICT_NO_ROOM]		= "no room in the stack for the value",
-	};
 	int j;
 
+	/* no generated pad: the entry of a cleanup pad */
+	if (plan->kind == BPF_SITE_CANCEL_ENTRY) {
+		verbose(env, "landing pad of the program behind the call at %d: the kernel enters it\n",
+			i);
+		return;
+	}
 	/*
 	 * A call can have a pad for a cancellation and one for the program's unwind_exit. Every
 	 * site can have one more for the frames that are cancelled already.
@@ -3263,7 +3320,7 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 	for (j = plan->nr_ents - 1; !plan->conflict && j >= 0; j--)
 		print_ent(env, &plan->ents[j]);
 	if (plan->conflict)
-		verbose(env, "conflict: %s\n", why[plan->conflict]);
+		verbose(env, "conflict: %s\n", conflict_why[plan->conflict]);
 	else if (plan->outside[BPF_PAD_RCU] || plan->outside[BPF_PAD_PREEMPT])
 		verbose(env, "rcu=%d preempt=%d sleeps outside rcu=%d preempt=%d\n",
 			plan->sections[BPF_PAD_RCU], plan->sections[BPF_PAD_PREEMPT],
@@ -3310,7 +3367,10 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pa
 void bpf_pad_note_left(struct bpf_verifier_env *env, struct bpf_subprog_info *sub,
 		       const struct bpf_pad_plan *plan, enum bpf_site_kind kind)
 {
-	sub->left_at |= bpf_site_is_call(kind) ? sites_below(env, plan) : BIT(bpf_site_base(kind));
+	if (bpf_site_is_cancelled(kind))
+		sub->left_at |= BIT(BPF_SITE_REMAINDER);
+	else
+		sub->left_at |= bpf_site_is_call(kind) ? sites_below(env, plan) : BIT(kind);
 }
 
 /* Did bpf_pad_skip_faults() walk @sub, and has no call in or below it got a new callee since? */
@@ -3385,9 +3445,11 @@ int bpf_pad_skip_faults(struct bpf_verifier_env *env, const struct bpf_pad_plan
 }
 
 /*
- * The pads of @sub keep the value over their calls in a hidden word of the frame, below the
- * hidden slots. Nothing else writes it. A subprog whose pads pass on R2 has a second word above
- * it, see bpf_pad_passes_r2(). Returns the reason of a conflict.
+ * Give @sub its value word: a hidden word of the frame, below the hidden slots, in which its pads
+ * keep the value over their calls. A subprog whose pads pass R2 on gets a second word above it, see
+ * bpf_pad_passes_r2(). Every pad that keeps the value asks, so the answer is remembered until the
+ * next bpf_pads_settle(), also a 'no' ('no_value_word'). Returns 0, BPF_CONFLICT_NO_ROOM or a
+ * negative errno.
  */
 static int take_value_word(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
 {
@@ -3396,10 +3458,13 @@ static int take_value_word(struct bpf_verifier_env *env, struct bpf_subprog_info
 
 	if (sub->value_off)
 		return 0;
+	if (sub->no_value_word)
+		return BPF_CONFLICT_NO_ROOM;
 	sub->hidden_words += words;
 	err = bpf_hidden_slots_fit(env);
 	if (err <= 0) {
 		sub->hidden_words -= words;
+		sub->no_value_word = !err;
 		return err ?: BPF_CONFLICT_NO_ROOM;
 	}
 	sub->value_off = -(int)bpf_stack_depth_with_slots(sub);
@@ -3429,24 +3494,36 @@ void bpf_pads_mark_used(struct bpf_verifier_env *env)
  * 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().
+ * That holds for every plan, also for those that are there because the kernel enters landing pads
+ * of the program: the entry of such a pad, a site that a frame gets to while the kernel unwinds it
+ * through the pad, unwind_exit where the pad ends, and a pad of the verifier in a caller that gets
+ * what such a frame left. What the program does in its pad is its own business. What the verifier
+ * adds around it has to be right, or the program does not load: no landing pad is passed by
+ * because the verifier has no plan.
  */
 int bpf_pads_settle(struct bpf_verifier_env *env)
 {
+	const struct bpf_pad_plan *reject = NULL;
 	struct bpf_subprog_info *sub;
 	struct bpf_pad_plan *plan;
-	int i, s, err;
+	int i, s, err, at = 0;
+	u64 plans = 0;
 
 	err = bpf_pads_must_unwind(env) ?: sites_of_subprogs(env);
 	if (err)
 		return err;
 	/* sort the releases first: hidden slots are inserted into that order */
 	for (i = 0; i < env->prog->len; i++) {
-		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next) {
+		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next, plans++) {
 			err = order_ents(env, plan);
 			if (err)
 				return err;
 		}
 	}
+	/* what follows looks at each insn and at the releases of each record a few times */
+	err = bpf_add_cost_and_check(env, env->prog->len + BPF_PAD_MAX_ENTS * plans, BPF_COST_XREG);
+	if (err)
+		return err;
 	err = settle_slots(env);
 	if (err)
 		return err;
@@ -3456,34 +3533,49 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next) {
 			if (!plan->used)
 				continue;
-			err = settle_plan(env, plan);
 			sub = bpf_find_containing_subprog(env, i);
-			if (!err && (plan_saves_value(env, plan, sub - env->subprog_info) ||
+			/* the record of an entry is no record of a pad: nothing to settle */
+			if (plan->kind != BPF_SITE_CANCEL_ENTRY) {
+				err = settle_plan(env, plan);
+				if (!err &&
+				    (plan_saves_value(env, plan, sub - env->subprog_info) ||
 				     (bpf_site_is_cancelled(plan->kind) && env->has_throw)))
-				err = take_value_word(env, sub);
-			if (err < 0)
-				return err;
-			plan->conflict = err;
-			if (plan_rejects(env, plan)) {
-				bpf_pad_log(env, i, plan);
-				return -EINVAL;
+					err = take_value_word(env, sub);
+				if (err < 0)
+					return err;
+				plan->conflict = err;
 			}
 			if (!plan->conflict)
 				continue;
-			/*
-			 * The frame cannot unwind and the site has another way out. The main pass
-			 * made what came back stuck, and no run that finds a subprog stuck late
-			 * gets here. So the program still has the site, and no pad.
-			 */
-			err = bpf_pad_skip_faults(env, plan, i);
-			if (err)
-				return err;
-			if (!env->faults_late) {
-				bpf_pad_log(env, i, plan);
-				return -EINVAL;
+			if (!plan_rejects(env, plan)) {
+				/*
+				 * The frame cannot be cancelled, and the site has another way to
+				 * continue: mark the callees as stuck. If that marked a new one,
+				 * the pass is repeated. If not, the program still has the site and
+				 * no pad, which is an error.
+				 */
+				err = bpf_pad_skip_faults(env, plan, i);
+				if (err)
+					return err;
+				if (env->faults_late)
+					continue;
 			}
+			/* the first one is the one that the log names */
+			if (!reject)
+				at = i;
+			reject = reject ?: plan;
 		}
 	}
+	/*
+	 * The error is raised here, behind all plans: a pass can have several conflicts that show
+	 * only now, and each of them is one that the next pass keeps more apart for, see
+	 * bpf_find_unproven_after_pass() and bpf_pads_note_causes(). One per pass would be a pass
+	 * per conflict.
+	 */
+	if (reject) {
+		bpf_pad_log(env, at, reject);
+		return -EINVAL;
+	}
 	/* all accesses of the program to its stack are known: the hidden words go below them */
 	for (s = 0; !env->faults_late && s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
@@ -3562,16 +3654,10 @@ static bool left_at_insn(const struct bpf_insn_aux_data *aux)
  * Kept apart, neither call is cancelled. The calls do not say what to keep apart, because their
  * arguments are constants, so the causes are recorded in the callee.
  *
- * An access to arena that faults leaves a function as well, and so does may_goto of the program.
- * The dependencies of the next pass know exit, unwind_exit and bpf_throw() as the ways out of a
- * function, and none of these stands for such an insn. Where only the calls together get to it,
- * the jumps that can skip it are the cause: the insn is noted, and they are what controls it.
- *
- * No pass that keeps more apart gives the frame of the call a place for a pointer that it passed
- * on and kept no copy of, or a way to tell whether the callee has released it. Where that is the
- * conflict, see conflict_of_ref(), and the callee is one that releases what the call could hand
- * over, the callee asks for it, see hand_over_more() in verifier.c.
- * @insn_idx: the site of @plan.
+ * If a reference has no location, or nothing tells whether it is held, no pass that keeps more
+ * apart helps. The callees that release an argument which the call could hand over ask for it
+ * ('asks_args'), see hand_over_more() in verifier.c. A cancelled frame did not leave at its call,
+ * so its function is marked for ask_below_cleanup_pads().
  */
 static void note_causes(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan)
 {
@@ -3585,6 +3671,8 @@ static void note_causes(struct bpf_verifier_env *env, int insn_idx, const struct
 	    conflict_of_ref(env, plan)) {
 		bpf_pad_for_each_callee(plan, s)
 			sub[s].asks_args |= sub[s].releases_args;
+	} else if (bpf_site_is_cancelled(plan->kind) && conflict_of_ref(env, plan)) {
+		bpf_find_containing_subprog(env, insn_idx)->cleanup_pad_ref_conflict = true;
 	}
 	if (bpf_site_base(plan->kind) != BPF_SITE_CANCEL_CALL)
 		return;
@@ -3592,6 +3680,77 @@ static void note_causes(struct bpf_verifier_env *env, int insn_idx, const struct
 		sub[s].below_conflict = true;
 }
 
+/*
+ * For each function with 'cleanup_pad_ref_conflict', see note_causes(), the callees of its calls
+ * that lead to a cleanup pad ask for a hand-over. A cancelled frame does not know which entry it
+ * came through, so the callees of all such calls ask.
+ */
+static void ask_below_cleanup_pads(struct bpf_verifier_env *env)
+{
+	struct bpf_subprog_info *sub = env->subprog_info;
+	const struct bpf_pad_plan *entry;
+	int f, i, s;
+
+	for (f = 0; f < env->subprog_cnt; f++) {
+		if (!sub[f].cleanup_pad_ref_conflict)
+			continue;
+		for (i = sub[f].start; i < sub[f + 1].start; i++) {
+			entry = bpf_pad_plan(&env->insn_aux_data[i], BPF_SITE_CANCEL_ENTRY);
+			if (!entry || !entry->visited)
+				continue;
+			bpf_pad_for_each_callee(entry, s)
+				sub[s].asks_args |= sub[s].releases_args;
+		}
+	}
+}
+
+/*
+ * The pass has an error, and the kernel entered landing pads of the program in it: a state went
+ * through the entry of a call, 'visited' of its plan, see bpf_pad_enter(). The kernel may have got
+ * into such a pad only because calls were verified together: the function of count() above with a
+ * landing pad behind its call. Kept apart nothing comes back unwound to that call, no state gets
+ * into the pad, and what such a state had a part in is gone. That can be any error, and neither
+ * the state nor the plan that has it needs to know of the pad:
+ *   - a conflict where the pad ends, at a site in its code, or in a caller that gets what the
+ *     pad left;
+ *   - an error or a conflict in what its code calls, also in a callback that it only arms;
+ *   - a conflict at a call of the normal path, in a function that the code of the pad calls as
+ *     well: the numbers that the pad passes take the trip count from its loop, and may_goto is in
+ *     the code for every call of the function;
+ *   - hidden slots that a function does not get because of what the code of the pad releases.
+ * So there is one rule: whatever the error is, every function in which the kernel entered a pad
+ * is marked. The calls behind which it did are causes, and so is what makes their callees unwind,
+ * see note_causes_below(). The marks say what the next pass keeps apart and nothing else: no
+ * verdict rests on them.
+ * They are those of this pass, and every pass that has an error makes them again while the
+ * kernel still gets into a pad: the causes have to be there for each step of
+ * bpf_partition_more() in turn, until the calls are apart. They are no step of their own. A pass
+ * after which nothing more is kept apart is the last one with them as without them, and the
+ * limit on the cost of a load that is rejected is the same, see do_check_all().
+ * A program that is rejected for another reason pays for them: for the dependencies of the calls
+ * of the marked functions, in every pass, and where only calls that are verified together get
+ * into the pad, for keeping those apart. An error behind such calls depends on the loop of their
+ * callee from then on, and costs what an error that reads the result of that loop costs.
+ */
+static void note_entered(struct bpf_verifier_env *env)
+{
+	const struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	const struct bpf_pad_plan *plan;
+	struct bpf_subprog_info *sub;
+	int i, s;
+
+	for (s = 0; s < env->subprog_cnt; s++) {
+		sub = &env->subprog_info[s];
+		if (!sub->has_cleanup_pads || sub->below_conflict)
+			continue;
+		bpf_add_cost(env, sub[1].start - sub->start, BPF_COST_SCAN);
+		for (i = sub->start; !sub->below_conflict && i < sub[1].start; i++) {
+			plan = bpf_pad_plan(&aux[i], BPF_SITE_CANCEL_ENTRY);
+			sub->below_conflict = plan && plan->visited;
+		}
+	}
+}
+
 /*
  * Record the causes of the errors of the pass in the functions that note_causes() and
  * note_entered() marked, and in the functions that were cancelled below them: the calls, accesses
@@ -3632,13 +3791,14 @@ static void note_causes_below(struct bpf_verifier_env *env)
 			break;
 		for (i = sub[s].start; i < sub[s + 1].start; i++) {
 			for (below = aux[i].pad_plans; below; below = below->next) {
-				if (bpf_site_base(below->kind) != BPF_SITE_CANCEL_CALL ||
-				    !below->visited)
+				if ((bpf_site_base(below->kind) != BPF_SITE_CANCEL_CALL &&
+				     below->kind != BPF_SITE_CANCEL_ENTRY) || !below->visited)
 					continue;
 				/*
-				 * The frame is left at this call, whatever what it calls
-				 * was left at: the check of a recursion is no insn to
-				 * note. The jumps that can skip the call are a cause.
+				 * The frame is cancelled at this call, or continues in the cleanup
+				 * pad after it. The jumps that can skip the call are a cause,
+				 * whatever cancelled the callee: the stack check of a recursion is
+				 * no insn that could be recorded.
 				 */
 				bpf_note_controlled_cause(env, i);
 				bpf_pad_for_each_callee(below, c) {
@@ -3680,9 +3840,10 @@ static void note_causes_below(struct bpf_verifier_env *env)
 }
 
 /*
- * The pass is over and has an error. Note the causes of the conflicts that are one: those that a
- * state made an error where it visited, see unwind_frame() and check_arena_site(), and those that
- * bpf_pads_settle() found.
+ * The pass ended with an error. Record its causes for the next pass: for each site whose missing
+ * pad is an error, whether a state found it in the pass, see unwind_frame() and check_arena_site(),
+ * or bpf_pads_settle() did, and for any error if a cancellation entered a cleanup pad, see
+ * note_entered().
  */
 void bpf_pads_note_causes(struct bpf_verifier_env *env)
 {
@@ -3691,6 +3852,7 @@ void bpf_pads_note_causes(struct bpf_verifier_env *env)
 
 	for (s = 0; s < env->subprog_cnt; s++) {
 		env->subprog_info[s].below_conflict = false;
+		env->subprog_info[s].cleanup_pad_ref_conflict = false;
 		env->subprog_info[s].asks_args = 0;
 	}
 	env->ref_conflict = false;
@@ -3698,6 +3860,8 @@ void bpf_pads_note_causes(struct bpf_verifier_env *env)
 		for (plan = env->insn_aux_data[i].pad_plans; plan; plan = plan->next)
 			if (plan->failed || (plan->used && plan_rejects(env, plan)))
 				note_causes(env, i, plan);
+	ask_below_cleanup_pads(env);
+	note_entered(env);
 	note_causes_below(env);
 	/* The caller checks the limits before the next pass. This is for a load that ends here. */
 	bpf_check_limits(env);
@@ -3805,6 +3969,13 @@ static bool insn_returns(const struct bpf_insn *insn)
  * says, which is a value like any other: the pad returns. Pads that share their last insns, as the
  * pads of one function of C++ do, are judged one by one, each from its first insn.
  *
+ * What a frame that the kernel unwinds runs from there on is what the pad gets to, and that need
+ * not be code of a pad: a pad can jump back in front of its call, or to the first insn of its
+ * function, and in a function that has no exit every pad only resumes. Such a frame runs the
+ * normal path of the function once more. What holds for it is not that it runs cleanup code only,
+ * it is that no insn which it can get to returns to its caller: it is left at unwind_exit or at a
+ * site, with cancel_exit, and nowhere else. See enter_cleanup_pad() in verifier.c.
+ *
  * The answer is a property of the insns, the same in every pass: 'cleanup_pad' of unwind_goto.
  * Dead branches are gone from the graph, see bpf_prune_dead_branches().
  */
@@ -3867,6 +4038,8 @@ int bpf_find_cleanup_pads(struct bpf_verifier_env *env)
 		ret = test_bit(pad, returns);
 		res = test_bit(pad, resumes);
 		env->insn_aux_data[i].cleanup_pad = !ret && res;
+		if (!ret && res)
+			bpf_find_containing_subprog(env, i)->has_cleanup_pads = true;
 		if (!(env->log.level & BPF_LOG_LEVEL2))
 			continue;
 		verbose(env, "landing pad at %d of the call at %d %s\n", pad, i - 1,
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 5b0700660bcf..834d0b0a9ea9 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -225,6 +225,7 @@ static inline bool in_sleepable_context(struct bpf_verifier_env *env);
 static bool in_rcu_callback(struct bpf_verifier_env *env);
 static const char *non_sleepable_context_description(struct bpf_verifier_env *env);
 static int check_arena_site(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
+static int enter_cleanup_pad(struct bpf_verifier_env *env);
 static int check_may_goto_site(struct bpf_verifier_env *env);
 static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog);
 
@@ -12129,6 +12130,13 @@ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int i
 	init_func_state(env, callee, BPF_MAIN_FUNC, 0, subprog);
 	/* the frame that says so is not there when the function is verified */
 	callee->in_rcu_callback_fn = in_rcu_callback(env);
+	/*
+	 * Keep a call out of a cancelled frame apart from the other calls of the function: a
+	 * cleanup pad passes other arguments, such as 0 in R0 where the program threw an object.
+	 */
+	for (i = 0; i <= state->curframe; i++)
+		if (state->frame[i]->cancelled)
+			callee->cancelled = BPF_FRAME_BELOW;
 	for (i = BPF_REG_1; i <= BPF_REG_5; i++)
 		if (live & BIT(i))
 			callee->regs[i] = caller->regs[i];
@@ -12217,14 +12225,22 @@ static int exit_func_on_its_own(struct bpf_verifier_env *env, int exit_idx)
  * @kernel. Record @callee at the site that the call becomes, see check_unwound_arrival(). There is
  * no site if @callee left with unwind_exit and the program has an unwind_goto after the call.
  */
-static int check_unwound_return(struct bpf_verifier_env *env, int call_idx, int callee,
-				bool kernel)
+static int check_unwound_return(struct bpf_verifier_env *env, const struct bpf_func_state *caller,
+				int call_idx, int callee, bool kernel)
 {
-	if (kernel)
-		return bpf_pad_note_callee(env, call_idx, callee, BPF_SITE_CANCEL_CALL);
+	enum bpf_site_kind cancelled = bpf_frame_is_cancelled(caller) ? BPF_SITE_CANCELLED : 0;
+	int err = 0;
+
+	if (kernel) {
+		/* The cancellation can enter the cleanup pad of the call. */
+		if (env->insn_aux_data[call_idx + 1].cleanup_pad)
+			err = bpf_pad_note_callee(env, call_idx, callee, BPF_SITE_CANCEL_ENTRY);
+		return err ?: bpf_pad_note_callee(env, call_idx, callee,
+						  BPF_SITE_CANCEL_CALL | cancelled);
+	}
 	if (bpf_is_unwind_goto(&env->prog->insnsi[call_idx + 1]))
 		return 0;
-	return bpf_pad_note_callee(env, call_idx, callee, BPF_SITE_CALL);
+	return bpf_pad_note_callee(env, call_idx, callee, BPF_SITE_CALL | cancelled);
 }
 
 static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, bool is_null);
@@ -12287,7 +12303,7 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 		return BPF_EXIT_NEEDS_CALLER;
 	}
 	if (exit->unwound) {
-		err = check_unwound_return(env, call_idx, callee->subprogno,
+		err = check_unwound_return(env, frame, call_idx, callee->subprogno,
 					   bpf_unwound_cancelled(exit->unwound));
 		if (err)
 			return err;
@@ -12553,7 +12569,7 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 
 			if (!(kernel ? sub->did_cancel : sub->did_unwind) || !sub->bail_unwinds)
 				continue;
-			err = check_unwound_return(env, *insn_idx, subprog, kernel);
+			err = check_unwound_return(env, caller, *insn_idx, subprog, kernel);
 			if (err)
 				return err;
 			branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
@@ -13056,7 +13072,8 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 		/* unwind_frame() has already marked a state that it brings here. */
 		bool kernel = bpf_unwound_cancelled(state->unwound);
 
-		err = check_unwound_return(env, callee->callsite, callee->subprogno, kernel);
+		err = check_unwound_return(env, caller, callee->callsite, callee->subprogno,
+					   kernel);
 		if (err)
 			return err;
 		state->unwound = bpf_unwound_mark(kernel, callee->in_callback_fn);
@@ -14119,6 +14136,11 @@ static int check_helper_call(struct bpf_verifier_env *env, struct bpf_insn *insn
 			verbose(env, "tail_call in a subprog would lead to reference leak\n");
 			return -EINVAL;
 		}
+		/* No cleanup pad reaches a tail call, see bpf_find_cleanup_pads(). */
+		if (verifier_bug_if(bpf_frame_is_cancelled(cur_func(env)), env,
+				    "a frame that the kernel unwinds makes a tail call at insn %d",
+				    env->insn_idx))
+			return -EFAULT;
 		if (env->cur_state->curframe) {
 			struct bpf_verifier_state *branch;
 
@@ -16766,7 +16788,9 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 
 	/* bpf_throw() is never called. The frame is cancelled here, see unwind_frame(). */
 	if (meta.func_id == special_kfunc_list[KF_bpf_throw]) {
-		err = check_unwound_value(env, BPF_REG_1, "R1");
+		/* A frame that is cancelled already has its value, so the cookie is dropped. */
+		err = bpf_frame_is_cancelled(cur_func(env)) ? 0 :
+		      check_unwound_value(env, BPF_REG_1, "R1");
 		err = err ?: push_unwind_edge(env, BPF_SITE_THROW);
 		return err ?: PROCESS_BPF_EXIT;
 	}
@@ -20031,13 +20055,21 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 	}
 
 	if (bpf_is_unwind_goto(insn)) {
+		bool kernel = env->cur_state->unwound == BPF_CANCELLED;
+
 		if (!env->cur_state->unwound)
 			return 0;
-		/* what the kernel unwinds does not get here, see check_unwound_arrival() */
-		if (verifier_bug_if(env->cur_state->unwound != BPF_UNWOUND, env,
+		/* After a cancelled callee a state takes unwind_goto only into a cleanup pad. */
+		if (verifier_bug_if(env->cur_state->unwound != BPF_UNWOUND &&
+				    !(kernel && cur_aux(env)->cleanup_pad), env,
 				    "unwind_goto at insn %d is taken for cancel_exit", *insn_idx))
 			return -EFAULT;
 		env->cur_state->unwound = false;
+		if (kernel) {
+			err = enter_cleanup_pad(env);
+			if (err)
+				return err;
+		}
 		*insn_idx += insn->off;
 		return 0;
 	}
@@ -20390,6 +20422,10 @@ static int check_ld_abs(struct bpf_verifier_env *env, struct bpf_insn *insn)
 		verifier_bug(env, "gen_ld_abs is null");
 		return -EFAULT;
 	}
+	/* LD_ABS returns when it fails, so no cleanup pad reaches it: bpf_find_cleanup_pads(). */
+	if (verifier_bug_if(bpf_frame_is_cancelled(cur_func(env)), env,
+			    "a frame that the kernel unwinds has LD_ABS at insn %d", env->insn_idx))
+		return -EFAULT;
 
 	/* check whether implicit source operand (register R6) is readable */
 	err = check_reg_arg(env, ctx_reg, SRC_OP);
@@ -21447,6 +21483,8 @@ static int check_arena_sp_insn(struct bpf_verifier_env *env, struct bpf_insn *in
 	return err ?: save_aux_ptr_type(env, PTR_TO_ARENA, false);
 }
 
+static int leave_cancelled_frame(struct bpf_verifier_env *env, const struct bpf_insn *insn);
+
 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
 {
 	int err, i;
@@ -21552,6 +21590,8 @@ static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)
 				env->insn_idx += insn->imm + 1;
 			return INSN_IDX_UPDATED;
 		} else if (opcode == BPF_EXIT) {
+			if (bpf_frame_is_cancelled(cur_func(env)))
+				return leave_cancelled_frame(env, insn);
 			if (bpf_is_unwind_exit(insn) && env->has_throw) {
 				err = check_unwound_value(env, BPF_REG_0, "R0");
 				if (err)
@@ -22010,16 +22050,19 @@ int bpf_flow_start_leftover(struct bpf_verifier_env *env)
 	return enter_callback(env, false, NULL);
 }
 
+static enum bpf_pad_conflict frame_cannot_unwind(struct bpf_verifier_env *env,
+						 const struct bpf_verifier_state *st);
+
 /*
- * @st came back from a call unwound and is at the insn behind the call. It does not go on there:
- * the frame is unwound in turn, at the call, see check_unwound_arrival(). What the kernel unwound
- * always, whatever the insn is. What left with unwind_exit of the program unless the program has
- * unwind_goto there, which is a jump for it.
+ * @st is at the insn after a call whose callee did not return. Does its frame leave in turn, at
+ * the call, see check_unwound_arrival()? If the callee left with unwind_exit, the state takes the
+ * program's unwind_goto when there is one. If the callee was cancelled, the state takes an
+ * unwind_goto only into a cleanup pad, in a frame that can be cancelled, see enter_cleanup_pad().
  */
-static bool unwound_in_turn(const struct bpf_verifier_env *env, const struct bpf_verifier_state *st)
+static bool unwound_in_turn(struct bpf_verifier_env *env, const struct bpf_verifier_state *st)
 {
 	if (st->unwound == BPF_CANCELLED)
-		return true;
+		return !env->insn_aux_data[env->insn_idx].cleanup_pad || frame_cannot_unwind(env, st);
 	return st->unwound == BPF_UNWOUND && !bpf_is_unwind_goto(&env->prog->insnsi[env->insn_idx]);
 }
 
@@ -22325,6 +22368,20 @@ static int check_arena_site(struct bpf_verifier_env *env, const struct bpf_reg_s
 		return 0;
 	}
 	sub->soft_unwinds = true;
+	/*
+	 * The states of a frame that is cancelled already have a record and a landing pad of their
+	 * own here, and each of them records. A missing landing pad is an error only if the program
+	 * keeps the entry that the frame came through, which bpf_pads_settle() knows.
+	 */
+	if (bpf_frame_is_cancelled(frame)) {
+		plan = bpf_pad_visit(env, st, env->insn_idx, BPF_SITE_FAULT | BPF_SITE_CANCELLED);
+		if (IS_ERR(plan))
+			return PTR_ERR(plan);
+		if (plan->conflict || frame->fault_edge)
+			return 0;
+		frame->fault_edge = true;
+		return push_unwind_edge(env, BPF_SITE_FAULT);
+	}
 	visits = frame_holds_resources(st) || aux->fault_full || bpf_pad_plan(aux, BPF_SITE_FAULT);
 	if (!visits) {
 		aux->fault_empty = true;
@@ -22456,6 +22513,7 @@ static bool site_is_certain(struct bpf_verifier_env *env, const struct bpf_pad_p
 				return true;
 		return false;
 	case BPF_SITE_CANCEL_CALL:
+	case BPF_SITE_CANCEL_ENTRY:
 		bpf_pad_for_each_callee(plan, s)
 			if (env->subprog_info[s].cancels_for_sure)
 				return true;
@@ -22485,16 +22543,22 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
 	struct bpf_verifier_state *cur = env->cur_state;
 	int cur_idx = env->insn_idx, err = 0;
-	bool kernel = bpf_site_is_cancel(kind), passes_on, late;
 	struct bpf_pad_plan *plan = NULL;
-	bool print_state, certain = true, stuck;
+	bool kernel, cancelled, passes_on, late;
+	bool print_state, certain, stuck;
 	enum bpf_pad_conflict conflict;
 	u32 cnt;
 
 	env->cur_state = st;
 	env->insn_idx = insn_idx;
+	/* A frame that is cancelled already has a record of its own at every kind of site. */
+	if (bpf_frame_is_cancelled(frame) && kind != BPF_SITE_REMAINDER)
+		kind |= BPF_SITE_CANCELLED;
+	cancelled = bpf_site_is_cancelled(kind);
+	kernel = bpf_site_is_cancel(kind);
+	certain = !cancelled;
 	passes_on = bpf_pad_passes_on(env, frame->subprogno, kind);
-	if (kind != BPF_SITE_FAULT) {
+	if (bpf_site_base(kind) != BPF_SITE_FAULT) {
 		/* Keep the suspects for an error that only bpf_pads_settle() raises. */
 		env->insn_aux_data[insn_idx].suspect_loops |= st->suspect_loops;
 		plan = bpf_pad_visit(env, st, insn_idx, kind);
@@ -22502,6 +22566,11 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		if (err)
 			goto out;
 		conflict = frame_cannot_unwind(env, st);
+		/*
+		 * The frame entered a cleanup pad before its function turned out to be one that
+		 * cannot be cancelled. The pass is repeated and enters no cleanup pad in it.
+		 */
+		env->faults_late |= conflict && cancelled;
 		/*
 		 * The frame cannot be cancelled. If the site can be skipped, that replaces any
 		 * other reason: no landing pad runs in this frame, see bpf_pads_settle().
@@ -22521,6 +22590,10 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		 * and a call above them either, but in a subprog that cannot unwind, and whether
 		 * it is one may be found later in the pass. Then this error was none, see
 		 * do_check_all().
+		 * It is an error also where a landing pad of the program that the kernel entered
+		 * has a part in it: what came back to the call left a frame below through such
+		 * a pad, or the state got here out of one, in a function that the pad calls.
+		 * The kernel enters the pad or the program is rejected.
 		 */
 		if (plan->conflict && certain && (bpf_pad_must_unwind(env, plan) || !stuck)) {
 			bpf_pad_log(env, insn_idx, plan);
@@ -22533,8 +22606,9 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		 * The frame of the call cannot be cancelled, and its callees were cancelled only at
 		 * sites that can be skipped. Mark them 'stuck', which stuck_frame_calls() missed.
 		 */
-		if (stuck && bpf_site_is_call(kind) && !bpf_pad_must_unwind(env, plan))
+		if (stuck && !cancelled && bpf_site_is_call(kind) && !bpf_pad_must_unwind(env, plan))
 			err = bpf_pad_skip_faults(env, plan, insn_idx);
+		/* @st ends here. If that is an error, bpf_pads_settle() raises it. */
 		if (plan->conflict)
 			goto out;
 	}
@@ -22543,7 +22617,11 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 	err = release_frame_resources(env, bpf_pad_plan(&env->insn_aux_data[insn_idx], kind));
 	if (err)
 		goto out;
-	if (passes_on) {
+	if (cancelled && env->has_throw) {
+		/* The pad loads the value that the entry stored, see bpf_pad_enter(). */
+		mark_reg_unknown(env, frame->regs, BPF_REG_0);
+		bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_0));
+	} else if (passes_on) {
 		/* R0 stays as the callee left it, unless a release invalidated it. */
 	} else if (!bpf_site_has_value(env, frame->subprogno, kind)) {
 		bpf_mark_reg_known_scalar(&frame->regs[BPF_REG_0], bpf_cancelled_retval(env));
@@ -22641,6 +22719,106 @@ static int check_unwound_arrival(struct bpf_verifier_env *env)
 			    kernel ? BPF_SITE_CANCEL_CALL : BPF_SITE_CALL);
 }
 
+/*
+ * The kernel unwound what the call before this insn called, and the program has unwind_goto here
+ * whose landing pad ONLY RESUMES, see bpf_find_cleanup_pads(): it runs what the program wants done
+ * when a frame is left, a destructor of C++ or Rust, and cannot end the unwinding. So it is not
+ * passed by. cancel_goto behind the call goes to the ENTRY that the verifier emits, and from there
+ * to the pad.
+ *
+ *	call foo			call foo
+ *	unwind_goto pad			unwind_goto pad
+ *	...				cancel_goto entry
+ * pad:	r6 = r0				...
+ *	call dtor		   pad:	r6 = r0
+ *	r0 = r6				call dtor
+ *	unwind_exit			r0 = r6
+ *					gotol rest
+ *					...
+ *				 entry: ax = K
+ *					if ax != 0 goto +1
+ *					K = 1
+ *					r0 = 0
+ *					gotol pad
+ *				  rest:	ax = K
+ *					if ax == 0 goto +3
+ *					r0 = V
+ *					r2 = 0
+ *					cancel_exit
+ *					unwind_exit
+ *
+ * The current frame is FORCED from here on, and never anything else again:
+ *   - The pad is verified once more, with what the frame holds when the kernel unwinds the callee,
+ *     and with 0 in R0. An error on that way is an error of the program like any other.
+ *   - A forced state and one of the normal path are never joined: the mark is in the join key.
+ *   - No insn that returns to the caller can be reached from the pad, so the only ways out are
+ *     unwind_exit of the program and the sites of the frame, see leave_cancelled_frame() and
+ *     unwind_frame(). Both leave with cancel_exit and the value of the kernel. The program cannot
+ *     go on, and it cannot change what it ends with.
+ *   - What unwinds in the pad itself does not change that either. unwind_exit of a callee is
+ *     taken where the program has unwind_goto for it, and the kernel that unwinds a callee
+ *     enters the landing pad of that call as it did this one: K is set, and it stays set.
+ *
+ * At run time K says the same as the mark: a hidden word of the frame that is 0 from the entry of
+ * the function on and that only the entry of a pad sets, see bpf_pad_entry_insns().
+ *
+ * Returns PROCESS_BPF_EXIT if the state ends.
+ */
+static int enter_cleanup_pad(struct bpf_verifier_env *env)
+{
+	struct bpf_verifier_state *st = env->cur_state;
+	struct bpf_func_state *frame = cur_func(env);
+	struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
+	int call_idx = env->insn_idx - 1;
+	struct bpf_pad_plan *plan;
+
+	plan = bpf_pad_enter(env, st, call_idx);
+	if (IS_ERR(plan))
+		return PTR_ERR(plan);
+	/* an error that bpf_pads_settle() raises, as for a site that is not certain */
+	if (plan->conflict)
+		return PROCESS_BPF_EXIT;
+	/*
+	 * The frame is going to leave with cancel_exit. Record for its callers what unwind_frame()
+	 * records, from what is known of the callee: where the frame leaves adds nothing to it.
+	 */
+	if (sub->bail_unwinds && !frame_is_top(st)) {
+		sub->must_cancel |= bpf_pad_must_unwind(env, plan);
+		sub->cancels_for_sure |= site_is_certain(env, plan, call_idx);
+	}
+	/* Logged at level 1, so that the log of an error says that this path is a cancellation. */
+	if (env->log.level & BPF_LOG_LEVEL)
+		verbose(env, "from %d to the landing pad at %d of func#%d: the kernel unwinds\n",
+			call_idx, env->insn_idx + 1 + env->prog->insnsi[env->insn_idx].off,
+			frame->subprogno);
+	frame->cancelled |= BPF_FRAME_CANCELLED;
+	/* A copy that left the frame at an access to arena before no longer stands for it. */
+	frame->fault_edge = false;
+	bpf_diag_mod_begin(env, &frame->regs[BPF_REG_0], NULL, BPF_DIAG_MOD_WRITE);
+	bpf_mark_reg_known_scalar(&frame->regs[BPF_REG_0], 0);
+	bpf_diag_mod_end(env);
+	bpf_equations_forget_xreg(env, st, bpf_xreg(st->curframe, BPF_REG_0));
+	return 0;
+}
+
+/*
+ * A cancelled frame, see enter_cleanup_pad(), gets to the unwind_exit of its cleanup pad. The insn
+ * is a site, BPF_SITE_REMAINDER: a generated pad releases what the frame still holds and leaves
+ * with cancel_exit and the value of the cancellation. The insn becomes a jump to code that tests
+ * the "cancelled" word first, because a frame that the program unwinds gets to the same insn. If
+ * the verifier cannot generate the pad, the program is rejected, see bpf_pads_settle().
+ */
+static int leave_cancelled_frame(struct bpf_verifier_env *env, const struct bpf_insn *insn)
+{
+	int err;
+
+	if (verifier_bug_if(!bpf_is_unwind_exit(insn), env,
+			    "a frame that the kernel unwinds returns at insn %d", env->insn_idx))
+		return -EFAULT;
+	err = unwind_frame(env, env->cur_state, env->insn_idx, BPF_SITE_REMAINDER);
+	return err ?: PROCESS_BPF_EXIT;
+}
+
 /* 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)
 {
@@ -22673,8 +22851,11 @@ static int check_recursion_guard(struct bpf_verifier_env *env)
 
 	if (!sub->recursive || env->insn_idx != sub->start)
 		return 0;
-	/* It got here by a jump, which goes past the check: at its entry a frame holds nothing. */
-	if (frame_holds_resources(env->cur_state))
+	/*
+	 * A frame that holds something or is cancelled is not at its entry. It got here by a jump
+	 * to the first insn, which does not run the check.
+	 */
+	if (frame_holds_resources(env->cur_state) || bpf_frame_is_cancelled(cur_func(env)))
 		return 0;
 	return push_unwind_edge(env, BPF_SITE_RECURSION);
 }
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 63/73] bpf: Reject a program whose cleanup pad a cancellation cannot enter
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (61 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 62/73] bpf: Verify a cleanup pad for a frame that is cancelled Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 64/73] bpf: Find the code that a cleanup pad can reach Kumar Kartikeya Dwivedi
                   ` (9 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  15 ++
 kernel/bpf/pads.c            | 448 +++++++++++++++++++++++++++++------
 kernel/bpf/verifier.c        |  11 +-
 3 files changed, 399 insertions(+), 75 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 1e87200119bc..aa204e909579 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -626,6 +626,9 @@ struct bpf_pad_plan {
 	bool visited;
 	bool used;			/* the program keeps the site, see bpf_pads_mark_used() */
 	bool failed;			/* a state made the conflict an error of the pass */
+	/* for bpf_pad_log(): a state came from a cancelled frame or below one, and one did not */
+	bool from_cleanup_pad;
+	bool from_normal;
 	/*
 	 * How many sections of each class the frame has entered since its call. Less than 0: it
 	 * has left that many sections of its callers, and the pad enters them again.
@@ -642,6 +645,8 @@ struct bpf_pad_plan {
 	/* enum bpf_pad_conflict: no location has a pointer. No error if a hidden slot has it. */
 	u8 no_place;
 	u8 no_irq_place;		/* the same for irq flags in the stack of a caller */
+	/* the groups that it asked hidden slots for, bits by enum bpf_pad_group: settle_slots() */
+	u8 asked_slots;
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
 	struct bpf_pad_ent *ents;	/* oldest first. The pad releases the last one first. */
@@ -1577,6 +1582,11 @@ struct bpf_subprog_info {
 	 * The value word: its landing pads keep the value there over their calls.
 	 */
 	s16 value_off;
+	/*
+	 * The "cancelled" word of a function in which a cancellation enters a cleanup pad: 0 from
+	 * the first insn of the function on, 1 once the frame is cancelled.
+	 */
+	s16 cancelled_off;
 	/*
 	 * The pending word: an argument waits there over the call of a subprog, the address of irq
 	 * flags that the subprog saves or a pointer that it releases, see bpf_pad_note_return()
@@ -1709,6 +1719,11 @@ struct bpf_subprog_info {
 	u16 left_at;
 	/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */
 	u8 no_slots: 4;
+	/*
+	 * Of those, the groups that it lost because a state in a cleanup pad for a cancellation
+	 * released something of a caller. For the log, see bpf_pad_log().
+	 */
+	u8 no_slots_cleanup_pad: 4;
 	/* the groups that it has hidden slots for. Each bpf_pads_settle() decides again. */
 	u8 slots: 4;
 	/*
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 8bcde2582519..01292cff77c9 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -1346,11 +1346,30 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 	return 0;
 }
 
-/* @sub gets no hidden slots for @groups, for what @st did */
+/*
+ * Does @st have a cancelled frame, or does it run a function that a cancelled frame called and that
+ * is verified separately? See 'cancelled' of struct bpf_func_state.
+ */
+static bool state_is_in_cleanup_pad(const struct bpf_verifier_state *st)
+{
+	int i;
+
+	for (i = 0; i <= st->curframe && st->frame[i]; i++)
+		if (st->frame[i]->cancelled)
+			return true;
+	return false;
+}
+
+/*
+ * @sub gets no hidden slots for @groups because of what @st did. If @st is in a cleanup pad, record
+ * that for the log, see bpf_pad_log().
+ */
 static void sub_no_slots(struct bpf_subprog_info *sub, const struct bpf_verifier_state *st,
 			 u8 groups)
 {
 	sub->no_slots |= groups;
+	if (state_is_in_cleanup_pad(st))
+		sub->no_slots_cleanup_pad |= groups;
 }
 
 /*
@@ -1423,6 +1442,11 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 		return ERR_PTR(-ENOMEM);
 	/* the frame is cancelled before it returns to the stores after its call */
 	took_locks_no_slots(env, st, st->frame[st->curframe]->took_locks);
+	/* for the log of a rejection, see bpf_pad_log() */
+	if (state_is_in_cleanup_pad(st))
+		plan->from_cleanup_pad = true;
+	else
+		plan->from_normal = true;
 	if (plan->conflict)
 		return plan;
 	err = visit_refs(env, plan, st, insn_idx);
@@ -1574,6 +1598,22 @@ void bpf_pad_no_slots(struct bpf_verifier_env *env, enum bpf_pad_group group)
 		env->subprog_info[st->frame[f]->subprogno].no_slots |= BIT(group);
 }
 
+/*
+ * The current insn releases a reference of a caller, and no call clears a hidden slot for it, see
+ * bpf_pad_no_slots(). If the state is in a cleanup pad, record that for the log, see bpf_pad_log().
+ */
+static void released_of_caller(struct bpf_verifier_env *env, enum bpf_pad_group group)
+{
+	const struct bpf_verifier_state *st = env->cur_state;
+	int f;
+
+	bpf_pad_no_slots(env, group);
+	if (!state_is_in_cleanup_pad(st))
+		return;
+	for (f = 0; f <= st->curframe; f++)
+		env->subprog_info[st->frame[f]->subprogno].no_slots_cleanup_pad |= BIT(group);
+}
+
 /*
  * The current insn releases refs[@idx], a reference that a caller of its frame holds. Record in
  * 'releases_args' each function, from the callee of that caller down to this frame, that got the
@@ -1650,20 +1690,15 @@ bool bpf_pad_reg_is_handle(const struct bpf_reg_state *reg, const struct bpf_ref
 }
 
 /*
- * The current insn releases refs[@idx], a pointer that a caller of its frame holds. If the call
- * that this caller made had the pointer in an argument register, see hand_over_refs() in
- * verifier.c, the call is what clears the hidden slot of the caller when the callee returns, as
- * it is for a lock, see took_lock_of_caller(): the callee notes the register, 'took_arg'. Nothing
- * else tells the slot at run time: the register waits in the pending word of the caller, and the
- * store behind the call looks for the slot that has the same, see bpf_pad_note_return().
- * The callee can be left before it returns, by itself or because a frame below it is unwound.
- * Then the slot is not cleared and the reference is gone: see bpf_pad_note_return().
- * False if the call cannot do that: no frame of this state holds the reference, no argument had
- * the pointer at offset 0, the call took another reference before, or a callback is on the way,
- * which returns to a helper.
- * And false until the program would be rejected without it: these are stores on the normal path,
- * and a call that hands the reference over needs none in its caller, see try_more() in
- * verifier.c.
+ * The current insn releases refs[@idx], a pointer that a caller of its frame holds. If the call of
+ * that caller had the pointer in an argument register, the call can clear the hidden slot of the
+ * caller when the callee returns, as it does for a lock: the callee records the register in
+ * 'took_arg', see bpf_pad_note_return().
+ *
+ * Returns false if the call cannot do that: no frame of this state holds the reference, the state
+ * is in a cleanup pad, no argument had the pointer at offset 0, the callee has released another
+ * argument, or a callback is in between. Also false until try_more() in verifier.c turns this on
+ * ('takes_refs'): these are stores on the normal path, and a hand-over needs none.
  */
 static bool took_ref_of_caller(struct bpf_verifier_env *env, int idx)
 {
@@ -1673,7 +1708,7 @@ static bool took_ref_of_caller(struct bpf_verifier_env *env, int idx)
 
 	for (f = st->curframe - 1; f > 0 && st->frame[f]->entry_refs > idx; f--)
 		;
-	if (f < 0 || st->frame[f]->entry_refs > idx)
+	if (f < 0 || st->frame[f]->entry_refs > idx || state_is_in_cleanup_pad(st))
 		return false;
 	callee = st->frame[f + 1];
 	for (k = 0; k < MAX_BPF_FUNC_REG_ARGS && callee->arg_refs[k] != idx + 1; k++)
@@ -1910,7 +1945,7 @@ void bpf_pad_note_release(struct bpf_verifier_env *env, int idx)
 			if (note)
 				note->for_caller = true;
 		} else {
-			bpf_pad_no_slots(env, group);
+			released_of_caller(env, group);
 		}
 		released_arg_of_caller(env, idx);
 		return;
@@ -1985,6 +2020,7 @@ void bpf_pad_note_args(struct bpf_func_state *callee, const struct bpf_func_stat
  *   - A pointer that can be NULL: nothing is held where it is.
  *   - An object in the stack, a reference that was made from another one, and one that another
  *     one was made from: they are released in the order of refs[].
+ *   - Any reference in a state that the kernel has brought into a landing pad of the program.
  *   - @subprog is recursive: the check at its entry takes a frame that holds something for one
  *     that got there by a jump, see check_recursion_guard() in verifier.c.
  */
@@ -1997,7 +2033,8 @@ int bpf_pad_handed_ref(struct bpf_verifier_env *env, const struct bpf_verifier_s
 	struct bpf_reg_state addr;
 
 	if (!(env->insn_aux_data[sub->start].live_regs_before & BIT(regno)) || sub->recursive ||
-	    !reg->id || reg->type == SCALAR_VALUE || type_may_be_null(reg->type))
+	    state_is_in_cleanup_pad(st) || !reg->id || reg->type == SCALAR_VALUE ||
+	    type_may_be_null(reg->type))
 		return -1;
 	/* @caller cannot hand over what a frame below it acquired */
 	if (caller->frameno < st->curframe)
@@ -2722,6 +2759,13 @@ static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_pl
 
 	if (!plan->used || plan->conflict)
 		return 0;
+	/*
+	 * A cancelled frame asks for none either: a path that only a cancellation takes must not
+	 * cost the normal path a store. Its pads do use the slots that the function has for another
+	 * site, see plan_take_slots().
+	 */
+	if (bpf_site_is_cancelled(plan->kind) || plan->kind == BPF_SITE_CANCEL_ENTRY)
+		return 0;
 	if (plan->no_place && all_ptrs)
 		groups |= BIT(BPF_PAD_GROUP_REFS);
 	if (plan->no_irq_place)
@@ -2734,6 +2778,39 @@ static u8 plan_needs_slots(struct bpf_verifier_env *env, const struct bpf_pad_pl
 	return groups;
 }
 
+/*
+ * Returns the groups whose hidden slots would have made the pad of @plan possible: the groups that
+ * its 'conflict' is about, of those that it asked for in settle_slots() and did not get
+ */
+static u8 conflict_groups(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
+{
+	u8 groups = 0;
+	int i;
+
+	switch (plan->conflict) {
+	case BPF_CONFLICT_SECTIONS_DIFFER:
+		groups = plan->sections_differ;
+		break;
+	case BPF_CONFLICT_NO_PLACE:
+		groups = BIT(BPF_PAD_GROUP_REFS);
+		if (plan->no_irq_place)
+			groups |= BIT(BPF_PAD_GROUP_LOCKS);
+		break;
+	case BPF_CONFLICT_NOT_ALWAYS_HELD:
+	case BPF_CONFLICT_CALLER_SAVED:
+		for (i = 0; i < plan->nr_ents; i++)
+			if (settle_ent(env, plan, &plan->ents[i]) == plan->conflict)
+				groups |= BIT(class_group(plan->ents[i].class));
+		/* 'no_place' of the record can be the same reason, see settle_plan() */
+		if (plan->no_place)
+			groups |= BIT(BPF_PAD_GROUP_REFS);
+		break;
+	default:
+		break;
+	}
+	return groups & plan->asked_slots;
+}
+
 /*
  * Is the pad of @plan impossible because of a reference, BPF_PAD_GROUP_REFS: no location holds the
  * pointer, or nothing tells whether it is held? 'no_place' is always about a pointer. Otherwise the
@@ -2769,7 +2846,8 @@ static int slot_words(const struct bpf_pad_note *note)
 /* Does the pad of @plan run in a frame that has set up its hidden slots? */
 static bool plan_has_slots(const struct bpf_pad_plan *plan)
 {
-	return bpf_site_base(plan->kind) != BPF_SITE_RECURSION && !plan->conflict;
+	return bpf_site_base(plan->kind) != BPF_SITE_RECURSION &&
+	       plan->kind != BPF_SITE_CANCEL_ENTRY && !plan->conflict;
 }
 
 /* Does @plan have room for @slots releases instead of those that it has of @group? */
@@ -2925,9 +3003,11 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 	if (pend_off)
 		pend_off = sub->pend_off ?:
 			   -(int)bpf_stack_depth_with_slots(sub) - ++words * BPF_REG_SIZE;
+	/* a cancelled frame without room does not cost the function its slots, see below */
 	for (i = sub->start; i < sub[1].start; i++)
 		for (plan = aux[i].pad_plans; plan; plan = plan->next)
 			if (plan->used && plan_has_slots(plan) &&
+			    !bpf_site_is_cancelled(plan->kind) &&
 			    !plan_has_room(plan, group, slots))
 				return 0;
 	sub->hidden_words += words;
@@ -2940,7 +3020,7 @@ static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
 		sub->pend_off = pend_off;
 	for (i = sub->start; i < sub[1].start; i++) {
 		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
-			/* the program does not have its site */
+			/* not a site that the program keeps, or a cancelled frame */
 			if (plan_has_slots(plan) && !plan_has_room(plan, group, slots))
 				plan->conflict = BPF_CONFLICT_SLOTS_FULL;
 			err = plan_has_slots(plan) ?
@@ -2967,13 +3047,14 @@ static int settle_slots(struct bpf_verifier_env *env)
 	struct bpf_pad_plan *plan;
 	int i, s, err;
 	bool all_ptrs;
-	u8 need;
+	u8 need, asks;
 
 	for (s = 0; s < env->subprog_cnt; s++) {
 		env->subprog_info[s].slots = 0;
 		env->subprog_info[s].hidden_words = 0;
 		env->subprog_info[s].value_off = 0;
 		env->subprog_info[s].no_value_word = false;
+		env->subprog_info[s].cancelled_off = 0;
 		env->subprog_info[s].pend_off = 0;
 	}
 	for (s = 0; s < env->subprog_cnt; s++) {
@@ -2983,9 +3064,14 @@ static int settle_slots(struct bpf_verifier_env *env)
 			if (bpf_must_abort())
 				return -EINTR;
 			need = 0;
-			for (i = sub->start; i < sub[1].start; i++)
-				for (plan = aux[i].pad_plans; plan; plan = plan->next)
-					need |= plan_needs_slots(env, plan, all_ptrs);
+			for (i = sub->start; i < sub[1].start; i++) {
+				for (plan = aux[i].pad_plans; plan; plan = plan->next) {
+					asks = plan_needs_slots(env, plan, all_ptrs);
+					/* for the log, see conflict_groups() */
+					plan->asked_slots |= asks;
+					need |= asks;
+				}
+			}
 			need &= ~sub->no_slots;
 			err = need ? subprog_take_slots(env, s, __ffs(need)) : 0;
 			if (err < 0)
@@ -3330,6 +3416,197 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 			plan->sections[BPF_PAD_PREEMPT]);
 }
 
+/*
+ * Returns a bitmap of the insns from which insn @at can be reached in its function, on the control
+ * flow graph, @at included. NULL if there is no memory. The walk is for the log only and is not
+ * charged, so it follows each edge of the function once, backwards from @at.
+ */
+static unsigned long *insns_that_reach(struct bpf_verifier_env *env, int at)
+{
+	const struct bpf_subprog_info *sub = bpf_find_containing_subprog(env, at);
+	unsigned long *reach = bitmap_zalloc(env->prog->len, BPF_VERIFIER_GFP);
+	/* an edge, and 1 + the edge before it that goes to the same insn */
+	struct { u32 from, prev; } *edges = NULL, *edge;
+	/* per insn: 1 + the last edge that goes to it. And the insns to walk back from. */
+	u32 *last, *todo;
+	struct bpf_iarray *succ;
+	int i, p, t, nr = 0, top = 0;
+
+	last = kvcalloc(env->prog->len, sizeof(*last), BPF_VERIFIER_GFP);
+	todo = kvmalloc_array(env->prog->len, sizeof(*todo), BPF_VERIFIER_GFP);
+	if (!reach || !last || !todo)
+		goto err;
+	for (p = sub->postorder_start; p < sub[1].postorder_start; p++) {
+		i = env->cfg.insn_postorder[p];
+		succ = bpf_insn_successors(env, i);
+		iarray_for_each(t, succ) {
+			edge = bpf_table_next(edges, nr);
+			if (!edge)
+				goto err;
+			*edge = (typeof(*edge)){ i, last[t] };
+			last[t] = ++nr;
+		}
+	}
+	__set_bit(at, reach);
+	todo[top++] = at;
+	while (top) {
+		t = todo[--top];
+		for (p = last[t]; p; p = edges[p - 1].prev) {
+			i = edges[p - 1].from;
+			if (!__test_and_set_bit(i, reach))
+				todo[top++] = i;
+		}
+	}
+out:
+	kvfree(edges);
+	kvfree(last);
+	kvfree(todo);
+	return reach;
+err:
+	bitmap_free(reach);
+	reach = NULL;
+	goto out;
+}
+
+/* Returns the first insn of the program's landing pad of the call at @call_idx */
+static int pad_of_call(struct bpf_verifier_env *env, int call_idx)
+{
+	return call_idx + 2 + bpf_jmp_offset(&env->prog->insnsi[call_idx + 1]);
+}
+
+/*
+ * Returns the first call of @sub after which a cancellation enters a cleanup pad, or -1, and sets
+ * *@more to the number of other such calls. With @reach only the cleanup pads whose first insn is
+ * in that bitmap count, see insns_that_reach(). When a pass is over, the entries that the program
+ * keeps are known ('used'). Until then the entries that a state went through are taken.
+ */
+static int first_entered_pad(struct bpf_verifier_env *env, const struct bpf_subprog_info *sub,
+			     const unsigned long *reach, int *more)
+{
+	const struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	const struct bpf_pad_plan *plan;
+	int i, used, first = -1;
+
+	for (used = 1; used >= 0 && first < 0; used--) {
+		*more = 0;
+		for (i = sub->start; sub->has_cleanup_pads && i < sub[1].start; i++) {
+			plan = bpf_pad_plan(&aux[i], BPF_SITE_CANCEL_ENTRY);
+			if (!plan || !(used ? plan->used : plan->visited))
+				continue;
+			if (reach && !test_bit(pad_of_call(env, i), reach))
+				continue;
+			if (first < 0)
+				first = i;
+			else
+				(*more)++;
+		}
+	}
+	return first;
+}
+
+/*
+ * Start the log line of an error that comes from a cancellation entering a cleanup pad of @sub. It
+ * names the first such cleanup pad, see first_entered_pad(). Returns false if there is none.
+ */
+static bool print_entered_pad(struct bpf_verifier_env *env, const struct bpf_subprog_info *sub,
+			      const unsigned long *reach)
+{
+	int more, call = first_entered_pad(env, sub, reach, &more);
+
+	if (call < 0)
+		return false;
+	verbose(env, "the kernel would enter the landing pad at %d of the call at %d",
+		pad_of_call(env, call), call);
+	if (more)
+		verbose(env, ", and %d more of func#%d", more, (int)(sub - env->subprog_info));
+	verbose(env, ": ");
+	return true;
+}
+
+/*
+ * Can a cleanup pad be the reason for @conflict in a frame above its own? It can if its code
+ * releases a lock or leaves a section of a caller on some paths only, or writes to the stack of a
+ * caller, where irq flags or an iterator are. The other reasons do not depend on a callee.
+ */
+static bool pad_can_cause(enum bpf_pad_conflict conflict)
+{
+	switch (conflict) {
+	case BPF_CONFLICT_SECTIONS_DIFFER:
+	case BPF_CONFLICT_PLAN_FULL:
+	case BPF_CONFLICT_SLOTS_FULL:
+	case BPF_CONFLICT_NOT_ALWAYS_HELD:
+	case BPF_CONFLICT_NO_PLACE:
+	case BPF_CONFLICT_ORDER_DIFFERS:
+	case BPF_CONFLICT_CALLER_SAVED:
+		return true;
+	default:
+		return false;
+	}
+}
+
+/*
+ * The conflict of @plan, a site at insn @i, is an error. The kernel enters a landing pad of the
+ * program that only resumes or the program is rejected: where such a pad has a part in the
+ * conflict the log says so, in front of the line of the conflict. It names a pad only where that
+ * pad is known to have the part.
+ *   - The plan is that of an entry: it has no value to keep.
+ *   - The frame is one that the kernel unwinds through such a pad: it has no plan where the pad
+ *     ends, or at a site in pad code. A frame does not know which entry it came through: the
+ *     first pad of the function that gets to the insn on the control flow graph is named, and
+ *     the others that do are counted.
+ *   - States got to the site out of such a pad, in a function that the pad calls. Its frame
+ *     does not know the pad. If states of the normal path got there as well, the function is
+ *     "also" called from the pad: the conflict may be one without the pad.
+ *   - What came back to the call of the plan left a frame below through such a pad, which may
+ *     have taken from what the frame of the call holds, or written to its stack. Which pad it
+ *     was is not known, and a pad on the way may have done nothing of the kind: the function
+ *     that came back is named, the pad is in it or below it.
+ *   - Such a pad released what a caller holds, and no function on the stack gets hidden slots
+ *     for that, see released_of_caller(): the plan needed them for it.
+ */
+static void print_cleanup_pad_conflict(struct bpf_verifier_env *env, int i,
+				       const struct bpf_pad_plan *plan)
+{
+	const struct bpf_subprog_info *sub = bpf_find_containing_subprog(env, i);
+	unsigned long *reach;
+	int s, c = -1;
+
+	if (!bpf_verifier_log_needed(&env->log))
+		return;
+	if (plan->kind == BPF_SITE_CANCEL_ENTRY) {
+		verbose(env, "the kernel would enter the landing pad at %d of the call at %d: its entry has no value to keep: %s\n",
+			pad_of_call(env, i), i, conflict_why[plan->conflict]);
+		return;
+	}
+	if (bpf_site_is_cancelled(plan->kind)) {
+		reach = insns_that_reach(env, i);
+		if (reach && print_entered_pad(env, sub, reach)) {
+			if (plan->kind == BPF_SITE_REMAINDER)
+				verbose(env, "what the pad leaves at unwind_exit at %d cannot be released\n",
+					i);
+			else
+				verbose(env, "a site in its code has no plan\n");
+		}
+		bitmap_free(reach);
+		return;
+	}
+	if (plan->from_cleanup_pad)
+		verbose(env, "func#%d is %scalled from a landing pad of the program that the kernel would enter\n",
+			(int)(sub - env->subprog_info), plan->from_normal ? "also " : "");
+	if (!pad_can_cause(plan->conflict))
+		return;
+	if (bpf_site_is_call(plan->kind) && (sites_below(env, plan) & BIT(BPF_SITE_REMAINDER)))
+		bpf_pad_for_each_callee(plan, s)
+			if (c < 0 && (env->subprog_info[s].left_at & BIT(BPF_SITE_REMAINDER)))
+				c = s;
+	if (c >= 0)
+		verbose(env, "the kernel would enter a landing pad of the program in or below func#%d: it may release or overwrite what a caller holds at the call at %d\n",
+			c, i);
+	else if (sub->no_slots_cleanup_pad & conflict_groups(env, plan))
+		verbose(env, "the kernel would enter a landing pad of the program: what its code releases of a caller may keep func#%d from getting hidden slots\n",
+			(int)(sub - env->subprog_info));
+}
+
 /*
  * Log that @subprog owns the references that its calls hand over in the argument registers @args,
  * see bpf_pad_handed_ref(). The log of an error about a reference at one of its sites says so,
@@ -3352,12 +3629,15 @@ void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pa
 
 	if (plan->conflict) {
 		print_sites_below(env, insn_idx, plan);
+		print_cleanup_pad_conflict(env, insn_idx, plan);
 		/* a release that the pad may not make is one of a pointer or of an object */
 		if (sub->owns_args && (plan->conflict == BPF_CONFLICT_NO_RELEASE ||
 				       conflict_of_ref(env, plan)))
 			bpf_pad_log_handed_over(env, sub - env->subprog_info, sub->owns_args);
 	}
-	print_plan(env, insn_idx, plan);
+	/* the line above has said why the entry cannot be generated */
+	if (plan->kind != BPF_SITE_CANCEL_ENTRY || !plan->conflict)
+		print_plan(env, insn_idx, plan);
 }
 
 /*
@@ -3471,6 +3751,60 @@ static int take_value_word(struct bpf_verifier_env *env, struct bpf_subprog_info
 	return 0;
 }
 
+/*
+ * @sub gets the hidden word K, and in a program with bpf_throw() the word for the value: the entry
+ * of a landing pad stores both. Returns 1 if the stack has no room.
+ */
+static int take_cancelled_words(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
+{
+	int err;
+
+	sub->hidden_words++;
+	err = bpf_hidden_slots_fit(env);
+	if (err <= 0) {
+		sub->hidden_words--;
+		return err ?: 1;
+	}
+	sub->cancelled_off = -(int)bpf_stack_depth_with_slots(sub);
+	if (!env->has_throw)
+		return 0;
+	err = take_value_word(env, sub);
+	return err < 0 ? err : !!err;
+}
+
+/*
+ * Give the functions in which a cancellation enters a cleanup pad their hidden words, see
+ * take_cancelled_words(). They are taken after all other hidden words, so that they never take the
+ * room of a word that the program needs in order to load. A function whose stack has no room for
+ * them rejects the program.
+ */
+static int take_cleanup_pad_words(struct bpf_verifier_env *env)
+{
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	struct bpf_subprog_info *sub;
+	struct bpf_pad_plan *plan;
+	int i, s, err;
+	bool enters;
+
+	for (s = 0; s < env->subprog_cnt; s++) {
+		sub = &env->subprog_info[s];
+		enters = false;
+		for (i = sub->start; sub->has_cleanup_pads && !enters && i < sub[1].start; i++) {
+			plan = bpf_pad_plan(&aux[i], BPF_SITE_CANCEL_ENTRY);
+			enters = plan && plan->used;
+		}
+		err = enters ? take_cancelled_words(env, sub) : 0;
+		if (err < 0)
+			return err;
+		if (!err)
+			continue;
+		print_entered_pad(env, sub, NULL);
+		verbose(env, "no room in the stack for the hidden words of func#%d\n", s);
+		return -EINVAL;
+	}
+	return 0;
+}
+
 /*
  * 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
@@ -3489,17 +3823,12 @@ void bpf_pads_mark_used(struct bpf_verifier_env *env)
 }
 
 /*
- * A pass that counts is over: all states have visited the plans. A state whose visit made a
- * 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().
- * That holds for every plan, also for those that are there because the kernel enters landing pads
- * of the program: the entry of such a pad, a site that a frame gets to while the kernel unwinds it
- * through the pad, unwind_exit where the pad ends, and a pad of the verifier in a caller that gets
- * what such a frame left. What the program does in its pad is its own business. What the verifier
- * adds around it has to be right, or the program does not load: no landing pad is passed by
- * because the verifier has no plan.
+ * A pass ended without an error, and all its states have been recorded at the sites. For each site
+ * that the program keeps, decide whether its pad can be generated, and give the functions their
+ * hidden slots and hidden words. A site without a pad and without another way to continue is an
+ * error of the pass, see plan_rejects(), and an unproven insn for the next pass, see
+ * bpf_find_unproven_after_pass(). That holds for the records around a cleanup pad as well: a
+ * cleanup pad that a cancellation can reach is entered, or the program is rejected.
  */
 int bpf_pads_settle(struct bpf_verifier_env *env)
 {
@@ -3537,9 +3866,7 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 			/* the record of an entry is no record of a pad: nothing to settle */
 			if (plan->kind != BPF_SITE_CANCEL_ENTRY) {
 				err = settle_plan(env, plan);
-				if (!err &&
-				    (plan_saves_value(env, plan, sub - env->subprog_info) ||
-				     (bpf_site_is_cancelled(plan->kind) && env->has_throw)))
+				if (!err && plan_saves_value(env, plan, sub - env->subprog_info))
 					err = take_value_word(env, sub);
 				if (err < 0)
 					return err;
@@ -3576,8 +3903,13 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 		bpf_pad_log(env, at, reject);
 		return -EINVAL;
 	}
+	if (env->faults_late)
+		return 0;
+	err = take_cleanup_pad_words(env);
+	if (err)
+		return err;
 	/* all accesses of the program to its stack are known: the hidden words go below them */
-	for (s = 0; !env->faults_late && s < env->subprog_cnt; s++) {
+	for (s = 0; s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
 		if (sub->hidden_words)
 			bpf_stack_take_hidden_words(sub);
@@ -3705,32 +4037,12 @@ static void ask_below_cleanup_pads(struct bpf_verifier_env *env)
 }
 
 /*
- * The pass has an error, and the kernel entered landing pads of the program in it: a state went
- * through the entry of a call, 'visited' of its plan, see bpf_pad_enter(). The kernel may have got
- * into such a pad only because calls were verified together: the function of count() above with a
- * landing pad behind its call. Kept apart nothing comes back unwound to that call, no state gets
- * into the pad, and what such a state had a part in is gone. That can be any error, and neither
- * the state nor the plan that has it needs to know of the pad:
- *   - a conflict where the pad ends, at a site in its code, or in a caller that gets what the
- *     pad left;
- *   - an error or a conflict in what its code calls, also in a callback that it only arms;
- *   - a conflict at a call of the normal path, in a function that the code of the pad calls as
- *     well: the numbers that the pad passes take the trip count from its loop, and may_goto is in
- *     the code for every call of the function;
- *   - hidden slots that a function does not get because of what the code of the pad releases.
- * So there is one rule: whatever the error is, every function in which the kernel entered a pad
- * is marked. The calls behind which it did are causes, and so is what makes their callees unwind,
- * see note_causes_below(). The marks say what the next pass keeps apart and nothing else: no
- * verdict rests on them.
- * They are those of this pass, and every pass that has an error makes them again while the
- * kernel still gets into a pad: the causes have to be there for each step of
- * bpf_partition_more() in turn, until the calls are apart. They are no step of their own. A pass
- * after which nothing more is kept apart is the last one with them as without them, and the
- * limit on the cost of a load that is rejected is the same, see do_check_all().
- * A program that is rejected for another reason pays for them: for the dependencies of the calls
- * of the marked functions, in every pass, and where only calls that are verified together get
- * into the pad, for keeping those apart. An error behind such calls depends on the loop of their
- * callee from then on, and costs what an error that reads the result of that loop costs.
+ * The pass has an error, and a cancellation entered a cleanup pad in it: a state went through the
+ * entry of a call, see bpf_pad_enter(). That may be so only because two calls are verified
+ * together, like the calls of count() above with a cleanup pad after them. The error can then be
+ * anywhere, and the pass that keeps the two calls apart has none. So after a pass with any error,
+ * mark every function in which a state entered a cleanup pad, for note_causes_below(). No verdict
+ * rests on the marks. Only a load that is rejected pays for them, in load time.
  */
 static void note_entered(struct bpf_verifier_env *env)
 {
@@ -3976,7 +4288,9 @@ static bool insn_returns(const struct bpf_insn *insn)
  * it is that no insn which it can get to returns to its caller: it is left at unwind_exit or at a
  * site, with cancel_exit, and nowhere else. See enter_cleanup_pad() in verifier.c.
  *
- * The answer is a property of the insns, the same in every pass: 'cleanup_pad' of unwind_goto.
+ * The answer is a property of the insns, the same in every pass: 'cleanup_pad' of unwind_goto. The
+ * kernel enters each of these pads when it unwinds what the call in front of it calls, in a
+ * function that can unwind, or the program is rejected: see bpf_pads_settle().
  * Dead branches are gone from the graph, see bpf_prune_dead_branches().
  */
 int bpf_find_cleanup_pads(struct bpf_verifier_env *env)
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 834d0b0a9ea9..31b1bac012fa 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -22586,14 +22586,9 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
 		stuck = plan->conflict == BPF_CONFLICT_CANNOT_UNWIND ||
 			plan->conflict == BPF_CONFLICT_NO_EXIT;
 		/*
-		 * There is no other way out. Not for may_goto of the program, an access to arena
-		 * and a call above them either, but in a subprog that cannot unwind, and whether
-		 * it is one may be found later in the pass. Then this error was none, see
-		 * do_check_all().
-		 * It is an error also where a landing pad of the program that the kernel entered
-		 * has a part in it: what came back to the call left a frame below through such
-		 * a pad, or the state got here out of one, in a function that the pad calls.
-		 * The kernel enters the pad or the program is rejected.
+		 * A missing landing pad is an error, unless the frame cannot be cancelled and the
+		 * site can be skipped. If the function turns out later in the pass to be one that
+		 * cannot be cancelled, do_check_all() drops the error.
 		 */
 		if (plan->conflict && certain && (bpf_pad_must_unwind(env, plan) || !stuck)) {
 			bpf_pad_log(env, insn_idx, plan);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 64/73] bpf: Find the code that a cleanup pad can reach
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (62 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 63/73] bpf: Reject a program whose cleanup pad a cancellation cannot enter Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:41   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 65/73] bpf: Emit the stub, the entry and the remainder of a cleanup pad Kumar Kartikeya Dwivedi
                   ` (8 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |   4 ++
 kernel/bpf/pads.c            | 125 +++++++++++++++++++++++++++++------
 2 files changed, 110 insertions(+), 19 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index aa204e909579..97892d66274e 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -1424,6 +1424,8 @@ struct bpf_insn_aux_data {
 	u32 jump_target:1;
 	/* an unwind_goto of the program that leads to a cleanup pad, see bpf_find_cleanup_pads() */
 	u32 cleanup_pad:1;
+	/* pad code: a cleanup pad of its function reaches the insn, see bpf_find_cleanup_pads() */
+	u32 cleanup_pad_code:1;
 	/* it can read or write the frame of a caller, in a call with a known callee */
 	u32 reads_outer:1;
 	u32 writes_outer:1;
@@ -1713,6 +1715,8 @@ struct bpf_subprog_info {
 	bool arg_refs_differ: 1;
 	/* it has an unwind_goto that leads to a cleanup pad, see bpf_find_cleanup_pads() */
 	bool has_cleanup_pads: 1;
+	/* "mixed": an insn of it is pad code and on the normal path, see bpf_find_cleanup_pads() */
+	bool cleanup_pads_mixed: 1;
 	/* a cancellation enters one of its cleanup pads, see bpf_mark_subprogs_that_unwind() */
 	bool enters_cleanup_pads: 1;
 	/* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 01292cff77c9..7907f59068be 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -4257,6 +4257,104 @@ static bool insn_returns(const struct bpf_insn *insn)
 	       (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND);
 }
 
+/*
+ * Find the code that a cancelled frame can run, in the functions that have a cleanup pad. Pad code
+ * ('cleanup_pad_code') is what can be reached from the first insn of a cleanup pad: a cancelled
+ * frame starts there and follows edges of the control flow graph. The normal path is what can be
+ * reached from the first insn of the function without the jump of an unwind_goto. The rest is the
+ * program's landing pad of a typed catch, which no cancelled frame runs:
+ *
+ *	   call a		   normal path
+ *	   unwind_goto 1f
+ *	   call b
+ *	   unwind_goto 2f
+ *	   exit
+ *	2: if r0 != 7 goto 3f	   a typed catch
+ *	   r0 = 0
+ *	   exit
+ *	1: call dtor		   pad code
+ *	3: unwind_exit
+ *
+ * A function is MIXED ('cleanup_pads_mixed') if one of its insns is pad code and on the normal path
+ * as well: the normal path falls or jumps into a cleanup pad, a cleanup pad jumps back before its
+ * call, or the function has no exit. In any other function a frame gets from the normal path into
+ * pad code in two ways only: by the jump of an unwind_goto, and through an entry.
+ *
+ * A function is MIXED, 'cleanup_pads_mixed', if one of its insns is pad code and on the normal path
+ * as well: a pad that the normal path falls into or jumps to, a pad that goes back in front of its
+ * call, or to the first insn of its function, any pad of a function that has no exit. In every
+ * other function the two share no insn, and a frame gets from the normal path into pad code in two
+ * ways only: by the jump of unwind_goto, when a callee left with unwind_exit, and through the entry
+ * of a pad, when the kernel unwound the callee.
+ *
+ * The exit that stands for the return of a tail call or of LD_ABS is no edge here, as it is none
+ * where the pads are judged: it can be unwind_exit of the code that resumes, and a tail call on
+ * the normal path would make every such function mixed.
+ */
+static int find_pad_code(struct bpf_verifier_env *env)
+{
+	const struct bpf_insn *insns = env->prog->insnsi, *insn;
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	int i, p, t, s, cnt, len = env->prog->len, err = 0;
+	struct bpf_subprog_info *sub;
+	unsigned long *pad, *normal;
+	struct bpf_iarray *succ;
+	bool changed;
+
+	pad = bitmap_zalloc(len, BPF_VERIFIER_GFP);
+	normal = bitmap_zalloc(len, BPF_VERIFIER_GFP);
+	if (!pad || !normal) {
+		err = -ENOMEM;
+		goto out;
+	}
+	for (s = 0; s < env->subprog_cnt; s++)
+		if (env->subprog_info[s].has_cleanup_pads)
+			__set_bit(env->subprog_info[s].start, normal);
+	for (i = 0; i < len; i++)
+		if (aux[i].cleanup_pad)
+			__set_bit(i + 1 + bpf_jmp_offset(&insns[i]), pad);
+	/* the successors of an insn come before it in the postorder: walk that from its end */
+	do {
+		changed = false;
+		err = bpf_add_cost_and_check(env, env->cfg.cur_postorder, BPF_COST_SCAN);
+		if (err)
+			goto out;
+		for (p = env->cfg.cur_postorder - 1; p >= 0; p--) {
+			i = env->cfg.insn_postorder[p];
+			if (!test_bit(i, pad) && !test_bit(i, normal))
+				continue;
+			insn = &insns[i];
+			succ = bpf_insn_successors(env, i);
+			cnt = insn_returns(insn) ? min(succ->cnt, 1) : succ->cnt;
+			for (t = 0; t < cnt; t++) {
+				if (test_bit(i, pad) && !__test_and_set_bit(succ->items[t], pad))
+					changed = true;
+				/* the second successor of an unwind_goto is its jump */
+				if (test_bit(i, normal) && !(t && bpf_is_unwind_goto(insn)) &&
+				    !__test_and_set_bit(succ->items[t], normal))
+					changed = true;
+			}
+		}
+	} while (changed);
+	for (s = 0; s < env->subprog_cnt; s++) {
+		sub = &env->subprog_info[s];
+		for (i = sub->start; sub->has_cleanup_pads && i < sub[1].start; i++) {
+			aux[i].cleanup_pad_code = test_bit(i, pad);
+			if (sub->cleanup_pads_mixed || !test_bit(i, pad) || !test_bit(i, normal))
+				continue;
+			sub->cleanup_pads_mixed = true;
+			if (env->log.level & BPF_LOG_LEVEL2)
+				verbose(env,
+					"insn %d of func#%d is on the normal path and in a landing pad that only resumes\n",
+					i, s);
+		}
+	}
+out:
+	bitmap_free(pad);
+	bitmap_free(normal);
+	return err;
+}
+
 /*
  * Find the cleanup pads of the program on the control flow graph, before the main pass. The landing
  * pad of an unwind_goto is a cleanup pad ('cleanup_pad' in the aux data of the unwind_goto) if,
@@ -4275,23 +4373,11 @@ static bool insn_returns(const struct bpf_insn *insn)
  *
  *	   a cleanup pad	   returns		   no unwind_exit
  *
- *	only resumes		returns			no unwind_exit
- *
- * A typed catch gets to its handler by a branch on what the personality routine of the program
- * says, which is a value like any other: the pad returns. Pads that share their last insns, as the
- * pads of one function of C++ do, are judged one by one, each from its first insn.
- *
- * What a frame that the kernel unwinds runs from there on is what the pad gets to, and that need
- * not be code of a pad: a pad can jump back in front of its call, or to the first insn of its
- * function, and in a function that has no exit every pad only resumes. Such a frame runs the
- * normal path of the function once more. What holds for it is not that it runs cleanup code only,
- * it is that no insn which it can get to returns to its caller: it is left at unwind_exit or at a
- * site, with cancel_exit, and nowhere else. See enter_cleanup_pad() in verifier.c.
- *
- * The answer is a property of the insns, the same in every pass: 'cleanup_pad' of unwind_goto. The
- * kernel enters each of these pads when it unwinds what the call in front of it calls, in a
- * function that can unwind, or the program is rejected: see bpf_pads_settle().
- * Dead branches are gone from the graph, see bpf_prune_dead_branches().
+ * A typed catch reaches its handler by a branch on a value, so its landing pad returns. Landing
+ * pads that share their last insns are judged one by one. A cleanup pad can jump back before its
+ * call, so a cancelled frame need not run cleanup code only. The verifier relies on one thing: no
+ * insn that the frame can reach returns to the caller. The answer depends on the insns alone, so it
+ * is the same in every pass.
  */
 int bpf_find_cleanup_pads(struct bpf_verifier_env *env)
 {
@@ -4299,7 +4385,7 @@ int bpf_find_cleanup_pads(struct bpf_verifier_env *env)
 	int i, p, t, pad, cnt, len = env->prog->len, err = 0;
 	unsigned long *returns, *resumes;
 	struct bpf_iarray *succ;
-	bool changed, ret, res;
+	bool changed, ret, res, found = false;
 
 	for (i = 0; i < len && !bpf_is_unwind_goto(&insns[i]); i++)
 		;
@@ -4353,12 +4439,13 @@ int bpf_find_cleanup_pads(struct bpf_verifier_env *env)
 		res = test_bit(pad, resumes);
 		env->insn_aux_data[i].cleanup_pad = !ret && res;
 		if (!ret && res)
-			bpf_find_containing_subprog(env, i)->has_cleanup_pads = true;
+			bpf_find_containing_subprog(env, i)->has_cleanup_pads = found = true;
 		if (!(env->log.level & BPF_LOG_LEVEL2))
 			continue;
 		verbose(env, "landing pad at %d of the call at %d %s\n", pad, i - 1,
 			ret ? "returns" : res ? "only resumes" : "has no unwind_exit");
 	}
+	err = found ? find_pad_code(env) : 0;
 out:
 	bitmap_free(returns);
 	bitmap_free(resumes);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 65/73] bpf: Emit the stub, the entry and the remainder of a cleanup pad
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (63 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 64/73] bpf: Find the code that a cleanup pad can reach Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 66/73] bpf: Let the entry of a cleanup pad save the pointers of the frame Kumar Kartikeya Dwivedi
                   ` (7 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  39 ++-
 kernel/bpf/fixups.c          | 601 ++++++++++++++++++++++++++++-------
 kernel/bpf/pads.c            |  90 +++++-
 kernel/bpf/verifier.c        |  54 +---
 4 files changed, 621 insertions(+), 163 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 97892d66274e..93147a22c81e 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -649,6 +649,13 @@ struct bpf_pad_plan {
 	u8 asked_slots;
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
+	/* BPF_SITE_CANCEL_ENTRY: its entry need not test the "cancelled" word: collect_pads() */
+	bool untested;
+	/*
+	 * BPF_SITE_CANCEL_ENTRY: a frame that was cancelled already reached the entry, so its call
+	 * is in pad code. collect_pads() checks that against the control flow graph.
+	 */
+	bool cancelled_visit;
 	struct bpf_pad_ent *ents;	/* oldest first. The pad releases the last one first. */
 	/* before[i]: bits of the entries that entry i must stand before, see put_before() */
 	u8 before[BPF_PAD_MAX_ENTS];
@@ -738,6 +745,9 @@ struct bpf_pad_note {
 	u8 entry: 1;
 };
 
+/* 'clear_stub' of an unwind_goto that gets no stub */
+#define BPF_CLEAR_STUB_NONE	U32_MAX
+
 /* The plans and the notes of an insn in the snapshot of a pass, see bpf_pads_move() */
 struct bpf_pads_moved {
 	struct bpf_pad_plan *plans;
@@ -1403,6 +1413,11 @@ struct bpf_insn_aux_data {
 	u64 fault_unwinds:1; /* in the final program a fault goes to 'fault_pad' of the subprog */
 	u64 unwind_goto_follows:1; /* the verifier added an unwind_goto after the insn */
 	u64 cancel_goto_follows:1; /* the verifier added a cancel_goto after the insn */
+	/*
+	 * An unwind_goto of the program: a cancelled frame took its jump, so its call is in pad
+	 * code. collect_stubs() checks that the control flow graph says the same.
+	 */
+	u64 cancelled_takes:1;
 	);
 
 	/* what one pass gives to the next pass, see bpf_flow_new_pass() */
@@ -1429,6 +1444,11 @@ struct bpf_insn_aux_data {
 	/* it can read or write the frame of a caller, in a call with a known callee */
 	u32 reads_outer:1;
 	u32 writes_outer:1;
+	/*
+	 * An unwind_goto of the program: 1 + the offset of its stub in the pads of the subprog, see
+	 * collect_stubs(). BPF_CLEAR_STUB_NONE: no stub, its call is in pad code. 0: not decided.
+	 */
+	u32 clear_stub;
 	/*
 	 * Per-instruction summary of stack slots in the current frame
 	 * that this instruction may write, may read, and that are live before it.
@@ -1585,8 +1605,9 @@ struct bpf_subprog_info {
 	 */
 	s16 value_off;
 	/*
-	 * The "cancelled" word of a function in which a cancellation enters a cleanup pad: 0 from
-	 * the first insn of the function on, 1 once the frame is cancelled.
+	 * The "cancelled" word: 1 in a frame that runs a cleanup pad for a cancellation, 0 in one
+	 * that runs it for the program's own unwinding. Only the stubs and the entries of the
+	 * function write it, or the first insn of a mixed function.
 	 */
 	s16 cancelled_off;
 	/*
@@ -1783,6 +1804,15 @@ static inline void bpf_subprog_set_stuck(struct bpf_subprog_info *sub, enum bpf_
 	sub->stuck_insn = insn_idx;
 }
 
+/*
+ * Does the first insn of @sub clear its "cancelled" word? Only in a mixed function, see
+ * bpf_pad_entry_insns(). In any other function the stubs and the entries write the word.
+ */
+static inline bool bpf_subprog_clears_cancelled(const struct bpf_subprog_info *sub)
+{
+	return sub->cancelled_off && sub->cleanup_pads_mixed;
+}
+
 /* The stack depth of @sub with its hidden slots and words */
 static inline u32 bpf_stack_depth_with_slots(const struct bpf_subprog_info *sub)
 {
@@ -2603,7 +2633,10 @@ void bpf_pads_note_causes(struct bpf_verifier_env *env);
 bool bpf_pad_can_be_shared(const struct bpf_pad_plan *plan);
 int bpf_hidden_slots_fit(struct bpf_verifier_env *env);
 int bpf_pad_slot_notes(struct bpf_verifier_env *env, int s, const struct bpf_pad_note **notes);
-int bpf_pad_entry_insns(const struct bpf_pad_note **notes, int nr, struct bpf_insn *buf);
+int bpf_pad_entry_insns(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
+			int nr, struct bpf_insn *buf);
+int bpf_pad_cancel_entry_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
+			       int subprog, struct bpf_insn *buf);
 int bpf_pad_insns_before(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
 			 int nr, const struct bpf_pad_note *note, struct bpf_insn *buf);
 int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index b00a011fa66c..75d3349624d1 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -613,18 +613,17 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
 }
 
 /*
- * The landing pad of a site in subprog @s. The only exit of a pad is its last insn. Nothing in a
- * pad is hardened against a cpu that mispredicts: only a program that is loaded with CAP_PERFMON
- * gets one, see frame_cannot_unwind().
- * The main program returns what the exception callback makes of the value. The pad has no index
- * yet: bpf_insert_sites() sets the offset of the call. The callback is not called a second time:
- * its unwind_exit gets to the exit of the pad like its exit does, and so does its cancel_exit.
- * unwind_goto and cancel_goto say so, to bpf_unwind_target() and bpf_cancel_target(): a return
- * address in a program without an entry is a lost unwind_exit or cancel_exit. Only a callback that
- * can leave that way gets the insn, and such a program needs a JIT that knows it already. A pad of
- * any other program is plain BPF: the interpreter and the other JITs run it.
- * bpf_mark_subprogs_that_unwind() ran, so it is known which callback that is.
- * Returns the number of insns, BPF_PAD_MAX_INSNS + 2 at most.
+ * Emit the landing pad of @plan, a site in subprog @s. In a program with an exception callback, a
+ * pad of the main program passes its value to the callback and returns what the callback returns:
+ *
+ *	the releases, r1 = value	bpf_pad_insns()
+ *	call exception_cb		bpf_insert_sites() sets the offset
+ *	unwind_goto 1f			if the callback can leave with unwind_exit
+ *	cancel_goto 1f			if the callback can leave with cancel_exit
+ * 1:	exit
+ *
+ * A pad has no nospec barrier: only a program that is loaded with CAP_PERFMON gets one, see
+ * frame_cannot_unwind(). Returns the number of insns, at most BPF_PAD_MAX_INSNS + 4.
  */
 static int emit_pad(struct bpf_verifier_env *env, int s, const struct bpf_pad_plan *plan,
 		    struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
@@ -781,7 +780,10 @@ static struct bpf_pad_plan *unvisited_plan(struct bpf_verifier_env *env, int i,
 	return plan;
 }
 
-/* The landing pads that go after a subprog: their insns, and where each pad ends */
+/*
+ * The insns that go after the last insn of a subprog: its stubs, see collect_stubs(), then its
+ * landing pads. 'ends' has the end of each pad in 'insns'.
+ */
 struct pad_buf {
 	struct bpf_insn *insns;
 	int *ends;
@@ -792,6 +794,7 @@ struct pad_buf {
 	int max_cnt;	/* the room of 'insns' */
 	int nr;		/* pads */
 	int cnt;	/* insns */
+	int stubs;	/* insns of the stubs, which come before the first pad */
 };
 
 /* Make room in @pads for @n more insns. The buffer is kept from one subprog to the next. */
@@ -817,7 +820,7 @@ static int reserve_pad_insns(struct pad_buf *pads, int n)
  */
 static int add_pad(struct pad_buf *pads, const struct bpf_insn *new, int n, bool share)
 {
-	int k, start = 0;
+	int k, start = pads->stubs;
 	void *mem;
 	u64 key = 0;
 
@@ -856,57 +859,354 @@ static int add_pad(struct pad_buf *pads, const struct bpf_insn *new, int n, bool
 }
 
 /*
- * The landing pads of the sites of subprog @s go after its last insn. Sites whose pads have the
- * same insns share one. @new and @new_aux have room for a pad. Returns the pads in @pads, which
- * has the memory of the subprog before, and the number of their insns.
+ * A unit is the code that one kind of site at one insn leads to. A site can have two records of
+ * what the frame holds: 'plan' for a frame that is not cancelled when it gets there, 'cancelled'
+ * for a frame that is, in a cleanup pad (BPF_SITE_CANCELLED). With one record the unit is its
+ * landing pad. With both, the "cancelled" word of the frame selects the pad, unless the pads have
+ * the same insns:
+ *
+ *	ax = cancelled
+ *	if ax == 0 goto 1f
+ *	the pad of 'cancelled'
+ * 1:	the pad of 'plan'
+ */
+struct pad_unit {
+	struct bpf_pad_plan *plan;
+	struct bpf_pad_plan *cancelled;
+};
+
+/* The most insns that a unit has */
+#define PAD_UNIT_MAX_INSNS	(2 * (BPF_PAD_MAX_INSNS + 4) + 3)
+
+/*
+ * Do the two records of @unit give the same landing pad? Both pads are emitted into @buf to
+ * compare them, and their aux data goes to @scratch. A pad that frees an object of the program
+ * is never the same as another: the type of the object is not in the insns.
+ */
+static bool unit_pads_are_same(struct bpf_verifier_env *env, int s, const struct pad_unit *unit,
+			       struct bpf_insn *buf, struct bpf_insn_aux_data *scratch)
+{
+	int len, other;
+
+	if (!bpf_pad_can_be_shared(unit->plan) || !bpf_pad_can_be_shared(unit->cancelled))
+		return false;
+	len = emit_pad(env, s, unit->cancelled, buf, scratch);
+	other = emit_pad(env, s, unit->plan, buf + len, scratch + len);
+	return other == len && !memcmp(buf, buf + len, len * sizeof(*buf));
+}
+
+/* Does the insn at @i have a unit for sites of @base? If so, it is in @unit. */
+static bool site_unit(struct bpf_verifier_env *env, int i, enum bpf_site_kind base,
+		      struct pad_unit *unit)
+{
+	const struct bpf_insn_aux_data *aux = &env->insn_aux_data[i];
+
+	unit->cancelled = NULL;
+	unit->plan = bpf_pad_plan(aux, base);
+	if (unit->plan && !plan_has_pad(env, i, unit->plan))
+		unit->plan = NULL;
+	if (base >= BPF_SITE_CANCEL_ENTRY)
+		return unit->plan;
+	unit->cancelled = bpf_pad_plan(aux, base | BPF_SITE_CANCELLED);
+	if (unit->cancelled && !plan_has_pad(env, i, unit->cancelled))
+		unit->cancelled = NULL;
+	return unit->plan || unit->cancelled;
+}
+
+/*
+ * Emit @unit, the code for a site of kind @base in subprog @s: landing pads, see struct pad_unit,
+ * except for two kinds.
+ *
+ * BPF_SITE_CANCEL_ENTRY is the entry of a cleanup pad, where the cancel_goto of the call leads:
+ *
+ *	bpf_pad_cancel_entry_insns()	cancelled = 1, r0 = 0
+ *	gotol pad			bpf_insert_sites() sets the offset
+ *
+ * BPF_SITE_REMAINDER is where an unwind_exit that a cancelled frame can reach jumps instead:
+ *
+ *	ax = cancelled
+ *	if ax == 0 goto 1f
+ *	the pad of the record		releases what the frame still holds, cancel_exit
+ * 1:	unwind_exit			the program's own unwinding leaves as before
+ *
+ * @aux gets the aux data of the insns, @scratch is for unit_pads_are_same(). Returns the number
+ * of insns, at most PAD_UNIT_MAX_INSNS.
+ */
+static int emit_unit(struct bpf_verifier_env *env, int s, enum bpf_site_kind base,
+		     const struct pad_unit *unit, struct bpf_insn *buf,
+		     struct bpf_insn_aux_data *aux, struct bpf_insn_aux_data *scratch)
+{
+	int cancelled_off = env->subprog_info[s].cancelled_off;
+	int n = 0, len;
+
+	if (base == BPF_SITE_CANCEL_ENTRY) {
+		n += bpf_pad_cancel_entry_insns(env, unit->plan, s, buf + n);
+		buf[n++] = BPF_JMP32_A(0);
+		return n;
+	}
+	if (base != BPF_SITE_REMAINDER &&
+	    (!(unit->plan && unit->cancelled) || unit_pads_are_same(env, s, unit, buf, scratch)))
+		return emit_pad(env, s, unit->plan ?: unit->cancelled, buf, aux);
+	buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_FP, cancelled_off);
+	buf[n++] = BPF_JMP_IMM(BPF_JEQ, BPF_REG_AX, 0, 0);
+	len = emit_pad(env, s, unit->cancelled ?: unit->plan, buf + n, aux + n);
+	buf[n - 1].off = len;
+	n += len;
+	if (base == BPF_SITE_REMAINDER) {
+		buf[n++] = BPF_RAW_INSN(BPF_JMP | BPF_EXIT, 0, BPF_UNWIND_EXIT, 0, 0);
+		return n;
+	}
+	return n + emit_pad(env, s, unit->plan, buf + n, aux + n);
+}
+
+/* Copy what the insns of a pad need in their aux data: a map, the type of an object to free */
+static void copy_pad_aux(struct bpf_insn_aux_data *to, const struct bpf_insn_aux_data *from)
+{
+	to->map_index = from->map_index;
+	to->map_off = from->map_off;
+	to->kptr_struct_meta = from->kptr_struct_meta;
+}
+
+/* Can @unit share its insns with an equal unit? Not an entry: it jumps to its own cleanup pad. */
+static bool unit_can_be_shared(enum bpf_site_kind base, const struct pad_unit *unit)
+{
+	return base != BPF_SITE_CANCEL_ENTRY &&
+	       (!unit->plan || bpf_pad_can_be_shared(unit->plan)) &&
+	       (!unit->cancelled || bpf_pad_can_be_shared(unit->cancelled));
+}
+
+/*
+ * Emit the stubs of subprog @s as the first insns of @pads. A stub clears the "cancelled" word
+ * where the program's own unwinding takes a frame into a landing pad of the program, so that pad
+ * code does not take the frame for a cancelled one:
+ *
+ *		call foo
+ *		unwind_goto stub	the program has: unwind_goto pad
+ *		...
+ *	stub:	cancelled = 0
+ *		gotol pad		fill_stub() sets the offset
+ *
+ * A function that has the word and is not mixed gets one stub for each landing pad that is not
+ * dead code. That includes a pad that is no cleanup pad: a typed catch that does not match joins
+ * pad code. An unwind_goto after a call in pad code keeps its target. A cancelled frame can make
+ * that call, and with its word cleared it would leave with unwind_exit, which a caller can catch.
+ *
+ * 'clear_stub' of each unwind_goto keeps the decision. Returns how many of them got a stub.
+ */
+static int collect_stubs(struct bpf_verifier_env *env, int s, struct pad_buf *pads)
+{
+	const struct bpf_subprog_info *sub = &env->subprog_info[s];
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	int i, to, users = 0, len = sub[1].start - sub->start;
+	const struct bpf_insn *insn;
+	/* per insn of the subprog: 1 + the start of the stub that jumps to the insn, or 0 */
+	u32 *stub_of;
+
+	if (!sub->cancelled_off || sub->cleanup_pads_mixed)
+		return 0;
+	stub_of = kvcalloc(len, sizeof(*stub_of), BPF_VERIFIER_GFP);
+	if (!stub_of)
+		return -ENOMEM;
+	for (i = sub->start + 1; i < sub[1].start; i++) {
+		insn = &env->prog->insnsi[i];
+		if (!bpf_is_unwind_goto(insn))
+			continue;
+		to = i + 1 + bpf_jmp_offset(insn);
+		if (!aux[to].seen)
+			continue;
+		if (aux[i - 1].cleanup_pad_code) {
+			aux[i].clear_stub = BPF_CLEAR_STUB_NONE;
+			continue;
+		}
+		/* a stub must not be where the main pass saw a cancelled frame take the jump */
+		if (verifier_bug_if(aux[i].cancelled_takes, env,
+				    "unwind_goto at insn %d of func#%d gets a stub in pad code",
+				    i, s)) {
+			users = -EFAULT;
+			break;
+		}
+		if (!stub_of[to - sub->start]) {
+			if (reserve_pad_insns(pads, 2)) {
+				users = -ENOMEM;
+				break;
+			}
+			pads->insns[pads->cnt++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP,
+							      sub->cancelled_off, 0);
+			pads->insns[pads->cnt++] = BPF_JMP32_A(0);
+			stub_of[to - sub->start] = pads->cnt - 1;
+		}
+		aux[i].clear_stub = stub_of[to - sub->start];
+		users++;
+	}
+	kvfree(stub_of);
+	pads->stubs = pads->cnt;
+	return users;
+}
+
+/*
+ * The stubs of subprog @s are in the program, from insn @pads on. Make the stub of the program's
+ * unwind_goto at insn @i jump to the target of that insn. insert_unwind_gotos() then makes the
+ * insn jump to the stub.
+ */
+static int fill_stub(struct bpf_verifier_env *env, int s, int i, int pads)
+{
+	const struct bpf_subprog_info *sub = &env->subprog_info[s];
+	struct bpf_insn clear = BPF_ST_MEM(BPF_DW, BPF_REG_FP, sub->cancelled_off, 0);
+	u32 clear_stub = env->insn_aux_data[i].clear_stub;
+	struct bpf_insn *stub;
+	int at, off;
+
+	if (!clear_stub || clear_stub == BPF_CLEAR_STUB_NONE)
+		return 0;
+	at = pads + clear_stub - 1;
+	if (verifier_bug_if(!sub->cancelled_off || sub->cleanup_pads_mixed || at + 2 > sub[1].start ||
+			    !bpf_is_unwind_goto(&env->prog->insnsi[i]), env,
+			    "insn %d of func#%d has a stub", i, s))
+		return -EFAULT;
+	stub = &env->prog->insnsi[at];
+	off = i + 1 + bpf_jmp_offset(&env->prog->insnsi[i]) - (at + 2);
+	/* a stub is the store and a jump that has no offset yet, or the offset of this target */
+	if (verifier_bug_if(memcmp(stub, &clear, sizeof(clear)) ||
+			    stub[1].code != (BPF_JMP32 | BPF_JA) ||
+			    (stub[1].imm && stub[1].imm != off), env,
+			    "the stub of insn %d is not at insn %d", i, at))
+		return -EFAULT;
+	stub[1].imm = off;
+	return 0;
+}
+
+/*
+ * Collect in @pads what goes after the last insn of subprog @s: its stubs, then one unit per site,
+ * see struct pad_unit. Units with the same insns are shared. 'pad' of each record gets the start
+ * of its unit, and @stubbed the number of unwind_gotos that have a stub. @new and @new_aux are
+ * scratch for one unit. Returns the number of insns.
  */
 static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *new,
-			struct bpf_insn_aux_data *new_aux, struct pad_buf *pads)
+			struct bpf_insn_aux_data *new_aux, struct pad_buf *pads, int *stubbed)
 {
-	int last = env->subprog_info[s + 1].start - 1, i, n, pad;
+	const struct bpf_subprog_info *sub = &env->subprog_info[s];
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
 	struct bpf_pad_plan *plan, *shared = NULL;
-
-	pads->nr = pads->cnt = 0;
-	for (i = env->subprog_info[s].start; i <= last; i++) {
+	int i, n, pad, base, last = sub[1].start - 1;
+	struct pad_unit unit;
+	bool unwinds, cancelled;
+
+	pads->nr = pads->cnt = pads->stubs = 0;
+	n = collect_stubs(env, s, pads);
+	if (n < 0)
+		return n;
+	*stubbed = n;
+	for (i = sub->start; i <= last; i++) {
+		if (aux[i].pad_plans && bpf_must_abort())
+			return -EINTR;
 		if (aux[i].loop_guard && !unvisited_plan(env, i, BPF_SITE_GUARD))
 			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().
+		 * The accesses to arena at which nothing is held get no unwind_goto. A bit in their
+		 * exception table entries sends a fault to the pad of the first of them, see
+		 * bpf_arena_fault(). An access that a cancelled frame can reach too gets an
+		 * unwind_goto: it needs a unit of two pads.
 		 */
-		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)
+		plan = bpf_pad_plan(&aux[i], BPF_SITE_FAULT | BPF_SITE_CANCELLED);
+		cancelled = plan && bpf_site_is_used(env, i, plan);
+		unwinds = aux[i].fault_empty && !aux[i].fault_skips;
+		aux[i].fault_unwinds = unwinds && !cancelled;
+		if (unwinds && (cancelled || !shared)) {
+			plan = unvisited_plan(env, i, BPF_SITE_FAULT);
+			if (!plan)
 				return -ENOMEM;
+			shared = cancelled ? shared : plan;
 		}
-		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
-			if (!plan_has_pad(env, i, plan))
+		for (base = 0; aux[i].pad_plans && base <= BPF_SITE_REMAINDER; base++) {
+			if (!site_unit(env, i, base, &unit))
 				continue;
 			/* bpf_pads_settle() settled every site that the program keeps */
-			if (verifier_bug_if(!plan->used || plan->conflict, env,
-					    "the landing pad of insn %d was not settled", i))
+			if (verifier_bug_if((unit.plan && (!unit.plan->used || unit.plan->conflict)) ||
+					    (unit.cancelled &&
+					     (!unit.cancelled->used || unit.cancelled->conflict)),
+					    env, "the landing pad of insn %d was not settled", i))
 				return -EFAULT;
-			n = emit_pad(env, s, plan, new, new_aux);
-			pad = add_pad(pads, new, n, bpf_pad_can_be_shared(plan));
+			/* these units read or write the "cancelled" word */
+			if (verifier_bug_if((unit.cancelled || base >= BPF_SITE_CANCEL_ENTRY) &&
+					    !sub->cancelled_off,
+					    env, "func#%d has no hidden word for insn %d", s, i))
+				return -EFAULT;
+			/*
+			 * An entry tests the "cancelled" word only if its call is in pad code or
+			 * the function is mixed. Decide it while 'cleanup_pad_code' matches the
+			 * insns, for both emissions of the entry.
+			 */
+			if (base == BPF_SITE_CANCEL_ENTRY)
+				unit.plan->untested = !sub->cleanup_pads_mixed &&
+						      !aux[i].cleanup_pad_code;
+			/*
+			 * The main pass saw a cancelled frame reach this entry. Without the test
+			 * the entry would overwrite what the first entry of the frame saved.
+			 */
+			if (verifier_bug_if(base == BPF_SITE_CANCEL_ENTRY && unit.plan->untested &&
+					    unit.plan->cancelled_visit, env,
+					    "the entry behind insn %d of func#%d does not test K",
+					    i, s))
+				return -EFAULT;
+			/*
+			 * A pad for cancelled frames and a remainder rely on the "cancelled"
+			 * word. They have to be in pad code, where a stub or an entry has written
+			 * the word, unless the function clears it at its first insn.
+			 */
+			if (verifier_bug_if(!bpf_subprog_clears_cancelled(sub) &&
+					    !aux[i].cleanup_pad_code &&
+					    (unit.cancelled || base == BPF_SITE_REMAINDER),
+					    env, "insn %d of func#%d reads K outside of pad code",
+					    i, s))
+				return -EFAULT;
+			n = emit_unit(env, s, base, &unit, new, new_aux, new_aux);
+			pad = add_pad(pads, new, n, unit_can_be_shared(base, &unit));
 			if (pad < 0)
 				return pad;
-			plan->pad = pad;
+			if (unit.plan)
+				unit.plan->pad = pad;
+			if (unit.cancelled)
+				unit.cancelled->pad = pad;
 		}
 	}
 	return pads->cnt;
 }
 
-/* The plan of the site of @kind at insn @i if it has unwind_goto or cancel_goto after it */
-static const struct bpf_pad_plan *goto_plan(struct bpf_verifier_env *env, int i,
-					    enum bpf_site_kind kind)
+/*
+ * Where the unit of the site of kind @base at insn @i starts, counted from the first insn that is
+ * appended to the subprog. -1 if there is none, or if an access to arena uses the shared pad.
+ */
+static int unit_pad(struct bpf_verifier_env *env, int i, enum bpf_site_kind base)
 {
-	const struct bpf_insn_aux_data *aux = &env->insn_aux_data[i];
-	const struct bpf_pad_plan *plan = bpf_pad_plan(aux, kind);
+	struct pad_unit unit;
 
-	return plan && bpf_site_is_used(env, i, plan) && !aux->fault_unwinds ? plan : NULL;
+	if (!site_unit(env, i, base, &unit) ||
+	    (base == BPF_SITE_FAULT && env->insn_aux_data[i].fault_unwinds))
+		return -1;
+	return (unit.plan ?: unit.cancelled)->pad;
+}
+
+/*
+ * Set @stub to where the stub of the program's unwind_goto at insn @i of subprog @s starts,
+ * counted like unit_pad(), or to -1 if the insn keeps its target. It is a verifier bug if
+ * collect_stubs() decided nothing for an insn whose target is not dead code, in a function that
+ * gets stubs: a frame would enter pad code with a stale "cancelled" word.
+ */
+static int goto_stub(struct bpf_verifier_env *env, int s, int i, int *stub)
+{
+	const struct bpf_subprog_info *sub = &env->subprog_info[s];
+	const struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	bool wanted = sub->cancelled_off && !sub->cleanup_pads_mixed;
+	u32 clear_stub = aux[i].clear_stub;
+	bool seen;
+
+	seen = aux[i + 1 + bpf_jmp_offset(&env->prog->insnsi[i])].seen;
+	if (verifier_bug_if(wanted ? seen && !clear_stub : clear_stub, env,
+			    "unwind_goto at insn %d of func#%d has %s stub", i, s,
+			    clear_stub ? "a" : "no"))
+		return -EFAULT;
+	*stub = clear_stub && clear_stub != BPF_CLEAR_STUB_NONE ? clear_stub - 1 : -1;
+	return 0;
 }
 
 /*
@@ -920,54 +1220,62 @@ static const struct bpf_pad_plan *goto_plan(struct bpf_verifier_env *env, int i,
  *	cancel_goto cancel_pad	unwind_goto pad		unwind_goto P	of the program
  *				cancel_goto cancel_pad	cancel_goto cancel_pad
  *
- * unwind_goto of the program takes the form that has 32 bits there: a jump that is taken around
- * its target would put two insns between it and cancel_goto. Where no state got to that unwind_goto
- * it is dead code, and a trap is going to stand in its place, or nothing at all: cancel_goto goes
- * in front of it, behind the call.
+ * At a call with a cleanup pad, cancel_goto leads to the entry of that pad, and P leads to its
+ * stub if it has one. If no state reached P, it is dead code and cancel_goto goes before it.
+ *
+ * Both insns are exception table entries of the insn before them. They are appended to that insn,
+ * so nothing gets between them and a jump to the next insn skips them. Both have a 32 bit offset,
+ * also P here: with 16 bits the patch list puts jumps after an insn whose target is too far.
  */
-static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added)
+static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added, const int *stubbed)
 {
 	struct bpf_insn unwind_goto = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0, 0);
 	struct bpf_insn cancel_goto = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_CANCEL_GOTO, 0, 0);
 	struct bpf_patch_list *pl = &env->patch_list;
-	const struct bpf_pad_plan *plan, *cancel_plan;
+	int i, s, pads, err, pad, cancel_pad, stub, stubs;
 	const struct bpf_subprog_info *sub;
 	const struct bpf_insn_patch *p;
 	struct bpf_insn *insn;
-	int i, s, pads, err;
+	bool seen;
 
 	for (s = 0; s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
 		pads = sub[1].start - added[s];
+		stubs = 0;
 		for (i = sub->start; added[s] && i < pads; i++) {
-			plan = goto_plan(env, i, BPF_SITE_CALL) ?: goto_plan(env, i, BPF_SITE_FAULT);
-			cancel_plan = goto_plan(env, i, BPF_SITE_CANCEL_CALL);
-			if (!plan && !cancel_plan)
+			/* so far every unwind_goto before the pads is the program's own */
+			insn = &env->prog->insnsi[i + 1];
+			stub = -1;
+			err = bpf_is_unwind_goto(insn) ? goto_stub(env, s, i + 1, &stub) : 0;
+			if (err)
+				return err;
+			pad = cancel_pad = -1;
+			if (env->insn_aux_data[i].pad_plans) {
+				pad = unit_pad(env, i, BPF_SITE_CALL);
+				if (pad < 0)
+					pad = unit_pad(env, i, BPF_SITE_FAULT);
+				cancel_pad = unit_pad(env, i, BPF_SITE_CANCEL_ENTRY);
+				/* cancel_goto leads to an entry or to a generated pad */
+				if (verifier_bug_if(cancel_pad >= 0 &&
+						    unit_pad(env, i, BPF_SITE_CANCEL_CALL) >= 0, env,
+						    "cancel_goto of insn %d has two pads", i))
+					return -EFAULT;
+				if (cancel_pad < 0)
+					cancel_pad = unit_pad(env, i, BPF_SITE_CANCEL_CALL);
+			}
+			if (pad < 0 && cancel_pad < 0 && stub < 0)
 				continue;
 			if (bpf_must_abort())
 				return -EINTR;
-			insn = &env->prog->insnsi[i + 1];
-			if (cancel_plan && bpf_is_unwind_goto(insn) &&
-			    env->insn_aux_data[i + 1].seen) {
-				/* the program has unwind_goto there: no plan for unwind_exit */
-				unwind_goto.imm = 0;
-				insn = __bpf_patch_list_add(pl, env->prog, i + 1, &unwind_goto, 1);
-				if (IS_ERR(insn))
-					return PTR_ERR(insn);
-				bpf_patch_list_jump(pl, insn,
-						    i + 2 + bpf_jmp_offset(&env->prog->insnsi[i + 1]),
-						    0);
-				err = bpf_patch_list_append(env, i + 1, &cancel_goto, 1);
-				if (err)
-					return err;
-				p = &pl->patches[pl->cnt - 1];
-				bpf_patch_list_jump(pl, &pl->insns[p->start + p->len - 1],
-						    pads + cancel_plan->pad, 0);
-				env->insn_aux_data[i].cancel_goto_follows = true;
-				continue;
-			}
+			/*
+			 * Is the program's unwind_goto live code? A state reaches the insn when the
+			 * callee returns, not only when the callee leaves with unwind_exit or a
+			 * cancellation enters the cleanup pad. cancel_goto goes after a live
+			 * unwind_goto, and right after the call otherwise.
+			 */
+			seen = bpf_is_unwind_goto(insn) && env->insn_aux_data[i + 1].seen;
 			/* what is appended to the site is not dead code, the next insn may be */
-			if (plan) {
+			if (pad >= 0) {
 				err = bpf_patch_list_append(env, i, &unwind_goto, 1);
 				if (err)
 					return err;
@@ -975,18 +1283,41 @@ static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added)
 				env->insn_aux_data[i].unwind_goto_follows = true;
 				p = &pl->patches[pl->cnt - 1];
 				bpf_patch_list_jump(pl, &pl->insns[p->start + p->len - 1],
-						    pads + plan->pad, 0);
+						    pads + pad, 0);
 			}
-			if (cancel_plan) {
+			if (cancel_pad >= 0 && !seen) {
 				err = bpf_patch_list_append(env, i, &cancel_goto, 1);
 				if (err)
 					return err;
 				env->insn_aux_data[i].cancel_goto_follows = true;
 				p = &pl->patches[pl->cnt - 1];
 				bpf_patch_list_jump(pl, &pl->insns[p->start + p->len - 1],
-						    pads + cancel_plan->pad, 0);
+						    pads + cancel_pad, 0);
 			}
+			if (stub < 0 && !(cancel_pad >= 0 && seen))
+				continue;
+			/* the program's unwind_goto in its 32 bit form, to its stub or target */
+			unwind_goto.imm = 0;
+			insn = __bpf_patch_list_add(pl, env->prog, i + 1, &unwind_goto, 1);
+			if (IS_ERR(insn))
+				return PTR_ERR(insn);
+			bpf_patch_list_jump(pl, insn, stub >= 0 ? pads + stub :
+					    i + 2 + bpf_jmp_offset(&env->prog->insnsi[i + 1]), 0);
+			stubs += stub >= 0;
+			if (cancel_pad < 0 || !seen)
+				continue;
+			err = bpf_patch_list_append(env, i + 1, &cancel_goto, 1);
+			if (err)
+				return err;
+			p = &pl->patches[pl->cnt - 1];
+			bpf_patch_list_jump(pl, &pl->insns[p->start + p->len - 1],
+					    pads + cancel_pad, 0);
+			env->insn_aux_data[i].cancel_goto_follows = true;
 		}
+		if (verifier_bug_if(stubs != stubbed[s], env,
+				    "%d unwind_goto of func#%d go to a stub, %d have one",
+				    stubs, s, stubbed[s]))
+			return -EFAULT;
 	}
 	return bpf_patch_list_commit(env);
 }
@@ -1001,15 +1332,16 @@ static int retarget_may_gotos(struct bpf_verifier_env *env, const int *added)
 {
 	struct bpf_patch_list *pl = &env->patch_list;
 	const struct bpf_subprog_info *sub;
-	const struct bpf_pad_plan *plan;
 	struct bpf_insn *insn;
-	int i, s;
+	int i, s, pad;
 
 	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++) {
-			plan = bpf_pad_plan(&env->insn_aux_data[i], BPF_SITE_MAY_GOTO);
-			if (!plan || !bpf_site_is_used(env, i, plan))
+			if (!env->insn_aux_data[i].pad_plans)
+				continue;
+			pad = unit_pad(env, i, BPF_SITE_MAY_GOTO);
+			if (pad < 0)
 				continue;
 			if (bpf_must_abort())
 				return -EINTR;
@@ -1017,7 +1349,7 @@ static int retarget_may_gotos(struct bpf_verifier_env *env, const int *added)
 			insn = __bpf_patch_list_add(pl, env->prog, i, &env->prog->insnsi[i], 1);
 			if (IS_ERR(insn))
 				return PTR_ERR(insn);
-			bpf_patch_list_jump(pl, insn, sub[1].start - added[s] + plan->pad, 0);
+			bpf_patch_list_jump(pl, insn, sub[1].start - added[s] + pad, 0);
 		}
 	}
 	return bpf_patch_list_commit(env);
@@ -1049,9 +1381,10 @@ static int insert_slot_stores(struct bpf_verifier_env *env, struct bpf_insn *buf
 
 	for (s = 0; s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
-		if (!sub->slots || !added[s])
+		/* a mixed function clears its "cancelled" word at the entry too */
+		if ((!sub->slots && !bpf_subprog_clears_cancelled(sub)) || !added[s])
 			continue;
-		nr = bpf_pad_slot_notes(env, s, notes);
+		nr = sub->slots ? bpf_pad_slot_notes(env, s, notes) : 0;
 		if (nr < 0)
 			return nr;
 		entry = sub->start + is_arena_sp_adj(&env->prog->insnsi[sub->start]);
@@ -1060,7 +1393,7 @@ static int insert_slot_stores(struct bpf_verifier_env *env, struct bpf_insn *buf
 			/* the patches are queued in the order of the insns */
 			n = 0;
 			if (i == entry && i > sub->start)
-				n = bpf_pad_entry_insns(notes, nr, buf);
+				n = bpf_pad_entry_insns(sub, notes, nr, 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))
@@ -1073,7 +1406,8 @@ static int insert_slot_stores(struct bpf_verifier_env *env, struct bpf_insn *buf
 			last = n ? bpf_patch_list_add(env, i, buf, n + 1) : NULL;
 			if (IS_ERR(last))
 				return PTR_ERR(last);
-			n = i == entry && i == sub->start ? bpf_pad_entry_insns(notes, nr, buf) : 0;
+			n = i == entry && i == sub->start ?
+			    bpf_pad_entry_insns(sub, notes, nr, buf) : 0;
 			err = n ? bpf_patch_list_insert(env, i, buf, n) : 0;
 			if (err)
 				return err;
@@ -1104,21 +1438,24 @@ static int insert_slot_stores(struct bpf_verifier_env *env, struct bpf_insn *buf
  */
 int bpf_insert_sites(struct bpf_verifier_env *env)
 {
+	struct bpf_insn unwind_goto = BPF_RAW_INSN(BPF_JMP32 | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0, 0);
 	struct bpf_insn patch[2] = { BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, 0, 0, 0) };
-	struct bpf_insn_aux_data *aux = env->insn_aux_data, *pad_aux;
+	struct bpf_insn_aux_data *aux = env->insn_aux_data, *pad_aux, *unit_aux;
 	struct bpf_insn *new, *insn;
-	const struct bpf_pad_plan *plan;
 	struct pad_buf pads = {};
 	struct bpf_subprog_info *sub;
-	int i, s, cnt, err = 0;
-	int *added;
+	int i, k, s, n, cnt, base, err = 0;
+	struct pad_unit unit;
+	int *added, *stubbed;
 
-	/* how many insns the pads after the subprog have */
+	/* per subprog: the insns appended to it, and how many of its unwind_gotos have a stub */
 	added = kvzalloc_objs(int, env->subprog_cnt, BPF_VERIFIER_GFP);
-	new = kvzalloc_objs(*new, max(BPF_PAD_MAX_INSNS + 2, BPF_PAD_MAX_SLOT_INSNS),
+	stubbed = kvzalloc_objs(int, env->subprog_cnt, BPF_VERIFIER_GFP);
+	new = kvzalloc_objs(*new, max(PAD_UNIT_MAX_INSNS, BPF_PAD_MAX_SLOT_INSNS + 1),
 			    BPF_VERIFIER_GFP);
-	pad_aux = kvzalloc_objs(*pad_aux, BPF_PAD_MAX_INSNS + 2, BPF_VERIFIER_GFP);
-	if (!added || !new || !pad_aux) {
+	pad_aux = kvzalloc_objs(*pad_aux, PAD_UNIT_MAX_INSNS, BPF_VERIFIER_GFP);
+	unit_aux = kvzalloc_objs(*unit_aux, PAD_UNIT_MAX_INSNS, BPF_VERIFIER_GFP);
+	if (!added || !stubbed || !new || !pad_aux || !unit_aux) {
 		err = -ENOMEM;
 		goto out;
 	}
@@ -1129,7 +1466,7 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 				     env->subprog_info[0].can_cancel;
 	for (s = 0; s < env->subprog_cnt && !err; s++) {
 		sub = &env->subprog_info[s];
-		cnt = collect_pads(env, s, new, pad_aux, &pads);
+		cnt = collect_pads(env, s, new, pad_aux, &pads, &stubbed[s]);
 		if (cnt < 0) {
 			err = cnt;
 			break;
@@ -1142,19 +1479,33 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 		}
 		added[s] = cnt;
 		for (i = sub->start; i < sub[1].start; i++) {
-			if (!aux[i].loop_guard)
+			if (aux[i].loop_guard) {
+				/* A jump to itself is a back edge. It goes through may_goto too. */
+				patch[1] = env->prog->insnsi[i];
+				insn = bpf_patch_list_add(env, i, patch, 2);
+				if (IS_ERR(insn)) {
+					err = PTR_ERR(insn);
+					goto out;
+				}
+				/* however far the pad is, see bpf_patch_list_jump() */
+				bpf_patch_list_jump(&env->patch_list, insn - 1, sub[1].start,
+						    cnt - unit_pad(env, i, BPF_SITE_GUARD));
+			}
+			if (!aux[i].clear_stub || aux[i].clear_stub == BPF_CLEAR_STUB_NONE)
 				continue;
-			/* A jump to itself is a back edge. It goes through may_goto too. */
-			patch[1] = env->prog->insnsi[i];
-			insn = bpf_patch_list_add(env, i, patch, 2);
+			/*
+			 * The program's unwind_goto gets its 32 bit form before the pads go in.
+			 * fill_stub() then reads its target, which has to be the landing pad. With
+			 * 16 bits the patch list can make the insn jump to a gotol of its own.
+			 */
+			insn = __bpf_patch_list_add(&env->patch_list, env->prog, i, &unwind_goto,
+						    1);
 			if (IS_ERR(insn)) {
 				err = PTR_ERR(insn);
 				goto out;
 			}
-			/* however far the pad is, see bpf_patch_list_jump() */
-			plan = bpf_pad_plan(&aux[i], BPF_SITE_GUARD);
-			bpf_patch_list_jump(&env->patch_list, insn - 1, sub[1].start,
-					    cnt - plan->pad);
+			bpf_patch_list_jump(&env->patch_list, insn,
+					    i + 1 + bpf_jmp_offset(&env->prog->insnsi[i]), 0);
 		}
 		if (cnt)
 			err = bpf_patch_list_append(env, i - 1, pads.insns, cnt);
@@ -1167,17 +1518,41 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 	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))
+			err = aux[i].pad_plans && bpf_must_abort() ? -EINTR :
+			      fill_stub(env, s, i, sub[1].start - added[s]);
+			if (err)
+				goto out;
+			for (base = 0; aux[i].pad_plans && base <= BPF_SITE_REMAINDER; base++) {
+				if (!site_unit(env, i, base, &unit))
 					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)
+				cnt = sub[1].start - added[s] + (unit.plan ?: unit.cancelled)->pad;
+				n = emit_unit(env, s, base, &unit, new, unit_aux, pad_aux);
+				/*
+				 * Emit the unit a second time, for its aux data. It has to give the
+				 * insns that are in the program. The aux data is copied after that
+				 * check: a unit that differs could be longer than the one there.
+				 */
+				if (verifier_bug_if(cnt + n > sub[1].start ||
+						    memcmp(new, &env->prog->insnsi[cnt],
+							   n * sizeof(*new)), env,
+						    "the pad of insn %d is not the one at insn %d",
+						    i, cnt)) {
+					err = -EFAULT;
+					goto out;
+				}
+				for (k = 0; k < n; k++)
+					copy_pad_aux(&aux[cnt + k], &unit_aux[k]);
+				memset(unit_aux, 0, n * sizeof(*unit_aux));
+				insn = &env->prog->insnsi[i];
+				if (base == BPF_SITE_FAULT && aux[i].fault_unwinds)
 					sub->fault_pad = cnt;
-				/* no call is made, see check_kfunc_call() */
-				if (bpf_site_base(plan->kind) == BPF_SITE_THROW)
-					env->prog->insnsi[i] = BPF_RAW_INSN(BPF_JMP32 | BPF_JA, 0, 0, 0,
-									    cnt - i - 1);
+				/* bpf_throw() is not called. The remainder replaces unwind_exit. */
+				if (base == BPF_SITE_THROW || base == BPF_SITE_REMAINDER)
+					*insn = BPF_JMP32_A(cnt - i - 1);
+				/* the entry jumps to the target of the program's unwind_goto */
+				if (base == BPF_SITE_CANCEL_ENTRY)
+					env->prog->insnsi[cnt + n - 1].imm =
+						i + 2 + bpf_jmp_offset(insn + 1) - (cnt + n);
 			}
 		}
 		/* a pad calls no subprog but the exception callback, see emit_pad() */
@@ -1187,12 +1562,14 @@ int bpf_insert_sites(struct bpf_verifier_env *env)
 					    i - 1;
 	}
 	err = insert_slot_stores(env, new, added);
-	err = err ?: insert_unwind_gotos(env, added);
+	err = err ?: insert_unwind_gotos(env, added, stubbed);
 	err = err ?: retarget_may_gotos(env, added);
 out:
 	kvfree(added);
+	kvfree(stubbed);
 	kvfree(new);
 	kvfree(pad_aux);
+	kvfree(unit_aux);
 	kvfree(pads.insns);
 	kvfree(pads.ends);
 	kvfree(pads.index.slots);
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index 7907f59068be..e888589d4cc5 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -112,15 +112,38 @@
  *
  * A landing pad of the program is a CLEANUP PAD if it can only clean up and continue unwinding,
  * like a C++ destructor or Rust drop glue, see bpf_find_cleanup_pads(). A cancellation runs the
- * cleanup pads of the frames that it leaves.
+ * cleanup pads of the frames that it leaves. The frame remembers in a hidden word, the "cancelled"
+ * word, whether the kernel cancels it or the program unwinds it:
+ *
+ *	what the program has	    what the verifier makes of it
+ *	  call foo		      call foo
+ *	  unwind_goto pad	      unwind_goto stub
+ *	  ...			      cancel_goto entry
+ *	  pad: call dtor	      ...
+ *	       unwind_exit	      pad:   call dtor
+ *					     gotol rest
+ *				      stub:  cancelled = 0	<- foo left with unwind_exit
+ *					     gotol pad
+ *				      entry: cancelled = 1	<- foo was cancelled
+ *					     r0 = 0
+ *					     gotol pad
+ *				      rest:  if cancelled == 0 goto +N
+ *					     release what the frame still holds
+ *					     cancel_exit
+ *					     unwind_exit
  *
  * In the main pass, enter_cleanup_pad() in verifier.c marks the frame as cancelled and verifies the
  * cleanup pad a second time for it, with 0 in R0. A cancelled frame never returns to its caller. It
- * leaves at the unwind_exit of the pad, which is a site for it (BPF_SITE_REMAINDER), or at
+ * leaves at the unwind_exit of the pad, through the remainder at 'rest' (BPF_SITE_REMAINDER), or at
  * a site inside the pad, where its states have a record and a pad of their own
  * (BPF_SITE_CANCELLED). A cleanup pad that a cancellation can reach is entered, or the program is
  * rejected.
  *
+ * Only the stub and the entry write the "cancelled" word, and only pad code reads it, see
+ * find_pad_code(). A call in pad code can be made by a frame that is cancelled already, so its
+ * unwind_goto gets no stub, and its entry tests the word before it stores. A mixed function, in
+ * which an insn is pad code and on the normal path as well, clears the word at its first insn.
+ *
  * A frame can be in fewer sections than it was called in. Its pad enters the sections that the
  * frame left, so that the caller is in the sections of its call wherever the callee is cancelled.
  * Here grow() is called with preemption disabled, and its load from arena can fault. The fault
@@ -1505,6 +1528,8 @@ struct bpf_pad_plan *bpf_pad_enter(struct bpf_verifier_env *env,
 	if (!plan)
 		return ERR_PTR(-ENOMEM);
 	plan->visited = true;
+	/* the frame is cancelled already, so the entry has to test: collect_pads() checks */
+	plan->cancelled_visit |= bpf_frame_is_cancelled(frame);
 	if (plan->conflict)
 		return plan;
 	if (env->has_throw && frame->regs[BPF_REG_0].type != SCALAR_VALUE)
@@ -3121,11 +3146,15 @@ int bpf_pad_slot_notes(struct bpf_verifier_env *env, int s, const struct bpf_pad
 }
 
 /*
- * The entry of a function: all words of its hidden slots are 0. The frame holds nothing of its own,
- * and a pad reads all slots, also at a site that is before the calls that fill them. But for the
- * slot of a reference that the call hands over: it takes the argument register.
+ * Emit the stores at the start of a function. All words of its hidden slots are cleared: the frame
+ * holds nothing yet, and a pad reads all slots, also at a site before the calls that fill them. The
+ * slot of a reference that the call hands over takes the argument register instead. A mixed
+ * function also clears its "cancelled" word here, see find_pad_code(): there code that reads the
+ * word can be reached from the first insn without passing a stub or an entry. Returns the number of
+ * insns.
  */
-int bpf_pad_entry_insns(const struct bpf_pad_note **notes, int nr, struct bpf_insn *buf)
+int bpf_pad_entry_insns(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
+			int nr, struct bpf_insn *buf)
 {
 	int i, k, n = 0;
 
@@ -3139,6 +3168,50 @@ int bpf_pad_entry_insns(const struct bpf_pad_note **notes, int nr, struct bpf_in
 			buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, notes[i]->off - k * BPF_REG_SIZE,
 					      0);
 	}
+	if (bpf_subprog_clears_cancelled(sub))
+		buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, sub->cancelled_off, 0);
+	return n;
+}
+
+/*
+ * Emit the entry of a cleanup pad, see enter_cleanup_pad() in verifier.c, except its last insn,
+ * which jumps to the cleanup pad. Returns the number of insns.
+ *
+ *	ax = K				behind a call in pad code:
+ *	if ax != 0 goto 1f		the kernel unwinds the frame already
+ *	K = 1
+ *	*(u64 *)(r10 - W) = r0		in a program with bpf_throw(): the value
+ * 1:	r0 = 0
+ *
+ * The first entry of a frame decides: K stays 1 until the frame is left, and the value that the
+ * program ends with is the one that the unwinding began with, whatever unwinds on the way. The
+ * pad gets 0 in R0, where unwind_exit of the program leaves what the program threw: the value of
+ * the kernel is none of its business, and a pad that takes R0 for an object of the program finds
+ * none.
+ * Only a call in pad code can be the second entry of a frame: a frame that the kernel unwinds runs
+ * nothing else, see bpf_find_cleanup_pads(). So only the entry of such a call tests K. Behind any
+ * other call the entry is the first one, 'untested' of its plan, and stores without the two insns
+ * of the test: it must not read the word, which nothing has written on that way. In a mixed
+ * function no call is known to be such a one, every entry tests, and the entry of the function
+ * clears K for them.
+ * Returns the number of insns.
+ */
+int bpf_pad_cancel_entry_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
+			       int subprog, struct bpf_insn *buf)
+{
+	const struct bpf_subprog_info *sub = &env->subprog_info[subprog];
+	int n = 0;
+
+	if (!plan->untested) {
+		buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_FP, sub->cancelled_off);
+		buf[n++] = BPF_JMP_IMM(BPF_JNE, BPF_REG_AX, 0, 0);
+	}
+	buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, sub->cancelled_off, 1);
+	if (env->has_throw)
+		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_0, sub->value_off);
+	if (!plan->untested)
+		buf[1].off = n - 2;
+	buf[n++] = BPF_MOV64_IMM(BPF_REG_0, 0);
 	return n;
 }
 
@@ -3752,8 +3825,9 @@ static int take_value_word(struct bpf_verifier_env *env, struct bpf_subprog_info
 }
 
 /*
- * @sub gets the hidden word K, and in a program with bpf_throw() the word for the value: the entry
- * of a landing pad stores both. Returns 1 if the stack has no room.
+ * Give @sub the hidden words that the entries of its cleanup pads store to, see
+ * bpf_pad_cancel_entry_insns(): the "cancelled" word, the save words, and in a program with
+ * bpf_throw() the value word. Returns 0, 1 if the stack has no room, or a negative errno.
  */
 static int take_cancelled_words(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
 {
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 31b1bac012fa..8386bc4df747 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -20069,6 +20069,9 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 			err = enter_cleanup_pad(env);
 			if (err)
 				return err;
+		} else if (bpf_frame_is_cancelled(cur_func(env))) {
+			/* A cancelled frame takes it: no stub for it, see collect_stubs(). */
+			cur_aux(env)->cancelled_takes = true;
 		}
 		*insn_idx += insn->off;
 		return 0;
@@ -22715,47 +22718,18 @@ static int check_unwound_arrival(struct bpf_verifier_env *env)
 }
 
 /*
- * The kernel unwound what the call before this insn called, and the program has unwind_goto here
- * whose landing pad ONLY RESUMES, see bpf_find_cleanup_pads(): it runs what the program wants done
- * when a frame is left, a destructor of C++ or Rust, and cannot end the unwinding. So it is not
- * passed by. cancel_goto behind the call goes to the ENTRY that the verifier emits, and from there
- * to the pad.
+ * The callee of the call before this insn was cancelled, and the program has an unwind_goto here
+ * that leads to a cleanup pad: a landing pad of the program that can only clean up and continue
+ * unwinding, such as a C++ destructor, see bpf_find_cleanup_pads(). A cancellation runs such a
+ * pad. At run time the cancel_goto after the call goes to an entry that sets the "cancelled" word
+ * of the frame, puts 0 into R0 and jumps to the pad, see the head comment of kernel/bpf/pads.c.
  *
- *	call foo			call foo
- *	unwind_goto pad			unwind_goto pad
- *	...				cancel_goto entry
- * pad:	r6 = r0				...
- *	call dtor		   pad:	r6 = r0
- *	r0 = r6				call dtor
- *	unwind_exit			r0 = r6
- *					gotol rest
- *					...
- *				 entry: ax = K
- *					if ax != 0 goto +1
- *					K = 1
- *					r0 = 0
- *					gotol pad
- *				  rest:	ax = K
- *					if ax == 0 goto +3
- *					r0 = V
- *					r2 = 0
- *					cancel_exit
- *					unwind_exit
- *
- * The current frame is FORCED from here on, and never anything else again:
- *   - The pad is verified once more, with what the frame holds when the kernel unwinds the callee,
- *     and with 0 in R0. An error on that way is an error of the program like any other.
- *   - A forced state and one of the normal path are never joined: the mark is in the join key.
- *   - No insn that returns to the caller can be reached from the pad, so the only ways out are
- *     unwind_exit of the program and the sites of the frame, see leave_cancelled_frame() and
- *     unwind_frame(). Both leave with cancel_exit and the value of the kernel. The program cannot
- *     go on, and it cannot change what it ends with.
- *   - What unwinds in the pad itself does not change that either. unwind_exit of a callee is
- *     taken where the program has unwind_goto for it, and the kernel that unwinds a callee
- *     enters the landing pad of that call as it did this one: K is set, and it stays set.
- *
- * At run time K says the same as the mark: a hidden word of the frame that is 0 from the entry of
- * the function on and that only the entry of a pad sets, see bpf_pad_entry_insns().
+ * Here the frame is marked BPF_FRAME_CANCELLED and gets 0 in R0, and the caller takes the jump. So
+ * the cleanup pad is verified a second time, for the cancelled frame. The mark is never cleared,
+ * and the verifier does not merge two states that differ in it. No insn that returns to the caller
+ * can be reached from a cleanup pad, so the frame leaves at the unwind_exit of the pad, see
+ * leave_cancelled_frame(), or at a site inside the pad, see unwind_frame(). Both leave with
+ * cancel_exit and the value of the cancellation.
  *
  * Returns PROCESS_BPF_EXIT if the state ends.
  */
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 66/73] bpf: Let the entry of a cleanup pad save the pointers of the frame
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (64 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 65/73] bpf: Emit the stub, the entry and the remainder of a cleanup pad Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:42   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 67/73] bpf: Run the cleanup pads of a program when the kernel cancels it Kumar Kartikeya Dwivedi
                   ` (6 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  51 +++-
 kernel/bpf/fixups.c          |  10 +-
 kernel/bpf/pads.c            | 553 ++++++++++++++++++++++++++++++-----
 kernel/bpf/states.c          |   1 +
 kernel/bpf/verifier.c        |  52 +++-
 5 files changed, 581 insertions(+), 86 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 93147a22c81e..46d186628e2a 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -385,6 +385,8 @@ struct bpf_reference_state {
 	u32 diag_id;	/* finds the acquire in the report of a leak, it is not renumbered */
 	/* the insn that brought it into its frame: insn_idx, or a call that returned with it */
 	int origin;
+	/* 1 + the save word of the frame that has the pointer, 0 if none, see bpf_pad_enter() */
+	u8 saved;
 	union {
 		/* For REF_TYPE_PTR. Compared and hashed as 8 bytes, see same_refs(): no holes. */
 		struct {
@@ -544,6 +546,7 @@ enum bpf_pad_conflict {
 	BPF_CONFLICT_CALLER_SAVED,
 	BPF_CONFLICT_NO_VALUE,
 	BPF_CONFLICT_NO_ROOM,
+	BPF_CONFLICT_SAVES_DIFFER,
 };
 
 /* How a subprog was found to be one that cannot be cancelled, see 'stuck' of bpf_subprog_info */
@@ -567,6 +570,8 @@ enum bpf_stuck_by {
 #define BPF_PAD_MAX_INSNS	(BPF_PAD_MAX_ENTS * (2 * BPF_PAD_MAX_ARGS + 2) + \
 				 BPF_PAD_NR_SECTIONS * BPF_PAD_MAX_SECTIONS + 5)
 #define BPF_PAD_MAX_CANDS	6
+/* The most save words of a function, see 'save_off' of struct bpf_subprog_info */
+#define BPF_PAD_MAX_SAVES	BPF_PAD_MAX_ENTS
 /*
  * The most insns that keep hidden slots up to date at one call: nine for each of at most
  * BPF_PAD_MAX_ENTS slots, five that compare and clear it and four that find a free one. Three per
@@ -580,6 +585,8 @@ enum bpf_place_loc {
 	BPF_PLACE_SPILL,	/* 8 bytes of the stack of the frame */
 	BPF_PLACE_MAP_VALUE,	/* the address of the only value of a map */
 	BPF_PLACE_IMM,		/* not a pointer: the constant 'delta', the flags of a release */
+	/* save word 'at' of a cancelled frame, a BPF_PLACE_SPILL after take_cancelled_words() */
+	BPF_PLACE_SAVED,
 };
 
 /* A location: where a landing pad finds the pointer that a release takes */
@@ -594,9 +601,17 @@ struct bpf_pad_place {
 /* The registers and the stack slots of a frame that are 0 */
 struct bpf_pad_nulls {
 	u16 regs;
+	u16 unsaved;		/* the save words in which the entry stored no pointer */
 	DECLARE_BITMAP(slots, MAX_BPF_STACK_SLOTS);
 };
 
+/* The kind of pointer that a save word holds in all frames of a function: what releases it */
+struct bpf_pad_save {
+	struct bpf_insn release;
+	u32 obj_type;
+	bool set;
+};
+
 /* One release of a landing pad: a resource of the frame, the call and where its arguments are */
 struct bpf_pad_ent {
 	u32 origin;		/* the lowest 'origin' of the references that it stands for */
@@ -606,6 +621,8 @@ struct bpf_pad_ent {
 	u8 class;		/* enum bpf_pad_class */
 	bool rcu;		/* an iterator that RCU protects: it is destroyed first */
 	bool always;		/* all states hold it */
+	/* BPF_SITE_CANCEL_ENTRY: 1 + the save word where the entry keeps the pointer, 0 if none */
+	u8 word;
 	/* per argument of the call: the locations that all states share. The pad uses the first. */
 	u8 nr_cands[BPF_PAD_MAX_ARGS];
 	struct bpf_pad_place cand[BPF_PAD_MAX_ARGS][BPF_PAD_MAX_CANDS];
@@ -647,8 +664,12 @@ struct bpf_pad_plan {
 	u8 no_irq_place;		/* the same for irq flags in the stack of a caller */
 	/* the groups that it asked hidden slots for, bits by enum bpf_pad_group: settle_slots() */
 	u8 asked_slots;
+	/* BPF_SITE_CANCEL_ENTRY: why the entry cannot save pointers, an enum bpf_pad_conflict */
+	u8 no_saves;
 	u8 nr_ents;
 	bool ordered;			/* see order_ents() */
+	/* BPF_SITE_CANCEL_ENTRY: 'ents' are what the frame holds at the call, see visit_saves() */
+	bool saves;
 	/* BPF_SITE_CANCEL_ENTRY: its entry need not test the "cancelled" word: collect_pads() */
 	bool untested;
 	/*
@@ -831,7 +852,12 @@ struct bpf_func_state {
 	bool in_rcu_callback_fn;
 	/* parent_id of the args that are gone when this frame returns */
 	u32 frame_id;
-	u32 cancelled;	/* the marks BPF_FRAME_CANCELLED and BPF_FRAME_BELOW */
+	u16 cancelled;	/* the marks BPF_FRAME_CANCELLED and BPF_FRAME_BELOW */
+	/*
+	 * Bit per save word: the entry stored a pointer there when the frame was cancelled. The
+	 * other words are 0. A word keeps its pointer when the cleanup pad releases the object.
+	 */
+	u16 saved_mask;
 	/*
 	 * Bit f: the frame, or a subprog that returned to it, released a lock or irq flags of
 	 * frame f. If the frame returns, a store after its call clears the hidden slot. If not,
@@ -1425,6 +1451,11 @@ struct bpf_insn_aux_data {
 	u32 acquires:1; /* a reference or a lock */
 	u32 releases:1;
 	u32 fault_full:1; /* an access to arena: its plan records every state */
+	/*
+	 * An unwind_goto of the program: the entry of its cleanup pad saves no pointers, because
+	 * the states at the call did not agree in an earlier pass, see settle_entries()
+	 */
+	u32 entry_saves_nothing:1;
 
 	/* below flags are initialized once */
 	u32 bb_end:1; /* last instruction of a basic block */
@@ -1615,6 +1646,11 @@ struct bpf_subprog_info {
 	 * flags that the subprog saves or a pointer that it releases, see bpf_pad_note_return()
 	 */
 	s16 pend_off;
+	/* the first save word, the others are above it, see bpf_pad_enter() */
+	s16 save_off;
+	u8 save_words;
+	/* what each save word holds in a cancelled frame, in this pass */
+	struct bpf_pad_save saves[BPF_PAD_MAX_SAVES];
 	u32 insns_total;
 	u32 insns_self;
 	/* offsets in range [stack_depth .. fastcall_stack_off)
@@ -2013,6 +2049,8 @@ struct bpf_verifier_env {
 	bool ref_conflict;
 	bool handed_back;		/* what was handed over was taken back, see try_more() */
 	bool pass_again;		/* the pass is repeated, see pass_needs_restart() */
+	bool saves_again;		/* because what an entry saves changed: settle_entries() */
+	bool ask_hidden_slots;		/* per subprog from now on, see bpf_hidden_slots_fit() */
 	bool fallthrough_first;		/* see find_failing_path() */
 	bool run_has_guess;		/* see run_path_sensitive() */
 	u32 failing_path_budget_shift;	/* see func_failing_path_budget() */
@@ -2042,7 +2080,10 @@ struct bpf_verifier_env {
 	unsigned long cb_pads[8];
 	u8 cb_pad_cnt;
 	bool pads_late;			/* a global subprog unwinds: see settle_late_unwinds() */
+	bool saves_late;		/* what an entry saves changed, see settle_entries() */
 	bool faults_late;		/* a site is not what it seemed: see check_arena_site() */
+	bool hidden_slots_unasked;	/* see bpf_hidden_slots_fit() */
+	bool slots_late;		/* no room for hidden words: bpf_hidden_slots_settle() */
 	bool pad_releases;		/* see release_frame_resources() */
 	bool calls_joined;		/* see flow_may_add_instance() */
 	bool extra_values;		/* a state can have constants that no run has */
@@ -2611,8 +2652,8 @@ size_t bpf_pad_plans_free(struct bpf_insn_aux_data *aux);
 void bpf_pads_new_round(struct bpf_verifier_env *env);
 void bpf_pads_move(struct bpf_verifier_env *env, struct bpf_pads_moved *moved, bool save);
 size_t bpf_pads_free_moved(struct bpf_pads_moved *moved, u32 cnt);
-struct bpf_pad_plan *bpf_pad_enter(struct bpf_verifier_env *env,
-				   const struct bpf_verifier_state *st, int call_idx);
+struct bpf_pad_plan *bpf_pad_enter(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+				   int call_idx);
 struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
 				   const struct bpf_verifier_state *st, int insn_idx,
 				   enum bpf_site_kind kind);
@@ -2632,11 +2673,13 @@ bool bpf_pads_conflict(struct bpf_verifier_env *env, const struct bpf_insn_aux_d
 void bpf_pads_note_causes(struct bpf_verifier_env *env);
 bool bpf_pad_can_be_shared(const struct bpf_pad_plan *plan);
 int bpf_hidden_slots_fit(struct bpf_verifier_env *env);
+int bpf_hidden_slots_settle(struct bpf_verifier_env *env);
 int bpf_pad_slot_notes(struct bpf_verifier_env *env, int s, const struct bpf_pad_note **notes);
 int bpf_pad_entry_insns(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
 			int nr, struct bpf_insn *buf);
 int bpf_pad_cancel_entry_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
-			       int subprog, struct bpf_insn *buf);
+			       int subprog, struct bpf_insn *buf, struct bpf_insn_aux_data *aux);
+int bpf_pad_check_saves(struct bpf_verifier_env *env, int s);
 int bpf_pad_insns_before(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
 			 int nr, const struct bpf_pad_note *note, struct bpf_insn *buf);
 int bpf_pad_insns_after(const struct bpf_subprog_info *sub, const struct bpf_pad_note **notes,
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 75d3349624d1..9aa61815e201 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -875,8 +875,8 @@ struct pad_unit {
 	struct bpf_pad_plan *cancelled;
 };
 
-/* The most insns that a unit has */
-#define PAD_UNIT_MAX_INSNS	(2 * (BPF_PAD_MAX_INSNS + 4) + 3)
+/* The most insns of a unit. An entry has up to four per save word. */
+#define PAD_UNIT_MAX_INSNS	(2 * (BPF_PAD_MAX_INSNS + 4) + 3 + 4 * BPF_PAD_MAX_SAVES)
 
 /*
  * Do the two records of @unit give the same landing pad? Both pads are emitted into @buf to
@@ -940,7 +940,7 @@ static int emit_unit(struct bpf_verifier_env *env, int s, enum bpf_site_kind bas
 	int n = 0, len;
 
 	if (base == BPF_SITE_CANCEL_ENTRY) {
-		n += bpf_pad_cancel_entry_insns(env, unit->plan, s, buf + n);
+		n += bpf_pad_cancel_entry_insns(env, unit->plan, s, buf + n, aux + n);
 		buf[n++] = BPF_JMP32_A(0);
 		return n;
 	}
@@ -1092,6 +1092,10 @@ static int collect_pads(struct bpf_verifier_env *env, int s, struct bpf_insn *ne
 	bool unwinds, cancelled;
 
 	pads->nr = pads->cnt = pads->stubs = 0;
+	/* the entries and the remainders have to agree on the save words */
+	n = sub->save_words ? bpf_pad_check_saves(env, s) : 0;
+	if (n)
+		return n;
 	n = collect_stubs(env, s, pads);
 	if (n < 0)
 		return n;
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index e888589d4cc5..d016bfdc53cb 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -136,8 +136,9 @@
  * cleanup pad a second time for it, with 0 in R0. A cancelled frame never returns to its caller. It
  * leaves at the unwind_exit of the pad, through the remainder at 'rest' (BPF_SITE_REMAINDER), or at
  * a site inside the pad, where its states have a record and a pad of their own
- * (BPF_SITE_CANCELLED). A cleanup pad that a cancellation can reach is entered, or the program is
- * rejected.
+ * (BPF_SITE_CANCELLED). Only R0 is live at the unwind_exit, so the entry (BPF_SITE_CANCEL_ENTRY)
+ * copies the pointers that the frame holds into hidden words, the save words, see visit_saves(). A
+ * cleanup pad that a cancellation can reach is entered, or the program is rejected.
  *
  * Only the stub and the entry write the "cancelled" word, and only pad code reads it, see
  * find_pad_code(). A call in pad code can be made by a frame that is cancelled already, so its
@@ -469,6 +470,7 @@ struct bpf_pad_plan *bpf_pad_plan_get(struct bpf_verifier_env *env, int insn_idx
 		return NULL;
 	plan->kind = kind;
 	plan->nulls.regs = U16_MAX;
+	plan->nulls.unsaved = U16_MAX;
 	bitmap_fill(plan->nulls.slots, MAX_BPF_STACK_SLOTS);
 	plan->next = aux->pad_plans;
 	aux->pad_plans = plan;
@@ -901,6 +903,7 @@ static void find_nulls(const struct bpf_func_state *frame, struct bpf_pad_nulls
 	int i, j;
 
 	memset(nulls, 0, sizeof(*nulls));
+	nulls->unsaved = ~frame->saved_mask;
 	for (i = BPF_REG_0; i < BPF_REG_FP; i++)
 		if (reg_is_null(&frame->regs[i]))
 			nulls->regs |= BIT(i);
@@ -914,9 +917,15 @@ static void find_nulls(const struct bpf_func_state *frame, struct bpf_pad_nulls
 	}
 }
 
-/* An address in the stack and the address of a map value are never 0 */
+/*
+ * Is @place 0 in the frame that @nulls describes? An address in the stack or of a map value never
+ * is. A save word is 0 only if the entry stored nothing there: the word keeps its pointer when the
+ * cleanup pad releases the object.
+ */
 static bool place_is_null(const struct bpf_pad_nulls *nulls, const struct bpf_pad_place *place)
 {
+	if (place->loc == BPF_PLACE_SAVED)
+		return nulls->unsaved & BIT(place->at);
 	if (place->loc == BPF_PLACE_REG)
 		return nulls->regs & BIT(place->at);
 	return place->loc == BPF_PLACE_SPILL &&
@@ -1028,6 +1037,67 @@ static int ptr_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
 	return ent_imm(env, ent, reg);
 }
 
+/* Does @ent release the kind of object that save word @word of @sub is for? See visit_saves(). */
+static bool ent_is_saved_kind(const struct bpf_subprog_info *sub, int word,
+			      const struct bpf_pad_ent *ent)
+{
+	const struct bpf_pad_save *save = &sub->saves[word];
+
+	return save->set && ent->class == BPF_PAD_REF && !ent->rcu &&
+	       ent->obj_type == save->obj_type &&
+	       !memcmp(&ent->release, &save->release, sizeof(ent->release));
+}
+
+/*
+ * The part of ref_ent() for a pointer @ref that the entry of the cleanup pad stored in a save word.
+ * The word is one more location, which is good wherever the frame leaves. @err is what ptr_ent()
+ * made of the registers. If no register but R0-R5 holds the pointer any more, the word is the only
+ * location, and the kind of object that the function keeps in the word says what releases it, see
+ * visit_saves(). A register that holds the pointer has to agree with that kind.
+ */
+static int saved_ptr_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
+			 const struct bpf_verifier_state *st, const struct bpf_reference_state *ref,
+			 int err)
+{
+	const struct bpf_func_state *frame = st->frame[st->curframe];
+	const struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
+	const struct bpf_pad_save *save = &sub->saves[ref->saved - 1];
+	struct bpf_pad_place *cand = ent->cand[0];
+	int i, n = ent->nr_cands[0];
+
+	if (verifier_bug_if(!save->set, env, "save word %d of func#%d has no pointer",
+			    ref->saved - 1, frame->subprogno))
+		return -EFAULT;
+	if (err == BPF_CONFLICT_NO_PLACE || err == BPF_CONFLICT_CALLER_SAVED) {
+		ent->release = save->release;
+		if (is_obj_drop(&ent->release)) {
+			if (!can_free_obj(env, &ent->release, save->obj_type))
+				return BPF_CONFLICT_NO_RELEASE;
+			ent->obj_type = save->obj_type;
+		}
+		if (takes_flags(&ent->release))
+			ent->cand[1][ent->nr_cands[1]++] =
+				(struct bpf_pad_place){ .loc = BPF_PLACE_IMM };
+	} else if (err) {
+		return err;
+	} else if (!ent_is_saved_kind(sub, ref->saved - 1, ent)) {
+		return BPF_CONFLICT_SAVES_DIFFER;
+	}
+	if (n == BPF_PAD_MAX_CANDS)
+		return 0;
+	/*
+	 * The word goes before R0-R5, which serve the first call of a pad only: settle_ent() takes
+	 * the first candidate that will do.
+	 */
+	for (i = 0; i < n && !(cand[i].loc == BPF_PLACE_REG && cand[i].at < BPF_REG_6); i++)
+		;
+	memmove(&cand[i + 1], &cand[i], (n - i) * sizeof(*cand));
+	cand[i] = (struct bpf_pad_place){ .loc = BPF_PLACE_SAVED, .at = ref->saved - 1,
+					  .maybe_null = true };
+	ent->nr_cands[0]++;
+	return 0;
+}
+
 /* The part of ref_ent() for @ref that is an iterator or a dynptr. @slot is its first slot. */
 static int obj_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
 		   const struct bpf_reference_state *ref, const struct bpf_stack_state *slot)
@@ -1070,6 +1140,9 @@ static int ref_ent(struct bpf_verifier_env *env, struct bpf_pad_ent *ent,
 		err = obj_ent(env, ent, ref, obj);
 	else if (class == BPF_PAD_REF)
 		err = ptr_ent(env, ent, st, insn_idx, ref);
+	/* only a pointer has a save word, see visit_saves() */
+	if (class == BPF_PAD_REF && !obj && ref->saved)
+		err = saved_ptr_ent(env, ent, st, ref, err);
 	if (class == BPF_PAD_RES_LOCK_IRQ) {
 		/* the same insn saved irq flags, the next of refs[]: the second argument */
 		if (verifier_bug_if(ref + 1 == st->refs + st->acquired_refs ||
@@ -1227,7 +1300,8 @@ static int order_ents(struct bpf_verifier_env *env, struct bpf_pad_plan *plan)
 	int i, j, k, n = plan->nr_ents, next;
 	u8 row, bit;
 
-	if (plan->ordered)
+	/* the record of an entry of a cleanup pad releases nothing, so it has no order */
+	if (plan->ordered || plan->kind == BPF_SITE_CANCEL_ENTRY)
 		return 0;
 	plan->ordered = true;
 	for (k = 0; k < n; k++) {
@@ -1365,6 +1439,7 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
 			ent->cand[0][j].null &= place_is_null(&nulls, &ent->cand[0][j]);
 	}
 	plan->nulls.regs &= nulls.regs;
+	plan->nulls.unsaved &= nulls.unsaved;
 	bitmap_and(plan->nulls.slots, plan->nulls.slots, nulls.slots, MAX_BPF_STACK_SLOTS);
 	return 0;
 }
@@ -1510,19 +1585,122 @@ static bool same_release(const struct bpf_pad_ent *a, const struct bpf_pad_ent *
 }
 
 /*
- * The kernel unwound what the call at @call_idx called, and the current frame of @st goes on in
- * the landing pad that the program has behind the call, see enter_cleanup_pad() in verifier.c. The
- * plan of the entry is no plan of a pad: the frame is not left, and nothing is released. It says
- * that the call has an entry, and what the entry has to find: in a program with bpf_throw() the
- * value of the kernel is in R0, a number, and goes to the hidden word of the frame.
- * With a conflict the state ends here, and bpf_pads_settle() rejects the program.
- * Returns the plan.
+ * Keep the candidates of @ent that the entry of a cleanup pad saves from: R6-R9 and stack slots.
+ * None if @err says that there is no location, or if @ent is no pointer, see visit_saves().
  */
-struct bpf_pad_plan *bpf_pad_enter(struct bpf_verifier_env *env,
-				   const struct bpf_verifier_state *st, int call_idx)
+static void save_cands(struct bpf_pad_ent *ent, int err)
+{
+	struct bpf_pad_place *cand = ent->cand[0];
+	int i, n = 0;
+
+	for (i = 0; !err && ent->class == BPF_PAD_REF && i < ent->nr_cands[0]; i++)
+		if (cand[i].loc == BPF_PLACE_SPILL ||
+		    (cand[i].loc == BPF_PLACE_REG && cand[i].at >= BPF_REG_6 &&
+		     cand[i].at < BPF_REG_FP))
+			cand[n++] = cand[i];
+	ent->nr_cands[0] = n;
+}
+
+/*
+ * Decide what the entry of the cleanup pad after the call at @call_idx saves for the current frame
+ * of @st, which the kernel starts to cancel there. A generated pad releases what the frame still
+ * holds where it leaves, but at the unwind_exit of the cleanup pad only R0 is live. So the entry
+ * copies the pointers that the frame holds in R6-R9 or in a stack slot into SAVE WORDS, hidden
+ * words of the frame. With a task in R6:
+ *
+ *	entry: cancelled = 1		    rest: ax = cancelled
+ *	       r0 = r6				  if ax == 0 goto +6
+ *	       *(u64 *)(r10 - 16) = r0		  r1 = *(u64 *)(r10 - 16)
+ *	       r0 = 0				  if r1 == 0 goto +1
+ *	       gotol pad			  call bpf_task_release
+ *						  r0 = V; r2 = 0
+ *						  cancel_exit
+ *						  unwind_exit
+ *
+ *   - Only a pointer is saved. The address of an object in the stack of a caller is not, because
+ *     the cleanup pad can write to its slots, nor the address of a lock that only a register has.
+ *     The cleanup pad has to release those itself, unless they have a location where the frame
+ *     leaves.
+ *   - Word j is for the j-th reference that the frame holds at the call ('saved' of the
+ *     reference). A word keeps its pointer when the cleanup pad releases the object: the state
+ *     says what is still held.
+ *   - A word holds one kind of object in all frames of a function: the type of a pointer says
+ *     what releases it, and no register need hold the pointer where the frame leaves.
+ *   - If the states at the call do not agree on what the frame holds, the entry saves nothing and
+ *     the pass is repeated, see settle_entries().
+ *
+ * Returns 0, the enum bpf_pad_conflict that says why the entry cannot save, or a negative errno.
+ */
+static int visit_saves(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
+		       const struct bpf_verifier_state *st, int call_idx)
 {
 	const struct bpf_func_state *frame = st->frame[st->curframe];
+	struct bpf_subprog_info *sub = &env->subprog_info[frame->subprogno];
+	int i, j, n, err, nr = st->acquired_refs - frame->entry_refs;
+	struct bpf_pad_place cand[BPF_PAD_MAX_CANDS];
+	struct bpf_pad_ent new, *ent;
+	struct bpf_pad_save *save;
+
+	if (nr > BPF_PAD_MAX_SAVES)
+		return BPF_CONFLICT_TOO_MUCH;
+	if (plan->saves && plan->nr_ents != nr)
+		return BPF_CONFLICT_SAVES_DIFFER;
+	if (!plan->ents)
+		plan->ents = kzalloc_objs(*plan->ents, BPF_PAD_MAX_ENTS, BPF_VERIFIER_GFP);
+	if (!plan->ents)
+		return -ENOMEM;
+	for (j = 0; j < nr; j++) {
+		i = frame->entry_refs + j;
+		ent = &plan->ents[j];
+		memset(&new, 0, sizeof(new));
+		/* what is no pointer has no word, but it has a position */
+		if (st->refs[i].type == REF_TYPE_PTR) {
+			err = ref_ent(env, &new, st, call_idx + 1, &st->refs[i]);
+			if (err < 0)
+				return err;
+			save_cands(&new, err);
+		}
+		if (!plan->saves) {
+			*ent = new;
+			ent->always = true;
+		} else if (!ent->nr_cands[0] != !new.nr_cands[0]) {
+			return BPF_CONFLICT_SAVES_DIFFER;
+		} else if (new.nr_cands[0]) {
+			n = common_cands(ent, &new, 0, cand);
+			if (!n || !same_release(ent, &new))
+				return BPF_CONFLICT_SAVES_DIFFER;
+			memcpy(ent->cand[0], cand, n * sizeof(*cand));
+			ent->nr_cands[0] = n;
+		}
+		if (!ent->nr_cands[0])
+			continue;
+		ent->word = j + 1;
+		save = &sub->saves[j];
+		if (!save->set)
+			*save = (struct bpf_pad_save){ .release = ent->release,
+						       .obj_type = ent->obj_type, .set = true };
+		if (!ent_is_saved_kind(sub, j, ent))
+			return BPF_CONFLICT_SAVES_DIFFER;
+	}
+	plan->nr_ents = nr;
+	plan->saves = true;
+	return 0;
+}
+
+/*
+ * The callee of the call at @call_idx was cancelled, and the current frame of @st continues in the
+ * cleanup pad after the call, see enter_cleanup_pad() in verifier.c. Record at the entry
+ * (BPF_SITE_CANCEL_ENTRY) what it saves, see visit_saves(), and mark the references of @st that get
+ * a save word. A frame that is cancelled already keeps what it has: nothing is recorded for it.
+ * Returns the record or an ERR_PTR(). If 'conflict' of the record is set, the state ends here, and
+ * bpf_pads_settle() has the pass repeated with an entry that saves nothing, or rejects the program.
+ */
+struct bpf_pad_plan *bpf_pad_enter(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+				   int call_idx)
+{
+	struct bpf_func_state *frame = st->frame[st->curframe];
 	struct bpf_pad_plan *plan;
+	int j, word, err;
 
 	plan = bpf_pad_plan_get(env, call_idx, BPF_SITE_CANCEL_ENTRY);
 	if (!plan)
@@ -1530,10 +1708,30 @@ struct bpf_pad_plan *bpf_pad_enter(struct bpf_verifier_env *env,
 	plan->visited = true;
 	/* the frame is cancelled already, so the entry has to test: collect_pads() checks */
 	plan->cancelled_visit |= bpf_frame_is_cancelled(frame);
-	if (plan->conflict)
+	if (plan->conflict || bpf_frame_is_cancelled(frame))
 		return plan;
-	if (env->has_throw && frame->regs[BPF_REG_0].type != SCALAR_VALUE)
+	if (env->has_throw && frame->regs[BPF_REG_0].type != SCALAR_VALUE) {
 		plan->conflict = BPF_CONFLICT_NO_VALUE;
+		return plan;
+	}
+	if (!plan->no_saves) {
+		err = visit_saves(env, plan, st, call_idx);
+		charge_plan(env, plan);
+		if (err < 0)
+			return ERR_PTR(err);
+		plan->no_saves = err;
+	}
+	if (env->insn_aux_data[call_idx + 1].entry_saves_nothing)
+		return plan;
+	err = plan->conflict = plan->no_saves;
+	/* release j of the record is the j-th reference of the frame: nothing sorts this record */
+	for (j = 0; !err && j < plan->nr_ents; j++) {
+		word = plan->ents[j].word;
+		if (!word)
+			continue;
+		st->refs[frame->entry_refs + j].saved = word;
+		frame->saved_mask |= BIT(word - 1);
+	}
 	return plan;
 }
 
@@ -2039,15 +2237,15 @@ void bpf_pad_note_args(struct bpf_func_state *callee, const struct bpf_func_stat
 }
 
 /*
- * A call of @subprog out of @caller, a frame of @st, has a pointer in R@regno whose reference
- * @caller holds: its index in refs[], which is what the call can HAND OVER, see the comment at the
- * top. -1 if there is none, or if it is not one that changes frames without more:
- *   - A pointer that can be NULL: nothing is held where it is.
- *   - An object in the stack, a reference that was made from another one, and one that another
- *     one was made from: they are released in the order of refs[].
- *   - Any reference in a state that the kernel has brought into a landing pad of the program.
- *   - @subprog is recursive: the check at its entry takes a frame that holds something for one
- *     that got there by a jump, see check_recursion_guard() in verifier.c.
+ * A call of @subprog from @caller, a frame of @st, has a pointer in R@regno. Returns the index in
+ * refs[] of the reference that the call can hand over with it, see the comment at the top of this
+ * file, or -1. A call does not hand over:
+ *   - a pointer that the callee does not read, or that can be NULL
+ *   - an object in the stack, a reference that was made from another one, or one that another
+ *     one was made from: these are released in the order of refs[]
+ *   - a reference that has a save word, or any reference of a state that is in a cleanup pad
+ *   - anything to a recursive @subprog: check_recursion_guard() in verifier.c takes a frame that
+ *     holds something at the first insn for one that got there by a jump
  */
 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)
@@ -2067,7 +2265,8 @@ int bpf_pad_handed_ref(struct bpf_verifier_env *env, const struct bpf_verifier_s
 	for (idx = caller->entry_refs; idx < end; idx++)
 		if (st->refs[idx].type == REF_TYPE_PTR && st->refs[idx].id == reg->id)
 			break;
-	if (idx >= end || st->refs[idx].parent_id || find_obj(st, &st->refs[idx], &addr))
+	if (idx >= end || st->refs[idx].parent_id || st->refs[idx].saved ||
+	    find_obj(st, &st->refs[idx], &addr))
 		return -1;
 	for (i = 0; i < st->acquired_refs; i++)
 		if (ref_is_child(st, i, idx))
@@ -3081,6 +3280,8 @@ static int settle_slots(struct bpf_verifier_env *env)
 		env->subprog_info[s].no_value_word = false;
 		env->subprog_info[s].cancelled_off = 0;
 		env->subprog_info[s].pend_off = 0;
+		env->subprog_info[s].save_off = 0;
+		env->subprog_info[s].save_words = 0;
 	}
 	for (s = 0; s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
@@ -3173,34 +3374,49 @@ int bpf_pad_entry_insns(const struct bpf_subprog_info *sub, const struct bpf_pad
 	return n;
 }
 
+/*
+ * Returns the release of @plan, the record of the entry of a cleanup pad, whose pointer goes to
+ * save word @word of @sub, see visit_saves(). NULL if the entry stores 0 there.
+ */
+static const struct bpf_pad_ent *saved_ent(const struct bpf_subprog_info *sub,
+					   const struct bpf_pad_plan *plan, int word)
+{
+	int j;
+
+	/* the function has hidden slots for pointers: every pad releases through them */
+	if (sub->slots & BIT(BPF_PAD_GROUP_REFS))
+		return NULL;
+	for (j = 0; j < plan->nr_ents; j++)
+		if (plan->ents[j].word == word + 1)
+			return &plan->ents[j];
+	return NULL;
+}
+
 /*
  * Emit the entry of a cleanup pad, see enter_cleanup_pad() in verifier.c, except its last insn,
  * which jumps to the cleanup pad. Returns the number of insns.
  *
- *	ax = K				behind a call in pad code:
- *	if ax != 0 goto 1f		the kernel unwinds the frame already
- *	K = 1
- *	*(u64 *)(r10 - W) = r0		in a program with bpf_throw(): the value
- * 1:	r0 = 0
+ *	   ax = cancelled	      only after a call in pad code and in a mixed function:
+ *	   if ax != 0 goto 1f	      the frame may be cancelled already
+ *	   cancelled = 1
+ *	   *(u64 *)(r10 - W) = r0     in a program with bpf_throw(): the value of the cancellation
+ *	   r0 = r6		      per save word of the function: the pointer, see
+ *	   *(u64 *)(r10 - S) = r0     visit_saves(), or 0
+ *	1: r0 = 0
  *
- * The first entry of a frame decides: K stays 1 until the frame is left, and the value that the
- * program ends with is the one that the unwinding began with, whatever unwinds on the way. The
- * pad gets 0 in R0, where unwind_exit of the program leaves what the program threw: the value of
- * the kernel is none of its business, and a pad that takes R0 for an object of the program finds
- * none.
- * Only a call in pad code can be the second entry of a frame: a frame that the kernel unwinds runs
- * nothing else, see bpf_find_cleanup_pads(). So only the entry of such a call tests K. Behind any
- * other call the entry is the first one, 'untested' of its plan, and stores without the two insns
- * of the test: it must not read the word, which nothing has written on that way. In a mixed
- * function no call is known to be such a one, every entry tests, and the entry of the function
- * clears K for them.
- * Returns the number of insns.
+ * The first entry of a frame decides what the program returns. The cleanup pad gets 0 in R0, where
+ * the program's own unwinding has the object that it threw. An entry without the test ('untested'
+ * of @plan) must not read the word, which nothing has written on that path. A pointer goes to its
+ * save word through R0: the offset of its location is a constant of the program, and a JIT blinds
+ * an insn on R0 but not one on AX.
  */
 int bpf_pad_cancel_entry_insns(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
-			       int subprog, struct bpf_insn *buf)
+			       int subprog, struct bpf_insn *buf, struct bpf_insn_aux_data *aux)
 {
 	const struct bpf_subprog_info *sub = &env->subprog_info[subprog];
-	int n = 0;
+	const struct bpf_pad_place *place;
+	const struct bpf_pad_ent *ent;
+	int word, off, first, n = 0;
 
 	if (!plan->untested) {
 		buf[n++] = BPF_LDX_MEM(BPF_DW, BPF_REG_AX, BPF_REG_FP, sub->cancelled_off);
@@ -3209,12 +3425,92 @@ int bpf_pad_cancel_entry_insns(struct bpf_verifier_env *env, const struct bpf_pa
 	buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, sub->cancelled_off, 1);
 	if (env->has_throw)
 		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_0, sub->value_off);
+	for (word = 0; word < sub->save_words; word++) {
+		off = sub->save_off + word * BPF_REG_SIZE;
+		ent = saved_ent(sub, plan, word);
+		if (!ent) {
+			buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, off, 0);
+			continue;
+		}
+		place = &ent->cand[0][0];
+		first = n;
+		n += load_handle(env, &buf[n], &aux[n], BPF_REG_0, place, place->delta);
+		if (place->delta)
+			buf[first + 1].off = 1;
+		buf[n++] = BPF_STX_MEM(BPF_DW, BPF_REG_FP, BPF_REG_0, off);
+	}
 	if (!plan->untested)
 		buf[1].off = n - 2;
 	buf[n++] = BPF_MOV64_IMM(BPF_REG_0, 0);
 	return n;
 }
 
+/*
+ * Check the save words of subprog @s before they are emitted. An entry has to store each pointer
+ * into a word that the function has, each into another word, and the pointer has to be of the kind
+ * that the word is for. A pad that reads a word has to release that kind, and an entry has to store
+ * into the word. Anything else would release what another reference left in the word.
+ */
+int bpf_pad_check_saves(struct bpf_verifier_env *env, int s)
+{
+	const struct bpf_subprog_info *sub = &env->subprog_info[s];
+	const struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	const struct bpf_pad_place *place;
+	const struct bpf_pad_plan *plan;
+	const struct bpf_pad_ent *ent;
+	u16 stored = 0, words;
+	int i, j, word;
+
+	for (i = sub->start; i < sub[1].start; i++) {
+		plan = bpf_pad_plan(&aux[i], BPF_SITE_CANCEL_ENTRY);
+		words = 0;
+		for (j = 0; plan && j < plan->nr_ents; j++) {
+			ent = &plan->ents[j];
+			word = ent->word - 1;
+			if (word < 0)
+				continue;
+			stored |= BIT(word);
+			if (!plan->used || plan->conflict)
+				continue;
+			if (verifier_bug_if(word >= sub->save_words || (words & BIT(word)) ||
+					    !ent->nr_cands[0] || !ent_is_saved_kind(sub, word, ent),
+					    env, "the entry at insn %d stores into save word %d",
+					    i, word))
+				return -EFAULT;
+			words |= BIT(word);
+		}
+	}
+	for (i = sub->start; i < sub[1].start; i++) {
+		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
+			if (!plan->used || plan->conflict || !bpf_site_is_cancelled(plan->kind))
+				continue;
+			for (j = 0; j < plan->nr_ents; j++) {
+				ent = &plan->ents[j];
+				/* the candidate that is emitted: a word is a stack slot by now */
+				place = &ent->cand[0][0];
+				/* load_handle() has no insn for any other form of it */
+				if (verifier_bug_if(ent->nr_cands[0] &&
+						    place->loc == BPF_PLACE_SAVED, env,
+						    "a save word of the pad of insn %d is no slot",
+						    i))
+					return -EFAULT;
+				if (!ent->nr_cands[0] || place->loc != BPF_PLACE_SPILL ||
+				    place->at < sub->save_off)
+					continue;
+				word = (place->at - sub->save_off) / BPF_REG_SIZE;
+				if (word >= sub->save_words)
+					continue;
+				if (verifier_bug_if(!(stored & BIT(word)) ||
+						    !ent_is_saved_kind(sub, word, ent), env,
+						    "the landing pad of insn %d reads save word %d",
+						    i, word))
+					return -EFAULT;
+			}
+		}
+	}
+	return 0;
+}
+
 /*
  * Emit the stores that fill a hidden slot of the call of @note with R@src, the pointer that the
  * release takes. The slot of a section takes 1. The store has no condition: 0 in R0 means that
@@ -3429,6 +3725,8 @@ static void print_ent(struct bpf_verifier_env *env, const struct bpf_pad_ent *en
 			verbose(env, "map#%d", place->at);
 		else if (place->loc == BPF_PLACE_IMM)
 			verbose(env, "%d", place->delta);
+		else if (place->loc == BPF_PLACE_SAVED)
+			verbose(env, "saved#%d", place->at);
 		else if (place->at == BPF_REG_FP)
 			verbose(env, "fp");
 		else
@@ -3456,6 +3754,7 @@ static const char * const conflict_why[] = {
 	[BPF_CONFLICT_CALLER_SAVED]	= "a handle is in R0-R5 only",
 	[BPF_CONFLICT_NO_VALUE]		= "the value of unwind_exit is not a number",
 	[BPF_CONFLICT_NO_ROOM]		= "no room in the stack for the value",
+	[BPF_CONFLICT_SAVES_DIFFER]	= "what the frames hold at the call differs",
 };
 
 /* Print what the pad of the site at insn @i releases, or why it cannot be generated */
@@ -3465,8 +3764,15 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
 
 	/* no generated pad: the entry of a cleanup pad */
 	if (plan->kind == BPF_SITE_CANCEL_ENTRY) {
-		verbose(env, "landing pad of the program behind the call at %d: the kernel enters it\n",
+		verbose(env, "landing pad of the program behind the call at %d: the kernel enters it",
 			i);
+		for (j = 0; j < plan->nr_ents; j++) {
+			if (!plan->ents[j].nr_cands[0])
+				continue;
+			verbose(env, ", saves ");
+			print_ent(env, &plan->ents[j]);
+		}
+		verbose(env, "\n");
 		return;
 	}
 	/*
@@ -3617,25 +3923,35 @@ static bool pad_can_cause(enum bpf_pad_conflict conflict)
 	}
 }
 
+/* Log the entries of @sub that save nothing, for the cleanup pads that start in @reach */
+static void print_saves_nothing(struct bpf_verifier_env *env, const struct bpf_subprog_info *sub,
+				const unsigned long *reach)
+{
+	const struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	const struct bpf_pad_plan *plan;
+	int i;
+
+	for (i = sub->start; i < sub[1].start - 1; i++) {
+		plan = bpf_pad_plan(&aux[i], BPF_SITE_CANCEL_ENTRY);
+		if (plan && plan->visited && aux[i + 1].entry_saves_nothing &&
+		    test_bit(pad_of_call(env, i), reach))
+			verbose(env, "the entry of the landing pad of the call at %d saves nothing\n",
+				i);
+	}
+}
+
 /*
- * The conflict of @plan, a site at insn @i, is an error. The kernel enters a landing pad of the
- * program that only resumes or the program is rejected: where such a pad has a part in the
- * conflict the log says so, in front of the line of the conflict. It names a pad only where that
- * pad is known to have the part.
- *   - The plan is that of an entry: it has no value to keep.
- *   - The frame is one that the kernel unwinds through such a pad: it has no plan where the pad
- *     ends, or at a site in pad code. A frame does not know which entry it came through: the
- *     first pad of the function that gets to the insn on the control flow graph is named, and
- *     the others that do are counted.
- *   - States got to the site out of such a pad, in a function that the pad calls. Its frame
- *     does not know the pad. If states of the normal path got there as well, the function is
- *     "also" called from the pad: the conflict may be one without the pad.
- *   - What came back to the call of the plan left a frame below through such a pad, which may
- *     have taken from what the frame of the call holds, or written to its stack. Which pad it
- *     was is not known, and a pad on the way may have done nothing of the kind: the function
- *     that came back is named, the pad is in it or below it.
- *   - Such a pad released what a caller holds, and no function on the stack gets hidden slots
- *     for that, see released_of_caller(): the plan needed them for it.
+ * The pad of @plan, a site at insn @i, cannot be generated, and that is an error. Log what a
+ * cleanup pad has to do with it, before the line of the error:
+ *   - @plan is the record of an entry, which has no value to keep.
+ *   - The frame is cancelled and has no pad at the unwind_exit of the cleanup pad, or at a site
+ *     inside it. A frame does not know which entry it came through, so the log names the first
+ *     cleanup pad of the function that reaches the insn on the control flow graph.
+ *   - States reached the site in a function that a cleanup pad calls.
+ *   - A callee of the call left a frame below through a cleanup pad, which may have released or
+ *     overwritten what the frame of the call holds. The log names the callee and says "may".
+ *   - A cleanup pad released what a caller holds, which cost a function on the stack the hidden
+ *     slots that the pad of @plan needed, see released_of_caller().
  */
 static void print_cleanup_pad_conflict(struct bpf_verifier_env *env, int i,
 				       const struct bpf_pad_plan *plan)
@@ -3659,6 +3975,7 @@ static void print_cleanup_pad_conflict(struct bpf_verifier_env *env, int i,
 					i);
 			else
 				verbose(env, "a site in its code has no plan\n");
+			print_saves_nothing(env, sub, reach);
 		}
 		bitmap_free(reach);
 		return;
@@ -3831,19 +4148,95 @@ static int take_value_word(struct bpf_verifier_env *env, struct bpf_subprog_info
  */
 static int take_cancelled_words(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
 {
-	int err;
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	struct bpf_pad_place *place;
+	struct bpf_pad_plan *plan;
+	int i, j, k, err, words = 0;
 
-	sub->hidden_words++;
+	/*
+	 * As many save words as the entry that saves the most needs. An entry that the program does
+	 * not keep counts too: the states that came through it reached sites whose pads test its
+	 * words.
+	 */
+	for (i = sub->start; i < sub[1].start; i++) {
+		plan = bpf_pad_plan(&aux[i], BPF_SITE_CANCEL_ENTRY);
+		for (j = 0; plan && j < BPF_PAD_MAX_SAVES; j++)
+			if (saved_ent(sub, plan, j))
+				words = max(words, j + 1);
+	}
+	sub->hidden_words += 1 + words;
 	err = bpf_hidden_slots_fit(env);
 	if (err <= 0) {
-		sub->hidden_words--;
+		sub->hidden_words -= 1 + words;
 		return err ?: 1;
 	}
-	sub->cancelled_off = -(int)bpf_stack_depth_with_slots(sub);
-	if (!env->has_throw)
-		return 0;
-	err = take_value_word(env, sub);
-	return err < 0 ? err : !!err;
+	sub->save_words = words;
+	sub->save_off = -(int)bpf_stack_depth_with_slots(sub);
+	sub->cancelled_off = sub->save_off + words * BPF_REG_SIZE;
+	err = env->has_throw ? take_value_word(env, sub) : 0;
+	if (err)
+		return err < 0 ? err : 1;
+	/* the pads of its cancelled frames read the save words: stack slots from now on */
+	for (i = sub->start; i < sub[1].start; i++) {
+		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
+			if (!bpf_site_is_cancelled(plan->kind))
+				continue;
+			for (j = 0; j < plan->nr_ents; j++) {
+				for (k = 0; k < plan->ents[j].nr_cands[0]; k++) {
+					place = &plan->ents[j].cand[0][k];
+					if (place->loc != BPF_PLACE_SAVED)
+						continue;
+					place->loc = BPF_PLACE_SPILL;
+					place->at = sub->save_off + place->at * BPF_REG_SIZE;
+				}
+			}
+		}
+	}
+	return 0;
+}
+
+/*
+ * Decide what the entries of the cleanup pads save, before the other records are looked at. What
+ * the entry of a call saves is one answer for all states at the call, see visit_saves(), and a pass
+ * has the answer from its start: 'entry_saves_nothing' of the insn after the call, as the pass
+ * before left it. Where the answer changes, the pass is repeated ('saves_late'):
+ *   - The entry was to save, and the states do not agree on what the frame holds. It saves
+ *     nothing from now on, which is no error by itself.
+ *   - The entry saved nothing, and the states agree, because this pass keeps more apart. It saves
+ *     again, but not in a pass that is repeated because an answer changed ('saves_again'). So the
+ *     repeats end: each takes saving away from at least one entry and gives it back to none.
+ * The record of an entry that saves nothing is emptied, because the emission reads the record.
+ */
+static void settle_entries(struct bpf_verifier_env *env)
+{
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	bool level2 = env->log.level & BPF_LOG_LEVEL2;
+	struct bpf_pad_plan *plan;
+	int i;
+
+	for (i = 0; i < env->prog->len - 1; i++) {
+		plan = bpf_pad_plan(&aux[i], BPF_SITE_CANCEL_ENTRY);
+		if (!plan)
+			continue;
+		if (!aux[i + 1].entry_saves_nothing) {
+			if (!plan->used || !plan->no_saves)
+				continue;
+			if (level2)
+				verbose(env, "the entry of the landing pad of the call at %d saves nothing: %s\n",
+					i, conflict_why[plan->no_saves]);
+			aux[i + 1].entry_saves_nothing = true;
+			env->saves_late = true;
+		} else if (plan->used && plan->saves && !plan->no_saves && !plan->conflict &&
+			   !env->saves_again) {
+			if (level2)
+				verbose(env, "the entry of the landing pad of the call at %d saves again\n",
+					i);
+			aux[i + 1].entry_saves_nothing = false;
+			env->saves_late = true;
+		} else {
+			plan->nr_ents = 0;
+		}
+	}
 }
 
 /*
@@ -3930,6 +4323,10 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 	err = settle_slots(env);
 	if (err)
 		return err;
+	/* if an answer changed, the repeated pass decides about the records */
+	settle_entries(env);
+	if (env->saves_late)
+		return 0;
 	for (i = 0; i < env->prog->len; i++) {
 		if (env->insn_aux_data[i].pad_plans && bpf_must_abort())
 			return -EINTR;
@@ -3968,12 +4365,15 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 		}
 	}
 	/*
-	 * The error is raised here, behind all plans: a pass can have several conflicts that show
-	 * only now, and each of them is one that the next pass keeps more apart for, see
-	 * bpf_find_unproven_after_pass() and bpf_pads_note_causes(). One per pass would be a pass
-	 * per conflict.
+	 * The error is raised here, after all records: a pass can have several sites whose missing
+	 * pad shows only now, and the next pass has to react to each of them, see
+	 * bpf_find_unproven_after_pass() and bpf_pads_note_causes(). It also comes after the check
+	 * that the hidden words fit.
 	 */
 	if (reject) {
+		err = bpf_hidden_slots_settle(env);
+		if (err)
+			return min(err, 0);
 		bpf_pad_log(env, at, reject);
 		return -EINVAL;
 	}
@@ -3982,6 +4382,9 @@ int bpf_pads_settle(struct bpf_verifier_env *env)
 	err = take_cleanup_pad_words(env);
 	if (err)
 		return err;
+	err = bpf_hidden_slots_settle(env);
+	if (err)
+		return min(err, 0);
 	/* all accesses of the program to its stack are known: the hidden words go below them */
 	for (s = 0; s < env->subprog_cnt; s++) {
 		sub = &env->subprog_info[s];
diff --git a/kernel/bpf/states.c b/kernel/bpf/states.c
index 9201e3cbc448..7eb9a3609080 100644
--- a/kernel/bpf/states.c
+++ b/kernel/bpf/states.c
@@ -493,6 +493,7 @@ static bool same_refs(const struct bpf_verifier_state *a, const struct bpf_verif
 
 	for (i = 0; i < a->acquired_refs; i++)
 		if (a->refs[i].type != b->refs[i].type || a->refs[i].id != b->refs[i].id ||
+		    a->refs[i].saved != b->refs[i].saved ||
 		    memcmp(&a->refs[i].ptr, &b->refs[i].ptr, sizeof(u64)))
 			return false;
 	return true;
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index 8386bc4df747..ada65af7e4a3 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -1572,6 +1572,7 @@ static struct bpf_reference_state *acquire_reference_state(struct bpf_verifier_e
 		return NULL;
 	state->refs[new_ofs].insn_idx = insn_idx;
 	state->refs[new_ofs].origin = insn_idx;
+	state->refs[new_ofs].saved = 0;
 
 	return &state->refs[new_ofs];
 }
@@ -6460,10 +6461,14 @@ static int try_max_stack_depth(struct bpf_verifier_env *env, bool with_slots)
  * check_max_stack_depth() fails without the hidden words as well: that error is not about them,
  * and check_after_pass() reports it.
  */
-int bpf_hidden_slots_fit(struct bpf_verifier_env *env)
+static int hidden_slots_fit(struct bpf_verifier_env *env)
 {
-	int err = try_max_stack_depth(env, true);
+	int err;
 
+	err = bpf_add_cost_and_check(env, env->prog->len + env->subprog_cnt, BPF_COST_COPY);
+	if (err)
+		return err;
+	err = try_max_stack_depth(env, true);
 	if (!err)
 		return 1;
 	if (err != -ENOMEM)
@@ -6473,6 +6478,39 @@ int bpf_hidden_slots_fit(struct bpf_verifier_env *env)
 	return !!err;
 }
 
+/*
+ * Returns 1 if the stack has room for the hidden words that a subprog just got, 0 if not.
+ * bpf_pads_settle() asks once per subprog, and a whole check_max_stack_depth() each time costs too
+ * much. So the answer is 1 at first, and bpf_hidden_slots_settle() checks all subprogs at once.
+ * Only if that fails, the pass is repeated with a real check per subprog.
+ */
+int bpf_hidden_slots_fit(struct bpf_verifier_env *env)
+{
+	if (env->ask_hidden_slots)
+		return hidden_slots_fit(env);
+	env->hidden_slots_unasked = true;
+	return 1;
+}
+
+/*
+ * Check the hidden words that bpf_hidden_slots_fit() accepted without a check. Returns 1 if the
+ * stack has no room for them. The pass is then repeated.
+ */
+int bpf_hidden_slots_settle(struct bpf_verifier_env *env)
+{
+	int err;
+
+	if (!env->hidden_slots_unasked)
+		return 0;
+	env->hidden_slots_unasked = false;
+	err = hidden_slots_fit(env);
+	if (err)
+		return min(err, 0);
+	env->ask_hidden_slots = true;
+	env->slots_late = true;
+	return 1;
+}
+
 static int __check_buffer_access(struct bpf_verifier_env *env,
 				 const char *buf_info,
 				 const struct bpf_reg_state *reg,
@@ -12337,6 +12375,7 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 	for (i = nheld; i < exit->acquired_refs; i++) {
 		caller->refs[i] = exit->refs[i];
 		caller->refs[i].origin = call_idx;
+		caller->refs[i].saved = 0;
 	}
 	caller->held = exit->held;
 
@@ -22744,7 +22783,10 @@ static int enter_cleanup_pad(struct bpf_verifier_env *env)
 	plan = bpf_pad_enter(env, st, call_idx);
 	if (IS_ERR(plan))
 		return PTR_ERR(plan);
-	/* an error that bpf_pads_settle() raises, as for a site that is not certain */
+	/*
+	 * The state ends here. bpf_pads_settle() raises the error, or repeats the pass with an
+	 * entry that saves nothing.
+	 */
 	if (plan->conflict)
 		return PROCESS_BPF_EXIT;
 	/*
@@ -23285,7 +23327,7 @@ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
 static bool pass_needs_restart(struct bpf_verifier_env *env)
 {
 	return (env->restart && bpf_flow_loops_lost_bound(env)) || env->guards_late ||
-	       env->pads_late || env->faults_late;
+	       env->pads_late || env->saves_late || env->faults_late || env->slots_late;
 }
 
 /*
@@ -24975,6 +25017,8 @@ static int check_funcs(struct bpf_verifier_env *env, struct bpf_snapshot *initia
 		initial->subprogs[i].releases_args |= env->subprog_info[i].releases_args;
 		initial->subprogs[i].asks_args = env->subprog_info[i].asks_args;
 	}
+	/* The last run changed what the entry of a cleanup pad saves, see bpf_pads_settle(). */
+	env->saves_again = env->pass_again && env->saves_late;
 	env->pass_again = false;
 	restore_snapshot(env, initial);
 	kvfree(env->callx_edges);
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 67/73] bpf: Run the cleanup pads of a program when the kernel cancels it
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (65 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 66/73] bpf: Let the entry of a cleanup pad save the pointers of the frame Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 68/73] bpf: End the path at a call of a global subprog that never returns Kumar Kartikeya Dwivedi
                   ` (5 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

A cancellation point inside a cleanup pad behaves as follows:

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

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

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

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

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 Documentation/bpf/verifier.rst | 109 ++++++++++++++++++++++++++++++++-
 include/uapi/linux/bpf.h       |  17 +++++
 kernel/bpf/verifier.c          |   4 ++
 tools/include/uapi/linux/bpf.h |  17 +++++
 4 files changed, 144 insertions(+), 3 deletions(-)

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


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 68/73] bpf: End the path at a call of a global subprog that never returns
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (66 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 67/73] bpf: Run the cleanup pads of a program when the kernel cancels it Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:26   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 69/73] bpf: Tell struct_ops when a program was cancelled Kumar Kartikeya Dwivedi
                   ` (4 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf_verifier.h |  13 +++++
 kernel/bpf/cfg.c             | 107 +++++++++++++++++++++++++++++++++++
 kernel/bpf/fixups.c          |  14 ++++-
 kernel/bpf/liveness.c        |  35 +++++++++++-
 kernel/bpf/pads.c            |  29 +++++-----
 kernel/bpf/verifier.c        |  20 ++++++-
 6 files changed, 197 insertions(+), 21 deletions(-)

diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
index 46d186628e2a..f71f116f74f3 100644
--- a/include/linux/bpf_verifier.h
+++ b/include/linux/bpf_verifier.h
@@ -1670,6 +1670,8 @@ struct bpf_subprog_info {
 	bool in_recursion: 1; /* recursive, or a recursive subprog gets to it */
 	bool addr_taken: 1; /* callx calls nothing else */
 	bool via_callx: 1; /* callx calls it */
+	/* a path from its first insn returns to the caller, see bpf_compute_might_return() */
+	bool might_return: 1;
 	bool tail_call_reachable: 1;
 	bool has_ld_abs: 1;
 	bool is_cb: 1;
@@ -3007,6 +3009,15 @@ u32 bpf_vlog_alignment(u32 pos);
 const char *bpf_disasm_kfunc_name(void *data, const struct bpf_insn *insn);
 
 struct bpf_subprog_info *bpf_find_containing_subprog(struct bpf_verifier_env *env, int off);
+
+/* A tail call that is taken and an LD_ABS or LD_IND that fails leave the subprog like exit */
+static inline bool bpf_insn_has_hidden_exit(const struct bpf_insn *insn)
+{
+	return (bpf_helper_call(insn) && insn->imm == BPF_FUNC_tail_call) ||
+	       (BPF_CLASS(insn->code) == BPF_LD &&
+		(BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND));
+}
+
 const char *bpf_subprog_name(const struct bpf_verifier_env *env, int subprog);
 struct bpf_iarray *bpf_insn_successors(struct bpf_verifier_env *env, u32 idx);
 
@@ -3044,11 +3055,13 @@ u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t);
 
 int bpf_find_subprog(struct bpf_verifier_env *env, int off);
 bool bpf_is_throw_kfunc(struct bpf_insn *insn);
+bool bpf_is_trap_kfunc(struct bpf_insn *insn);
 int bpf_compute_const_regs(struct bpf_verifier_env *env);
 int bpf_prune_dead_branches(struct bpf_verifier_env *env);
 int bpf_check_cfg(struct bpf_verifier_env *env);
 void bpf_free_subprog_jts(struct bpf_verifier_env *env);
 int bpf_compute_postorder(struct bpf_verifier_env *env);
+int bpf_compute_might_return(struct bpf_verifier_env *env);
 
 struct bpf_map_desc {
 	struct bpf_map *ptr;
diff --git a/kernel/bpf/cfg.c b/kernel/bpf/cfg.c
index 71ec6063dce6..a46e97dd8661 100644
--- a/kernel/bpf/cfg.c
+++ b/kernel/bpf/cfg.c
@@ -832,6 +832,113 @@ int bpf_check_cfg(struct bpf_verifier_env *env)
 	return ret;
 }
 
+/*
+ * Might @subprog return to its caller? It does if a path from its first insn reaches an exit insn
+ * or an insn with a hidden exit, see bpf_insn_has_hidden_exit(). A path ends at unwind_exit, at a
+ * call of bpf_throw() or __bpf_trap(), and at a call of a subprog that does not return. After such
+ * a call the path continues only at the target of an unwind_goto of the program, where unwind_exit
+ * of the callee comes back. A cancellation adds no path: it enters only cleanup pads, which do not
+ * return.
+ *
+ * bpf_check_cfg() is more lenient. There the insn after such a call stays reachable, so that what
+ * a compiler leaves after a call that does not return is not rejected as unreachable code.
+ */
+static int subprog_might_return(struct bpf_verifier_env *env, int subprog,
+				unsigned long *seen, int *stack)
+{
+	struct bpf_subprog_info *sub = &env->subprog_info[subprog];
+	struct bpf_insn *insns = env->prog->insnsi;
+	int top = 0, t, i, callee, pad;
+	struct bpf_iarray *succ;
+
+	bitmap_clear(seen, sub->start, sub[1].start - sub->start);
+	t = sub->start;
+	__set_bit(t, seen);
+	stack[top++] = t;
+	while (top) {
+		struct bpf_insn *insn;
+
+		t = stack[--top];
+		insn = &insns[t];
+		if (bpf_is_unwind_exit(insn))
+			continue;
+		if (insn->code == (BPF_JMP | BPF_EXIT) || bpf_insn_has_hidden_exit(insn))
+			return 1;
+		if (bpf_is_trap_kfunc(insn))
+			continue;
+		if (bpf_pseudo_call(insn)) {
+			callee = bpf_find_subprog(env, t + insn->imm + 1);
+			if (verifier_bug_if(callee < 0, env, "no callee of insn %d", t))
+				return -EFAULT;
+			if (!env->subprog_info[callee].might_return) {
+				if (!bpf_is_unwind_goto(&insns[t + 1]))
+					continue;
+				/* unwind_exit of the callee leads to the program's landing pad */
+				pad = t + 1 + bpf_jmp_offset(&insns[t + 1]) + 1;
+				if (!__test_and_set_bit(pad, seen))
+					stack[top++] = pad;
+				continue;
+			}
+		}
+		/* a call of bpf_throw() has no successor */
+		succ = bpf_insn_successors(env, t);
+		for (i = 0; i < succ->cnt; i++) {
+			if (__test_and_set_bit(succ->items[i], seen))
+				continue;
+			stack[top++] = succ->items[i];
+		}
+	}
+	return 0;
+}
+
+/*
+ * Compute 'might_return' of every subprog. No subprog returns until a path shows that it does, and
+ * the subprogs are walked until nothing changes. Callees come first, so only a cycle of calls takes
+ * more than one walk. A subprog that stays unmarked never returns: it only throws, for example, or
+ * calls itself on every path.
+ */
+int bpf_compute_might_return(struct bpf_verifier_env *env)
+{
+	struct bpf_subprog_info *si = env->subprog_info;
+	int *stack, i, subprog, ret = 0;
+	unsigned long *seen;
+	bool changed;
+
+	seen = bitmap_zalloc(env->prog->len, BPF_VERIFIER_GFP);
+	stack = kvmalloc_objs(*stack, env->prog->len, BPF_VERIFIER_GFP);
+	if (!seen || !stack) {
+		ret = -ENOMEM;
+		goto out;
+	}
+
+	for (i = 0; i < env->subprog_cnt; i++)
+		si[i].might_return = false;
+	do {
+		changed = false;
+		/* a cycle of calls takes a round for each link */
+		ret = bpf_add_cost_and_check(env, env->cfg.cur_postorder, BPF_COST_SCAN);
+		if (ret)
+			goto out;
+		for (i = 0; i < env->subprog_cnt; i++) {
+			subprog = env->subprog_topo_order[i];
+			if (si[subprog].might_return)
+				continue;
+			ret = subprog_might_return(env, subprog, seen, stack);
+			if (ret < 0)
+				goto out;
+			if (ret) {
+				si[subprog].might_return = true;
+				changed = true;
+			}
+		}
+	} while (changed);
+	ret = 0;
+out:
+	bitmap_free(seen);
+	kvfree(stack);
+	return ret;
+}
+
 struct dfs_state {
 	u32 traversed:1;
 	u32 next_succ:31;
diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
index 9aa61815e201..c2497b4fc953 100644
--- a/kernel/bpf/fixups.c
+++ b/kernel/bpf/fixups.c
@@ -1748,8 +1748,8 @@ void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
 	struct bpf_insn trap = BPF_JMP_IMM(BPF_JA, 0, 0, -1);
 	struct bpf_insn *insn = env->prog->insnsi;
 	const int insn_cnt = env->prog->len;
-	bool unwinds, calls;
-	int i;
+	bool unwinds, calls, traps;
+	int i, callee;
 
 	for (i = 0; i < insn_cnt; i++, insn++) {
 		unwinds = bpf_is_pad_goto(insn) && aux_data[i + 1 + bpf_jmp_offset(insn)].seen;
@@ -1759,8 +1759,16 @@ void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
 		 * its cancel_exit needs cancel_goto.
 		 * The cpu predicts that it returns to what follows, or speculates to an exit.
 		 * Don't let the removal of dead code put something else there.
+		 * After a call of a subprog that does not return, see bpf_compute_might_return(),
+		 * the trap is kept whoever loads the program: should a return ever get there, it
+		 * must not find code that was verified for another path.
 		 */
-		if ((unwinds || (calls && !env->bypass_spec_v1)) && !aux_data[i + 1].seen) {
+		traps = calls && !env->bypass_spec_v1;
+		if (calls && !traps && bpf_pseudo_call(insn)) {
+			callee = bpf_find_subprog(env, i + insn->imm + 1);
+			traps = callee >= 0 && !env->subprog_info[callee].might_return;
+		}
+		if ((unwinds || traps) && !aux_data[i + 1].seen) {
 			memcpy(insn + 1, &trap, sizeof(trap));
 			aux_data[i + 1].zext_dst = false;
 			aux_data[i + 1].seen = env->check_cnt;
diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
index 93f8d1686496..7ebcd369d229 100644
--- a/kernel/bpf/liveness.c
+++ b/kernel/bpf/liveness.c
@@ -392,9 +392,7 @@ bpf_insn_successors(struct bpf_verifier_env *env, u32 idx)
 	 * from the subprogram, which is a hidden edge to its exit. A subprogram
 	 * with neither an exit insn nor bpf_throw() has no exit to model.
 	 */
-	if (unlikely((bpf_helper_call(insn) && insn->imm == BPF_FUNC_tail_call) ||
-		     (BPF_CLASS(insn->code) == BPF_LD &&
-		      (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND)))) {
+	if (unlikely(bpf_insn_has_hidden_exit(insn))) {
 		u32 exit_idx = bpf_find_containing_subprog(env, idx)->exit_idx;
 
 		if (exit_idx != U32_MAX)
@@ -1860,6 +1858,26 @@ static int record_arg_access(struct bpf_verifier_env *env,
 	return err;
 }
 
+/*
+ * Is the insn at @idx dead code after a call of a subprog that does not return, see
+ * bpf_compute_might_return()? The callee comes back to the call only when it unwinds or is
+ * cancelled. The frame then leaves through a generated pad, which finds the pointers of the frame
+ * in what is live at this insn. So for liveness the insn reads what the pad may read, as a call of
+ * bpf_throw() does. That does not apply where the program has an unwind_goto there, nor where a
+ * jump leads to the insn.
+ */
+static bool behind_call_without_return(struct bpf_verifier_env *env, int idx)
+{
+	const struct bpf_insn *insns = env->prog->insnsi;
+	int callee;
+
+	if (!idx || !bpf_pseudo_call(&insns[idx - 1]) || bpf_is_unwind_goto(&insns[idx]) ||
+	    bpf_is_jump_target(env, idx))
+		return false;
+	callee = bpf_find_subprog(env, idx + insns[idx - 1].imm);
+	return callee >= 0 && !env->subprog_info[callee].might_return;
+}
+
 /* Record stack access for a given 'at' state of helper/kfunc/global subprog 'insn' */
 static int record_call_access(struct bpf_verifier_env *env,
 			      struct func_instance *instance,
@@ -2213,6 +2231,13 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,
 		if (err)
 			goto err_free;
 
+		/* the generated pad of the call may read any stack slot of the frame */
+		if (behind_call_without_return(env, idx)) {
+			err = mark_stack_read_all(env, instance, instance->depth, idx, true);
+			if (err)
+				goto err_free;
+		}
+
 		if (BPF_CLASS(insn->code) == BPF_JMP && BPF_OP(insn->code) == BPF_CALL) {
 			err = record_call_access(env, instance, at_in[i], idx);
 			if (err)
@@ -2842,6 +2867,10 @@ static void compute_insn_live_regs(struct bpf_verifier_env *env,
 		break;
 	}
 
+	/* the generated pad of the call may take a pointer from R6-R9 */
+	if (behind_call_without_return(env, insn - env->prog->insnsi))
+		use |= mask_widen(GENMASK(BPF_REG_9, BPF_REG_6));
+
 	info->def = def;
 	info->use = use;
 }
diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
index d016bfdc53cb..8c77525f4967 100644
--- a/kernel/bpf/pads.c
+++ b/kernel/bpf/pads.c
@@ -4728,10 +4728,7 @@ static bool insn_returns(const struct bpf_insn *insn)
 {
 	if (insn->code == (BPF_JMP | BPF_EXIT))
 		return !bpf_is_unwind_exit(insn);
-	if (bpf_helper_call(insn) && insn->imm == BPF_FUNC_tail_call)
-		return true;
-	return BPF_CLASS(insn->code) == BPF_LD &&
-	       (BPF_MODE(insn->code) == BPF_ABS || BPF_MODE(insn->code) == BPF_IND);
+	return bpf_insn_has_hidden_exit(insn);
 }
 
 /*
@@ -4757,16 +4754,11 @@ static bool insn_returns(const struct bpf_insn *insn)
  * call, or the function has no exit. In any other function a frame gets from the normal path into
  * pad code in two ways only: by the jump of an unwind_goto, and through an entry.
  *
- * A function is MIXED, 'cleanup_pads_mixed', if one of its insns is pad code and on the normal path
- * as well: a pad that the normal path falls into or jumps to, a pad that goes back in front of its
- * call, or to the first insn of its function, any pad of a function that has no exit. In every
- * other function the two share no insn, and a frame gets from the normal path into pad code in two
- * ways only: by the jump of unwind_goto, when a callee left with unwind_exit, and through the entry
- * of a pad, when the kernel unwound the callee.
- *
- * The exit that stands for the return of a tail call or of LD_ABS is no edge here, as it is none
- * where the pads are judged: it can be unwind_exit of the code that resumes, and a tail call on
- * the normal path would make every such function mixed.
+ * Two edges are not followed. One goes from a tail call, LD_ABS or LD_IND to the exit insn that
+ * stands for its return, which is often the unwind_exit of the cleanup pads. The other goes from
+ * the call of a subprog that does not return, see bpf_compute_might_return(), to the insn after it,
+ * where a compiler often puts the cleanup pad of that call. A trap stands there if that code is
+ * dead, see bpf_opt_hard_wire_dead_code_branches().
  */
 static int find_pad_code(struct bpf_verifier_env *env)
 {
@@ -4801,6 +4793,15 @@ static int find_pad_code(struct bpf_verifier_env *env)
 			if (!test_bit(i, pad) && !test_bit(i, normal))
 				continue;
 			insn = &insns[i];
+			s = bpf_pseudo_call(insn) ? bpf_find_subprog(env, i + 1 + insn->imm) : -1;
+			if (s >= 0 && !env->subprog_info[s].might_return) {
+				/* the callee does not return: only its landing pad follows */
+				t = i + 1 < len && bpf_is_unwind_goto(insn + 1) ?
+				    i + 2 + bpf_jmp_offset(insn + 1) : -1;
+				if (t >= 0 && test_bit(i, pad) && !__test_and_set_bit(t, pad))
+					changed = true;
+				continue;
+			}
 			succ = bpf_insn_successors(env, i);
 			cnt = insn_returns(insn) ? min(succ->cnt, 1) : succ->cnt;
 			for (t = 0; t < cnt; t++) {
diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
index bd76774ca60f..d154a7891d07 100644
--- a/kernel/bpf/verifier.c
+++ b/kernel/bpf/verifier.c
@@ -12621,6 +12621,13 @@ static int check_func_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 						 BPF_REG_0);
 		}
 
+		/*
+		 * The callee never returns, see bpf_compute_might_return(). Only the states that
+		 * were pushed above come back from the call, so this path ends.
+		 */
+		if (!env->subprog_info[subprog].might_return)
+			return PROCESS_BPF_EXIT;
+
 		/* continue with next insn after call */
 		return 0;
 	}
@@ -15713,6 +15720,12 @@ bool bpf_is_throw_kfunc(struct bpf_insn *insn)
 	       insn->imm == special_kfunc_list[KF_bpf_throw];
 }
 
+bool bpf_is_trap_kfunc(struct bpf_insn *insn)
+{
+	return bpf_pseudo_kfunc_call(insn) && insn->off == 0 &&
+	       insn->imm == special_kfunc_list[KF___bpf_trap];
+}
+
 static bool is_bpf_wq_set_callback_kfunc(u32 btf_id)
 {
 	return btf_id == special_kfunc_list[KF_bpf_wq_set_callback];
@@ -16567,7 +16580,7 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 		mark_reg_unknown(env, regs, BPF_REG_0);
 		reg_set_srange32(&regs[BPF_REG_0], -MAX_ERRNO, -1);
 		reg_bounds_sync(&regs[BPF_REG_0]);
-	} else if (!insn->off && insn->imm == special_kfunc_list[KF___bpf_trap]) {
+	} else if (bpf_is_trap_kfunc(insn)) {
 		verbose(env, "unexpected __bpf_trap() due to uninitialized variable?\n");
 		return -EFAULT;
 	}
@@ -27469,6 +27482,11 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (ret < 0)
 		goto skip_full_check;
 
+	/* needs the topological order of the subprogs, callees first */
+	ret = bpf_compute_might_return(env);
+	if (ret < 0)
+		goto skip_full_check;
+
 	/* what no JIT can run is reported first */
 	ret = mark_recursive_subprogs(env);
 	if (ret < 0)
-- 
2.53.1-Meta


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 69/73] bpf: Tell struct_ops when a program was cancelled
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (67 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 68/73] bpf: End the path at a call of a global subprog that never returns Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:26   ` bot+bpf-ci
  2026-12-01  4:39 ` [PATCH bpf-next v1 70/73] bpf: Tell struct_ops when cancel_exit returns to the kernel Kumar Kartikeya Dwivedi
                   ` (3 subsequent siblings)
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

Three cases need care:

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

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

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

Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf.h          | 13 +++++++++++++
 include/linux/bpf_verifier.h |  7 ++++---
 include/linux/filter.h       |  1 +
 kernel/bpf/core.c            | 12 ++++++++++++
 kernel/bpf/pads.c            | 34 +++++++++++++++++++++++++++++++++-
 kernel/bpf/syscall.c         |  7 ++++++-
 kernel/bpf/verifier.c        |  8 ++++++++
 7 files changed, 77 insertions(+), 5 deletions(-)

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


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 70/73] bpf: Tell struct_ops when cancel_exit returns to the kernel
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (68 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 69/73] bpf: Tell struct_ops when a program was cancelled Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 71/73] bpf: Let a struct_ops say what a cancelled program returns Kumar Kartikeya Dwivedi
                   ` (2 subsequent siblings)
  72 siblings, 0 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

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

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

Two cases need care:

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 arch/arm64/net/bpf_jit_comp.c | 45 +++++++++++++++++++++++------------
 arch/x86/net/bpf_jit_comp.c   | 30 +++++++++++++++--------
 include/linux/bpf_unwind.h    |  4 +++-
 include/linux/filter.h        |  1 +
 kernel/bpf/core.c             | 37 ++++++++++++++++++++++++----
 kernel/bpf/pads.c             | 21 +++++++---------
 6 files changed, 95 insertions(+), 43 deletions(-)

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


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 71/73] bpf: Let a struct_ops say what a cancelled program returns
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (69 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 70/73] bpf: Tell struct_ops when cancel_exit returns to the kernel Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` bot+bpf-ci
  2026-12-01  5:47   ` sashiko-bot
  2026-12-01  4:39 ` [PATCH bpf-next v1 72/73] bpf: Give cancelled tcp_congestion_ops programs values that TCP can take Kumar Kartikeya Dwivedi
  2026-12-01  4:39 ` [PATCH bpf-next v1 73/73] sched_ext: Treat a cancelled program as a scheduler error Kumar Kartikeya Dwivedi
  72 siblings, 2 replies; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

Implement the callback for bpf_qdisc:

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 include/linux/bpf.h   | 34 ++++++++++++++++++++++------------
 kernel/bpf/verifier.c | 22 +++++++++++++++++++++-
 net/sched/bpf_qdisc.c | 21 +++++++++++++++++++++
 3 files changed, 64 insertions(+), 13 deletions(-)

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


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 72/73] bpf: Give cancelled tcp_congestion_ops programs values that TCP can take
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (70 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 71/73] bpf: Let a struct_ops say what a cancelled program returns Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:46   ` sashiko-bot
  2026-12-01  4:39 ` [PATCH bpf-next v1 73/73] sched_ext: Treat a cancelled program as a scheduler error Kumar Kartikeya Dwivedi
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

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

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

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

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

Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 net/ipv4/bpf_tcp_ca.c | 31 +++++++++++++++++++++++++++++++
 1 file changed, 31 insertions(+)

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


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* [PATCH bpf-next v1 73/73] sched_ext: Treat a cancelled program as a scheduler error
  2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
                   ` (71 preceding siblings ...)
  2026-12-01  4:39 ` [PATCH bpf-next v1 72/73] bpf: Give cancelled tcp_congestion_ops programs values that TCP can take Kumar Kartikeya Dwivedi
@ 2026-12-01  4:39 ` Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` bot+bpf-ci
  72 siblings, 1 reply; 115+ messages in thread
From: Kumar Kartikeya Dwivedi @ 2026-12-01  4:39 UTC (permalink / raw)
  To: bpf
  Cc: Tejun Heo, Alexei Starovoitov, Andrii Nakryiko, Daniel Borkmann,
	Eduard Zingerman, Emil Tsalapatis, Ihor Solodrai, kkd,
	kernel-team

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

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

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

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

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

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

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

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

Two things stay as they are:

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

Cc: Tejun Heo <tj@kernel.org>
Co-developed-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Alexei Starovoitov <ast@kernel.org>
Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>
---
 kernel/sched/ext/ext.c | 21 +++++++++++++++++++++
 1 file changed, 21 insertions(+)

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


^ permalink raw reply related	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 11/73] bpf: Let a state leave its frame at may_goto without an exit insn
  2026-12-01  4:38 ` [PATCH bpf-next v1 11/73] bpf: Let a state leave its frame at may_goto without an exit insn Kumar Kartikeya Dwivedi
@ 2026-12-01  5:25   ` sashiko-bot
  0 siblings, 0 replies; 115+ messages in thread
From: sashiko-bot @ 2026-12-01  5:25 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, bpf

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] bpf: false R2 entry liveness when exit_idx is bpf_throw() at
  subprog start
--

commit 9ee4059c1175b782fb337afa593df33f1f44177a
Author: Alexei Starovoitov <ast@kernel.org>

bpf: Let a state leave its frame at may_goto without an exit insn

This commit adds unwind_frame() so a state can leave its frame directly at
a verifier-inserted may_goto or recursion guard during the main pass, and
removes bail_insn in favor of exit_idx.

> diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
> index f6456e5be5fd1..4d04d17603ae2 100644
> --- a/kernel/bpf/liveness.c
> +++ b/kernel/bpf/liveness.c
> @@ -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);

[Severity: Medium]
Can replacing bail_insn with exit_idx mark R2 live at subprogram entry when
exit_idx is a bpf_throw() call at sub->start?

Unlike bail_insn, which was only set on BPF_EXIT instructions, exit_idx
falls back to the first bpf_throw() call when a subprogram has no BPF_EXIT.
If a static subprogram returns a register pair in R0:R2 (ret_reg_pair is
true), takes 0 or 1 argument (arg_slot_cnt <= 1), has no BPF_EXIT, and
begins with bpf_throw() at sub->start, exit_idx equals sub->start and
BIT(BPF_REG_2) is added to insn_aux[sub->start].live_regs_before.

code_arg_slots() then sees R2 live at sub->start and returns 2, causing
btf_check_func_arg_match() to fail with -EINVAL, and analyze_subprog() and
func_is_on_its_own() treat caller-saved R2 as a live incoming argument of
the callee, rejecting valid callers that leave a stack pointer in R2.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1796099737.git.memxor@gmail.com?part=11

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 73/73] sched_ext: Treat a cancelled program as a scheduler error
  2026-12-01  4:39 ` [PATCH bpf-next v1 73/73] sched_ext: Treat a cancelled program as a scheduler error Kumar Kartikeya Dwivedi
@ 2026-12-01  5:25   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:25 UTC (permalink / raw)
  To: memxor, bpf
  Cc: tj, ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3045 bytes --]

> sched_ext: Treat a cancelled program as a scheduler error

TL;DR:
- sched_ext now disables schedulers on bpf_throw() with a usable return value;
  is that intended?
- Comment, changelog and exit message ("see its stderr stream") may be
  inaccurate for bpf_throw()

> diff --git a/kernel/sched/ext/ext.c b/kernel/sched/ext/ext.c
> --- a/kernel/sched/ext/ext.c
> +++ b/kernel/sched/ext/ext.c

[ ... ]

> @@ -9435,6 +9435,25 @@ static int bpf_scx_validate(void *kdata)
>  	return 0;
>  }
>  
> +/*
> + * @prog, an op of a scheduler or an async callback of one, was unwound.
> + * The op returns 0 without having computed it, which would be taken for a
> + * CPU or for success, so this is as fatal to the scheduler as scx_bpf_error().
> + * The rq lock of the op's caller may be held here. scx_error() only
> + * claims the exit and leaves the disabling to irq_work and the helper kthread.
> + */
> +static void bpf_scx_cancelled(const struct bpf_prog *prog)
> +{
> +	struct scx_sched *sch;
> +
> +	guard(rcu)();
> +
> +	sch = scx_prog_sched(prog->aux);
> +	if (sch)
> +		scx_error(sch, "program %s (ops.%s, id %u) was unwound, see its stderr stream",
> +			  prog->aux->name, prog->aux->attach_func_name, prog->aux->id);
> +}

The comment says "The op returns 0 without having computed it", and the
commit message says "The program returns a default value, which is 0 for
a program of a scheduler".  Is that accurate for bpf_throw()?

The documentation of ->cancelled in include/linux/bpf.h says the program
is about to return the value of @cancelled_retval, or the argument of
bpf_throw().  Also, bpf_pad_insns() does this:

    if (!subprog && env->exception_callback_subprog)
            dst = BPF_REG_1;

so after bpf_throw(), or after any cancellation in a scheduler that has an
exception callback, the op returns a value the program chose.
pad_reports() returns true for every pad of subprog 0, including the
bpf_throw() site, so bpf_scx_cancelled() runs for these cases too.

A scheduler that uses bpf_throw() or bpf_assert() with a usable cookie or
a fallback exception callback kept running before this series, and is now
disabled.  Is that intended?  If so, could the comment and changelog say
that sched_ext deliberately treats bpf_throw() as fatal, rather than
giving the unreturned-value rationale?

Also, the exit message says "see its stderr stream", and the commit message
says "The stderr stream of the program says why the kernel cancelled it."
For bpf_throw() nothing is written to the program's BPF_STDERR stream,
since the verifier turns the call into a jump to the landing pad.  The
cookie passed to bpf_throw() is not in the exit message either.

Could the message say that the program may have called bpf_throw(), or
leave out the stream reference when there is nothing to read?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 02/73] bpf: Require CAP_PERFMON for unwind_exit and unwind_goto
  2026-12-01  4:38 ` [PATCH bpf-next v1 02/73] bpf: Require CAP_PERFMON for unwind_exit and unwind_goto Kumar Kartikeya Dwivedi
@ 2026-12-01  5:25   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:25 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 1428 bytes --]

> bpf: Require CAP_PERFMON for unwind_exit and unwind_goto

TL;DR: Nit only: the flow_drain() comment change in verifier.c is unrelated to
this commit, isn't in the commit message, and describes frame-leaving behavior
the function doesn't have yet. It may belong in an earlier patch.

> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c

[ ... ]

> @@ -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;

This isn't a bug, but should this comment change go with f1003a022189
("bpf: Let a state leave its frame at may_goto without an exit insn")?

The new comment is not mentioned in the commit message.  It also describes
leaving a frame "at a site", which flow_drain() does not do at this point:
every pushed state still goes through
bpf_flow_deliver(env, &elem->st, elem->insn_idx, ...).


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 51/73] bpf: Log why a call is a site and which functions cannot be cancelled
  2026-12-01  4:39 ` [PATCH bpf-next v1 51/73] bpf: Log why a call is a site and which functions cannot be cancelled Kumar Kartikeya Dwivedi
@ 2026-12-01  5:25   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:25 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3357 bytes --]

> bpf: Log why a call is a site and which functions cannot be cancelled

TL;DR: Verifier log may misreport why a bpf_rbtree_add comparator cannot
unwind, blaming a missing landing pad instead of the node's fields; the
BPF_STUCK_NO_PAD comment and commit message are inaccurate.

> diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
> --- a/include/linux/bpf_verifier.h
> +++ b/include/linux/bpf_verifier.h

[ ... ]

> +/* 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 */

Is this description accurate for every user of BPF_STUCK_NO_PAD?

subprog_cannot_unwind() is also called from check_kfunc_call() for the
comparator of bpf_rbtree_add, and that kfunc does have an unwind label:

static bool kfunc_has_cb_pad(u32 btf_id)
{
        return is_bpf_rbtree_add_kfunc(btf_id);
}

The comparator is marked there because the node type has fields with
destructors (or NMI-unsafe fields in a tracing program), not because a
label is missing.

With BPF_HAS_CB_PADS, a level 2 log then prints "func#C cannot unwind, the
call at N has no landing pad for it" for the bpf_rbtree_add call, which
points at the call instead of the node type.

Should the comment and the log text say that the helper or kfunc cannot
pass on a cancelled callback, or should the bpf_rbtree_add case get its own
stuck_by value?

[ ... ]

> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c

[ ... ]

> @@ -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;
>  }

subprog_cannot_unwind() always records BPF_STUCK_NO_PAD, and the commit
message says the resulting line means "the call hands the function to a
helper that has no unwind label for it".

That is only true for the push_callback_call() caller, which calls it when
!insn_has_cb_pad(insn).  The two callers in the is_bpf_rbtree_add_kfunc()
branch of check_kfunc_call() mark the comparator because dropping the node
would run field destructors (or NMI-unsafe code), even though
bpf_rbtree_add has an unwind label:

check_kfunc_call()
    if (is_bpf_rbtree_add_kfunc(meta.func_id)) {
        /* When the comparator unwinds, the kfunc drops the node at its
         * unwind label. ...
        err = subprog_cannot_unwind(env, meta.subprogno);

These calls run before push_callback_call() -> stuck_frame_calls(), so a
comparator that is not yet stuck gets BPF_STUCK_NO_PAD, and the log claims
a missing landing pad when the real reason is the node's fields.

Could this use a separate enum value for the rbtree_add cases, or wording
that does not claim a missing label?

[ ... ]


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 71/73] bpf: Let a struct_ops say what a cancelled program returns
  2026-12-01  4:39 ` [PATCH bpf-next v1 71/73] bpf: Let a struct_ops say what a cancelled program returns Kumar Kartikeya Dwivedi
@ 2026-12-01  5:25   ` bot+bpf-ci
  2026-12-01  5:47   ` sashiko-bot
  1 sibling, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:25 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3517 bytes --]

> bpf: Let a struct_ops say what a cancelled program returns

TL;DR: Commit message claim that a cancelled hid_bpf program returning 0
behaves as without a program looks inaccurate: hid-core may get a
half-rewritten descriptor or event. Fix the changelog, or return a negative
errno for hid_bpf?

> bpf: Let a struct_ops say what a cancelled program returns
>
> Currently a cancelled struct_ops program returns 0, or NULL for a pointer.
> The verifier chooses the value by the program type, and all struct_ops
> programs have one type. What 0 means is up to the member. For
> Qdisc_ops::enqueue() it is NET_XMIT_SUCCESS, so the sender is told that
> the packet is on its way. A cancelled enqueue() did not queue the packet,
> and its landing pad frees the packet if the program still holds it.
> Add a callback, ->cancelled_retval(), to struct bpf_struct_ops. The
> verifier calls it at load time with the program, and the callback returns
> the value for the member that the program is attached to, or 0. The value
> becomes a constant in the program, so it must depend on nothing but the
> member.
> The verifier does not run check_return_code() on the value. So it asks
> only about a member that returns an integer, for which every value is
> accepted. A member that returns nothing or a pointer keeps 0, and so does
> a struct_ops without the callback.
> Implement the callback for bpf_qdisc:
>   enqueue()   NET_XMIT_DROP
>   init()      -ECANCELED. With 0, qdisc_create() would attach a qdisc
>               whose init() was cancelled halfway. With the error it calls
>               destroy() and frees the qdisc, as for any init() that fails.
> The other struct_ops in the tree keep 0 for every member:
> - For hid_bpf, 0 lets hid-core handle the event or the request as it does
>   without a program.
> - bpf_tcp_ops, smc_hs_ctrl and io_uring have no member that returns an
>   errno.
> [ ... ]

The commit message says that for hid_bpf, 0 lets hid-core handle the event
or the request as it does without a program. Is that accurate for
hid_bpf_ops::hid_rdesc_fixup()?

call_hid_bpf_rdesc_fixup() in drivers/hid/bpf/hid_bpf_dispatch.c copies the
descriptor into ctx_kern.data, which the program rewrites in place, and then
does:

    ret = hdev->bpf.rdesc_ops->hid_rdesc_fixup(&ctx_kern.ctx);
    if (ret < 0)
        goto ignore_bpf;
    ...
    return krealloc(ctx_kern.data, *size, GFP_KERNEL);
  ignore_bpf:
    kfree(ctx_kern.data);
    return rdesc;

If a cancelled rdesc_fixup returns 0, for example from a bpf_for() loop that
ran out of time halfway through rewriting the buffer, hid-core receives the
half-rewritten copy as the report descriptor.

A negative value such as -ECANCELED would take the ignore_bpf path and keep
the original descriptor, which is what happens without a program. This is
the same kind of case that this patch fixes for Qdisc_ops::init().

hid_device_event() looks similar: with 0, hid-core processes the program's
partly modified copy of the event (ctx_kern.data) rather than the original
data.

This patch does not change hid behaviour, and no later commit in the series
adds a hid_bpf callback. Could the changelog state this correctly?
Alternatively, should hid_bpf return a negative errno from a cancelled
hid_rdesc_fixup()?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 60/73] bpf: Don't let hidden stack words turn on the private stack
  2026-12-01  4:39 ` [PATCH bpf-next v1 60/73] bpf: Don't let hidden stack words turn on the private stack Kumar Kartikeya Dwivedi
@ 2026-12-01  5:25   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:25 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3408 bytes --]

> bpf: Don't let hidden stack words turn on the private stack

TL;DR: Excluding hidden words from the private-stack decision may move small
frames to the kernel stack, so a deep subprog chain that loaded before could
now fail with -EINVAL; the changelog says placement is unchanged.

> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c

[ ... ]

> @@ -6392,14 +6403,17 @@ static int check_max_stack_depth(struct bpf_verifier_env *env)
>  			continue;
>  		}
>  		/*
>  		 * Request private stack support only if the subprog stack
>  		 * depth is no less than BPF_PRIV_STACK_MIN_SIZE. This is to
>  		 * avoid jit penalty if the stack usage is small.
> +		 * Only the stack that the insns of the program use counts: the hidden words of
> +		 * the landing pads must not make a small function pay for a private stack.
>  		 */
> -		if (round_up_stack_depth(env, si[s].stack_depth) >= BPF_PRIV_STACK_MIN_SIZE) {
> +		if (round_up_stack_depth(env, bpf_stack_depth_of_prog(&si[s])) >=
> +		    BPF_PRIV_STACK_MIN_SIZE) {
>  			si[s].priv_stack_mode = PRIV_STACK_ADAPTIVE;
>  			env->prog->aux->jits_use_priv_stack = true;
>  		}

This changes which frames count against the combined kernel stack limit,
so a program that loaded before this patch can now be rejected.

A PRIV_STACK_ADAPTIVE subprog is left out of the chain sum, because
subprog_stack_size() returns only its outgoing args:

    if (sub->priv_stack_mode == PRIV_STACK_ADAPTIVE)
        return args;
    return round_up_stack_depth(env, sub->stack_depth + args);

Before the patch, hidden words that took a frame to 64 bytes or more gave
it a private stack, which removed the whole frame from the sum that
check_call_depth() compares with env->stack_limit.

After the patch, a frame whose program stack rounds below 64 stays on the
kernel stack, and adds stack_depth (hidden words included) to the chain.

bpf_hidden_slots_fit() runs this same check_max_stack_depth() as a trial
via try_max_stack_depth(env, true).  If the trial now fails while the
check without hidden words passes, take_value_word() returns
BPF_CONFLICT_NO_ROOM, plan_rejects() is true in bpf_pads_settle(), and the
load fails with -EINVAL ("no room in the stack for the value").

For example, take a tracing program on an arch with a private stack but
no large stack (riscv64, ppc64), so env->stack_limit = MAX_BPF_STACK =
512.  With a static chain of 9 subprogs, each with 48 bytes of program
stack and one hidden word:

    before: each frame is 56 bytes, rounds to 64, goes to the private
            stack, chain sum is about 0
    after:  each frame stays on the kernel stack at 64 bytes,
            9 * 64 = 576 > 512, so the hidden words do not fit
            (without them 9 * 48 = 432 fits)

The last paragraph of the commit message says "Where the hidden words are
kept does not change", but for every frame that loses its private stack
the hidden words move from the private stack to the kernel stack.

Could the changelog state this trade-off?  Or should a frame fall back to
the private stack when the hidden words do not fit in the kernel stack
chain?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 48/73] bpf: Find at a site that a frame holds more than a landing pad releases
  2026-12-01  4:39 ` [PATCH bpf-next v1 48/73] bpf: Find at a site that a frame holds more than a landing pad releases Kumar Kartikeya Dwivedi
@ 2026-12-01  5:25   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:25 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3212 bytes --]

> bpf: Find at a site that a frame holds more than a landing pad releases

TL;DR: The new early count in visit_refs() may reject programs that loaded
before: at call sites, the hand-over retry that would move a passed reference
into the callee is never tried, so loading fails with "too much is held".

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c

[ ... ]

> @@ -1269,8 +1278,9 @@ static int visit_refs(struct bpf_verifier_env *env, struct bpf_pad_plan *plan,
> +	/*
> +	 * 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;

Can this early count make a program fail to load that loaded before the
patch?

At a BPF_SITE_CALL plan (check_unwound_arrival()->unwind_frame()->
bpf_pad_visit()->visit_refs()), the caller frame's refs[] can include a
pointer P that the caller passed to a static subprog in R1 and kept no copy
of.  The callee releases P on its normal path, but it can unwind before that
release.

Before the patch, a state holding 8 located references plus P filled 8
entries, and P took the no-location branch (plan->no_place = err;
continue;).  settle_plan() then returned BPF_CONFLICT_NO_PLACE, which
conflict_of_ref() treats as a reference conflict, so note_causes() set
env->ref_conflict and sub[s].asks_args |= sub[s].releases_args.
try_more()->hand_over_more() then made the callee own the argument, and on
the next pass the caller held 8 at the call site, which fits.

With the patch, the same first-pass state gives pos = 9 > BPF_PAD_MAX_ENTS,
and visit_refs() returns BPF_CONFLICT_TOO_MUCH before the main loop.
conflict_of_ref() has no case for it:

	switch (plan->conflict) {
	case BPF_CONFLICT_NO_PLACE:
	...
	default:
		return false;

So note_causes() sets neither ref_conflict nor asks_args, try_more() returns
false because of !env->ref_conflict, and the load fails with "too much is
held".  The hand-over that would have brought the frame within the limit is
never tried.  The same applies to the takes_refs and handing back steps of
try_more(), which are also gated on ref_conflict.

The commit message says "If it is more than a landing pad releases, the
verifier cannot generate a pad for that state".  That holds for one pass,
but at a call site the count includes references that the hand-over passes
would move into the callee.

Could the early check skip BPF_SITE_CALL states where the excess is
references that bpf_pad_handed_ref() could hand over, or could
conflict_of_ref() return true for BPF_CONFLICT_TOO_MUCH when plan->no_place
is set?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 63/73] bpf: Reject a program whose cleanup pad a cancellation cannot enter
  2026-12-01  4:39 ` [PATCH bpf-next v1 63/73] bpf: Reject a program whose cleanup pad a cancellation cannot enter Kumar Kartikeya Dwivedi
@ 2026-12-01  5:25   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:25 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3843 bytes --]

> bpf: Reject a program whose cleanup pad a cancellation cannot enter

TL;DR:
- Comment and log text may misstate why a function lost hidden slots (e.g.
  callee returning with a lock); verifier log only
- Comment saying only rejected loads pay for the marks may be inaccurate; nit

> diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
> --- a/include/linux/bpf_verifier.h
> +++ b/include/linux/bpf_verifier.h

[ ... ]

> @@ -1708,8 +1718,13 @@ struct bpf_subprog_info {
>  	/* where it is cancelled or unwinds, callees included: bits by enum bpf_site_kind */
>  	u16 left_at;
>  	/* in this pass it cannot have hidden slots for these groups, bits by enum bpf_pad_group */
>  	u8 no_slots: 4;
> +	/*
> +	 * Of those, the groups that it lost because a state in a cleanup pad for a cancellation
> +	 * released something of a caller. For the log, see bpf_pad_log().
> +	 */
> +	u8 no_slots_cleanup_pad: 4;

Does this comment match what sub_no_slots() records?

The writer sets the bit for any reason, not only for a release of a caller:

static void sub_no_slots(struct bpf_subprog_info *sub, const struct bpf_verifier_state *st,
			 u8 groups)
{
	sub->no_slots |= groups;
	if (state_is_in_cleanup_pad(st))
		sub->no_slots_cleanup_pad |= groups;
}

Some callers in bpf_pad_note_return() are about what the callee acquired:

	sub_no_slots(sub, st, BIT(BPF_PAD_GROUP_LOCKS)); /* callee returns holding a lock */

A cancelled frame's cleanup pad can call a static subprog that returns
holding a bpf_res_spin_lock.  In that case nr_locks reaches sub_no_slots()
with state_is_in_cleanup_pad(st) true, so no_slots_cleanup_pad gets LOCKS
although nothing of a caller was released.

print_cleanup_pad_conflict() then prints "what its code releases of a
caller may keep func#%d from getting hidden slots", and the stated reason
is wrong for that case.

Should the recording be limited to the release paths, or should the comment
and the log line say "what its code did"?  Only the verifier log is
affected, not acceptance or rejection.

[ ... ]

> @@ -3976,7 +4288,9 @@ static bool insn_returns(const struct bpf_insn *insn)
 [ ... ]

>   * The pass has an error, and a cancellation entered a cleanup pad in it: a state went through the
>   * entry of a call, see bpf_pad_enter(). That may be so only because two calls are verified
>   * together, like the calls of count() above with a cleanup pad after them. The error can then be
>   * anywhere, and the pass that keeps the two calls apart has none. So after a pass with any error,
>   * mark every function in which a state entered a cleanup pad, for note_causes_below(). No verdict
>   * rests on the marks. Only a load that is rejected pays for them, in load time.
>   */
>  static void note_entered(struct bpf_verifier_env *env)

Is "Only a load that is rejected pays for them" accurate?

note_entered() runs from bpf_pads_note_causes() after any pass with an
error, and check_pass() does:

	if (ret && env->err)
		bpf_pads_note_causes(env);

Say pass 0 fails on a conflict at a site in function G that has nothing to
do with cleanup pads, while a cancellation entered a cleanup pad in
function F without a conflict.  note_entered() marks F, so pass 1 also
keeps apart the jumps around F's calls and the loops below them.  If pass 1
has no error, do_check_all() accepts the load, which has still paid for the
marks.

The count() case described in the same comment also has the accepted load
paying for the extra pass.  Would something like "Only a load that has a
pass with an error pays for them, in load time" be closer to the code?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 26/73] bpf: Use hidden slots for a pointer that has no location at a site
  2026-12-01  4:38 ` [PATCH bpf-next v1 26/73] bpf: Use hidden slots for a pointer that has no location at a site Kumar Kartikeya Dwivedi
@ 2026-12-01  5:25   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:25 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 1303 bytes --]

> bpf: Use hidden slots for a pointer that has no location at a site

TL;DR: Nit only: the new no_place field in struct bpf_pad_plan could use a
short comment saying what it holds. No functional problem is reported.

> diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
> --- a/include/linux/bpf_verifier.h
> +++ b/include/linux/bpf_verifier.h
> @@ -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;

This isn't a bug, but could no_place get a short comment like the one on
'conflict', saying that it holds the enum bpf_pad_conflict that
settle_plan() reports unless hidden slots hold the pointer?

visit_refs() stores it, plan_take_slots() clears it, and settle_plan()
returns it as the error reason, so a reader currently has to read all
three functions to learn what it holds.


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 39/73] bpf: Refuse freplace on a function that can unwind
  2026-12-01  4:39 ` [PATCH bpf-next v1 39/73] bpf: Refuse freplace on a function that can unwind Kumar Kartikeya Dwivedi
@ 2026-12-01  5:25   ` bot+bpf-ci
  2026-12-01  5:51   ` sashiko-bot
  1 sibling, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:25 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3014 bytes --]

> bpf: Refuse freplace on a function that can unwind

TL;DR: Marking the main program as can_unwind may make settle_late_unwinds()
trigger a needless extra verification pass, possibly doubling verification
cost and hitting the cost limit on large programs.

> diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
> --- a/kernel/bpf/fixups.c
> +++ b/kernel/bpf/fixups.c

[ ... ]

> @@ -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;

The added comment says the main program is marked only for
bpf_check_attach_target(), but bpf_mark_subprogs_that_unwind() is also called
during every verification pass, from settle_late_unwinds() and
mark_used_sites().

Can this change the restart decision in settle_late_unwinds()?

    bpf_mark_subprogs_that_unwind(env);
    for (s = 0; s < env->subprog_cnt; s++, sub++) {
        unwinds = sub->can_unwind;
        sub->can_unwind = initial->subprogs[s].can_unwind;
        late |= unwinds && !initial->subprogs[s].did_unwind &&
                bpf_subprog_is_global(env, s);
        sub->did_unwind = unwinds;
    }
    ...
    env->pads_late = late;

Before this patch subprog 0 was skipped, so its can_unwind never changed
here.  Now it is set whenever the main program keeps a site (a loop that
needs may_goto, an arena access that can fault, a used call site).

initial->subprogs[0].did_unwind is never updated, since check_funcs() copies
did_unwind into @initial only for i >= 1, and the main program is a global
subprog, so bpf_subprog_is_global(env, 0) is true.  That makes late true and
leaves env->pads_late set even when no global subprog unwinds late.

For example, take a global main with a "while (!ready)" loop that calls a
global subprog g() which has a loop with a trip count.  In pass 0 g() takes
its guard edge and unwinds in-pass, which sets env->pads_late.  At the end
of the pass bpf_flow_drop_guards() drops g()'s guard and g() no longer
can_unwind.  Before the patch late was false and the pass was accepted.  Now
main has loop_guard set, so late is true, pass_needs_restart() is true and
do_check_all() runs another full pass.

env->cost and env->insn_processed accumulate across passes, so this doubles
the verification work for such programs and raises the reported
verified_insns.  Could a large program that fit in one pass now hit "the
limit on cost or memory ended pass N"?

Would skipping s == 0 in settle_late_unwinds(), or marking subprog 0 only in
bpf_insert_sites(), avoid this?  The issue does not appear to be fixed later
in the series.


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 58/73] bpf: Check that a helper whose callback may unwind has an unwind label
  2026-12-01  4:39 ` [PATCH bpf-next v1 58/73] bpf: Check that a helper whose callback may unwind has an unwind label Kumar Kartikeya Dwivedi
@ 2026-12-01  5:26   ` bot+bpf-ci
  2026-12-01  5:47   ` sashiko-bot
  1 sibling, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:26 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 2545 bytes --]

> bpf: Check that a helper whose callback may unwind has an unwind label

TL;DR: Commit message only: the quoted "verifier bug" log line omits the
appended condition suffix and the possible WARN_ONCE splat.

>     bpf: Check that a helper whose callback may unwind has an unwind label
>
>     Currently the verifier knows which helpers and kfuncs have an unwind
>     label from two lists that are kept by hand, helper_has_cb_pad() and
>     kfunc_has_cb_pad(), and it takes every map_for_each_callback() op to have
>     one. Nothing checks the lists against the functions.
>     A function that is in a list and has no unwind label is not noticed at
>     run time. unwind_exit or cancel_exit of its callback looks up a return
>     address in the text of the kernel and finds no exception table entry.
>     That is no error for the lookup, because a frame that the kernel called,
>     such as an async callback, has no entry either. So the callback returns
>     to its helper as if it had not unwound, the program continues, and
>     nothing warns.
>     Check when a program is loaded. Where the lists say that a call has an
>     unwind label, check_cb_pad() looks for an exception table entry of
>     bpf_call_cb() in the function that is called: the helper, the kfunc, and
>     for bpf_for_each_map_elem() also the op of the map. If there is none, the
>     load fails with a verifier bug. If bpf_find_vma() lost its label, the
>     message would be:
>       verifier bug: bpf_find_vma has no landing pad for its callback
>     The message says "landing pad" where it means the unwind label.
>     [ ... ]
>     Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>

The commit message quotes the log line for a missing unwind label as:

  verifier bug: bpf_find_vma has no landing pad for its callback

check_cb_pad() reports through verifier_bug_if(), which appends the
stringified condition to the format:

  verifier_bug(env, fmt " (" #cond ")", ##args);

so the printed line would be:

  verifier bug: bpf_find_vma has no landing pad for its callback (!func_has_cb_pad(addr))

verifier_bug() also goes through BPF_WARN_ONCE(), which is WARN_ONCE() under
CONFIG_DEBUG_KERNEL.

Should the quoted message include the " (!func_has_cb_pad(addr))" suffix,
and mention the warning splat?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 23/73] bpf: Record why a callee is cancelled when its call gets no landing pad
  2026-12-01  4:38 ` [PATCH bpf-next v1 23/73] bpf: Record why a callee is cancelled when its call gets no landing pad Kumar Kartikeya Dwivedi
@ 2026-12-01  5:26   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:26 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3732 bytes --]

> bpf: Record why a callee is cancelled when its call gets no landing pad

TL;DR:
- bpf_pads_note_causes() may print a misleading "BPF program is too complex"
  line after the real verifier error, or twice
- Comments describe code not yet in this commit

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c

[ ... ]

> +/*
> + * Record the causes of the errors of the pass in the functions that note_causes() and
> + * note_entered() marked, and in the functions that were cancelled below them: the calls, accesses
> + * to arena and may_gotos of the program at which a function is cancelled, and the conditional jumps
> + * that leave a loop which has a may_goto of the verifier. One walk serves all errors.
> + */
> +static void note_causes_below(struct bpf_verifier_env *env)

This isn't a bug, but this comment describes code that is not in this
commit.  note_entered() is not defined at this point in the series, and the
walk only looks at call plans:

    if (below->kind != BPF_SITE_CALL || !below->visited)
            continue;

enum bpf_site_kind has only BPF_SITE_GUARD, BPF_SITE_RECURSION and
BPF_SITE_CALL here, so there are no accesses to arena or may_gotos of the
program to record.

The comment of bpf_note_controlled_cause() in kernel/bpf/precision.c has
the same problem.  It lists "an access that faults" as a use, but its only
caller passes call insns.

Can the comments describe what this commit does, and be extended when
note_entered() and the arena and may_goto sites arrive?

[ ... ]

> +void bpf_pads_note_causes(struct bpf_verifier_env *env)
> +{

[ ... ]

> +	note_causes_below(env);
> +	/* The caller checks the limits before the next pass. This is for a load that ends here. */
> +	bpf_check_limits(env);
> +}

Can this unconditional bpf_check_limits() print a misleading "BPF program
is too complex" line after the real error?

The first error of a pass goes through note_error(), which sets
env->log.level = 0 and cuts env->pass_max_cost.  If the rest of the pass
costs more than that, an in-pass bpf_check_limits() sets env->over_limit
= true, and its verbose() prints nothing because the log level is 0.

check_funcs() then restores the log level and resets pass_max_cost:

    env->log.level = level;
    env->pass_max_cost = U64_MAX;
    return ret == -EINTR ? ret : env->err ?: ret;

check_pass() sees ret && env->err and calls bpf_pads_note_causes(), and
bpf_check_limits() finds over_limit still set:

    if (env->cost <= min(env->max_cost, env->pass_max_cost) && env->mem <= env->max_mem &&
        !env->over_limit)
            return 0;
    verbose(env, "BPF program is too complex: cost %llu of %llu, memory %llu of %llu\n", ...);

This now prints at the user's log level, and it prints max_cost as the
limit, which can be well above the reported cost.  Before this patch
nothing printed after check_funcs() returned in this case, and
do_check_all() deliberately leaves out its own limit message when env->err
is set.

The same call also prints the message a second time when
bpf_pads_settle() already went over the limit on the after-pass path.

The next pass, bpf_partition_more() and find_calls_to_unproven() already
check the limits.  Could the call be dropped, or made only when this walk
pushes the cost over the limit while env->over_limit is still clear?  This
is not changed later in the series: bpf_pads_note_causes() at c916df4614a0
still ends with the same bpf_check_limits() call.


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 68/73] bpf: End the path at a call of a global subprog that never returns
  2026-12-01  4:39 ` [PATCH bpf-next v1 68/73] bpf: End the path at a call of a global subprog that never returns Kumar Kartikeya Dwivedi
@ 2026-12-01  5:26   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:26 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 2830 bytes --]

> bpf: End the path at a call of a global subprog that never returns

TL;DR: Nits only: the "callee never returns" check is open-coded in three or
four places with different spellings; the review suggests a shared helper (and
using callee_subprog() in liveness.c) so they cannot drift apart.

> diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
> --- a/kernel/bpf/fixups.c
> +++ b/kernel/bpf/fixups.c

[ ... ]

> +		traps = calls && !env->bypass_spec_v1;
> +		if (calls && !traps && bpf_pseudo_call(insn)) {
> +			callee = bpf_find_subprog(env, i + insn->imm + 1);
> +			traps = callee >= 0 && !env->subprog_info[callee].might_return;
> +		}

This isn't a bug, but the test "this pseudo call calls a subprog that does
not return" is open-coded here, in behind_call_without_return() and in
find_pad_code(), each time with a differently spelled call target
(i + insn->imm + 1, idx + insns[idx - 1].imm, i + 1 + insn->imm).

Could a small helper that takes the index of the call and says whether its
callee does not return replace these copies, so the three edges cannot
drift apart?

[ ... ]

> diff --git a/kernel/bpf/liveness.c b/kernel/bpf/liveness.c
> --- a/kernel/bpf/liveness.c
> +++ b/kernel/bpf/liveness.c

[ ... ]

> +static bool behind_call_without_return(struct bpf_verifier_env *env, int idx)
> +{
> +	const struct bpf_insn *insns = env->prog->insnsi;
> +	int callee;
> +
> +	if (!idx || !bpf_pseudo_call(&insns[idx - 1]) || bpf_is_unwind_goto(&insns[idx]) ||
> +	    bpf_is_jump_target(env, idx))
> +		return false;
> +	callee = bpf_find_subprog(env, idx + insns[idx - 1].imm);
> +	return callee >= 0 && !env->subprog_info[callee].might_return;
> +}

This isn't a bug, but liveness.c already has callee_subprog() for looking
up the callee of a call.  Could behind_call_without_return() use it
instead of computing the target by hand?

[ ... ]

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c

[ ... ]

> @@ -4801,6 +4793,15 @@ static int find_pad_code(struct bpf_verifier_env *env)
>  			insn = &insns[i];
> +			s = bpf_pseudo_call(insn) ? bpf_find_subprog(env, i + 1 + insn->imm) : -1;
> +			if (s >= 0 && !env->subprog_info[s].might_return) {
> +				/* the callee does not return: only its landing pad follows */

This isn't a bug, but this is the third (and with subprog_might_return()
in cfg.c, the fourth) spelling of the same check on a call edge.  Would a
shared helper, something like bpf_call_returns(env, idx) in the spirit of
may_not_return() for might_throw in precision.c, keep these checks
consistent?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 69/73] bpf: Tell struct_ops when a program was cancelled
  2026-12-01  4:39 ` [PATCH bpf-next v1 69/73] bpf: Tell struct_ops when a program was cancelled Kumar Kartikeya Dwivedi
@ 2026-12-01  5:26   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:26 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3282 bytes --]

> bpf: Tell struct_ops when a program was cancelled

TL;DR:
- The ->cancelled() doc may be inaccurate: with an exception callback, program
  code chooses the returned value after the call, which could mislead
  struct_ops authors
- Commit message example names st_ops->unwound(), not ->cancelled() (nit)

>     bpf: Tell struct_ops when a program was cancelled
>
>     [ ... ]
>     Add a callback, ->cancelled(), to struct bpf_struct_ops. In a program of a
>     struct_ops that sets it, the landing pad that returns to the kernel calls
>     it after all frames have released what they held:
>
>       pad: r1 = r6
>            call bpf_task_release
>       +    r1 = prog->aux
>       +    call bpf_prog_report_cancelled    <- calls st_ops->unwound(prog)
>            r0 = 0
>            exit

This isn't a bug, but the example says bpf_prog_report_cancelled() "calls
st_ops->unwound(prog)".  The patch adds no ->unwound() member, and
bpf_prog_report_cancelled() calls aux->st_ops->cancelled(aux->prog).  Should
this read st_ops->cancelled(prog), to match the "->cancelled()" name used
elsewhere in the message?

> diff --git a/include/linux/bpf.h b/include/linux/bpf.h
> --- a/include/linux/bpf.h
> +++ b/include/linux/bpf.h

[ ... ]

> @@ -2297,6 +2297,18 @@ struct btf_member;
> + * @cancelled: A callback that is invoked when an invocation of a program of
> + *	       this struct_ops, an op or an async callback of one, was unwound
> + *	       up to the kernel, before the invocation returns. No path of the
> + *	       program chose what it returns then: it is 0, NULL for a pointer,
> + *	       or what bpf_throw() was passed. A struct_ops that cannot take

Is this description of the return value accurate when the program has an
exception callback?

In the main program, bpf_pad_insns() emits the call of
bpf_prog_report_cancelled(), and emit_pad() then appends the call of the
exception callback:

    n += bpf_pad_insns(env, plan, s, buf + n, aux + n);
    if (!s && cb) {
        ...
        buf[n++] = BPF_CALL_REL(0);    /* call exception_cb */

The op then returns the exception callback's R0.  For a struct_ops member
returning an integer, check_return_code() accepts any value from it, and the
comment of bpf_cancelled_retval() says "If the program has an exception
callback, the callback gets the value and chooses what the program returns."

So ->cancelled() can be called for an invocation whose result is chosen by
program code after the callback ran.  The same applies to the BPF_SITE_CALL
pad of the main program, which pad_reports() also reports: with bpf_throw()
in the program, the pad returns the R0 that the callee chose.

A struct_ops that relies on this text to treat the result of the op as
meaningless could be wrong.  Could the doc mention that the exception
callback, which runs after ->cancelled(), chooses the returned value?  The
rewrite of this text later in the series (9fda643a105f, "bpf: Let a
struct_ops say what a cancelled program returns") still does not cover the
exception callback case.


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 50/73] bpf: Reject a program that has no landing pad for a fault in arena
  2026-12-01  4:39 ` [PATCH bpf-next v1 50/73] bpf: Reject a program that has no landing pad for a fault in arena Kumar Kartikeya Dwivedi
@ 2026-12-01  5:26   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:26 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 5001 bytes --]

> bpf: Reject a program that has no landing pad for a fault in arena

TL;DR: Nits only: three code comments in the arena landing-pad patch look
inaccurate or incomplete (the "faulted access not verified" claim, a dropped
kfunc case, the bail_unwinds restart description). No functional bug is
reported.

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c

[ ... ]

> /*
> + * Is the conflict of @plan an error? It is one at every site: a prog that goes on from a loop that
> + * was out of time, or from an access that faulted, was not verified. But not where the frame cannot
> + * unwind and the site has another way out, see bpf_pad_must_unwind(): what comes back to a call
> + * there is stuck, see bpf_pad_skip_faults().
>   */
>  static bool plan_rejects(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan)
>  {
> +	return plan->conflict && (bpf_pad_must_unwind(env, plan) || !plan_is_stuck(plan));
>  }

This isn't a bug, but is the claim that a prog that goes on "from an access
that faulted, was not verified" accurate?

In a function that can be cancelled, check_arena_site() pushes the cancelled
copy of the state with push_unwind_edge() and the normal path goes on
through the access:

    frame->fault_edge = true;
    return push_unwind_edge(env, BPF_SITE_FAULT);

On that normal path check_mem_access() leaves the destination of an arena
load unknown:

    } else if (reg->type == PTR_TO_ARENA) {
        if (t == BPF_READ && value_regno >= 0)
            mark_reg_unknown(env, regs, value_regno);

So a skipped fault (load reads 0, store not done) is an execution that the
main pass already verified.  bpf_pad_must_unwind() itself says the access
can be skipped when it faults, and check_arena_site() keeps the skip as the
fallback for stuck functions and JITs without unwind_exit.

The statement holds for may_goto of the program, where check_may_goto_site()
returns 1 and no state takes the jump.  For faults the reason given in the
commit message is that "a program that loads does not tell which of its
faults end it".  Could the comment say that instead?

> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c

[ ... ]

>  /*
> + * The current frame calls @subprog, with a call, callx or a helper that has an unwind label. If the
> + * frame cannot be cancelled, or its function is 'stuck' and has a caller in the program, a
> + * cancellation of @subprog would have nowhere to go. So mark @subprog 'stuck' too, see
> + * check_may_goto_site(). If a state has left @subprog before, or a frame of @subprog has made a
> + * call before, the pass is repeated with the mark set from its start.
>   */
>  static void stuck_frame_calls(struct bpf_verifier_env *env, int subprog)

This isn't a bug, but the old comment listed "a call, callx, a helper or a
kfunc that has a landing pad for its callback", and the new one drops the
kfunc.

push_callback_call() is reached from check_kfunc_call() as well as
check_helper_call(), and it calls stuck_frame_calls(env, subprog)
unconditionally, before the insn_has_cb_pad() test:

    stuck_frame_calls(env, subprog);
    ...
    if (!insn_has_cb_pad(insn)) {
        err = subprog_cannot_unwind(env, subprog);

That covers the bpf_rbtree_add kfunc, which has an unwind label through
kfunc_has_cb_pad().  Could the comment say "a helper or a kfunc" again, and
mention that the call is made whether or not the helper has an unwind label?

[ ... ]

>  		/*
> +		 * A repeated run starts with bail_unwinds as subprog_cannot_unwind() left it. Any
> +		 * other run starts from the first value: it may not get to the call that clears it.
>  		 */
>  		if (!env->pass_again)
>  			initial->subprogs[i].bail_unwinds =
>  				initial->subprogs[i].bail_unwinds_at_first;
>  		else if (env->faults_late)
>  			initial->subprogs[i].bail_unwinds &= env->subprog_info[i].bail_unwinds;

This isn't a bug, but the comment says a repeated run starts with
bail_unwinds as subprog_cannot_unwind() left it, while the code carries the
value over only when env->faults_late is set.

do_check_all() also repeats a pass through pass_needs_restart() for
env->restart with bpf_flow_loops_lost_bound(), env->guards_late and
env->pads_late.  In that case pass_again is true, faults_late is false, and
the snapshot keeps its old value.  For example push_callback_call() ->
subprog_cannot_unwind() sets sub->bail_unwinds = false for a callback
without a callback pad without setting faults_late, and a pass repeated for
a loop or guard reason then starts with bail_unwinds == true again.

The value is cleared again at the call, so nothing breaks, but could the
comment say that the value is carried only when the pass is repeated
because of faults_late, and why other repeats may start from the snapshot
value?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 53/73] bpf: Give the unwind label of a helper a second way in
  2026-12-01  4:39 ` [PATCH bpf-next v1 53/73] bpf: Give the unwind label of a helper a second way in Kumar Kartikeya Dwivedi
@ 2026-12-01  5:26   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:26 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 2984 bytes --]

> bpf: Give the unwind label of a helper a second way in

TL;DR: On x86, the new unwind stub's nop may let an optimized kprobe on the
preceding function's tail corrupt the return target, executing garbage. Fixed
later in the series; please fold the fix in for bisectability.

> diff --git a/include/linux/bpf_unwind.h b/include/linux/bpf_unwind.h
> --- a/include/linux/bpf_unwind.h
> +++ b/include/linux/bpf_unwind.h

[ ... ]

> @@ -99,13 +117,21 @@ do {
>  	asm_goto_output(BPF_KCFI_CHECK(type)					\
>  		 "	" CALL_NOSPEC "\n"					\
>  		 "1:\n"								\
> -		 _ASM_EXTABLE_TYPE(1b, %l[unwound], EX_TYPE_BPF)		\
> +		 "	.subsection 1\n"					\
> +		 "4:	nop\n"							\
> +		 "	clc\n"							\
> +		 "	.byte 0x73, 0x01\n"	/* jnc 6f */			\
> +		 "5:	stc\n"							\
> +		 "6:	sbb %%ecx, %%ecx\n"					\
> +		 "	jmp %l[" __stringify(unwound) "]\n"			\
> +		 "	.previous\n"						\
> +		 _ASM_EXTABLE_TYPE(1b, 4b, EX_TYPE_BPF)				\

In this commit the x86 bpf_unwind_target() is unchanged and still returns
'(unsigned long)&e->fixup + e->fixup', which is now stub+0, the nop.  The
commit message says so: "the lookup of both JITs still returns the start of
the stub, which runs into the first entry point."

Since x86 does not select LD_DEAD_CODE_DATA_ELIMINATION, the subsection 1
stubs of a translation unit land after the last function in that unit's
.text, with no symbol covering them.  kallsyms then counts the stubs as
part of that last function, which need not be on the kprobe blacklist.

Can an optimized kprobe on the tail of that function cover the stub's nop?
can_optimize() looks only for extable keys and jumps into the range, so it
cannot see a ret target such as the stub entry, and nop and ret are both
boostable in can_boost().

For example, if the tail is 'pop %rbx; pop %r12; ret' (4 bytes), a probe at
'pop %rbx' copies those 4 bytes plus the stub's nop.  The 5-byte jmp then
covers stub+0.  A callback that leaves bpf_loop() or
bpf_for_each_map_elem() through unwind_exit would return into the last byte
of the jmp's rel32 and execute garbage.  Before this commit the target was
a label inside the helper, which is notrace/NOKPROBE.

The same intermediate state also contradicts the rule documented at
BPF_CB_PAD_OFF, "A stack walk looks up the insn before a return address ...
that has to be an insn of the stub", because stub+0-1 is outside the stub.

This is fixed later in the series by 6d04b6a4d90c ("bpf, x86: Return to
cancel_goto at cancel_exit"), which changes the nop to int3 and makes the
lookup add BPF_CB_PAD_OFF/BPF_CB_CANCEL_OFF.  Could those two changes be
folded into this commit so it is safe to bisect on x86?  Otherwise, could
the old in-function target be kept until the JIT lookup honours
BPF_CB_PAD_OFF?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 31/73] bpf: Give a callee a hidden slot for the reference that it is handed
  2026-12-01  4:38 ` [PATCH bpf-next v1 31/73] bpf: Give a callee a hidden slot for the reference that it is handed Kumar Kartikeya Dwivedi
@ 2026-12-01  5:26   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:26 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 2191 bytes --]

> bpf: Give a callee a hidden slot for the reference that it is handed

TL;DR: Documentation only: verifier.rst paragraphs may now contradict each
other, and the claims that a hand-over stores nothing at run time may no
longer hold for callees that get a hidden slot.

> diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
> --- a/Documentation/bpf/verifier.rst
> +++ b/Documentation/bpf/verifier.rst

[ ... ]

> @@ -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.

This isn't a bug, but the paragraph just above this hunk, which is not
changed, still says:

  The program is still rejected if the callee has no location for the
  pointer at one of its sites

After this patch that rejection only happens when the callee is entered
somewhere with nothing to hand over.  In the other cases the entry slot is
where the landing pad reads the pointer.  Do the two paragraphs now
contradict each other?

Also, the text before it says "The landing pad of the call releases nothing,
and nothing is added at run time", and the "All passes" description says
the hand-over stores nothing.  Both now hold only for a callee that needs no
hidden slots, since the other kind runs a store at its entry.  Could the
first clause be limited to a callee that gets no hidden slots, that is, one
entered as a callback, on its own, or with a pointer the caller does not
hold?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 24/73] bpf: Record what each call acquires and releases
  2026-12-01  4:38 ` [PATCH bpf-next v1 24/73] bpf: Record what each call acquires and releases Kumar Kartikeya Dwivedi
@ 2026-12-01  5:31   ` sashiko-bot
  0 siblings, 0 replies; 115+ messages in thread
From: sashiko-bot @ 2026-12-01  5:31 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, bpf

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] bpf: under-counted note->held on NULL return in
  bpf_pad_note_return()
--

commit 8812639e48841c61905030b2e860b98938bc3bc3
Author: Kumar Kartikeya Dwivedi <memxor@gmail.com>

bpf: Record what each call acquires and releases

This commit records in struct bpf_pad_note what each call instruction
acquires or releases during the main verification pass, preparing for
hidden stack slots that landing pads will use to release resources.

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> index 5c0973e2e2411..657f17f2aaabb 100644
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c
[ ... ]
> @@ -1144,6 +1155,278 @@ struct bpf_pad_plan *bpf_pad_visit(struct bpf_verifier_env *env,
[ ... ]
> +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)
> +{
> +	const struct bpf_func_state *callee = st->frame[st->curframe];
> +	const struct bpf_reference_state *ref = &st->refs[callee->entry_refs];
> +	struct bpf_subprog_info *sub = &env->subprog_info[caller->subprogno];
> +	struct bpf_insn_aux_data *aux = &env->insn_aux_data[call_idx];
> +	const struct bpf_reg_state *r0 = &callee->regs[BPF_REG_0];
> +	int i, nr = st->acquired_refs - callee->entry_refs, in_r0 = 0;
> +	struct bpf_pad_place place;
> +	struct bpf_pad_ent ent;
> +
> +	for (i = 0; i < BPF_PAD_NR_SECTIONS; i++)
> +		if (frame_sections(st, i))
> +			sub->no_slots |= BIT(i);
> +	if (plain && nr == 1 && ref->type == REF_TYPE_PTR && !ref->parent_id)
> +		add_ref_cand(&place, &in_r0, r0, ref, BPF_PLACE_REG, BPF_REG_0);
> +	if (in_r0 && slot_ent(env, &ent, st, ref, r0, true) &&
> +	    can_release_under_lock(env, st, caller, &ent)) {
> +		note_acquire(env, sub, call_idx, &ent, BPF_REG_0,
> +			     count_refs(st, caller->entry_refs, callee->entry_refs,
> +					BPF_PAD_GROUP_REFS));
> +	} else {
> +		for (i = 0; i < nr; i++)
> +			sub->no_slots |= BIT(class_group(ref_class(&ref[i])));\
> +		aux->call_brings_nothing |= plain && !reg_is_null(r0);
> +	}
> +	if (aux->call_brings_nothing && aux->pad_note && aux->pad_note->acquires)
> +		sub->no_slots |= BIT(BPF_PAD_GROUP_REFS);
> +}

[Severity: Medium]
Can bpf_pad_note_return() leave aux->pad_note->held under-counted when a
subprogram returns NULL (nr == 0 and reg_is_null(r0)) while the caller
already holds references of BPF_PAD_GROUP_REFS?

When a subprogram called in a loop acquires and returns a reference on
trip 0 (while the caller holds 0 references) and returns NULL on a later
trip (while the caller still holds the reference from trip 0), the NULL
return takes the else branch with aux->call_brings_nothing remaining false
and never updates aux->pad_note->held with the caller's held count (or
checks it against BPF_PAD_MAX_ENTS).  Once hidden slots are wired up in
commit "bpf: Add hidden stack slots for landing pads", the call is given
only 1 + note->held = 1 slot with an unconditional store of R0, so the
NULL return overwrites the active pointer in that slot with 0 and a
subsequent landing pad leaks the reference.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1796099737.git.memxor@gmail.com?part=24

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 25/73] bpf: Add hidden stack slots for landing pads
  2026-12-01  4:38 ` [PATCH bpf-next v1 25/73] bpf: Add hidden stack slots for landing pads Kumar Kartikeya Dwivedi
@ 2026-12-01  5:40   ` sashiko-bot
  2026-12-01  5:42   ` bot+bpf-ci
  1 sibling, 0 replies; 115+ messages in thread
From: sashiko-bot @ 2026-12-01  5:40 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, bpf

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] bpf: wrong release register in bpf_pad_note_release() clears
  wrong slot
--

commit 9104e9a3b93e493a258c21287cd7baded3ef930f
Author: Kumar Kartikeya Dwivedi <memxor@gmail.com>

bpf: Add hidden stack slots for landing pads

This commit adds hidden stack slots below a function's stack frame to track
held resources at run time when landing pads cannot determine from the PC
or a NULL check whether a resource is held.

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> index 657f17f2aaabb..a9a2b56364abe 100644
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c
[ ... ]
> +/*
> + * The call of @rel releases: the slot of the group that has the handle is cleared, whichever call
> + * filled it in this run. The first match ends the search: two references to one object are the
> + * same handle in two slots, and one of them is released. No match: the call was given NULL.
> + * Sections are all alike: the first slot that is not 0.
> + */
> +static int clear_insns(const struct bpf_pad_note **notes, int nr, const struct bpf_pad_note *rel,
> +		       struct bpf_insn *buf)
> +{
> +	int i, k, n = 0, off, delta, reg;
> +
> +	for (i = 0; i < nr; i++) {
> +		if (class_group(notes[i]->ent.class) != rel->group)
> +			continue;
> +		delta = rel->delta - notes[i]->ent.cand[0][0].delta;
> +		/*
> +		 * The delta is made of constants that the program chose, the offsets of a node in
> +		 * its object. It is added in R0, which a call is about to clobber: there the JIT
> +		 * blinds it like any other constant of the program. An insn on AX is not blinded.
> +		 */
> +		reg = delta ? BPF_REG_0 : BPF_REG_AX;
> +		for (k = 0; k < notes[i]->nr_slots; k++) {
> +			off = notes[i]->off - k * BPF_REG_SIZE;
> +			buf[n++] = BPF_LDX_MEM(BPF_DW, reg, BPF_REG_FP, off);
> +			if (delta)
> +				buf[n++] = BPF_ALU64_IMM(BPF_ADD, reg, delta);
> +			if (rel->group < BPF_PAD_NR_SECTIONS)
> +				buf[n++] = BPF_JMP_IMM(BPF_JEQ, reg, 0, 2);
> +			else
> +				buf[n++] = BPF_JMP_REG(BPF_JNE, reg, rel->reg, 2);
> +			buf[n++] = BPF_ST_MEM(BPF_DW, BPF_REG_FP, off, 0);
> +			buf[n++] = BPF_JMP_A(0);
> +		}
> +	}

[Severity: Medium]
Can clear_insns() zero the wrong hidden slot when a release helper takes
the reference in R2-R5 while R1 also points into the same object?

bpf_pad_note_release() finds rel->reg by scanning R1..R5 in order and
stopping at the first register matching ref:

kernel/bpf/pads.c:bpf_pad_note_release() {
    ...
	for (r = BPF_REG_1; r <= BPF_REG_5 && !nr; r++)
		if (env->insn_aux_data[env->insn_idx].live_regs_before & BIT(r))
			add_cand(&place, &nr, &frame->regs[r], ref, obj ? &addr : NULL,
				 BPF_PLACE_REG, r);
	if (!nr || place.delta != (s16)place.delta)
		sub->no_slots |= BIT(group);
	else
		note_release(env, sub, group, place.at, place.delta);
}

If one path calls bpf_kptr_xchg(&p->next, p), R1 and R2 share p's ref id,
so bpf_pad_note_release() records R1 and offsetof(typeof(*p), next) as
rel->reg and rel->delta instead of R2.  If another path reaches the same
call instruction with R1 = &p->next and R2 = NULL, release_reg() returns
early on NULL without calling bpf_pad_note_release().  At run time on the
R2 = NULL path, the instructions emitted by clear_insns() match R1 against
p's slot + delta and zero p's hidden slot even though nothing was
released, so a subsequent unwind pad will skip releasing p and leak it.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1796099737.git.memxor@gmail.com?part=25

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 21/73] bpf: Add unwind_goto after helpers with a callback
  2026-12-01  4:38 ` [PATCH bpf-next v1 21/73] bpf: Add unwind_goto after helpers with a callback Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 8245 bytes --]

> bpf: Add unwind_goto after helpers with a callback

TL;DR:
- Verifier may now reject programs that loaded before: subprogs called from
  non-unwindable callbacks, and recursive callbacks/rbtree comparators
- Commit message misstates these rejections
- Comment wording nit

> diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
> --- a/include/linux/bpf_verifier.h
> +++ b/include/linux/bpf_verifier.h

[ ... ]

> @@ -1358,13 +1358,13 @@ struct bpf_subprog_info {
>  	/*
>  	 * 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;

this isn't a bug, but the new wording does not cover the bpf_rbtree_add()
case.  check_kfunc_call() now calls subprog_cannot_unwind() for a comparator
whose kfunc does have an unwind label (kfunc_has_cb_pad() is true for
bpf_rbtree_add), which clears bail_unwinds as well:

	err = subprog_cannot_unwind(env, meta.subprogno);

Could the comment use wording similar to subprog_cannot_unwind()'s own, for
example "Not if the helper or kfunc that calls it cannot pass an unwind on"?

> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c

[ ... ]

> @@ -6062,9 +6089,9 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
>  				 */
>  				if (bpf_pseudo_call(&insn[i]) ||
>  				    !func_is_kept_for_later(env, i, si[s + 1].start)) {
>  					err = bpf_call_graph_add(&cg, s, j);
> -					cg.marks[j] |= bpf_pseudo_call(&insn[i]) ? CALLED : CB;
> +					cg.marks[j] |= CALLED;
>  				}

[ ... ]

> @@ -6086,14 +6113,8 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
>  	bpf_call_graph_sort(&cg, 0);
>  
> -	/* A helper doesn't expect its callback to unwind, so what the callback calls cannot either */
> -	for (s = 0; s < cnt; s++)
> -		if (cg.marks[s] & CB)
> -			cg.marks[s] |= BELOW_CB;
> -	bpf_call_graph_mark_callees(&cg, BELOW_CB);
> -
>  	/*
>  	 * A function that the program calls can leave with unwind_exit or cancel_exit, if the JIT
>  	 * supports them and the loader has CAP_PERFMON. A function that only the kernel calls, like
>  	 * the main program or a timer callback, returns to the kernel.
> @@ -6101,9 +6122,9 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
>  	for (s = 0; s < cnt; s++) {
>  		si[s].bail_unwinds = si[s].can_unwind ||
>  				     (s && env->prog->jit_requested && bpf_jit_supports_unwind() &&
>  				      !bpf_prog_is_offloaded(env->prog->aux) && bpf_may_unwind(env) &&
> -				      (cg.marks[s] & (CALLED | BELOW_CB)) == CALLED);
> +				      (cg.marks[s] & CALLED));
>  		si[s].did_unwind = si[s].can_unwind;
>  	}

With BELOW_CB gone, what keeps a subprog called from a callback whose helper
has no unwind label from unwinding into a frame that cannot unwind?

subprog_cannot_unwind() clears bail_unwinds of the callback only, not of what
the callback calls.  So a static subprog C called from such a callback keeps
bail_unwinds = true.  If C has a loop the verifier cannot bound,
check_loop_guard() asks frame_can_unwind() for C's frame, which is true
because C is not in_callback_fn and sub->bail_unwinds is set, so
push_unwind_edge(BPF_SITE_GUARD) runs.  unwind_frame() then returns to the
callback frame, and check_unwound_arrival() calls
unwind_frame(..., BPF_SITE_CALL) for it, where
frame->in_callback_fn && !sub->bail_unwinds makes frame_can_unwind() false:

    if (kind == BPF_SITE_CALL && !frame_can_unwind(env, st, false)) {
        ...
        plan->conflict = BPF_CONFLICT_CANNOT_UNWIND;

The program is rejected ("landing pad of call at N: conflict: the frame
cannot unwind").  A global subprog called from such a callback ends the same
way through mark_unwind_above() and the next pass.  Before the patch C had
BELOW_CB and bail_unwinds false, so its may_goto left the loop and the
program loaded.

This affects bpf_rbtree_add() comparators that the new check_kfunc_call()
code marks as cannot-unwind when they call such a subprog.  On x86-64 and
arm64 kernels with BPF_HAS_CB_PADS == 0, it affects every bpf_loop(),
bpf_for_each_map_elem(), bpf_find_vma() and bpf_user_ringbuf_drain() callback
that calls such a subprog.

The commit message lists "The callback of a helper without an unwind label
cannot be cancelled" among the things that stay as they are, and its list of
what changes for programs that load today does not mention this rejection.
Also, a guarded loop in the callback itself still leaves the loop, while the
same loop one call below makes the load fail.  Should the changelog mention
that such programs no longer load at this point?

[ ... ]

> @@ -11661,13 +11664,12 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
>  		env->subprog_info[subprog].is_loop_cb = true;
>  	else
>  		env->subprog_info[subprog].is_other_cb = true;
>  
> -	err = check_cb_unwind(env, insn, insn_idx, subprog);
> +	err = check_cb_unwind(env, insn, subprog);
>  	if (err)
>  		return err;
> -	/* the helper has no pad, or nothing takes the program from its call to a pad */
> -	if (!insn_has_cb_pad(insn) || !bpf_is_unwind_goto(insn + 1)) {
> +	if (!insn_has_cb_pad(insn)) {
>  		err = subprog_cannot_unwind(env, subprog);
>  		if (err)
>  			return err;
>  	}

Is a recursive callback of a helper without an unwind label now rejected,
when it loaded before?

A callback whose address is not kept for later is now CALLED, so it starts
with bail_unwinds = true:

    si[s].bail_unwinds = si[s].can_unwind || (... && (cg.marks[s] & CALLED));

Here check_cb_unwind() runs before subprog_cannot_unwind() clears that
default.  check_cb_unwind() asks bpf_subprog_unwinds(), which is
can_unwind || (recursive && bail_unwinds), so for a recursive callback
without unwind_exit it returns true and takes:

    if (!BPF_HAS_CB_PADS) {
        verbose(env, "callback cannot unwind: the helpers have no pads\n");
        return -ENOTSUPP;
    }

Before the patch bail_unwinds was false at this point, check_cb_unwind()
returned 0, and subprog_cannot_unwind() ran.

BPF_HAS_CB_PADS is 0 on x86-64 and arm64 when CONFIG_CC_HAS_ASM_GOTO_OUTPUT
is off (GCC < 11.5, 12.0-12.3 and 13.0-13.2), while bpf_jit_supports_unwind()
is still true.  There the selftest verifier_budget.c "budget: recursion
through a helper that calls a callback" (__arch_x86_64 __arch_arm64
__success __retval(0)) would now fail: calls_loop() -> bpf_loop() ->
loop_cb() -> calls_loop() makes loop_cb recursive, and with CAP_PERFMON and
the JIT on, check_cb_unwind() returns -ENOTSUPP.

Should subprog_cannot_unwind() run before check_cb_unwind() for a helper
without an unwind label, so that a recursive callback without unwind_exit
keeps loading as it did?

[ ... ]

> @@ -16165,33 +16167,41 @@ static int check_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
>  		/*
> -		 * The pad of the kfunc drops the node when the comparator
[ ... ]
>  		if (bpf_obj_free_runs_dtor(meta.arg_btf, meta.arg_btf_id)) {
>  			if (bpf_subprog_unwinds(&env->subprog_info[meta.subprogno])) {
>  				verbose(env,
>  					"%s with a comparator that unwinds cannot be used on types with a list head, an rb root or a referenced kptr\n",
>  					func_name);
>  				return -EINVAL;
>  			}
>  			err = subprog_cannot_unwind(env, meta.subprogno);
>  			if (err)
>  				return err;
>  		}

The rbtree_add path has the same ordering.  It calls bpf_subprog_unwinds()
before subprog_cannot_unwind(), so a recursive comparator on a node type with
a list head, an rb root or a referenced kptr is now rejected with the
message above.  The same happens for a type with NMI unsafe fields in an
NMI-capable program.

The commit message says such a comparator "is rejected as before", but in
the parent bpf_subprog_unwinds() was false for it, so it was not rejected.
Is that statement accurate?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 62/73] bpf: Verify a cleanup pad for a frame that is cancelled
  2026-12-01  4:39 ` [PATCH bpf-next v1 62/73] bpf: Verify a cleanup pad for a frame that is cancelled Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3611 bytes --]

> bpf: Verify a cleanup pad for a frame that is cancelled

TL;DR: Commit message only: the claim that no program is verified differently
looks wrong, since bpf_pads_settle() changes (deferred rejection, new cost
charge) may alter pass count, cost or verdict for all programs.

>     Currently a state that returns from a call cancelled is cancelled in
>     turn at that call, through the generated pad, whatever landing pad the
>     program has there. Before a cancellation can run a cleanup pad, the
>     verifier has to check the pad for the cancelled frame: with 0 in R0, and
>     with what the frame holds when its callee is cancelled.
>     Add that to the main pass. Nothing calls bpf_find_cleanup_pads() yet, so
>     no program is verified differently.
>     [ ... ]
>     It now looks at all sites before it raises the first error, so that the
>     next pass can react to every one.
>     [ ... ]
>     Signed-off-by: Kumar Kartikeya Dwivedi <memxor@gmail.com>

The message says "Nothing calls bpf_find_cleanup_pads() yet, so no program
is verified differently."  Is that accurate?

The bpf_pads_settle() part of the patch does not depend on
bpf_find_cleanup_pads().  check_pass() calls it after every error-free
pass, for every program, including programs without any unwind_goto:

    ret = mark_used_sites(env, initial) ?: bpf_pads_settle(env);

Two changes in it affect existing programs.

First, the rejection is deferred until all plans have been seen:

    /* the first one is the one that the log names */
    if (!reject)
            at = i;
    reject = reject ?: plan;
    ...
    if (reject) {
            bpf_pad_log(env, at, reject);
            return -EINVAL;
    }

Before the patch, the first plan_rejects() plan returned -EINVAL at once,
so later used plans were never settled and their conflict (for example
NOT_ALWAYS_HELD, SECTIONS_DIFFER or NO_ROOM) stayed 0.  Now every used plan
is settled, so bpf_find_unproven_after_pass() (through bpf_pads_conflict())
and bpf_pads_note_causes() see more conflicts, and the next pass keeps
apart a different set of calls.

bpf_pad_skip_faults() also now runs for stuck sites that come after a
rejecting plan.  If it marks a new subprog stuck, env->faults_late is set,
and do_check_all() takes the branch:

    if (ret && env->faults_late && !env->over_limit)

and repeats the pass, where before the program went on to partitioning or
rejection.  So the number of passes, the budget used and possibly the
verdict can change for programs that have no cleanup pads.

Second, a new cost charge runs on every settle:

    err = bpf_add_cost_and_check(env, env->prog->len + BPF_PAD_MAX_ENTS * plans, BPF_COST_XREG);

This adds 16 * (len + 8 * plans) to every successful pass of every program,
so the limits are reached sooner.

The paragraph of the message that says "It now looks at all sites before it
raises the first error" does describe the first change, so that one appears
intended.  But the unconditional claim that no program is verified
differently is wrong as written, and someone bisecting a change in verifier
behavior (pass count, cost, or a verdict near the limit) to this commit
would be misled.

Could the claim be qualified, or could the bpf_pads_settle() change
(deferred rejection plus the cost charge) be split into its own patch?
Both are still present at the end of the series.


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 29/73] bpf: Let a callee hold a reference that its call hands over
  2026-12-01  4:38 ` [PATCH bpf-next v1 29/73] bpf: Let a callee hold a reference that its call hands over Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3226 bytes --]

> bpf: Let a callee hold a reference that its call hands over

TL;DR: Possible logging gap: bpf_pad_log() is only reached for visit-time
conflicts, so errors found later in bpf_pads_settle() may not print the
"callee holds a handed-over reference" line the comment promises. Diagnostics
only.

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c

[ ... ]

> +/*
> + * Log that @subprog owns the references that its calls hand over in the argument registers @args,
> + * see bpf_pad_handed_ref(). The log of an error about a reference at one of its sites says so,
> + * because no insn of the function acquired what its pad has to release.
> + */
> +void bpf_pad_log_handed_over(struct bpf_verifier_env *env, int subprog, u8 args)

[ ... ]

>  /* Log what the pad of the site of @plan at @insn_idx releases, or why it cannot be generated */
>  void bpf_pad_log(struct bpf_verifier_env *env, int insn_idx, const struct bpf_pad_plan *plan)
>  {
> +	const struct bpf_subprog_info *sub = bpf_find_containing_subprog(env, insn_idx);
> +
> +	if (plan->conflict) {
> +		/* a release that the pad may not make is one of a pointer or of an object */
> +		if (sub->owns_args && (plan->conflict == BPF_CONFLICT_NO_RELEASE ||
> +				       conflict_of_ref(env, plan)))
> +			bpf_pad_log_handed_over(env, sub - env->subprog_info, sub->owns_args);
> +	}
>  	print_plan(env, insn_idx, plan);
>  }

The comment on bpf_pad_log_handed_over() says the log of an error about a
reference at one of its sites says that the function holds a handed-over
reference.  Does that happen for the cases the commit message lists as
still rejected?

bpf_pad_log() is only called from unwind_frame() during the main pass, which
sees only the conflict that bpf_pad_visit() set.  A pointer without a
location is not a visit conflict, because visit_refs() stores it in
plan->no_place and continues.  BPF_CONFLICT_NOT_ALWAYS_HELD and
BPF_CONFLICT_CALLER_SAVED for a reference come only from
settle_ent()/settle_plan().

Those are found later in bpf_pads_settle(), which logs them directly:

    plan->conflict = err;
    if (plan->conflict) {
            print_plan(env, i, plan);
            return -EINVAL;
    }

So when the callee has no location for the handed-over pointer at one of
its sites, or holds it on some paths only, the final log shows only
"landing pad of ... conflict: no place has the handle on all paths" (or "...
held on some paths only"), and the "func#%d holds the reference that its
call hands over" line is not printed.  At log level 1 the hand_over_more()
message is not printed either.

Later commits in the series change this print_plan() in bpf_pads_settle()
to bpf_pad_log(): c68ba30b8446 ("bpf: Log why a call is a site and which
functions cannot be cancelled") and then 2fc97018416d ("bpf: Verify a
cleanup pad for a frame that is cancelled").  In this commit, does the
conflict_of_ref() branch of bpf_pad_log() do what its comment says?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 64/73] bpf: Find the code that a cleanup pad can reach
  2026-12-01  4:39 ` [PATCH bpf-next v1 64/73] bpf: Find the code that a cleanup pad can reach Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3313 bytes --]

> bpf: Find the code that a cleanup pad can reach

TL;DR: The comment and commit message say a function with no exit is "mixed",
but the code only sets that when an insn is both pad and normal code. The
wording looks inaccurate and may mislead readers of later commits.

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

[ ... ]

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c

[ ... ]

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

[ ... ]

> +	for (s = 0; s < env->subprog_cnt; s++) {
> +		sub = &env->subprog_info[s];
> +		for (i = sub->start; sub->has_cleanup_pads && i < sub[1].start; i++) {
> +			aux[i].cleanup_pad_code = test_bit(i, pad);
> +			if (sub->cleanup_pads_mixed || !test_bit(i, pad) || !test_bit(i, normal))
> +				continue;
> +			sub->cleanup_pads_mixed = true;

Is "or the function has no exit" accurate, both in this comment and in the
commit message?  cleanup_pads_mixed is only set when one insn has both the
pad and the normal bit set, and there is no separate no-exit case.

If "no exit" means exit_idx == U32_MAX, as in frame_cannot_unwind(), such a
function has no unwind_exit, so bpf_find_cleanup_pads() finds no cleanup pad
in it.  has_cleanup_pads stays false and find_pad_code() never looks at the
function.

If it means no plain exit, the function is still not necessarily mixed:

    call g
    unwind_goto +2
    r0 = 0
    unwind_exit
    call dtor
    unwind_exit

The normal path is {0,1,2,3} and the pad code is {4,5}.  They share no insn,
so the function is not mixed although it has no exit.

A function without a plain exit only becomes mixed indirectly: its landing
pads that continue the function are classified as cleanup pads, and the code
they run then overlaps the normal path.

The next commit, 696e1c8c75a1 ("bpf: Emit the stub, the entry and the
remainder of a cleanup pad"), uses cleanup_pads_mixed to decide whether a
function clears the "cancelled" word at its first insn and gets no stubs.
A reader who trusts this sentence would expect any function without an exit
to take that path.

The comment also contains a second paragraph that repeats the claim as "any
pad of a function that has no exit".  b27a88cc13c8 ("bpf: End the path at a
call of a global subprog that never returns") removes that second copy, but
the first paragraph keeps the sentence up to c916df4614a0, the end of the
series.


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 28/73] bpf: Let hidden slots follow what a subprog does for its caller
  2026-12-01  4:38 ` [PATCH bpf-next v1 28/73] bpf: Let hidden slots follow what a subprog does for its caller Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 5454 bytes --]

> bpf: Let hidden slots follow what a subprog does for its caller

TL;DR:
- pads.c: if pad_note_get() allocation fails on a plain subprog return, the
  caller may get wrong hidden slots, so a pad could release an unheld resource
  or skip one
- nit: bpf_pad_arg split from bpf_func_state's comment

> diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
> --- a/include/linux/bpf_verifier.h
> +++ b/include/linux/bpf_verifier.h

[ ... ]

> @@ -651,12 +685,19 @@ static inline bool bpf_trip_is_saved(const struct loop_stack_entry *entry)
>  
>  #define LOOP_STACK_SIZE 16
>  
>  /* 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 {

This isn't a bug, but struct bpf_pad_arg is now between struct
bpf_func_state and the comment that documents it.  The "state of the
program: type of all registers and stack info" comment now sits above
the bpf_pad_arg comment and definition, and bpf_func_state is left
without one.

Could the bpf_pad_arg definition move above the old comment?

[ ... ]

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c

[ ... ]

> +	head = plain ? pad_note_get(env, call_idx) : NULL;
> +	/*
> +	 * No store follows this return: the frame is a callback, which returns to its helper, it
> +	 * left with unwind_exit, or there is no memory for the note. The caller gets no slots for
> +	 * what the frame returns with, nor for a lock that the frame has released for it.
> +	 */
> +	if (!head) {
> +		for (i = 0; i < BPF_PAD_NR_SECTIONS; i++)
> +			if (frame_sections(st, i))
> +				sub_no_slots(sub, st, BIT(i));
> +		for (i = 0; i < nr; i++)
> +			sub_no_slots(sub, st, BIT(class_group(ref_class(&ref[i]))));
> +		took_locks_no_slots(env, st, callee->took_locks & BIT(caller->frameno));
> +		goto out;
> +	}

When pad_note_get() fails on a plain return, does this branch drop
information that the return carries?

The comment says "No store follows this return".  That holds for a
callback return and for unwind_exit, but not for the allocation failure.
That return is a normal exit and reaches the stores that
insert_slot_stores() emits after the call.  Those stores are built only
from the notes that other returns record.

For the failed return, the branch marks no_slots only for groups that the
frame comes back holding.  It skips what this return contributes
otherwise:

  aux->call_brings_nothing |= !reg_is_null(r0);   (set only in the head path)
  head->nohold_r0[] and head->hold_r0[]
  head->keeps

Only the first plain return to a call allocates the note, since
aux->pad_note is NULL until then in each pass.  The allocation uses
BPF_VERIFIER_GFP (GFP_KERNEL_ACCOUNT | __GFP_RETRY_MAYFAIL | __GFP_NOWARN),
so it can fail under memcg pressure or failslab, and a later return to the
same call can then allocate successfully.

For example, a callee returns a non-NULL scalar with nothing acquired on
its first explored path (state B, R0 = 1), and returns an acquired pointer
in R0 on another path (state A):

1. B returns first and the allocation fails.  nr == 0 and
   frame_sections() == 0, so nothing is marked and call_brings_nothing
   stays false.

2. A returns, the allocation succeeds, and note_acquire() records a REFS
   note with src R0.  At out: the test
   "aux->call_brings_nothing && insn_acquires(aux, BPF_PAD_GROUP_REFS)"
   is false.

3. If a site in the caller needs a slot for the pointer (for instance it
   is only in R1 at a call of a cancellable subprog), subprog_take_slots()
   gives the caller REFS slots with cond BPF_PAD_ALWAYS, and
   bpf_pad_insns_after() emits an unconditional "*(fp - off) = r0" after
   the call.

4. On the runtime path of B the slot holds 1.  plan_take_slots() added the
   slot to every pad of the subprog, so a pad reached on that path calls
   the release kfunc on 1.

Before this patch, B's return set
"aux->call_brings_nothing |= plain && !reg_is_null(r0)" without allocating
anything, and the later aux->pad_note->acquires test removed the REFS
slots.

Sections fail the same way.  Take a return without the section and with
R0 == 0 that fails the allocation, followed by a return with the section
and R0 == 0.  nohold_r0 stays 0, subprog_take_slots() picks
BPF_PAD_ALWAYS, and the slot is set to 1 on a path that holds no section,
so the pad calls rcu_read_unlock() or preempt_enable() without a matching
lock.  A lost 'keeps' does the same for a 'takes' clear: the slot is
cleared on a path that still holds the resource, so the pad never releases
it.

Should this give the caller no slots for any group when plain is true and
head is NULL, for example:

  sub->no_slots |= GENMASK(BPF_PAD_NR_GROUPS - 1, 0);

Or at minimum keep "aux->call_brings_nothing |= plain && !reg_is_null(r0)"
on this path?  The branch is unchanged up to the end of the series
(c916df4614a0, "sched_ext: Treat a cancelled program as a scheduler
error"), and I did not find a later fix.


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 37/73] bpf: Share one landing pad among accesses to arena where nothing is held
  2026-12-01  4:39 ` [PATCH bpf-next v1 37/73] bpf: Share one landing pad among accesses to arena where nothing is held Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 1764 bytes --]

> bpf: Share one landing pad among accesses to arena where nothing is held

TL;DR: Nit only: comments in insert_unwind_gotos() and bpf_insert_sites()
still describe an unwind_goto after every arena access, but accesses with
fault_unwinds now use the shared fault_pad instead.

> diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
> --- a/kernel/bpf/fixups.c
> +++ b/kernel/bpf/fixups.c

[ ... ]

> @@ -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;
>  }

This isn't a bug, but the comments around this code still describe the old
layout.

The header of insert_unwind_gotos() says unwind_goto is added "after the
accesses to arena that are" sites, and the header of bpf_insert_sites()
still says "unwind_goto after calls and after accesses to arena", with a
diagram showing "call foo / or an access to arena" followed by
"unwind_goto pad" and "pad: the releases  each site has its own pad".

With this change an access with fault_unwinds gets no unwind_goto and
shares prog->aux->fault_pad, so a reader would expect an unwind_goto after
every access that cancels.

Could these comments be updated to say that accesses with fault_unwinds
get no unwind_goto and use the shared fault_pad instead?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 13/73] bpf: Emit landing pads that leave RCU sections
  2026-12-01  4:38 ` [PATCH bpf-next v1 13/73] bpf: Emit landing pads that leave RCU sections Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 5677 bytes --]

> bpf: Emit landing pads that leave RCU sections

TL;DR:
- Possible load failure (-EFAULT, WARN) for CAP_BPF-only programs: loop latch
  seen only speculatively gets a landing pad
- Programs with over 8 nested RCU/preempt sections in a loop may now be
  rejected
- Comment block placed between a diagram and its struct (nit)

> diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
> --- a/include/linux/bpf_verifier.h
> +++ b/include/linux/bpf_verifier.h
> @@ -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 {

this isn't a bug, but the new block of landing pad definitions was inserted
between the "A state in a loop, see bpf_flow_loop_enter()" diagram comment
and struct loop_stack_entry, which that comment documents.

Could the new block go above that comment or below struct loop_stack_entry,
so the diagram stays next to the struct it describes?

[ ... ]

> diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
> --- a/kernel/bpf/fixups.c
> +++ b/kernel/bpf/fixups.c

[ ... ]

> @@ -606,40 +677,59 @@ static int emit_unwind_exit(struct bpf_verifier_env *env, int s, struct bpf_insn
>  	for (s = 0; s < env->subprog_cnt && !err; s++) {
>  		sub = &env->subprog_info[s];
> +		cnt = collect_pads(env, s, new, &pads);
> +		if (cnt < 0) {
> +			err = cnt;
> +			break;
> +		}
> +		/* a pad has no nospec barrier, see emit_pad() */
> +		if (verifier_bug_if(cnt && !bpf_may_unwind(env), env,
> +				    "func#%d has landing pads without CAP_PERFMON", s)) {
> +			err = -EFAULT;
> +			break;
> +		}

Can this verifier_bug_if() fire for a valid program loaded with CAP_BPF but
without CAP_PERFMON?

state_can_unwind() now returns false without bpf_may_unwind(), so
check_loop_guard() sets guard_no_unwind for non-speculative states.  A
speculative state skips that test though:

kernel/bpf/verifier.c:check_loop_guard() {
    ...
	if (env->cur_state->speculative)
		goto out;
    ...
out:
	aux->loop_guard = true;
	aux->guard_unwinds = !aux->guard_no_unwind;
	if (aux->guard_no_unwind)
		err = PTR_ERR_OR_ZERO(push_stack(env, aux->guard_to, env->insn_idx, false));
	else
		err = push_unwind_edge(env, BPF_SITE_GUARD);
    ...
}

push_unwind_edge() returns 0 for a speculative state, so if only speculative
states reach a guard, guard_no_unwind stays clear and guard_unwinds is set.
collect_pads() then creates an empty plan for it ("no state got there in the
pass") and emits a pad, so cnt is non-zero.

Speculative states exist only when !bypass_spec_v1, which is the same case
where bpf_may_unwind() is false.  A loop with two latches, where the second
latch is reached only through a branch the verifier knows is never taken,
would do it:

  h: r3 = *(u8 *)(r6 + 0); if r3 > 1000 goto B
  A: call bpf_get_prandom_u32; if r0 == 0 goto out; goto h
  B: call bpf_get_prandom_u32; if r0 == 0 goto out; goto h
  out: r0 = 0; exit

Latch A gets guard_no_unwind from the real states, and latch B gets
guard_unwinds from the speculative state.  bpf_flow_drop_guards() keeps
loop_guard on B because the loop needs a guard, and the dead code is only
removed after bpf_insert_sites().

Before this patch the same site got emit_unwind_exit() with a nospec barrier
and the program loaded.  Now the load fails with -EFAULT and a WARN_ONCE under
CONFIG_DEBUG_KERNEL.  This also looks to be at odds with the commit message
statement that only a program loaded with CAP_PERFMON gets landing pads.

Should guard_unwinds stay clear in check_loop_guard() when the state is
speculative and !bpf_may_unwind(env), or should collect_pads() skip a plan
that no non-speculative state visited?

The commit 2a7319aac6e1 ("bpf: Let a may_goto that the verifier adds go to
its landing pad only") later in the series removes guard_unwinds and
guard_no_unwind, but the commits in between still have this, so bisection
can land on it.  It was not confirmed that the later rework closes this
exact case.

[ ... ]

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> --- /dev/null
> +++ b/kernel/bpf/pads.c

[ ... ]

> +	for (class = 0; class < BPF_PAD_NR_SECTIONS; class++) {
> +		nr = frame_sections(st, class);
> +		if (nr > BPF_PAD_MAX_SECTIONS)
> +			plan->conflict = BPF_CONFLICT_TOO_MUCH;

Can this reject a program that loads today?

Before this patch, state_can_unwind() returned false for a frame that had
entered a section, so may_goto left the loop and the code after it released
the sections.  The section test is gone, so such a frame now always takes
push_unwind_edge() and reaches bpf_pad_visit().

Nothing caps active_rcu_locks or active_preempt_locks, so a loop with more
than 8 nested bpf_rcu_read_lock() (or bpf_preempt_disable()) calls gets
BPF_CONFLICT_TOO_MUCH.  unwind_frame() then reports "landing pad of may_goto
at N: conflict: too much is held" and the program is rejected.

The commit message lists what changes for programs that load today, but does
not mention this rejection.  Should the loop be left the old way when
frame_sections() exceeds BPF_PAD_MAX_SECTIONS?  Only CAP_PERFMON loaders are
affected, and no later commit in the series was found that changes this.

[ ... ]


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 15/73] bpf: Add unwind_goto after calls of subprogs
  2026-12-01  4:38 ` [PATCH bpf-next v1 15/73] bpf: Add unwind_goto after calls of subprogs Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 12302 bytes --]

> bpf: Add unwind_goto after calls of subprogs

TL;DR:
- Programs using function-table callbacks may be rejected by the verifier,
  depending on call order, though they loaded before
- Possible NULL write to cg.marks in mark_recursive_subprogs() on allocation
  failure

> diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
> --- a/include/linux/bpf_verifier.h
> +++ b/include/linux/bpf_verifier.h

[ ... ]

> @@ -1311,12 +1330,15 @@ struct bpf_subprog_info {
> +	/*
> +	 * 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;

The comment says a subprog that a helper calls does not get bail_unwinds.
Is that true for a subprog whose address comes from a table of functions
(env->func_ptrs) rather than from ld_imm64?

mark_recursive_subprogs() marks only ld_imm64 callbacks as CB/BELOW_CB.  A
subprog in env->func_ptrs gets CALLED only:

	for (i = 0; i < env->func_ptr_cnt; i++) {
		...
			cg.marks[j] |= CALLED;

So with CAP_PERFMON and an unwinding JIT it starts the pass with
bail_unwinds set.  The program can still read the pointer from the table
and pass it to a helper (check_func_ptr_read(), see the selftest
callx_rodata_callback_one_of_two), and then two programs that loaded before
this patch are now rejected:

(a) The subprog is recursive (it calls itself, or it does callx and is in
the table).  In push_callback_call() check_cb_unwind() runs before
subprog_cannot_unwind(), and bpf_subprog_unwinds() still returns
sub->recursive && sub->bail_unwinds.  So bpf_loop(n, table[0], ctx, 0)
without an unwind_goto fails with "no unwind_goto after the call of
bpf_loop()".  Before the patch the plain call that forms the recursion set
plain_call, so bail_unwinds was false and the program loaded.

(b) The subprog has a loop that gets a may_goto.  If the program first
calls it with callx and later passes it to bpf_loop(), check_loop_guard()
-> frame_can_unwind() sees bail_unwinds and unwinds, and unwind_frame() sets
did_unwind.  At the bpf_loop() call subprog_cannot_unwind() then fails with
"callback cannot unwind at insn N: X() does".  If bpf_loop() comes first,
bail_unwinds is cleared and the same subprog loads, so the result depends on
insn order.  Before the patch, plain_callx && addr_taken set plain_call and
the may_goto left the loop.

did_unwind combines two things: the subprog has an unwind_exit of its own,
and the verifier chose to unwind it at a site where it could have fallen
back.  Because of that, subprog_cannot_unwind() cannot tell a real conflict
from a choice it could undo.

The commit message lists the cases that fail with "the frame cannot
unwind".  It does not mention these two errors, and no selftest covers
"callback cannot unwind at insn".

Later commits in the series fix this.  0c46504b2d72 ("bpf: Add unwind_goto
after helpers with a callback") removes the unwind_goto requirement from
check_cb_unwind(), which fixes (a) for helpers that have a callback pad such
as bpf_loop().  e25530913ac3 ("bpf: Check that a helper whose callback may
unwind has an unwind label") makes subprog_cannot_unwind() repeat the pass
(env->faults_late) instead of failing on did_unwind, which fixes (b).  The
regression is present in this commit and in the commits between.

> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c

[ ... ]

> @@ -3359,12 +3359,30 @@ static int record_callx_edge(struct bpf_verifier_env *env, int caller, int calle
> +static int subprog_cannot_unwind(struct bpf_verifier_env *env, int subprog)
> +{
> +	struct bpf_subprog_info *sub = &env->subprog_info[subprog];
> +
> +	if (sub->did_unwind) {
> +		verbose(env, "callback cannot unwind at insn %d: %s() does\n",
> +			env->insn_idx, bpf_subprog_name(env, subprog));
> +		return -EINVAL;
> +	}
> +	sub->bail_unwinds = false;
> +	return 0;
> +}

Can this reject programs that loaded before this commit, depending on the
order in which the verifier explores the program?

A subprog F that is reached through a function-pointer table in a frozen map
only gets CALLED, so it has bail_unwinds when JIT unwind and CAP_PERFMON are
available.  check_func_ptr_read() turns a single-target read of the table
into a PTR_TO_FUNC, and ARG_PTR_TO_FUNC accepts it, so F can also be the
callback of bpf_loop().

Consider a program that calls F directly (or through callx) and later passes
table[0] == F to bpf_loop(), with no unwind_goto after the helper call, and
F contains a loop with no trip count:

On the direct call, check_loop_guard() finds that frame_can_unwind() is true
for F's frame.  push_unwind_edge() is followed by unwind_frame(), which does:

	st->unwound = sub->bail_unwinds && !frame_is_top(st);
	...
	sub->did_unwind |= st->unwound;

Later push_callback_call() runs for bpf_loop().  check_cb_unwind() returns 0
because F neither can_unwind nor is recursive.  bpf_is_unwind_goto(insn + 1)
is false, so subprog_cannot_unwind() runs, sees did_unwind and fails with
"callback cannot unwind at insn N: F() does".

-EINVAL is recoverable, but every pass explores in the same order and
restores did_unwind from the snapshot, so do_check_all() ends in REJECT.
Before the patch the plain call (or plain_callx) set plain_call, so
bail_unwinds was false, the may_goto left the loop and the program loaded.
If the helper call happens to be explored first, bail_unwinds is cleared and
the same program loads.

The comment says "Fails if @subprog already left at a site", but the commit
message's list of what changes for programs that load today does not mention
this rejection.

The same root cause has a second effect.  subprog_cannot_unwind() clears
bail_unwinds only for the callback itself.  The callees of such a
function-table callback keep bail_unwinds, because nothing marks them
BELOW_CB.  A may_goto in a callee then unwinds into the callback frame,
where frame_can_unwind() returns false (in_callback_fn), and the program is
rejected with "landing pad of call at N: conflict: the frame cannot unwind".
This contradicts the commit message's statement that in a callback and in
what it calls 'a may_goto still leaves the loop'.  A recursive
function-table callback fails even earlier, in check_cb_unwind() ("no
unwind_goto after the call of bpf_loop()"), because recursive &&
bail_unwinds holds before subprog_cannot_unwind() can clear it.

Later in the series, 0c46504b2d72 ("bpf: Add unwind_goto after helpers with
a callback") stops calling subprog_cannot_unwind() for helpers that have an
unwind label, such as bpf_loop().  e49eff9842d3 ("bpf: Cancel a program at a
fault in arena") and e67560bb7d19 ("bpf: Cancel the program when the time of
its own may_goto is up") change subprog_cannot_unwind() to repeat the pass
instead of failing, and e67560bb7d19 adds stuck_frame_calls().  The
regression still exists at this commit.

[ ... ]

> @@ -6007,55 +6023,62 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
[ ... ]
>  	for (i = 0; i < env->func_ptr_cnt; i++) {
>  		j = bpf_find_subprog(env, env->func_ptrs[i].xlated_off);
> -		if (j >= 0)
> +		if (j >= 0) {
>  			si[j].addr_taken = true;
> +			cg.marks[j] |= CALLED;
> +		}
>  	}

Can this write through a NULL cg.marks?  This loop has no check of err,
unlike the loops around it that are guarded by !err.

bpf_call_graph_init() allocates cg->marks with kvcalloc(cnt, sizeof(u16),
BPF_VERIFIER_GFP), and BPF_VERIFIER_GFP is GFP_KERNEL_ACCOUNT |
__GFP_RETRY_MAYFAIL | __GFP_NOWARN, so it can fail, for example when the
loader's memcg is at its limit:

	cg->marks = kvcalloc(cnt, sizeof(u16), BPF_VERIFIER_GFP);
	if (!cg->first || !cg->marks)
		return -ENOMEM;

On failure cg->marks is NULL.  Before this patch the loop only set
si[j].addr_taken.  Now it also does 'cg.marks[j] |= CALLED;', which writes
through NULL whenever env->func_ptr_cnt > 0.

resolve_func_ptrs() fills env->func_ptrs before this function runs
(bpf_check() calls it before mark_recursive_subprogs()), for any program
that uses callx and has a frozen map holding function offsets (this needs
allow_ptr_leaks).  So a privileged loader under memory pressure, or with
failslab injection, can hit a NULL write during program load instead of
getting -ENOMEM.  The code is unchanged at the end of the series
(c916df4614a0).  Would gating the loop on !err, or jumping to out right
after a failed init, avoid this?

[ ... ]

>  		si[s].bail_unwinds = si[s].can_unwind ||
> -				     (s && !si[s].plain_call && !bpf_subprog_is_global(env, s) &&
> -				      bpf_jit_supports_unwind() &&
> -				      !bpf_prog_is_offloaded(env->prog->aux));
> +				     (s && !bpf_subprog_is_global(env, s) &&
> +				      env->prog->jit_requested && bpf_jit_supports_unwind() &&
> +				      !bpf_prog_is_offloaded(env->prog->aux) && bpf_may_unwind(env) &&
> +				      (cg.marks[s] & (CALLED | BELOW_CB)) == CALLED);

Can valid programs that loaded before this patch be rejected here when a
helper calls a callback whose address comes from a table of functions
(env->func_ptrs) rather than from ld_imm64?

CB, and through it BELOW_CB, is set only for a bpf_pseudo_func ld_imm64.  A
subprog in func_ptrs gets only CALLED.  push_callback_call() expects such a
callback ("might be taken in another function or read from a map, see
check_func_ptr_read()"), and its callees do not get BELOW_CB, so they keep
bail_unwinds too.

Before this patch, any plain callx set plain_callx, which made every
addr_taken subprog plain_call.  Their plain calls made their callees
plain_call too.  None of them had bail_unwinds, and a may_goto there left
the loop.  Now:

1. A table-derived callback X passed to bpf_loop() calls static Y, and Y has
a loop without a trip count.  frame_can_unwind(Y) is true, because Y has
bail_unwinds and no reference and is not in_callback_fn.  So the guard
unwinds Y.  The state comes back to X at the call, and
check_unwound_arrival() runs unwind_frame(BPF_SITE_CALL).
frame_can_unwind(X) is false because X's frame is in_callback_fn, so the
plan gets BPF_CONFLICT_CANNOT_UNWIND and bpf_pads_settle() rejects the
program with "conflict: the frame cannot unwind".  The commit message says
that in a callback and in what it calls 'a may_goto still leaves the loop',
and that does not hold here.

2. If X itself contains a callx, then X -> node cnt -> X is a cycle, so X is
recursive with bail_unwinds.  In push_callback_call(), check_cb_unwind() runs
before the new subprog_cannot_unwind() block, bpf_subprog_unwinds(X) is
true, and the program fails with "no unwind_goto after the call of
bpf_loop()" before bail_unwinds can be cleared.

3. If X is also reached through callx earlier in the pass, its guard unwinds
and sets did_unwind.  The later bpf_loop(X) then fails in
subprog_cannot_unwind() with "callback cannot unwind at insn N: X() does".
Each pass restores subprog_info from the initial snapshot, so every pass
repeats the same order and the program is rejected.  Whether it loads
depends on the order of the two calls.

The comment above check_cb_unwind() also still describes the old rule
("unwinds ... when it is recursive and unwind_goto follows every call of it
that mark_recursive_subprogs() saw").  That rule no longer decides
bail_unwinds.

Later in the series this is reworked.  0c46504b2d72 ("bpf: Add unwind_goto
after helpers with a callback") removes CB/BELOW_CB and lets callbacks of
helpers with an unwind label unwind.  0d9be4be994d ("bpf: Use cancel_exit to
leave a frame that the kernel cancels") adds stuck_frame_calls(), which
marks the callees of a frame that cannot unwind at run time and repeats the
pass, and e49eff9842d3 ("bpf: Cancel a program at a fault in arena") makes
subprog_cannot_unwind() repeat the pass instead of failing.  At this commit
the rejection is real.


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 22/73] bpf: Let a may_goto that the verifier adds go to its landing pad only
  2026-12-01  4:38 ` [PATCH bpf-next v1 22/73] bpf: Let a may_goto that the verifier adds go to its landing pad only Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 5189 bytes --]

> bpf: Let a may_goto that the verifier adds go to its landing pad only

TL;DR:
- Docs claim frames are cancelled, but a program's own unwind_goto after a
  call can run its landing pad and continue
- Fixups.c comment describes code from later commits and wrongly says each
  site has its own pad

> diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
> --- a/Documentation/bpf/verifier.rst
> +++ b/Documentation/bpf/verifier.rst

[ ... ]

> +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.

Is this description accurate when the caller has an unwind_goto of its own
after the call?

check_unwound_return() returns 0 without recording a BPF_SITE_CALL when the
program already has an unwind_goto:

    if (bpf_is_unwind_goto(&env->prog->insnsi[call_idx + 1]))
            return 0;

and check_cond_jmp_op() then jumps to the program's own target:

    if (bpf_is_unwind_goto(insn)) {
            if (!env->cur_state->unwound)
                    return 0;
            env->cur_state->unwound = false;
            *insn_idx += insn->off;

So with 'call wait; unwind_goto catch; ... catch: r0 = 42; exit', where
wait() has a loop that gets a verifier may_goto, the pad of wait() leaves
with unwind_exit, the program's own landing pad runs, and the program
returns 42.  It is not cancelled and does not return
bpf_cancelled_retval().  The program's unwind_goto jumps to program code
that can continue running, not to "the landing pad of the call in the
caller".

The same guarantee is stated in the intro of the Cancellation section ("Each
frame of the program then releases what it holds, and the program returns a
value that the kernel chooses") and in the glossary entry for 'cancel'.

Later commits in the series describe this gap: 4faf343a962e ("bpf: Add
cancel_goto and cancel_exit, which only the verifier emits") says the
cancellation lands in the program's landing pad, which can continue
running, and 0d9be4be994d ("bpf: Use cancel_exit to leave a frame that the
kernel cancels") fixes the code and rewrites this paragraph.  At this
commit the documentation describes a guarantee that the code does not yet
provide.

> diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
> --- a/kernel/bpf/fixups.c
> +++ b/kernel/bpf/fixups.c

[ ... ]

>  /*
>   * Emit what the main pass decided about the sites: may_goto before the insns that it
> - * marked, see check_loop_guard(), unwind_goto after calls, and the landing pads. It verified the
> - * edge from the insn to where may_goto goes. What a pad does it did to the states that left the
> - * frame at the site, see unwind_frame().
> + * marked, see check_loop_guard(), unwind_goto after calls, and the landing pads. What a pad does it
> + * did to the states that left the frame at the site, see unwind_frame().
>   *
> - *	may_goto to		or	may_goto pad
> - *	insn				insn
> - *					...
> - *					last insn of the subprog
> - *				pad:	the releases
> - *					r0 = bpf_cancelled_retval()
> - *					exit
> + *	may_goto pad		before an insn of a loop, see check_loop_guard(). A may_goto
> + *	insn			of the program that is a site jumps to its pad too.
> + *	call foo		or an access to arena
> + *	unwind_goto pad		or cancel_goto, or both, see insert_unwind_gotos()
> + *	gotol pad		in place of a call of bpf_throw()
> + *	...
> + *	last insn of the subprog
> + * pad:	the releases		each site has its own pad, see collect_pads()
> + *	r0 = bpf_cancelled_retval()
> + *	cancel_exit		or exit, see unwind_exit_insn()

This isn't a bug, but does this diagram describe code that this commit does
not have?

enum bpf_site_kind has only BPF_SITE_GUARD, BPF_SITE_RECURSION and
BPF_SITE_CALL here, so "A may_goto insn of the program that is a site" does
not exist yet, and the commit message says "A may_goto of the program
itself is not changed."  There are also no arena-access sites, no
cancel_goto, no bpf_throw() rewrite to gotol, and no BPF_CANCEL_EXIT at
this commit; insert_unwind_gotos() emits only:

    struct bpf_insn unwind_goto = BPF_RAW_INSN(BPF_JMP | BPF_JCOND, 0, BPF_UNWIND_GOTO, 0, 0);

These arrive later in e67560bb7d19 ("bpf: Cancel the program when the time
of its own may_goto is up"), e49eff9842d3 ("bpf: Cancel a program at a
fault in arena"), 4faf343a962e, 8df41abc2f1f ("bpf: Make bpf_throw() cancel
the program through landing pads") and 0d9be4be994d.

The line "each site has its own pad, see collect_pads()" also seems to
contradict collect_pads(), which shares a pad between sites whose insns are
the same:

    if (pad < cnt)
            continue;

That one is still the case at the end of the series.


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 14/73] bpf: Release locks and irq flags in landing pads
  2026-12-01  4:38 ` [PATCH bpf-next v1 14/73] bpf: Release locks and irq flags in landing pads Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 2554 bytes --]

> bpf: Release locks and irq flags in landing pads

TL;DR: Comment-only mismatch: ent->origin may keep the first-visited state's
value, not the lowest, so verifier log text can depend on exploration order.
The emitted pads look correct. A later patch adds the fix.

> diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
> --- a/include/linux/bpf_verifier.h
> +++ b/include/linux/bpf_verifier.h

[ ... ]

> +	u32 origin;		/* the lowest 'origin' of the references that it stands for */

[ ... ]

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c

[ ... ]

> +	memset(ent, 0, sizeof(*ent));
> +	ent->origin = ref->origin;

[ ... ]

> +			ent = match_ent(plan, &new, !pass);
> +			if (!ent && !pass)
> +				continue;
> +			if (!ent && plan->visited)
> +				return BPF_CONFLICT_NOT_ALWAYS_HELD;
> +			if (!ent && plan->nr_ents == BPF_PAD_MAX_ENTS)
> +				return BPF_CONFLICT_TOO_MUCH;
> +			ent = ent ?: add_ent(plan, &new);
> +			if (!ent)
> +				return -ENOMEM;
> +			ent->ref = i;
> +			for (arg = 0; arg < BPF_PAD_MAX_ARGS; arg++)
> +				ent->nr_cands[arg] = common_cands(ent, &new, arg, ent->cand[arg]);

Is ent->origin really the lowest origin of the references the entry stands
for, as the comment in struct bpf_pad_ent says?

ent->origin is only set from ref->origin in ref_ent() and copied in
add_ent().  When a later state's reference matches an existing entry in
visit_refs(), only ent->ref and ent->nr_cands[] are updated, and ent->origin
keeps the value from whichever state reached the site first.

For example, if a lock is taken at insn 9 on one path and at insn 5 on
another, with the pointer in R6 on both, and the path through insn 9 reaches
the site first, ent->origin stays 9.  That value is what match_ent() compares
in the origin pass, and what print_ent() logs as "spin_lock@9(...)", so the
log depends on exploration order.

The emitted pads look correct since origin is only a matching preference and
log text, but the field does not match its comment.  A later commit in the
series, f0052bda37ba ("bpf: Check pointers for NULL in landing pads"), adds
"ent->origin = min(ent->origin, new.origin);" at this spot.  Should that line
be part of this patch, or should the comment say it is the origin of the
first visit?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 19/73] bpf: Check pointers for NULL in landing pads
  2026-12-01  4:38 ` [PATCH bpf-next v1 19/73] bpf: Check pointers for NULL " Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 1783 bytes --]

> bpf: Check pointers for NULL in landing pads

TL;DR: Nit only, no bug found: the rule for which candidate a landing pad uses
is duplicated in ent_is_clobbered() and settle_ent(); suggests a shared helper
so they can't drift apart.

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c

[ ... ]

> +/* Is the candidate that settle_ent() is going to take for @ent one of R0-R5? */
> +static bool ent_is_clobbered(const struct bpf_pad_ent *ent)
> +{
> +	int i;
> +
> +	for (i = 0; i < ent->nr_cands[0] && !ent->always && !ent->cand[0][i].null; i++)
> +		;
> +	return i < ent->nr_cands[0] && place_is_caller_saved(&ent->cand[0][i]);
> +}

[ ... ]

>  static int settle_ent(struct bpf_verifier_env *env, const struct bpf_pad_plan *plan,
>  		      struct bpf_pad_ent *ent)
>  {
>  	struct bpf_pad_place *cand = ent->cand[0];
> +	int i;
>  
> +	for (i = 0; i < ent->nr_cands[0] && !ent->always && !cand[i].null; i++)
> +		;
> +	if (i == ent->nr_cands[0])
> +		return BPF_CONFLICT_NOT_ALWAYS_HELD;
> +	swap(cand[0], cand[i]);

this isn't a bug, but the rule for which candidate the pad uses is written
out twice, once in ent_is_clobbered() and once in settle_ent(), and the
comment on ent_is_clobbered() says it has to predict what settle_ent()
takes.

order_ents() sorts on the ent_is_clobbered() answer, so it only works while
the two loops agree.

Could the two share one small helper that returns the index of the
candidate the pad uses, so order_ents() and settle_ent() cannot drift
apart?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 16/73] bpf: Let the kernel cancel a program in a global subprog
  2026-12-01  4:38 ` [PATCH bpf-next v1 16/73] bpf: Let the kernel cancel a program in a global subprog Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 6208 bytes --]

> bpf: Let the kernel cancel a program in a global subprog

TL;DR:
- Programs holding references across a global subprog call may now fail to
  load; fixed later in series, so bisection breaks
- fexit/fmod_ret/fsession may no longer attach to some global functions;
  undocumented
- Comments mention cancel_exit not yet present (nit)

> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c

[ ... ]

> @@ -6064,13 +6088,13 @@ static int mark_recursive_subprogs(struct bpf_verifier_env *env)
>  	bpf_call_graph_mark_callees(&cg, BELOW_CB);
>  
>  	/*
> -	 * What only the kernel calls returns to it: the main prog, the callback of a timer.
> -	 * Callers of a global subprog look at can_unwind before the subprog is verified.
> +	 * A function that the program calls can leave with unwind_exit or cancel_exit, if the JIT
> +	 * supports them and the loader has CAP_PERFMON. A function that only the kernel calls, like
> +	 * the main program or a timer callback, returns to the kernel.
>  	 */
>  	for (s = 0; s < cnt; s++) {
>  		si[s].bail_unwinds = si[s].can_unwind ||
> -				     (s && !bpf_subprog_is_global(env, s) &&
> -				      env->prog->jit_requested && bpf_jit_supports_unwind() &&
> +				     (s && env->prog->jit_requested && bpf_jit_supports_unwind() &&
>  				      !bpf_prog_is_offloaded(env->prog->aux) && bpf_may_unwind(env) &&
>  				      (cg.marks[s] & (CALLED | BELOW_CB)) == CALLED);
>  		si[s].did_unwind = si[s].can_unwind;

Can programs that load at the parent commit be rejected here?

Before this patch a global subprog had bail_unwinds == can_unwind, so in
check_loop_guard() the may_goto that the verifier adds took guard_no_unwind
and left the loop. With !bpf_subprog_is_global() removed, the guard now
unwinds the global frame.  unwind_frame() sets did_unwind and pads_late,
and in the next pass check_func_call() pushes the unwound branch
unconditionally:

    if (env->subprog_info[subprog].did_unwind &&
        env->subprog_info[subprog].bail_unwinds) {
        ...
        branch = push_stack(env, *insn_idx + 1, *insn_idx, false);
        branch->unwound = true;

That branch reaches check_unwound_arrival() -> unwind_frame() with
kind == BPF_SITE_CALL in the caller.  frame_can_unwind() still refuses any
frame that acquired a REF_TYPE_PTR:

    for (i = frame->entry_refs; i < st->acquired_refs; i++)
        if (st->refs[i].type == REF_TYPE_PTR)
            return false;

so the plan gets BPF_CONFLICT_CANNOT_UNWIND ("the frame cannot unwind"),
and since the branch is unconditional the load fails.  For example, as
root with the JIT on:

    __noinline int spin(int n) { int i = 0; while (i != n) i++; return i; }
    SEC("tc") int prog(struct __sk_buff *skb) {
        struct bpf_sock *sk = bpf_sk_lookup_tcp(skb, &t, sizeof(t), -1, 0);
        if (!sk) return 0;
        spin(skb->len);
        bpf_sk_release(sk);
        return 0;
    }

An open-coded iterator in the caller (bpf_for(...) { global_fn(); }) or a
held dynptr fails the same way, because both acquire REF_TYPE_PTR.

The commit message's "What changes for programs that load today" does not
mention these new rejections.  This is fixed later in the series by
3683790e1e6d ("bpf: Let the kernel cancel a frame that holds
references"), so this commit and the three after it still reject these
programs, which matters for bisection.

Separately, there is a related change in which programs can attach.  Global
subprogs now get bail_unwinds, and the landing pad that bpf_insert_sites()
emits for a verifier-added may_goto in such a subprog ends in
unwind_exit_insn(), which sets sub->can_unwind.  jit_subprogs() copies that
into func[i]->aux->can_unwind, and bpf_check_attach_target() then refuses
everything except fentry:

    tgt_can_unwind = subprog && aux->func && aux->func[subprog]->aux->can_unwind;
    if (tgt_can_unwind && !prog_extension &&
        prog->expected_attach_type != BPF_TRACE_FENTRY) {
        bpf_log(log, "Only fentry can attach to %s, which can unwind\n", tname);

Can fexit, fmod_ret and fsession programs no longer attach to global
functions that they could attach to at the parent commit, where the
may_goto left the loop and can_unwind stayed false?  The same happens to
every non-main caller that gets an unwind_goto and a pad for a call of it.

The refusal looks needed, since unwind_exit would return into the
trampoline, but "What changes for programs that load today" does not list
it.  The later commit 0c46504b2d72 ("bpf: Add unwind_goto after helpers
with a callback") does list the same effect for callbacks ("Only fentry
can attach to a callback in which the program can be cancelled."), and
9068ee38c87b ("bpf: Refuse freplace on a function that can unwind")
extends the refusal to freplace.  No later commit restores the old
behaviour.

[ ... ]

> @@ -24024,12 +24060,41 @@ static int check_after_pass(struct bpf_verifier_env *env)
>  	return 0;
>  }
>  
> +/*
> + * A state left a global subprog with unwind_exit or cancel_exit, and the callers did not know. If
> + * the subprog still leaves that way after the pass, as bpf_insert_sites() will see it, did_unwind
> + * and did_cancel go to the next pass, in which the callers expect it.
> + */
> +static void settle_late_unwinds(struct bpf_verifier_env *env, const struct bpf_snapshot *initial)

This isn't a bug, but this comment and the one added in
mark_recursive_subprogs() ("can leave with unwind_exit or cancel_exit")
refer to cancel_exit and did_cancel, which do not exist at this commit.
settle_late_unwinds() and the carry in check_funcs() handle only
did_unwind.

Those terms only become accurate later, with 4faf343a962e ("bpf: Add
cancel_goto and cancel_exit, which only the verifier emits") and
0d9be4be994d ("bpf: Use cancel_exit to leave a frame that the kernel
cancels").  Could the comments describe did_unwind and unwind_exit here,
and have the cancel parts added by those commits?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 42/73] bpf: Make bpf_throw() cancel the program through landing pads
  2026-12-01  4:39 ` [PATCH bpf-next v1 42/73] bpf: Make bpf_throw() cancel the program through landing pads Kumar Kartikeya Dwivedi
@ 2026-12-01  5:41   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:41 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 3550 bytes --]

> bpf: Make bpf_throw() cancel the program through landing pads

TL;DR: Documentation-only nits in verifier.rst: the intro says the kernel
chooses the return value, which contradicts bpf_throw(); and the doc may
misstate that bpf_throw() is rejected only in uncancellable functions,
omitting the JIT unwinding requirement.

> diff --git a/Documentation/bpf/verifier.rst b/Documentation/bpf/verifier.rst
> --- a/Documentation/bpf/verifier.rst
> +++ b/Documentation/bpf/verifier.rst

[ ... ]

> @@ -908,20 +908,20 @@ A recursion in frames is not joined. It has to end in ``MAX_CALL_FRAMES``.
> [ ... ]
>  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.

This isn't a bug, but the introduction still says the program returns a value
that the kernel chooses.  For bpf_throw() the value is the argument of
bpf_throw(), or whatever the exception callback returns, as the paragraph
about the pad of the main function says further down.  Should the sentence be
reworded so the two do not disagree?

[ ... ]

> @@ -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.

Is it accurate to say that bpf_throw() is rejected only in a function that
cannot be cancelled?  The main function can still be cancelled on a JIT
without unwind_exit, but check_unwind_insns() rejects any program that
contains bpf_throw() when the JIT does not support unwinding:

kernel/bpf/failing_path.c:check_unwind_insns() {
    ...
	if (bpf_is_throw_kfunc(insn)) {
		env->has_throw = true;
		seen = true;
	}
    ...
	if (!bpf_jit_supports_unwind() || bpf_prog_is_offloaded(env->prog->aux)) {
		verbose(env, "JIT does not support unwinding\n");
		return -ENOTSUPP;
	}
    ...
}

So on s390x, powerpc64 and for an offloaded program, bpf_throw() in the main
function is rejected as well, unlike a may_goto loop in the same place.  The
commit message states this ("One that is loaded with CAP_BPF alone, or on
s390x or powerpc64, is rejected now").

Should the document say that a program with bpf_throw() needs a JIT that has
unwind_exit and unwind_goto in every function, for example next to the
CAP_PERFMON sentence in the section about capabilities?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 25/73] bpf: Add hidden stack slots for landing pads
  2026-12-01  4:38 ` [PATCH bpf-next v1 25/73] bpf: Add hidden stack slots for landing pads Kumar Kartikeya Dwivedi
  2026-12-01  5:40   ` sashiko-bot
@ 2026-12-01  5:42   ` bot+bpf-ci
  1 sibling, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:42 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 5341 bytes --]

> bpf: Add hidden stack slots for landing pads

TL;DR:
- Possible out-of-bounds write past plan->ents[] in subprog_take_slots(): room
  check skips unused plans, though they are still modified
- Hidden stack words may enable the private stack for small programs (not a
  safety issue)

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c

[ ... ]

> +static int subprog_take_slots(struct bpf_verifier_env *env, int s, int group)
> +{

[ ... ]

> +	for (i = sub->start; i < sub[1].start; i++) {
> +		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
> +			for (j = 0, left = 0; j < plan->nr_ents; j++)
> +				left += class_group(plan->ents[j].class) != group;
> +			if (plan->used && plan_has_slots(plan) &&
> +			    left + slots > BPF_PAD_MAX_ENTS)
> +				return 0;
> +		}
> +	}

[ ... ]

> +	for (i = sub->start; i < sub[1].start; i++) {
> +		for (plan = aux[i].pad_plans; plan; plan = plan->next) {
> +			err = plan_has_slots(plan) ? plan_take_slots(plan, group, notes, nr) : 0;
> +			if (err)
> +				return err;
> +		}
> +	}

Can this overflow plan->ents[] for a plan that is not used?

The room check above only covers plans with plan->used set, but the loop
that converts the plans calls plan_take_slots() for every plan where
plan_has_slots() is true, used or not.

plan_take_slots() keeps the left entries of the other groups and then calls
add_ent() once per slot.  add_ent() has no capacity check:

	ent = &plan->ents[pos];
	memmove(ent + 1, ent, (plan->nr_ents++ - pos) * sizeof(*ent));
	*ent = *new;

and plan->ents is allocated with kzalloc_objs(*plan->ents,
BPF_PAD_MAX_ENTS, ...).  When nr_ents is already BPF_PAD_MAX_ENTS, this
writes past the end of the array.

Unused plans that hold entries do occur.  bpf_pads_mark_used() says 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.
Such a GUARD plan still has the entries its visits recorded, has no
conflict, and passes plan_has_slots().

For example, a function holds 8 task references while it runs a bounded
loop, which leaves an unused GUARD plan with 8 REFS entries.  Elsewhere in
the same function, a call that can be cancelled is reached with and
without bpf_rcu_read_lock(), so the RCU group needs one slot.  The used
plan holds at most 7 other entries and passes the room check, but then:

check_pass()
  bpf_pads_settle()
    settle_slots()
      subprog_take_slots()
        plan_take_slots()
          add_ent()

keeps the 8 entries of the unused GUARD plan and inserts the RCU slot at
position 0, so the memmove() writes one struct bpf_pad_ent past the
allocation.  The same can happen with the LOCKS group and an unused plan
holding 8 references, or when several groups are taken one after another.

The comment above bpf_pad_slot_notes() relies on a bound described as
"see plan_has_room()", but plan_has_room() does not exist in this commit.

A later commit in the series, e49eff9842d3 ("bpf: Cancel a program at a
fault in arena"), adds plan_has_room() and sets plan->conflict =
BPF_CONFLICT_SLOTS_FULL on any plan without room before plan_take_slots()
can run on it.  This commit and the ones before that fix still have the
overflow.  Should the room check cover every plan that plan_take_slots()
changes, not only the used ones?

[ ... ]

> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c

[ ... ]

> @@ -24184,9 +24237,12 @@ static int check_pass(struct bpf_verifier_env *env, struct bpf_snapshot *initial
>  	mark_used_sites(env, initial);
> -	ret = check_after_pass(env) ?: bpf_pads_settle(env);
> +	ret = bpf_pads_settle(env) ?: check_after_pass(env);

Do the hidden words now count toward the private stack threshold?

bpf_pads_settle() sets sub->stack_depth = bpf_stack_depth_with_slots(sub)
for each subprog with hidden words, and check_after_pass() ->
check_max_stack_depth() then tests:

	if (round_up_stack_depth(env, si[s].stack_depth) >= BPF_PRIV_STACK_MIN_SIZE) {
		si[s].priv_stack_mode = PRIV_STACK_ADAPTIVE;
		env->prog->aux->jits_use_priv_stack = true;
	}

try_max_stack_depth() makes the same decision with the hidden words
included.  A tracepoint, raw_tp, perf_event or kprobe.multi function on a
JIT with private stack support, with 48 bytes of stack and one hidden slot,
gets depth round_up(48, 8) + 8 = 56, which rounds to 64, so it becomes
PRIV_STACK_ADAPTIVE where it would otherwise stay on the kernel stack.
The words of removed bpf_fastcall spills that keep_fastcall_stack leaves in
the frame count the same way.

This is not a safety problem, since the private stack is sized from the
same stack_depth, and only functions that need hidden slots are affected.
The commit message lists the costs of hidden slots but not this one.

A later commit in the series, 3de7ddfb1533 ("bpf: Don't let hidden stack
words turn on the private stack"), adds hidden_in_depth and
fastcall_spills_gone and compares bpf_stack_depth_of_prog() with
BPF_PRIV_STACK_MIN_SIZE instead.


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 49/73] bpf: Cancel the program when the time of its own may_goto is up
  2026-12-01  4:39 ` [PATCH bpf-next v1 49/73] bpf: Cancel the program when the time of its own may_goto is up Kumar Kartikeya Dwivedi
@ 2026-12-01  5:42   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:42 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 9462 bytes --]

> bpf: Cancel the program when the time of its own may_goto is up

TL;DR:
- Selftests may fail on JITs without unwind support (s390x, riscv64,
  powerpc64, loongarch): may_goto_far, cond_break5, stack_arg
- Inaccurate may_goto_nop comment and commit message
- Misplaced prototype and stale test comment (nits)

> diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
> --- a/include/linux/bpf_verifier.h
> +++ b/include/linux/bpf_verifier.h

[ ... ]

> @@ -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;

Does this comment match what bpf_mark_may_goto_nops() actually marks?

The walk also skips 'ja' nops and every self addr_space_cast, so in
'may_goto +1; ja +0; r0 = 0' the may_goto is marked even though it does not
jump over only may_gotos.

Also, bpf_opt_remove_nops() does not always remove a marked insn.  Its own
comment says "If the cast stays, so does the may_goto that jumps over it",
and insn_is_nop() keeps insns with indirect_target or nospec set, which
bpf_mark_may_goto_nops() does not check.  When the program is not is_priv,
sanitize_dead_code() runs and no nops are removed at all.

The commit message repeats this with "The verifier removes such an insn".
Would something like "a may_goto that jumps only over nops and casts that
may become nops; it is not a site, and bpf_opt_remove_nops() usually
removes it" be accurate?

[ ... ]

> @@ -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 */

this isn't a bug, but this prototype sits in the flow.c block of
bpf_verifier.h while bpf_mark_may_goto_nops() is defined in
kernel/bpf/fixups.c and called from bpf_check().  Could it move to the
'/* Functions in fixups.c, called from bpf_check() */' block next to
bpf_opt_remove_nops() and bpf_lower_cast_mov()?

[ ... ]

> diff --git a/tools/testing/selftests/bpf/prog_tests/may_goto_far.c b/tools/testing/selftests/bpf/prog_tests/may_goto_far.c
> --- a/tools/testing/selftests/bpf/prog_tests/may_goto_far.c
> +++ b/tools/testing/selftests/bpf/prog_tests/may_goto_far.c

[ ... ]

> @@ -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);
>  }

Does this expectation hold on every architecture?  Retval 2 only holds
where the may_goto is a cancellation site.  For the four 'subprog'
subtests the may_goto is in subprog 1, which has a caller in the program,
so it can be cancelled only when bail_unwinds is set:

    si[s].bail_unwinds = si[s].can_unwind ||
                         (s && env->prog->jit_requested &&
                          bpf_jit_supports_unwind() && ...);

Only the x86 and arm64 JITs override bpf_jit_supports_unwind().  On s390,
powerpc, riscv and loongarch, which do support the timed may_goto,
frame_cannot_unwind() returns BPF_CONFLICT_CANNOT_UNWIND, the subprog is
marked stuck and the insn stays a plain jump:

    if (sub->stuck || frame_cannot_unwind(env, env->cur_state)) {
            ...
            sub->stuck = true;
            return 0;
    }

After the time is up the jump goes to the target the program gives it, r0
is 0 from 'r0 = r9', and the program returns 0, so ASSERT_EQ(topts.retval,
2) fails.  The same happens with the interpreter (bpf_jit_enable=0), where
jit_requested is false and every subtest returns 0.

may_goto_far is not in DENYLIST.s390x, and s390x runs test_progs in BPF CI.
timed_may_goto.c, in contrast, skips when !is_jit_enabled() and stops
before its unwinding checks on anything but x86_64 and aarch64.

Should the subprog subtests be skipped, or expect 0, when the JIT cannot
unwind, and should the test skip without a JIT?

Also, this isn't a bug, but the header comment above test_far() still
begins 'Syscall prog that loops until may_goto expires', while the load now
uses BPF_PROG_TYPE_SCHED_CLS.

[ ... ]

> diff --git a/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c b/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c
> --- a/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c
> +++ b/tools/testing/selftests/bpf/progs/verifier_iterating_callbacks.c

[ ... ]

>  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;
>  }

Will cond_break5 pass on JITs that cannot unwind?  __load_if_JITed() only
skips the interpreter, and the test has no __arch_x86_64/__arch_arm64 tag.

The time slice is used up in static_subprog(), whose frame has a caller in
the program.  Its cond_break is cancelled only if the subprog has
bail_unwinds, and frame_cannot_unwind() returns BPF_CONFLICT_CANNOT_UNWIND
for '!frame_is_top(st) && !sub->bail_unwinds'.  Only x86 and arm64 override
bpf_jit_supports_unwind(); s390x, riscv64, powerpc64 and loongarch use the
weak default of false but return true from bpf_jit_supports_timed_may_goto().

There check_may_goto_site() marks static_subprog stuck and the may_goto
stays a plain jump.  The commit message says this too: "a frame cannot be
cancelled if ... it has a caller in the program and the JIT has no
unwind_exit".  static_subprog() then leaves its loop with a large cnt, main
has no may_goto after the call, and the program returns 1 instead of 0.

Before this patch the test expected 1 and passed on every JIT.  Now
verifier_iterating_callbacks/cond_break5 would fail on s390x, which BPF CI
runs, and on riscv64, powerpc64 and loongarch.  cond_break4 is not affected
because its loop is in the main prog.

Should cond_break5 carry the same __arch_x86_64/__arch_arm64 tags used by
the other unwinding tests in this patch, or expect 1 where the subprog
cannot unwind?

[ ... ]

> diff --git a/tools/testing/selftests/bpf/progs/verifier_stack_arg.c b/tools/testing/selftests/bpf/progs/verifier_stack_arg.c
> --- a/tools/testing/selftests/bpf/progs/verifier_stack_arg.c
> +++ b/tools/testing/selftests/bpf/progs/verifier_stack_arg.c

[ ... ]

> @@ -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)

Does __retval(2) hold on riscv64?  This test has no __arch_ tag and sits in
the block guarded by:

    #if (defined(__TARGET_ARCH_x86) || defined(__TARGET_ARCH_arm64) || \
        (defined(__TARGET_ARCH_riscv) && __riscv_xlen == 64)) && \
        defined(__BPF_FEATURE_STACK_ARGUMENT)

riscv64 implements bpf_jit_supports_timed_may_goto() but not
bpf_jit_supports_unwind().  spins_then_reads_8args() is a subprog called
from main, so frame_is_top() is false and bail_unwinds is false there.
frame_cannot_unwind() then returns BPF_CONFLICT_CANNOT_UNWIND,
check_may_goto_site() marks the function stuck and the may_goto stays a
plain jump.  When the time is up the callee loads its stack args and the
program returns 876 as before, so verifier_stack_arg fails on riscv64
(it is not in DENYLIST.riscv64).

verifier_patch_list.c in the same patch handles this split with
__arch_x86_64 __arch_arm64 on patch_list_insert_in_front and a separate
patch_list_insert_in_front_no_pads for s390x, riscv64 and loongarch.
Should this test get the same treatment, with a riscv64 variant that
still expects 876?

[ ... ]


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 66/73] bpf: Let the entry of a cleanup pad save the pointers of the frame
  2026-12-01  4:39 ` [PATCH bpf-next v1 66/73] bpf: Let the entry of a cleanup pad save the pointers of the frame Kumar Kartikeya Dwivedi
@ 2026-12-01  5:42   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:42 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 5632 bytes --]

> bpf: Let the entry of a cleanup pad save the pointers of the frame

TL;DR:
- Possible program rejection: extra save words may exhaust stack room, with no
  fallback
- An entry that saves nothing may still claim a save word, so a program can be
  rejected depending on entry order
- Level 2 log may report saves that are not emitted

> diff --git a/kernel/bpf/pads.c b/kernel/bpf/pads.c
> --- a/kernel/bpf/pads.c
> +++ b/kernel/bpf/pads.c

[ ... ]

> +		if (!ent->nr_cands[0])
> +			continue;
> +		ent->word = j + 1;
> +		save = &sub->saves[j];
> +		if (!save->set)
> +			*save = (struct bpf_pad_save){ .release = ent->release,
> +						       .obj_type = ent->obj_type, .set = true };
> +		if (!ent_is_saved_kind(sub, j, ent))
> +			return BPF_CONFLICT_SAVES_DIFFER;

An entry that ends up saving nothing still claims the kind of each save
word here.

bpf_pad_enter() calls visit_saves() even when entry_saves_nothing is set,
and visit_saves() fills sub->saves[j] from the first state before it finds
out that the states disagree. That entry then stores 0 into every word, but
its claim stays in sub->saves[] for the rest of the pass and in every
repeated pass.

Say function f has two entries, E1 and E2. E1's states disagree (a task in
R6 on one path, in R7 on another), so E1 saves nothing and its cleanup pad
releases the task itself. E2 holds a socket at position 0 and needs it
saved. If E1 is visited first, sub->saves[0] gets the task kind, E2 then
gets BPF_CONFLICT_SAVES_DIFFER from ent_is_saved_kind() and saves nothing,
and the remainder of E2 has no location for the socket, so the program is
rejected. Visited in the other order, the program loads.

The commit message says an entry saves nothing if "a word would get a
second kind of object", but here no frame ever stores the first kind in that
word.

Should sub->saves[] be claimed only when the entry actually saves, that is
when entry_saves_nothing is clear?

[ ... ]

> @@ -3465,8 +3764,15 @@ static void print_plan(struct bpf_verifier_env *env, int i, const struct bpf_pad
>
>  	/* no generated pad: the entry of a cleanup pad */
>  	if (plan->kind == BPF_SITE_CANCEL_ENTRY) {
> -		verbose(env, "landing pad of the program behind the call at %d: the kernel enters it\n",
> +		verbose(env, "landing pad of the program behind the call at %d: the kernel enters it",
>  			i);
> +		for (j = 0; j < plan->nr_ents; j++) {
> +			if (!plan->ents[j].nr_cands[0])
> +				continue;
> +			verbose(env, ", saves ");
> +			print_ent(env, &plan->ents[j]);
> +		}
> +		verbose(env, "\n");
>  		return;
>  	}

This isn't a bug in the verifier result, but the level 2 log can report
saves that the emitted entry does not make.

print_plan() prints ", saves <ent>" for every ent with a candidate, while
the emission and the word count use saved_ent(), which returns NULL for
every word when the function has hidden slots for references:

	if (sub->slots & BIT(BPF_PAD_GROUP_REFS))
		return NULL;

In that case take_cancelled_words() computes save_words = 0 and
bpf_pad_cancel_entry_insns() emits no save stores, yet the log still says
for example "the kernel enters it, saves ref@M(r6)".  The same text can
appear in front of a rejection in bpf_pad_log().

Would it be better to print only the ents for which saved_ent() returns
non-NULL?

[ ... ]

> @@ -3831,19 +4148,95 @@ static int take_value_word(struct bpf_verifier_env *env, struct bpf_subprog_info
>   */
>  static int take_cancelled_words(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
>  {

[ ... ]

> +	for (i = sub->start; i < sub[1].start; i++) {
> +		plan = bpf_pad_plan(&aux[i], BPF_SITE_CANCEL_ENTRY);
> +		for (j = 0; plan && j < BPF_PAD_MAX_SAVES; j++)
> +			if (saved_ent(sub, plan, j))
> +				words = max(words, j + 1);
> +	}
> +	sub->hidden_words += 1 + words;
>  	err = bpf_hidden_slots_fit(env);
>  	if (err <= 0) {
> -		sub->hidden_words--;
> +		sub->hidden_words -= 1 + words;
>  		return err ?: 1;
>  	}

Can this reject a program that loaded before this commit?

visit_saves() gives a save word to every pointer that the frame holds in
R6-R9 or in a live stack slot at a cancellable call.  It runs at the entry,
before the cleanup pad is explored, so it cannot know whether the pad
releases the object itself. Here "words" is the highest word any entry
record uses, not the highest word a pad actually reads.

Take a function whose cleanup pad releases a task held in R6 by itself
(r1 = r6; call bpf_task_release; unwind_exit), so nothing is held at
unwind_exit. Before this commit only the "cancelled" word was taken (plus
the value word with bpf_throw()); now one more word is reserved that the
remainder never reads.  If the call chain is within 8 bytes of the stack
limit or of a rounding boundary, bpf_hidden_slots_fit() fails, and
take_cleanup_pad_words() rejects the program with "no room in the stack for
the hidden words of func#%d" (-EINVAL).

There is no retry with an entry that saves nothing: settle_entries() has
that fallback for BPF_CONFLICT_SAVES_DIFFER and BPF_CONFLICT_TOO_MUCH, but
not for lack of stack room.  The commit message says a function "pays in
stack only: 8 bytes per save word", but not that this can turn an accepted
program into a rejected one.

Could the words be counted only up to the highest one that a pad of a
cancelled frame reads, or could the entry fall back to saving nothing when
the words do not fit?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 57/73] bpf: Use cancel_exit to leave a frame that the kernel cancels
  2026-12-01  4:39 ` [PATCH bpf-next v1 57/73] bpf: Use cancel_exit to leave a frame that the kernel cancels Kumar Kartikeya Dwivedi
@ 2026-12-01  5:42   ` bot+bpf-ci
  0 siblings, 0 replies; 115+ messages in thread
From: bot+bpf-ci @ 2026-12-01  5:42 UTC (permalink / raw)
  To: memxor, bpf
  Cc: ast, andrii, daniel, eddyz87, emil, ihor.solodrai, kkd,
	kernel-team, ast, andrii, daniel, martin.lau, eddyz87,
	yonghong.song, mason, ihor.solodrai

[-- Attachment #1: Type: text/plain, Size: 1632 bytes --]

> bpf: Use cancel_exit to leave a frame that the kernel cancels

TL;DR: Nit only: the new insert_unwind_gotos() comment documents an @stubbed
parameter that doesn't exist until a later patch in the series. Could that
sentence move to that patch?

> diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
> --- a/kernel/bpf/fixups.c
> +++ b/kernel/bpf/fixups.c

[ ... ]

>  /*
> - * Add unwind_goto after the calls that are sites, see check_unwound_arrival(), and after the
> [ ... ]
> + * Add unwind_goto and cancel_goto after the sites, now that the pads are in the program. @added is
> + * the number of insns appended to each subprog, @stubbed the number of its unwind_gotos with a
> + * stub. An access to arena that is a site gets an unwind_goto, and so does a call without one to
> [ ... ]
>   */
>  static int insert_unwind_gotos(struct bpf_verifier_env *env, const int *added)

The new header comment of insert_unwind_gotos() documents "@stubbed the
number of its unwind_gotos with a stub", but the function takes only (env,
added) and nothing in this commit creates a stub.

The parameter and the stubs first appear in a later commit of the series,
696e1c8c75a1 ("bpf: Emit the stub, the entry and the remainder of a cleanup
pad"), which changes the signature to insert_unwind_gotos(env, added,
stubbed).

Could the @stubbed sentence be dropped here and added in that later commit?


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

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

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 72/73] bpf: Give cancelled tcp_congestion_ops programs values that TCP can take
  2026-12-01  4:39 ` [PATCH bpf-next v1 72/73] bpf: Give cancelled tcp_congestion_ops programs values that TCP can take Kumar Kartikeya Dwivedi
@ 2026-12-01  5:46   ` sashiko-bot
  0 siblings, 0 replies; 115+ messages in thread
From: sashiko-bot @ 2026-12-01  5:46 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, bpf

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] bpf: multi-line comment style violation above
  bpf_tcp_ca_cancelled_retval()
--

commit d61aeecc80ea9ee35fbdcf25dbc56aaed0f107d2
Author: Kumar Kartikeya Dwivedi <memxor@gmail.com>

bpf: Give cancelled tcp_congestion_ops programs values that TCP can take

This commit implements .cancelled_retval() for bpf_tcp_congestion_ops so
that cancelled tcp_congestion_ops programs return safe minimum values for
ssthresh, undo_cwnd, tso_segs, and sndbuf_expand instead of 0.

> diff --git a/net/ipv4/bpf_tcp_ca.c b/net/ipv4/bpf_tcp_ca.c
> index 2a71dc81562f4..4b9ea3058b6f6 100644
> --- a/net/ipv4/bpf_tcp_ca.c
> +++ b/net/ipv4/bpf_tcp_ca.c
> @@ -256,6 +256,36 @@ static int bpf_tcp_ca_validate(void *kdata)
>  	return tcp_validate_congestion_control(kdata);
>  }
>  
> +/* What a program returns when the kernel cancels it, which ends the program
> + * early, for example at a loop that runs out of time. The value is a constant,

[Severity: Low]
This isn't a bug, but BPF code uses the multi-line comment style with the
opening /* on its own line and the comment text starting on the following
line.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1796099737.git.memxor@gmail.com?part=72

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 58/73] bpf: Check that a helper whose callback may unwind has an unwind label
  2026-12-01  4:39 ` [PATCH bpf-next v1 58/73] bpf: Check that a helper whose callback may unwind has an unwind label Kumar Kartikeya Dwivedi
  2026-12-01  5:26   ` bot+bpf-ci
@ 2026-12-01  5:47   ` sashiko-bot
  1 sibling, 0 replies; 115+ messages in thread
From: sashiko-bot @ 2026-12-01  5:47 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, bpf

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] bpf: cb_pads placed in per_pass resets check_cb_pad() cache
  every pass
--

commit 380cfb3192a5afe13d0abaeae652daee9480f8e4
Author: Kumar Kartikeya Dwivedi <memxor@gmail.com>

bpf: Check that a helper whose callback may unwind has an unwind label

This commit checks at program load time that helpers, kfuncs, and map
callback ops listed as having an unwind label have a bpf_call_cb()
exception table entry.

> diff --git a/include/linux/bpf_verifier.h b/include/linux/bpf_verifier.h
> index c500504cbfe17..6efe11f458b7e 100644
> --- a/include/linux/bpf_verifier.h
> +++ b/include/linux/bpf_verifier.h
> @@ -1902,6 +1902,9 @@ struct bpf_verifier_env {
>  	bool run_over_budget;		/* in one of its functions, see find_failing_path() */
>  	bool restart;			/* see bpf_flow_next_is_no_bound() */
>  	bool guards_late;		/* see bpf_flow_needs_guard() */
> +	/* the helpers and kfuncs whose unwind label was found, see check_cb_pad() */
> +	unsigned long cb_pads[8];
> +	u8 cb_pad_cnt;
>  	bool pads_late;			/* a global subprog unwinds: see settle_late_unwinds() */
>  	bool faults_late;		/* a site is not what it seemed: see check_arena_site() */
>  	bool pad_releases;		/* see release_frame_resources() */

[Severity: Low]
Should cb_pads and cb_pad_cnt be placed outside the per_pass group in
struct bpf_verifier_env?

check_cb_pad() caches verified functions so each is checked once per load,
but fields in per_pass are restored from the initial snapshot by
check_funcs() -> restore_snapshot(env, initial) at the start of every
verifier pass and path-sensitive run, resetting cb_pad_cnt to 0 and
repeating the kallsyms and exception table scan on each pass.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1796099737.git.memxor@gmail.com?part=58

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 71/73] bpf: Let a struct_ops say what a cancelled program returns
  2026-12-01  4:39 ` [PATCH bpf-next v1 71/73] bpf: Let a struct_ops say what a cancelled program returns Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` bot+bpf-ci
@ 2026-12-01  5:47   ` sashiko-bot
  1 sibling, 0 replies; 115+ messages in thread
From: sashiko-bot @ 2026-12-01  5:47 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, bpf

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Low] bpf: non-standard multi-line comment style above
  bpf_qdisc_cancelled_retval()
--

commit 244ad2a9c98f183d25b7f3f7eb78663a3d90e39b
Author: Kumar Kartikeya Dwivedi <memxor@gmail.com>

bpf: Let a struct_ops say what a cancelled program returns

This commit adds a cancelled_retval() callback to struct bpf_struct_ops so
struct_ops implementations can specify the return value of a cancelled
program, and implements it for bpf_qdisc.

> diff --git a/net/sched/bpf_qdisc.c b/net/sched/bpf_qdisc.c
> index 5098cf5a487c0..4b274c76163af 100644
> --- a/net/sched/bpf_qdisc.c
> +++ b/net/sched/bpf_qdisc.c
> @@ -453,6 +453,26 @@ static int bpf_qdisc_validate(void *kdata)
>  	return 0;
>  }
>  
> +/* What a program returns when the kernel cancels it, which ends the program
> + * early, for example at a loop that runs out of time:
> + *
> + * ->enqueue()	NET_XMIT_DROP. The program may not have queued the packet, and
> + *		the kernel has freed the packet if the program still held it.
> + * ->init()	-ECANCELED, so that qdisc_create() calls ->destroy() and frees
> + *		the qdisc, as for any ->init() that fails.
> + * ->dequeue() returns NULL. ->reset() and ->destroy() return nothing.
> + */

[Severity: Low]
This isn't a bug, but BPF multi-line comments place the opening /* on its
own line with the comment text starting on the next line.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1796099737.git.memxor@gmail.com?part=71

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 39/73] bpf: Refuse freplace on a function that can unwind
  2026-12-01  4:39 ` [PATCH bpf-next v1 39/73] bpf: Refuse freplace on a function that can unwind Kumar Kartikeya Dwivedi
  2026-12-01  5:25   ` bot+bpf-ci
@ 2026-12-01  5:51   ` sashiko-bot
  1 sibling, 0 replies; 115+ messages in thread
From: sashiko-bot @ 2026-12-01  5:51 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, bpf

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] bpf: false late unwinds for subprog 0 in
  settle_late_unwinds()
--

commit 4a1e048f994fc17a773dbe271079f0b7119352ca
Author: Alexei Starovoitov <ast@kernel.org>

bpf: Refuse freplace on a function that can unwind

This commit marks subprog 0 as able to unwind when it has an unwind or
cancellation site and rejects freplace attachment to functions (including
the main program) that can unwind.

> diff --git a/kernel/bpf/fixups.c b/kernel/bpf/fixups.c
> index 75ad6f567e145..a20830a628e75 100644
> --- a/kernel/bpf/fixups.c
> +++ b/kernel/bpf/fixups.c
> @@ -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;

[Severity: Medium]
Can setting subprog_info[0].can_unwind here cause settle_late_unwinds() to
falsely keep env->pads_late set?

bpf_mark_subprogs_that_unwind() is also called by settle_late_unwinds() at
the end of check_funcs() whenever env->pads_late was set during the pass:

kernel/bpf/verifier.c:settle_late_unwinds() {
    ...
	bpf_mark_subprogs_that_unwind(env);
	for (s = 0; s < env->subprog_cnt; s++, sub++) {
		unwinds = sub->can_unwind;
		sub->can_unwind = initial->subprogs[s].can_unwind;
		late |= unwinds && !initial->subprogs[s].did_unwind &&
			bpf_subprog_is_global(env, s);
		sub->did_unwind = unwinds;
	}
	env->pads_late = late;
}

For the main program (s == 0), bpf_subprog_is_global(env, 0) is true, while
initial->subprogs[0].did_unwind remains false across pass restarts because
check_funcs() only propagates did_unwind into initial->subprogs[i] for
i >= 1.

When a global subprog (s >= 1) speculatively triggers unwind_frame() on a
loop whose guard is later dropped by bpf_flow_drop_guards(), and subprog 0
has any kept site of its own, the s == 0 iteration of settle_late_unwinds()
sets env->pads_late = true. In pass 0 this forces an unnecessary pass
restart; if reached on a later pass where bpf_flow_new_pass() no longer
updates loop->guarded (flow->start_cnt >= 3), do_check_all() restarts the
pass repeatedly until bpf_check_limits() fails with -E2BIG.

Starting the loop in settle_late_unwinds() at s = 1 (or excluding s == 0
from the late calculation) would avoid treating subprog 0 as a late-unwinding
global subprog.

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1796099737.git.memxor@gmail.com?part=39

^ permalink raw reply	[flat|nested] 115+ messages in thread

* Re: [PATCH bpf-next v1 36/73] bpf: Cancel a program at a fault in arena
  2026-12-01  4:39 ` [PATCH bpf-next v1 36/73] bpf: Cancel a program at a fault in arena Kumar Kartikeya Dwivedi
@ 2026-12-01  5:52   ` sashiko-bot
  0 siblings, 0 replies; 115+ messages in thread
From: sashiko-bot @ 2026-12-01  5:52 UTC (permalink / raw)
  To: Kumar Kartikeya Dwivedi, bpf

Thank you for your contribution! Sashiko AI review found 1 potential
issue to consider:
- [Medium] bpf: stale must_unwind from loop guards in unwind_frame()
  rejects valid progs
--

commit af6a8f2fbfcbcd96ae67354d19f5ed09116636d1
Author: Kumar Kartikeya Dwivedi <memxor@gmail.com>

bpf: Cancel a program at a fault in arena

This commit treats arena accesses as cancellation sites so that a fault in
arena unwinds and cancels the BPF program through a landing pad when one
can be generated, or falls back to skipping the faulting access when a
landing pad cannot be generated.

> diff --git a/kernel/bpf/verifier.c b/kernel/bpf/verifier.c
> index 478fdc2d66424..07fdc4fc7ebcc 100644
> --- a/kernel/bpf/verifier.c
> +++ b/kernel/bpf/verifier.c
[ ... ]
> @@ -22110,7 +22227,8 @@ static int unwind_frame(struct bpf_verifier_env *env, struct bpf_verifier_state
>  		env->pads_late = true;
>  	}
>  	sub->did_unwind |= st->unwound;
> -	sub->unwinds_for_sure |= st->unwound && certain;
> +	sub->must_unwind |= st->unwound && plan && bpf_pad_must_unwind(env, plan);
> +	sub->unwinds_for_sure |= st->unwound && plan && bpf_pad_must_unwind(env, plan) && certain;
>  	if (env->log.level & BPF_LOG_LEVEL2)
>  		verbose(env, "from %d to %s of func#%d\n", insn_idx,
>  			st->unwound ? "unwind_exit" : "exit", frame->subprogno);

[Severity: Medium]
Can a speculative loop guard leave sub->must_unwind set after the loop is
proven bounded, causing the verifier to reject a valid program instead of
skipping its arena faults?

During pass 0, every non-rt_bounded loop starts with loop->guarded set, so
check_loop_guard() pushes a speculative BPF_SITE_GUARD unwind edge where
site_is_certain() is false.  unwind_frame() sets sub->must_unwind without
checking certain, and bpf_pads_must_unwind() only propagates must_unwind
upward across calls without recomputing it after bpf_flow_drop_guards()
clears loop_guard on bounded loops.

If a subprogram contains both a bounded loop and an arena access,
sub->must_unwind stays true even though the subprogram only unwinds at the
arena fault.  When that subprogram is used as a non-unwinding callback or
called from a site with a landing pad conflict (such as a caller in nine
RCU sections), subprog_cannot_unwind() or bpf_pads_settle() rejects the
program with -EINVAL instead of calling skip_faults().

-- 
Sashiko AI review · https://sashiko.dev/#/patchset/cover.1796099737.git.memxor@gmail.com?part=36

^ permalink raw reply	[flat|nested] 115+ messages in thread

end of thread, other threads:[~2026-12-01  5:52 UTC | newest]

Thread overview: 115+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-12-01  4:38 [PATCH bpf-next v1 00/73] Cancellations Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 01/73] bpf: Refuse a program that is too large for bpf_prog->pages Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 02/73] bpf: Require CAP_PERFMON for unwind_exit and unwind_goto Kumar Kartikeya Dwivedi
2026-12-01  5:25   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 03/73] bpf: Reject bpf_percpu_obj_drop() of a type with special fields Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 04/73] bpf: Drop the edge after bpf_throw() from the control flow graph Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 05/73] bpf: Let a helper call its callback with an unwind label Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 06/73] bpf, x86, arm64: Add landings that redo what follows a helper call Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 07/73] bpf: Let a callback unwind out of a helper that has an unwind label Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 08/73] bpf: Let the inlined bpf_loop pass on a callback that unwinds Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 09/73] bpf: Give the helpers that call a callback an unwind label Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 10/73] bpf: Let the comparator of bpf_rbtree_add unwind Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 11/73] bpf: Let a state leave its frame at may_goto without an exit insn Kumar Kartikeya Dwivedi
2026-12-01  5:25   ` sashiko-bot
2026-12-01  4:38 ` [PATCH bpf-next v1 12/73] bpf: Choose what a cancelled program returns by its type Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 13/73] bpf: Emit landing pads that leave RCU sections Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 14/73] bpf: Release locks and irq flags in landing pads Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 15/73] bpf: Add unwind_goto after calls of subprogs Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 16/73] bpf: Let the kernel cancel a program in a global subprog Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 17/73] bpf: Release references in landing pads Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 18/73] bpf: Release iterators and dynptrs " Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 19/73] bpf: Check pointers for NULL " Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 20/73] bpf: Let the kernel cancel a frame that holds references Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 21/73] bpf: Add unwind_goto after helpers with a callback Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 22/73] bpf: Let a may_goto that the verifier adds go to its landing pad only Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 23/73] bpf: Record why a callee is cancelled when its call gets no landing pad Kumar Kartikeya Dwivedi
2026-12-01  5:26   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 24/73] bpf: Record what each call acquires and releases Kumar Kartikeya Dwivedi
2026-12-01  5:31   ` sashiko-bot
2026-12-01  4:38 ` [PATCH bpf-next v1 25/73] bpf: Add hidden stack slots for landing pads Kumar Kartikeya Dwivedi
2026-12-01  5:40   ` sashiko-bot
2026-12-01  5:42   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 26/73] bpf: Use hidden slots for a pointer that has no location at a site Kumar Kartikeya Dwivedi
2026-12-01  5:25   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 27/73] bpf: Restore the sections of the call when a frame is cancelled Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 28/73] bpf: Let hidden slots follow what a subprog does for its caller Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 29/73] bpf: Let a callee hold a reference that its call hands over Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 30/73] bpf: Let a call clear the hidden slot of what its callee releases Kumar Kartikeya Dwivedi
2026-12-01  4:38 ` [PATCH bpf-next v1 31/73] bpf: Give a callee a hidden slot for the reference that it is handed Kumar Kartikeya Dwivedi
2026-12-01  5:26   ` bot+bpf-ci
2026-12-01  4:38 ` [PATCH bpf-next v1 32/73] bpf: Give unwind_goto a 32 bit offset and prepare it for arena accesses Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 33/73] bpf, x86: Go to the landing pad when an access to arena faults Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 34/73] bpf, arm64: " Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 35/73] bpf: Let a register be the location of a lock in a global variable Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 36/73] bpf: Cancel a program at a fault in arena Kumar Kartikeya Dwivedi
2026-12-01  5:52   ` sashiko-bot
2026-12-01  4:39 ` [PATCH bpf-next v1 37/73] bpf: Share one landing pad among accesses to arena where nothing is held Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 38/73] bpf: Keep R0, R6-R9 and the stack live at a call of bpf_throw() Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 39/73] bpf: Refuse freplace on a function that can unwind Kumar Kartikeya Dwivedi
2026-12-01  5:25   ` bot+bpf-ci
2026-12-01  5:51   ` sashiko-bot
2026-12-01  4:39 ` [PATCH bpf-next v1 40/73] bpf: Let landing pads pass on the value of unwind_exit Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 41/73] bpf: Keep a reference of the caller that a function finds NULL Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 42/73] bpf: Make bpf_throw() cancel the program through landing pads Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 43/73] bpf, x86: Remove the exception boundary Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 44/73] bpf, arm64: " Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 45/73] s390/bpf: " Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 46/73] powerpc64/bpf: " Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 47/73] bpf: Remove the stack walk of bpf_throw() Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 48/73] bpf: Find at a site that a frame holds more than a landing pad releases Kumar Kartikeya Dwivedi
2026-12-01  5:25   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 49/73] bpf: Cancel the program when the time of its own may_goto is up Kumar Kartikeya Dwivedi
2026-12-01  5:42   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 50/73] bpf: Reject a program that has no landing pad for a fault in arena Kumar Kartikeya Dwivedi
2026-12-01  5:26   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 51/73] bpf: Log why a call is a site and which functions cannot be cancelled Kumar Kartikeya Dwivedi
2026-12-01  5:25   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 52/73] bpf: Add cancel_goto and cancel_exit, which only the verifier emits Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 53/73] bpf: Give the unwind label of a helper a second way in Kumar Kartikeya Dwivedi
2026-12-01  5:26   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 54/73] bpf, x86: Put the landing of unwind_goto after the function Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 55/73] bpf, x86: Return to cancel_goto at cancel_exit Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 56/73] bpf, arm64: " Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 57/73] bpf: Use cancel_exit to leave a frame that the kernel cancels Kumar Kartikeya Dwivedi
2026-12-01  5:42   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 58/73] bpf: Check that a helper whose callback may unwind has an unwind label Kumar Kartikeya Dwivedi
2026-12-01  5:26   ` bot+bpf-ci
2026-12-01  5:47   ` sashiko-bot
2026-12-01  4:39 ` [PATCH bpf-next v1 59/73] bpf: Find the landing pads of a program that can only clean up Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 60/73] bpf: Don't let hidden stack words turn on the private stack Kumar Kartikeya Dwivedi
2026-12-01  5:25   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 61/73] bpf: Add a landing pad per site for frames that are cancelled already Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 62/73] bpf: Verify a cleanup pad for a frame that is cancelled Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 63/73] bpf: Reject a program whose cleanup pad a cancellation cannot enter Kumar Kartikeya Dwivedi
2026-12-01  5:25   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 64/73] bpf: Find the code that a cleanup pad can reach Kumar Kartikeya Dwivedi
2026-12-01  5:41   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 65/73] bpf: Emit the stub, the entry and the remainder of a cleanup pad Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 66/73] bpf: Let the entry of a cleanup pad save the pointers of the frame Kumar Kartikeya Dwivedi
2026-12-01  5:42   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 67/73] bpf: Run the cleanup pads of a program when the kernel cancels it Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 68/73] bpf: End the path at a call of a global subprog that never returns Kumar Kartikeya Dwivedi
2026-12-01  5:26   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 69/73] bpf: Tell struct_ops when a program was cancelled Kumar Kartikeya Dwivedi
2026-12-01  5:26   ` bot+bpf-ci
2026-12-01  4:39 ` [PATCH bpf-next v1 70/73] bpf: Tell struct_ops when cancel_exit returns to the kernel Kumar Kartikeya Dwivedi
2026-12-01  4:39 ` [PATCH bpf-next v1 71/73] bpf: Let a struct_ops say what a cancelled program returns Kumar Kartikeya Dwivedi
2026-12-01  5:25   ` bot+bpf-ci
2026-12-01  5:47   ` sashiko-bot
2026-12-01  4:39 ` [PATCH bpf-next v1 72/73] bpf: Give cancelled tcp_congestion_ops programs values that TCP can take Kumar Kartikeya Dwivedi
2026-12-01  5:46   ` sashiko-bot
2026-12-01  4:39 ` [PATCH bpf-next v1 73/73] sched_ext: Treat a cancelled program as a scheduler error Kumar Kartikeya Dwivedi
2026-12-01  5:25   ` bot+bpf-ci

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox