Skip to contentSkip to conversation

bpf: better error reporting when verifier hits 1M instructions limit

RFC PATCH Superseded Eduard Zingerman 3 participants 19 messages May 26

Subsystems (4)

v1 of 3 Superseded Latest is v3 →

lore
Share & tools
lore

Eduard Zingerman

author maintainer
#0 lore raw

cover bpf: better error reporting when verifier hits 1M instructions limit

When the BPF verifier exceeds the 1M instruction budget, the current error output shows a random execution trace that happens to be active at the moment, which is not very helpful for debugging.

This series improves the error report using a profiler-inspired
approach: collect and count "callchain" stack traces that the verifier visits during program validation, and report the top 3 hottest traces when the budget is exhausted. To minimize performance an memory impact of such profiling, only collect samples when verifier visits loop headers, iterator next, may_goto and callback-calling instructions.

For callchains ending at iterator next, may_goto, or callback-calling instructions, identify which registers or stack slots most frequently differ between cached and current states.

Here is an example of the report for scx lavd_dispatch, with verifier limited to 200K instructions to trigger the error:

lavd_dispatch():
; void BPF_STRUCT_OPS(lavd_dispatch, s32 cpu, struct task_struct *prev) @ main.bpf.c:889 ... disassembly ...

consume_task():

    ; bool consume_task(u64 cpu_dsq_id, u64 cpdom_dsq_id) @ balance.bpf.c:410
    ... disassembly ...

#1 most visited simulated stacktrace (visited 1807 times):

    lavd_dispatch/124 (.../scx/scheds/rust/scx_lavd/src/bpf/main.bpf.c:1107)
    consume_task/2715 (.../scx/scheds/rust/scx_lavd/src/bpf/balance.bpf.c:316)

#2 most visited simulated stacktrace (visited 1682 times):

    lavd_dispatch/124 (.../scx/scheds/rust/scx_lavd/src/bpf/main.bpf.c:1107)
    consume_task/2994 (.../scx/scheds/rust/scx_lavd/src/bpf/balance.bpf.c:386)

#3 most visited simulated stacktrace (visited 8 times):
lavd_dispatch/255 (.../scx/scheds/rust/scx_lavd/src/bpf/main.bpf.c:1022)
Most varying: R7 (frame 0)

BPF program is too large. Processed 200001 insn

---
Eduard Zingerman (6):
bpf: move live registers and scc printout to a standalone function
bpf: compute loops hierarchy
selftests/bpf: test cases for loop hierarchy computation
bpf: report hot simulated callchains when 1M instructions limit is met
bpf: report register diff summary for hot callchains selftests/bpf: test budget exhaustion profiling report

 include/linux/bpf_verifier.h                       |  38 ++++
 kernel/bpf/Makefile                                |   2 +-
 kernel/bpf/fixups.c                                |   5 +
 kernel/bpf/liveness.c                              |  22 +-
 kernel/bpf/loops.c                                 | 184 +++++++++++++++++
 kernel/bpf/states.c                                | 174 ++++++++++++++--
 kernel/bpf/verifier.c                              | 230 +++++++++++++++++++++
 tools/testing/selftests/bpf/prog_tests/verifier.c  |   4 +
 .../selftests/bpf/progs/verifier_budget_report.c   | 175 ++++++++++++++++
 .../selftests/bpf/progs/verifier_live_stack.c      |   2 +-
 .../selftests/bpf/progs/verifier_loop_hierarchy.c  | 223 ++++++++++++++++++++
 11 files changed, 1014 insertions(+), 45 deletions(-)

---
base-commit: 8496d9020ff37a33c2a7b2fc84350fd03ffbde78
change-id: 20260525-better-1m-reporting-1d795a21cf72

author maintainer
#1 lore raw

RFC PATCH 1/6 bpf: move live registers and scc printout to a standalone function

Tests for multiple analyses performed by the verifier need the verifier log to contain analysis results alongside the program disassembly. This patch moves log level 2 program dump from bpf_compute_live_registers() to a standalone function called from bpf_check(), in order to provide a common logging function for such analyses (and thus avoid printing program disassembly multiple times).

This is a preparatory refactoring, subsequent commit extends this log with loop hierarchy.

---
 kernel/bpf/liveness.c                              | 22 +--------------
 kernel/bpf/verifier.c                              | 31 ++++++++++++++++++++++
 .../selftests/bpf/progs/verifier_live_stack.c      |  2 +-
 3 files changed, 33 insertions(+), 22 deletions(-)
kernel/bpf/liveness.c +1 -21
index 0aadfbae0acc..16d030fdd83a 100644
@@ -2209,7 +2209,7 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)
 	struct bpf_insn *insns = env->prog->insnsi;
 	struct insn_live_regs *state;
 	int insn_cnt = env->prog->len;
-	int err = 0, i, j;
+	int err = 0, i;
 	bool changed;
 
 	/* Use the following algorithm:
@@ -2270,26 +2270,6 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)
 	for (i = 0; i < insn_cnt; ++i)
 		insn_aux[i].live_regs_before = state[i].in;
 
-	if (env->log.level & BPF_LOG_LEVEL2) {
-		verbose(env, "Live regs before insn:\n");
-		for (i = 0; i < insn_cnt; ++i) {
-			if (env->insn_aux_data[i].scc)
-				verbose(env, "%3d ", env->insn_aux_data[i].scc);
-			else
-				verbose(env, "    ");
-			verbose(env, "%3d: ", i);
-			for (j = BPF_REG_0; j < BPF_REG_10; ++j)
-				if (insn_aux[i].live_regs_before & BIT(j))
-					verbose(env, "%d", j);
-				else
-					verbose(env, ".");
-			verbose(env, " ");
-			bpf_verbose_insn(env, &insns[i]);
-			if (bpf_is_ldimm64(&insns[i]))
-				i++;
-		}
-	}
-
 out:
 	kvfree(state);
 	return err;
kernel/bpf/verifier.c +31 -0
index c8d980fdd709..3d569e36128c 100644
@@ -19619,6 +19619,34 @@ int bpf_fixup_kfunc_call(struct bpf_verifier_env *env, struct bpf_insn *insn,
 	return 0;
 }
 
+/* Various log level 2 information about the program */
+static void log_program(struct bpf_verifier_env *env)
+{
+	struct bpf_insn_aux_data *insn_aux = env->insn_aux_data;
+	struct bpf_insn *insns = env->prog->insnsi;
+	u32 insn_cnt = env->prog->len;
+	u32 i, j;
+
+	verbose(env, "Program dump (scc? insn#: live_regs_before):\n");
+	for (i = 0; i < insn_cnt; ++i) {
+		verbose_linfo(env, i, "    ; ");
+		if (env->insn_aux_data[i].scc)
+			verbose(env, "%3d ", env->insn_aux_data[i].scc);
+		else
+			verbose(env, "    ");
+		verbose(env, "%3d: ", i);
+		for (j = BPF_REG_0; j < BPF_REG_10; ++j)
+			if (insn_aux[i].live_regs_before & BIT(j))
+				verbose(env, "%d", j);
+			else
+				verbose(env, ".");
+		verbose(env, " ");
+		bpf_verbose_insn(env, &insns[i]);
+		if (bpf_is_ldimm64(&insns[i]))
+			i++;
+	}
+}
+
 int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	      struct bpf_log_attr *attr_log)
 {
@@ -19771,6 +19799,9 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (ret < 0)
 		goto skip_full_check;
 
+	if (env->log.level & BPF_LOG_LEVEL2)
+		log_program(env);
+
 	ret = mark_fastcall_patterns(env);
 	if (ret < 0)
 		goto skip_full_check;
tools/testing/selftests/bpf/progs/verifier_live_stack.c +1 -1
index 401152b2b64f..923572df4bbf 100644
@@ -64,7 +64,7 @@ SEC("socket")
 __log_level(2)
 __msg("stack use/def subprog#0 must_write_not_same_slot (d0,cs0):")
 __msg("6: (7b) *(u64 *)(r2 +0) = r0{{$}}")
-__msg("Live regs before insn:")
+__msg("Program dump")
 __naked void must_write_not_same_slot(void)
 {
 	asm volatile (
Signature · 1 line
2.53.0
author maintainer
#2 lore raw

RFC PATCH 2/6 bpf: compute loops hierarchy

In reply to Eduard Zingerman

Add an analysis phase computing the loops hierarchy to the bpf verifier. The algorithm is based on the paper:
"A New Algorithm for Identifying Loops in Decompilation" by Wei et al, adapted to be non-recursive.

Record the loops hierarchy per instruction:
- The field insn_aux_data->loop_header records the innermost loop header containing it.
- The field insn_aux_data->loop records additional information about the loop if this instruction is a loop header (at the moment it only tracks irreduciblity of the loop, additional information will be added later).

Subsequent patches use loop header entries as sampling points for callchain profiling, for better error reports when the 1M instruction budget is exhausted.

---
 include/linux/bpf_verifier.h |  10 +++
 kernel/bpf/Makefile          |   2 +-
 kernel/bpf/fixups.c          |   5 ++
 kernel/bpf/loops.c           | 184 +++++++++++++++++++++++++++++++++++++++++++
 kernel/bpf/verifier.c        |  10 ++-
 5 files changed, 209 insertions(+), 2 deletions(-)
include/linux/bpf_verifier.h +10 -0
index 5cbad3b64130..d0a1fb135cbf 100644
@@ -656,6 +656,10 @@ struct bpf_iarray {
 	u32 items[];
 };
 
+struct bpf_loop {
+	bool irreducible;
+};
+
 struct bpf_insn_aux_data {
 	union {
 		enum bpf_reg_type ptr_type;	/* pointer type for load/store insns */
@@ -742,6 +746,10 @@ struct bpf_insn_aux_data {
 	u16 const_reg_map_mask;
 	u16 const_reg_subprog_mask;
 	u32 const_reg_vals[10];
+	/* index of a loop header of the innermost loop containing this instruction, -1 if none */
+	s32 loop_header;
+	/* additional information about the loop if this instruction is a loop header */
+	struct bpf_loop *loop;
 };
 
 #define MAX_USED_MAPS 64 /* max number of maps accessed by one eBPF program */
@@ -1608,4 +1616,6 @@ int bpf_jit_subprogs(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_compute_loops(struct bpf_verifier_env *env);
+
 #endif /* _LINUX_BPF_VERIFIER_H */
kernel/bpf/Makefile +1 -1
index 4dc41bf5780c..787d183ba5b4 100644
@@ -6,7 +6,7 @@ cflags-nogcse-$(CONFIG_X86)$(CONFIG_CC_IS_GCC) := -fno-gcse
 endif
 CFLAGS_core.o += -Wno-override-init $(cflags-nogcse-yy)
 
-obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o
+obj-$(CONFIG_BPF_SYSCALL) += syscall.o verifier.o inode.o helpers.o tnum.o cnum.o log.o token.o liveness.o const_fold.o loops.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_iter.o
 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
kernel/bpf/fixups.c +5 -0
index 12739add2dda..57294524dab8 100644
@@ -450,6 +450,11 @@ void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
 			aux_data[i].jt = NULL;
 		}
 
+		if (aux_data[i].loop) {
+			kvfree(aux_data[i].loop);
+			aux_data[i].loop = NULL;
+		}
+
 		if (bpf_is_ldimm64(&insns[i]))
 			i++;
 	}
kernel/bpf/loops.c new file +184 -0

184 lines not on this page · raw message

kernel/bpf/verifier.c +9 -1
index 3d569e36128c..2b3584712ad2 100644
@@ -19627,13 +19627,17 @@ static void log_program(struct bpf_verifier_env *env)
 	u32 insn_cnt = env->prog->len;
 	u32 i, j;
 
-	verbose(env, "Program dump (scc? insn#: live_regs_before):\n");
+	verbose(env, "Program dump (scc? loop_header? insn#: live_regs_before):\n");
 	for (i = 0; i < insn_cnt; ++i) {
 		verbose_linfo(env, i, "    ; ");
 		if (env->insn_aux_data[i].scc)
 			verbose(env, "%3d ", env->insn_aux_data[i].scc);
 		else
 			verbose(env, "    ");
+		if (env->insn_aux_data[i].loop_header >= 0)
+			verbose(env, "%3d ", env->insn_aux_data[i].loop_header);
+		else
+			verbose(env, "    ");
 		verbose(env, "%3d: ", i);
 		for (j = BPF_REG_0; j < BPF_REG_10; ++j)
 			if (insn_aux[i].live_regs_before & BIT(j))
@@ -19791,6 +19795,10 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (ret < 0)
 		goto skip_full_check;
 
+	ret = bpf_compute_loops(env);
+	if (ret < 0)
+		goto skip_full_check;
+
 	ret = bpf_compute_scc(env);
 	if (ret < 0)
 		goto skip_full_check;
Signature · 1 line
2.53.0
#3 lore raw

Re: [PATCH RFC bpf-next 2/6] bpf: compute loops hierarchy

Should this use kvfree() instead of kfree()? The three buffers are allocated with kvcalloc(), which can return either kmalloc or vmalloc memory depending on size. With env->prog->len up to 1,000,000…
Quoted 4 lines
include/linux/bpf_verifier.h +0 -0
index 5cbad3b64130..d0a1fb135cbf 100644

[ ... ]

Quoted 11 lines
kernel/bpf/loops.c new file +5 -0
new file mode 100644
index 000000000000..4bbcd923e960
@@ -0,0 +1,184 @@
+// SPDX-License-Identifier: GPL-2.0-only
+/* Copyright (c) 2026 Meta Platforms, Inc. and affiliates. */
+
+#include <linux/slab.h>
+#include <linux/bpf_verifier.h>

[ ... ]

Quoted 17 lines
kernel/bpf/loops.c new file +17 -0
+int bpf_compute_loops(struct bpf_verifier_env *env)
+{
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	int i, err = 0, len = env->prog->len;
+	struct loops_dfs dfs = {};
+
+	dfs.dfs_pos = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);
+	dfs.state = kvcalloc(len, sizeof(struct dfs_state), GFP_KERNEL_ACCOUNT);
+	dfs.stack = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);
+	if (!dfs.dfs_pos || !dfs.state || !dfs.stack) {
+		err = -ENOMEM;
+		goto out;
+	}
+	for (i = 0; i < len; i++)
+		aux[i].loop_header = -1;
+	for (i = 0; i < env->subprog_cnt; i++) {
+		err = compute_loops_in_subprog(env, &dfs, i);

kernel/bpf/loops.c line 184

Quoted 10 lines
kernel/bpf/loops.c new file +10 -0
+		if (err)
+			goto out;
+	}
+
+out:
+	kfree(dfs.dfs_pos);
+	kfree(dfs.stack);
+	kfree(dfs.state);
+	return err;
+}

Should this use kvfree() instead of kfree()? The three buffers are allocated with kvcalloc(), which can return either kmalloc or vmalloc memory depending on size. With env->prog->len up to 1,000,000 instructions, these allocations can easily exceed kmalloc's maximum size and fall back to vmalloc.

Calling kfree() on vmalloc memory causes undefined behavior since kfree() expects slab-allocated objects. The matching function is kvfree(), which checks is_vmalloc_addr() and dispatches appropriately.

This affects both the success path and the error path through goto out, since the cleanup is unconditional.

For reference, bpf_compute_scc() in kernel/bpf/cfg.c uses kvfree() for buffers allocated the same way with kvcalloc().

[ ... ]

---
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/26444655429

author maintainer
#4 lore raw

Re: [PATCH RFC bpf-next 2/6] bpf: compute loops hierarchy

On Tue, 2026-05-26 at 10:05 +0000, [email protected] wrote:

[...]

Quoted 25 lines
Quoted 25 lines
kernel/bpf/loops.c new file +25 -0
+int bpf_compute_loops(struct bpf_verifier_env *env)
+{
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	int i, err = 0, len = env->prog->len;
+	struct loops_dfs dfs = {};
+
+	dfs.dfs_pos = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);
+	dfs.state = kvcalloc(len, sizeof(struct dfs_state), GFP_KERNEL_ACCOUNT);
+	dfs.stack = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);
+	if (!dfs.dfs_pos || !dfs.state || !dfs.stack) {
+		err = -ENOMEM;
+		goto out;
+	}
+	for (i = 0; i < len; i++)
+		aux[i].loop_header = -1;
+	for (i = 0; i < env->subprog_cnt; i++) {
+		err = compute_loops_in_subprog(env, &dfs, i);
+		if (err)
+			goto out;
+	}
+
+out:
+	kfree(dfs.dfs_pos);
+	kfree(dfs.stack);
+	kfree(dfs.state);
Quoted 8 lines

Review

Quoted 2 lines
(quoted diff) +2 -0
+	return err;
+}

Should this use kvfree() instead of kfree()? The three buffers are allocated with kvcalloc(), which can return either kmalloc or vmalloc memory depending on size. With env->prog->len up to 1,000,000 instructions, these allocations can easily exceed kmalloc's maximum size and fall back to vmalloc.

It should use kvfree(), yes.

#5 lore raw

Re: [PATCH RFC bpf-next 2/6] bpf: compute loops hierarchy

In reply to Eduard Zingerman
Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [High] bpf_compute_loops() incorrectly uses kfree() to free memory allocated with kvcalloc(). --

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [High] bpf_compute_loops() incorrectly uses kfree() to free memory allocated with kvcalloc(). --

commit ef2f37474f7b031f628d088384c6723a83200838
Author: Eduard Zingerman <[email protected]>

bpf: compute loops hierarchy

This commit adds an analysis phase to the BPF verifier to compute the loops hierarchy using a non-recursive algorithm. It records the loop header per instruction and tracks loop irreducibility to provide better callchain profiling.

Quoted 5 lines
kernel/bpf/loops.c new file +0 -0
new file mode 100644
index 0000000000000..4bbcd923e960a

[ ... ]

Quoted 13 lines
kernel/bpf/loops.c new file +13 -0
+int bpf_compute_loops(struct bpf_verifier_env *env)
+{
+	struct bpf_insn_aux_data *aux = env->insn_aux_data;
+	int i, err = 0, len = env->prog->len;
+	struct loops_dfs dfs = {};
+
+	dfs.dfs_pos = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);
+	dfs.state = kvcalloc(len, sizeof(struct dfs_state), GFP_KERNEL_ACCOUNT);
+	dfs.stack = kvcalloc(len, sizeof(int), GFP_KERNEL_ACCOUNT);
+	if (!dfs.dfs_pos || !dfs.state || !dfs.stack) {
+		err = -ENOMEM;
+		goto out;
+	}

[ ... ]

kernel/bpf/loops.c line 182

Quoted 4 lines
kernel/bpf/loops.c new file +4 -0
+out:
+	kfree(dfs.dfs_pos);
+	kfree(dfs.stack);
+	kfree(dfs.state);

[Severity: High]
Should these be freed using kvfree() instead of kfree()?

Since these arrays are allocated using kvcalloc() and BPF programs can contain up to 1 million instructions, the allocations can grow to several megabytes. In such cases, kvcalloc() will fall back to vmalloc().

Calling kfree() on a vmalloc address will blindly call virt_to_page() for a virtual address, which can lead to a kernel panic or slab corruption.

Quoted 2 lines
kernel/bpf/loops.c new file +2 -0
+	return err;
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=2
author maintainer
#6 lore raw

RFC PATCH 3/6 selftests/bpf: test cases for loop hierarchy computation

In reply to Eduard Zingerman

Test cases covering the following branches in bpf_compute_loops():
- Case B: simple backedge creating a loop (loop_single)
- Case B: two independent loops (loop_two_independent)
- Case B + D: nested loops where inner header's loop_header points to outer (loop_nested)
- Case C: diamond CFG with no loops (fwd_edges_no_loop)
- Case D: sibling inner loops within one outer loop (loop_nested_siblings)
- Three levels of loop nesting (loop_three_levels)
- Loop with if-else body containing forward branches (loop_with_if_else)

---
 tools/testing/selftests/bpf/prog_tests/verifier.c  |   2 +
 .../selftests/bpf/progs/verifier_loop_hierarchy.c  | 223 +++++++++++++++++++++
 2 files changed, 225 insertions(+)
tools/testing/selftests/bpf/prog_tests/verifier.c +2 -0
index 219ff2969868..35d92d176c1f 100644
@@ -57,6 +57,7 @@
 #include "verifier_live_stack.skel.h"
 #include "verifier_liveness_exp.skel.h"
 #include "verifier_load_acquire.skel.h"
+#include "verifier_loop_hierarchy.skel.h"
 #include "verifier_loops1.skel.h"
 #include "verifier_lwt.skel.h"
 #include "verifier_map_in_map.skel.h"
@@ -208,6 +209,7 @@ void test_verifier_leak_ptr(void)             { RUN(verifier_leak_ptr); }
 void test_verifier_linked_scalars(void)       { RUN(verifier_linked_scalars); }
 void test_verifier_live_stack(void)           { RUN(verifier_live_stack); }
 void test_verifier_liveness_exp(void)         { RUN(verifier_liveness_exp); }
+void test_verifier_loop_hierarchy(void)       { RUN(verifier_loop_hierarchy); }
 void test_verifier_loops1(void)               { RUN(verifier_loops1); }
 void test_verifier_lwt(void)                  { RUN(verifier_lwt); }
 void test_verifier_map_in_map(void)           { RUN(verifier_map_in_map); }
tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c new file +223 -0

223 lines not on this page · raw message

Signature · 1 line
2.53.0
#7 lore raw

Re: [PATCH RFC bpf-next 3/6] selftests/bpf: test cases for loop hierarchy computation

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider: - [Medium] The expected verifier log output in `fwd_edges_no_loop` incorrectly expects an unconditional…

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The expected verifier log output in fwd_edges_no_loop incorrectly expects an unconditional jump (05) for a conditional jump instruction, which will cause the selftest to fail. --

commit f35c2f4d237eac02dd241fbf85f69d40722f62de
Author: Eduard Zingerman <[email protected]>

selftests/bpf: test cases for loop hierarchy computation

This commit adds test cases covering various branches in bpf_compute_loops for loop hierarchy computation. It includes tests for single bounded loops, independent loops, nested loops, diamond control flow graphs, and irreducible loops.

Quoted 5 lines
tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c new file +0 -0
new file mode 100644
index 0000000000000..db26157e3e14a

[ ... ]

tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c line 90

Quoted 6 lines
tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c new file +6 -0
+/* Case C: forward edges, no loops. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("          0: {{.*}} (b7) r0 = 1")
+__msg("          1: {{.*}} (05) goto pc+2")

[Severity: Medium]
Will this test case fail because of a mismatch in the expected verifier log?

The inline assembly below uses "if r0 > 0 goto 1f;", which is a conditional jump. This translates to opcode 0x25 (if r0 > 0x0 goto pc+2), but the __msg assertion explicitly expects opcode 0x05 (goto pc+2), which is an unconditional jump.

Quoted 15 lines
tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c new file +15 -0
+__msg("          2: {{.*}} (b7) r0 = 2")
+__msg("          3: {{.*}} (05) goto pc+1")
+__msg("          4: {{.*}} (b7) r0 = 3")
+__msg("          5: {{.*}} (95) exit")
+__naked void fwd_edges_no_loop(void)
+{
+	asm volatile ("					\
+	r0 = 1;						\
+	if r0 > 0 goto 1f;				\
+	r0 = 2;						\
+	goto 2f;					\
+1:	r0 = 3;						\
+2:	exit;						\
+"	::: __clobber_all);
+}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=3
author maintainer
#8 lore raw

Re: [PATCH RFC bpf-next 3/6] selftests/bpf: test cases for loop hierarchy computation

Quoted 32 lines · On Tue, 2026-05-26 at 10:25 +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 1 potential issue(s) to consider:
- [Medium] The expected verifier log output in fwd_edges_no_loop incorrectly expects an unconditional jump (05) for a conditional jump instruction, which will cause the selftest to fail. --

commit f35c2f4d237eac02dd241fbf85f69d40722f62de
Author: Eduard Zingerman <[email protected]>

selftests/bpf: test cases for loop hierarchy computation

This commit adds test cases covering various branches in bpf_compute_loops for loop hierarchy computation. It includes tests for single bounded loops, independent loops, nested loops, diamond control flow graphs, and irreducible loops.

Quoted 5 lines
tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c new file +0 -0
new file mode 100644
index 0000000000000..db26157e3e14a

[ ... ]

tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c line 90

Quoted 6 lines
tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c new file +6 -0
+/* Case C: forward edges, no loops. */
+SEC("socket")
+__success
+__log_level(2)
+__msg("          0: {{.*}} (b7) r0 = 1")
+__msg("          1: {{.*}} (05) goto pc+2")

[Severity: Medium]
Will this test case fail because of a mismatch in the expected verifier log?

Quoted 4 lines

The inline assembly below uses "if r0 > 0 goto 1f;", which is a conditional jump. This translates to opcode 0x25 (if r0 > 0x0 goto pc+2), but the __msg assertion explicitly expects opcode 0x05 (goto pc+2), which is an unconditional jump.

The code is adjusted by constant prop phase.
I'll just the test case to call urandom() and keep conditionals.

[...]

author maintainer
#9 lore raw

RFC PATCH 4/6 bpf: report hot simulated callchains when 1M instructions limit is met

In reply to Eduard Zingerman

When the verifier exceeds the 1M instruction budget, the current error output shows a random execution trace that happens to be active when the limit is hit, which is not very helpful for debugging.

To rectify this, employ a profiler-inspired technique:
collect and count "callchain" stack traces that the verifier visits during program validation and report the top 3 hot traces. Sample callchains at instructions marked as force checkpoints and loop header entries.

When 1M instructions is met, print a report containing:
- callchains verifier visited most often;
- disassembly of the subprograms referenced from the printed callchains.

Here is an example of the report:

budget_nested_call_loop():

    ; asm volatile ("                                     \ @ verifier_budget_report.c:44
    0: (b7) r0 = 0
    1: (85) call pc+1
    2: (95) exit

budget_nested_call_loop__inner():

    ; asm volatile ("                                     \ @ verifier_budget_report.c:54
    3: (b7) r0 = 0
    4: (07) r0 += 1
    5: (05) goto pc-2

#1 most visited simulated stacktrace (visited 499999 times):

    budget_nested_call_loop/1 (.../verifier_budget_report.c:44)
    budget_nested_call_loop__inner/4 (.../verifier_budget_report.c:54)
---
 include/linux/bpf_verifier.h |  14 ++++
 kernel/bpf/verifier.c        | 155 +++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 169 insertions(+)
include/linux/bpf_verifier.h +14 -0
index d0a1fb135cbf..347a155d8e21 100644
@@ -9,6 +9,8 @@
 #include <linux/filter.h> /* for MAX_BPF_STACK */
 #include <linux/tnum.h>
 #include <linux/cnum.h>
+#include <linux/hashtable.h>
+#include <linux/jhash.h>
 
 /* Maximum variable offset umax_value permitted when resolving memory accesses.
  * In practice this is far bigger than any realistic pointer offset; this limit
@@ -660,6 +662,17 @@ struct bpf_loop {
 	bool irreducible;
 };
 
+struct bpf_callchain {
+	u32 insn_idx[MAX_CALL_FRAMES];
+	u32 curframe;
+};
+
+struct bpf_callchain_entry {
+	struct hlist_node node;
+	struct bpf_callchain cc;
+	u64 count;
+};
+
 struct bpf_insn_aux_data {
 	union {
 		enum bpf_reg_type ptr_type;	/* pointer type for load/store insns */
@@ -1043,6 +1056,7 @@ struct bpf_verifier_env {
 	u32 scc_cnt;
 	struct bpf_iarray *succ;
 	struct bpf_iarray *gotox_tmp_buf;
+	DECLARE_HASHTABLE(callchain_htab, 8);
 };
 
 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
kernel/bpf/verifier.c +155 -0

185 lines not on this page · raw message

Signature · 1 line
2.53.0
#10 lore raw

Re: [PATCH RFC bpf-next 4/6] bpf: report hot simulated callchains when 1M instructions limit is met

Should this allocation use GFP_KERNEL_ACCOUNT instead? Looking across kernel/bpf/verifier.c, every other transient verifier allocation uses GFP_KERNEL_ACCOUNT (see kzalloc_obj, kvzalloc_obj…
Quoted 62 lines
include/linux/bpf_verifier.h +14 -0
index d0a1fb135cbf..347a155d8e21 100644
@@ -9,6 +9,8 @@
 #include <linux/filter.h> /* for MAX_BPF_STACK */
 #include <linux/tnum.h>
 #include <linux/cnum.h>
+#include <linux/hashtable.h>
+#include <linux/jhash.h>
 
 /* Maximum variable offset umax_value permitted when resolving memory accesses.
  * In practice this is far bigger than any realistic pointer offset; this limit
@@ -660,6 +662,17 @@ struct bpf_loop {
 	bool irreducible;
 };
 
+struct bpf_callchain {
+	u32 insn_idx[MAX_CALL_FRAMES];
+	u32 curframe;
+};
+
+struct bpf_callchain_entry {
+	struct hlist_node node;
+	struct bpf_callchain cc;
+	u64 count;
+};
+
 struct bpf_insn_aux_data {
 	union {
 		enum bpf_reg_type ptr_type;	/* pointer type for load/store insns */
@@ -1043,6 +1056,7 @@ struct bpf_verifier_env {
 	u32 scc_cnt;
 	struct bpf_iarray *succ;
 	struct bpf_iarray *gotox_tmp_buf;
+	DECLARE_HASHTABLE(callchain_htab, 8);
 };
 
 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
kernel/bpf/verifier.c +15 -0
index 2b3584712ad2..8eb8f1ce17c7 100644
@@ -17247,6 +17247,152 @@ static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in
 	return INSN_IDX_UPDATED;
 }
 
+static void compute_callchain(struct bpf_verifier_state *st, struct bpf_callchain *cc)
+{
+	int i;
+
+	cc->curframe = st->curframe;
+	for (i = 0; i <= st->curframe; i++)
+		cc->insn_idx[i] = bpf_frame_insn_idx(st, i);
+}
+
+static int update_callchain_profile(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
+{
+	struct bpf_callchain_entry *entry;
+	struct bpf_callchain cc;
+	u32 hash;
+

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17274

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+	compute_callchain(st, &cc);
+	hash = jhash2(cc.insn_idx, cc.curframe + 1, cc.curframe + 1);
+	hash_for_each_possible(env->callchain_htab, entry, node, hash) {
+		if (entry->cc.curframe == cc.curframe &&
+		    !memcmp(entry->cc.insn_idx, cc.insn_idx, (cc.curframe + 1) * sizeof(u32))) {
+			entry->count++;
+			return 0;
+		}
+	}
+	entry = kzalloc(sizeof(*entry), GFP_KERNEL);

Should this allocation use GFP_KERNEL_ACCOUNT instead? Looking across kernel/bpf/verifier.c, every other transient verifier allocation uses GFP_KERNEL_ACCOUNT (see kzalloc_obj, kvzalloc_obj, krealloc, and kvcalloc throughout the file).

The callchain hash entries have the same lifecycle as other verifier
data: attached to env->callchain_htab and freed at the end of bpf_check().

Programs approaching the 1M instruction limit can generate many distinct callchains sampled at force checkpoints and loop headers, so the allocations could be substantial for memcg tracking.

Quoted 7 lines
kernel/bpf/verifier.c +7 -0
+	if (!entry)
+		return -ENOMEM;
+	entry->cc = cc;
+	entry->count = 1;
+	hash_add(env->callchain_htab, &entry->node, hash);
+	return 0;
+}

[ ... ]

Quoted 9 lines
kernel/bpf/verifier.c +1 -0
@@ -19673,6 +19826,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 		return -ENOMEM;
 
 	env->bt.env = env;
+	hash_init(env->callchain_htab);
 
 	len = (*prog)->len;
 	env->insn_aux_data =

kernel/bpf/verifier.c int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr, · line 20105

Quoted 7 lines
kernel/bpf/verifier.c +1 -0
@@ -19945,6 +20099,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	bpf_clear_insn_aux_data(env, 0, env->prog->len);
 	vfree(env->insn_aux_data);
 err_free_env:
+	free_callchain_profile(env);
 	bpf_stack_liveness_free(env);
 	kvfree(env->cfg.insn_postorder);
 	kvfree(env->scc_info);

---
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/26444655429

author maintainer
#11 lore raw

Re: [PATCH RFC bpf-next 4/6] bpf: report hot simulated callchains when 1M instructions limit is met

On Tue, 2026-05-26 at 10:05 +0000, [email protected] wrote:

[...]

Quoted 13 lines
Quoted 13 lines
kernel/bpf/verifier.c +13 -0
+static int update_callchain_profile(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
+{
+	struct bpf_callchain_entry *entry;
+	struct bpf_callchain cc;
+	u32 hash;
+
+	compute_callchain(st, &cc);
+	hash = jhash2(cc.insn_idx, cc.curframe + 1, cc.curframe + 1);
+	hash_for_each_possible(env->callchain_htab, entry, node, hash) {
+		if (entry->cc.curframe == cc.curframe &&
+		    !memcmp(entry->cc.insn_idx, cc.insn_idx, (cc.curframe + 1) * sizeof(u32))) {
+			entry->count++;
+			return 0;
Quoted 8 lines

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17274

Quoted 3 lines
kernel/bpf/verifier.c +3 -0
+		}
+	}
+	entry = kzalloc(sizeof(*entry), GFP_KERNEL);

Should this allocation use GFP_KERNEL_ACCOUNT instead?  Looking across kernel/bpf/verifier.c, every other transient verifier allocation uses GFP_KERNEL_ACCOUNT (see kzalloc_obj, kvzalloc_obj, krealloc, and kvcalloc throughout the file).

It should.

#12 lore raw

Re: [PATCH RFC bpf-next 4/6] bpf: report hot simulated callchains when 1M instructions limit is met

In reply to Eduard Zingerman
Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider: - [High] Missing Memcg Accounting for callchain profiles - [High] Stack buffer overflow when updating…

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Missing Memcg Accounting for callchain profiles
- [High] Stack buffer overflow when updating printed_subs bitmap
- [Medium] Uninitialized stack memory copied to heap in update_callchain_profile
- [Low] Log buffer truncation due to subprogram disassemblies preceding callchain summary
- [Low] Compiler warning on 32-bit architectures due to incorrect format specifier for ptrdiff_t --

commit 77e8a884bb6c0c1595ff19bac7fba4cb9e4a26ac
Author: Eduard Zingerman <[email protected]>

bpf: report hot simulated callchains when 1M instructions limit is met

This patch introduces a mechanism to report the hottest simulated callchains when the BPF verifier hits the 1M instruction budget. It collects and counts callchains during verification, printing a summary and disassembly of the relevant subprograms to help debugging.

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 2b3584712ad28..8eb8f1ce17c76 100644

[ ... ]

Quoted 19 lines
kernel/bpf/verifier.c +15 -0
@@ -17247,6 +17247,152 @@ static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in
 	return INSN_IDX_UPDATED;
 }
 
+static void compute_callchain(struct bpf_verifier_state *st, struct bpf_callchain *cc)
+{
+	int i;
+
+	cc->curframe = st->curframe;
+	for (i = 0; i <= st->curframe; i++)
+		cc->insn_idx[i] = bpf_frame_insn_idx(st, i);
+}
+
+static int update_callchain_profile(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
+{
+	struct bpf_callchain_entry *entry;
+	struct bpf_callchain cc;
+	u32 hash;
+

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17274

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+	compute_callchain(st, &cc);
+	hash = jhash2(cc.insn_idx, cc.curframe + 1, cc.curframe + 1);
+	hash_for_each_possible(env->callchain_htab, entry, node, hash) {
+		if (entry->cc.curframe == cc.curframe &&
+		    !memcmp(entry->cc.insn_idx, cc.insn_idx, (cc.curframe + 1) * sizeof(u32))) {
+			entry->count++;
+			return 0;
+		}
+	}
+	entry = kzalloc(sizeof(*entry), GFP_KERNEL);

[Severity: High]
Does this code allow an unprivileged user (or one inside a container) to bypass memory limits?

Since the verifier allocates these callchain profiles dynamically during verification (up to the 1M instruction budget), missing the __GFP_ACCOUNT flag could cause large amounts of unaccounted kernel memory to be consumed, potentially leading to an OOM condition.

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17277

Quoted 3 lines
kernel/bpf/verifier.c +3 -0
+	if (!entry)
+		return -ENOMEM;
+	entry->cc = cc;

[Severity: Medium]
Will this copy uninitialized stack memory to the heap?

In compute_callchain(), only cc.curframe and the active elements of the cc.insn_idx array are initialized. The remainder of the array on the stack remains uninitialized. Assigning the whole struct here copies those uninitialized bytes, which will trigger KMSAN warnings.

Quoted 4 lines
kernel/bpf/verifier.c +4 -0
+	entry->count = 1;
+	hash_add(env->callchain_htab, &entry->node, hash);
+	return 0;
+}

[ ... ]

Quoted 8 lines
kernel/bpf/verifier.c +8 -0
+static void print_callchain_entry(struct bpf_verifier_env *env,
+				  struct bpf_callchain_entry *entry, int idx)
+{
+	struct bpf_callchain *cc = &entry->cc;
+	const struct bpf_line_info *linfo;
+	struct bpf_subprog_info *sub;
+	int i, insn_idx;
+

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17312

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+	verbose(env, "#%d most visited simulated stacktrace (visited %llu times):\n",
+		idx, entry->count);
+	for (i = 0; i <= cc->curframe; i++) {
+		insn_idx = cc->insn_idx[i];
+		sub = bpf_find_containing_subprog(env, insn_idx);
+		linfo = bpf_find_linfo(env->prog, insn_idx);
+		if (sub->name)
+			verbose(env, "  %s/%d", sub->name, insn_idx);
+		else
+			verbose(env, "  subprog#%ld/%d", sub - env->subprog_info, insn_idx);

[Severity: Low]
Does this generate a compiler warning on 32-bit architectures?

The expression sub - env->subprog_info yields a ptrdiff_t. On 32-bit systems, ptrdiff_t is typically int, so using %ld causes a -Wformat warning. Could this be changed to %td?

Quoted 6 lines
kernel/bpf/verifier.c +6 -0
+		if (linfo)
+			verbose(env, " (%s:%u)",
+				btf_name_by_offset(env->prog->aux->btf, linfo->file_name_off),
+				BPF_LINE_INFO_LINE_NUM(linfo->line_col));
+		verbose(env, "\n");
+	}

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17328

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+}
+
+static void disasm_subprog(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
+{
+	u32 i, end = (sub + 1)->start;
+
+	if (sub->name)
+		verbose(env, "%s():\n", sub->name);
+	else
+		verbose(env, "subprog#%ld:\n", sub - env->subprog_info);

[Severity: Low]
Similar to the previous comment, does this need %td instead of %ld for the ptrdiff_t type?

Quoted 7 lines
kernel/bpf/verifier.c +7 -0
+	env->prev_linfo = NULL;
+	for (i = sub->start; i < end; i++) {
+		verbose_linfo(env, i, "  ; ");
+		verbose(env, "  %d: ", i);
+		bpf_verbose_insn(env, &env->prog->insnsi[i]);
+		if (bpf_is_ldimm64(&env->prog->insnsi[i]))
+			i++;

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17345

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+	}
+}
+
+/*
+ * Print several most visited simulated stack traces,
+ * and a disasembly of related subprograms.
+ */
+static void print_hotspots(struct bpf_verifier_env *env)
+{
+	DECLARE_BITMAP(printed_subs, BPF_MAX_SUBPROGS) = {};

[Severity: High]
Does this code overflow the stack array when processing fake or exception subprograms?

The verifier allocates extra slots for fake and exception subprograms, meaning env->subprog_cnt can reach BPF_MAX_SUBPROGS + 2. Sizing the bitmap strictly for BPF_MAX_SUBPROGS could result in out-of-bounds stack writes in the loop below.

Quoted 4 lines
kernel/bpf/verifier.c +4 -0
+	struct bpf_callchain_entry *top[3] = {};
+	struct bpf_callchain_entry *entry;
+	struct bpf_subprog_info *sub;
+	int i, j, bkt, nr_top = 0;

[ ... ]

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17394

Quoted 11 lines
kernel/bpf/verifier.c +11 -0
+	for_each_set_bit(i, printed_subs, env->subprog_cnt) {
+		disasm_subprog(env, &env->subprog_info[i]);
+		verbose(env, "\n");
+	}
+
+	/* Print the hot callchains */
+	for (i = 0; i < nr_top; i++) {
+		print_callchain_entry(env, top[i], i + 1);
+		verbose(env, "\n");
+	}
+}

[Severity: Low]
Could printing the disassemblies first cause the callchain summary to be truncated?

For non-trivial BPF programs, subprograms can contain thousands of instructions. If these are printed before the hot callchains, the user-provided log buffer might fill up completely, preventing the actual callchain summary from being visible.

Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=4
author maintainer
#13 lore raw

Re: [PATCH RFC bpf-next 4/6] bpf: report hot simulated callchains when 1M instructions limit is met

Quoted 50 lines · On Tue, 2026-05-26 at 10:45 +0000, [email protected] wrote:

Thank you for your contribution! Sashiko AI review found 5 potential issue(s) to consider:
- [High] Missing Memcg Accounting for callchain profiles
- [High] Stack buffer overflow when updating printed_subs bitmap
- [Medium] Uninitialized stack memory copied to heap in update_callchain_profile
- [Low] Log buffer truncation due to subprogram disassemblies preceding callchain summary
- [Low] Compiler warning on 32-bit architectures due to incorrect format specifier for ptrdiff_t --

commit 77e8a884bb6c0c1595ff19bac7fba4cb9e4a26ac
Author: Eduard Zingerman <[email protected]>

bpf: report hot simulated callchains when 1M instructions limit is met
This patch introduces a mechanism to report the hottest simulated callchains when the BPF verifier hits the 1M instruction budget. It collects and counts callchains during verification, printing a summary and disassembly of the relevant subprograms to help debugging.

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 2b3584712ad28..8eb8f1ce17c76 100644

[ ... ]

Quoted 25 lines
kernel/bpf/verifier.c +0 -0
@@ -17247,6 +17247,152 @@ static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in
  	return INSN_IDX_UPDATED;
  }

kernel/bpf/verifier.c +21 -0
+static void compute_callchain(struct bpf_verifier_state *st, struct bpf_callchain *cc)
+{
+	int i;
+
+	cc->curframe = st->curframe;
+	for (i = 0; i <= st->curframe; i++)
+		cc->insn_idx[i] = bpf_frame_insn_idx(st, i);
+}
+
+static int update_callchain_profile(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
+{
+	struct bpf_callchain_entry *entry;
+	struct bpf_callchain cc;
+	u32 hash;
+
+	compute_callchain(st, &cc);
+	hash = jhash2(cc.insn_idx, cc.curframe + 1, cc.curframe + 1);
+	hash_for_each_possible(env->callchain_htab, entry, node, hash) {
+		if (entry->cc.curframe == cc.curframe &&
+		    !memcmp(entry->cc.insn_idx, cc.insn_idx, (cc.curframe + 1) * sizeof(u32))) {
+			entry->count++;
Quoted 8 lines

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17274

Quoted 4 lines
kernel/bpf/verifier.c +4 -0
+			return 0;
+		}
+	}
+	entry = kzalloc(sizeof(*entry), GFP_KERNEL);

[Severity: High]
Does this code allow an unprivileged user (or one inside a container) to bypass memory limits?

Yes, should be changed to GFP_KERNEL_ACCOUNT.

Quoted 11 lines

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17277

Quoted 3 lines
kernel/bpf/verifier.c +3 -0
+	if (!entry)
+		return -ENOMEM;
+	entry->cc = cc;

[Severity: Medium]
Will this copy uninitialized stack memory to the heap?

In compute_callchain(), only cc.curframe and the active elements of the cc.insn_idx array are initialized. The remainder of the array on the stack remains uninitialized. Assigning the whole struct here copies those uninitialized bytes, which will trigger KMSAN warnings.

That's fine from algorithm perspective. It only uses initialized part of the array. I can change the code if it triggers KMSAN.

Quoted 30 lines
Quoted 5 lines
kernel/bpf/verifier.c +4 -0
+	entry->count = 1;
+	hash_add(env->callchain_htab, &entry->node, hash);
+	return 0;
+}

[ ... ]

Quoted 8 lines
kernel/bpf/verifier.c +8 -0
+static void print_callchain_entry(struct bpf_verifier_env *env,
+				  struct bpf_callchain_entry *entry, int idx)
+{
+	struct bpf_callchain *cc = &entry->cc;
+	const struct bpf_line_info *linfo;
+	struct bpf_subprog_info *sub;
+	int i, insn_idx;
+

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17312

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+	verbose(env, "#%d most visited simulated stacktrace (visited %llu times):\n",
+		idx, entry->count);
+	for (i = 0; i <= cc->curframe; i++) {
+		insn_idx = cc->insn_idx[i];
+		sub = bpf_find_containing_subprog(env, insn_idx);
+		linfo = bpf_find_linfo(env->prog, insn_idx);
+		if (sub->name)
+			verbose(env, "  %s/%d", sub->name, insn_idx);
+		else
+			verbose(env, "  subprog#%ld/%d", sub - env->subprog_info, insn_idx);

[Severity: Low]
Does this generate a compiler warning on 32-bit architectures?

Quoted 3 lines

The expression sub - env->subprog_info yields a ptrdiff_t. On 32-bit systems, ptrdiff_t is typically int, so using %ld causes a -Wformat warning. Could this be changed to %td?

Okay

Quoted 12 lines
Quoted 12 lines
kernel/bpf/verifier.c +12 -0
+		if (linfo)
+			verbose(env, " (%s:%u)",
+				btf_name_by_offset(env->prog->aux->btf, linfo->file_name_off),
+				BPF_LINE_INFO_LINE_NUM(linfo->line_col));
+		verbose(env, "\n");
+	}
+}
+
+static void disasm_subprog(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)
+{
+	u32 i, end = (sub + 1)->start;
+
Quoted 8 lines

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17328

Quoted 4 lines
kernel/bpf/verifier.c +4 -0
+	if (sub->name)
+		verbose(env, "%s():\n", sub->name);
+	else
+		verbose(env, "subprog#%ld:\n", sub - env->subprog_info);

[Severity: Low]
Similar to the previous comment, does this need %td instead of %ld for the ptrdiff_t type?

Okay

Quoted 22 lines
Quoted 7 lines
kernel/bpf/verifier.c +7 -0
+	env->prev_linfo = NULL;
+	for (i = sub->start; i < end; i++) {
+		verbose_linfo(env, i, "  ; ");
+		verbose(env, "  %d: ", i);
+		bpf_verbose_insn(env, &env->prog->insnsi[i]);
+		if (bpf_is_ldimm64(&env->prog->insnsi[i]))
+			i++;

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17345

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+	}
+}
+
+/*
+ * Print several most visited simulated stack traces,
+ * and a disasembly of related subprograms.
+ */
+static void print_hotspots(struct bpf_verifier_env *env)
+{
+	DECLARE_BITMAP(printed_subs, BPF_MAX_SUBPROGS) = {};

[Severity: High]
Does this code overflow the stack array when processing fake or exception subprograms?

Quoted 4 lines

The verifier allocates extra slots for fake and exception subprograms, meaning env->subprog_cnt can reach BPF_MAX_SUBPROGS + 2. Sizing the bitmap strictly for BPF_MAX_SUBPROGS could result in out-of-bounds stack writes in the loop below.

Good point.

Quoted 23 lines
Quoted 4 lines
kernel/bpf/verifier.c +4 -0
+	struct bpf_callchain_entry *top[3] = {};
+	struct bpf_callchain_entry *entry;
+	struct bpf_subprog_info *sub;
+	int i, j, bkt, nr_top = 0;

[ ... ]

kernel/bpf/verifier.c static int check_indirect_jump(struct bpf_verifier_env *env, struct bpf_insn *in · line 17394

Quoted 11 lines
kernel/bpf/verifier.c +11 -0
+	for_each_set_bit(i, printed_subs, env->subprog_cnt) {
+		disasm_subprog(env, &env->subprog_info[i]);
+		verbose(env, "\n");
+	}
+
+	/* Print the hot callchains */
+	for (i = 0; i < nr_top; i++) {
+		print_callchain_entry(env, top[i], i + 1);
+		verbose(env, "\n");
+	}
+}

[Severity: Low]
Could printing the disassemblies first cause the callchain summary to be truncated?

Quoted 4 lines

For non-trivial BPF programs, subprograms can contain thousands of instructions. If these are printed before the hot callchains, the user-provided log buffer might fill up completely, preventing the actual callchain summary from being visible.

That's fine, app always can pass a bigger buffer.
Humans look at the log end to see the error.
I suspect bots do too.

author maintainer
#14 lore raw

RFC PATCH 5/6 bpf: report register diff summary for hot callchains

In reply to Eduard Zingerman

When a hot callchain ends at a iter_next, may_goto, or callback-calling instruction, compare cached states from explored_states to identify which registers or stack slots most frequently differ between states. Report the top 3 most varying locations.

The full states diff computation would require some statistical analysis similar to k-means. To keep things simple, approximate this by modifying states_equal() to return the first location where old and current states differ, and counting most frequent diff locations.

---
 include/linux/bpf_verifier.h |  14 ++++
 kernel/bpf/states.c          | 174 +++++++++++++++++++++++++++++++++++++------
 kernel/bpf/verifier.c        |  54 +++++++++++---
 3 files changed, 211 insertions(+), 31 deletions(-)
include/linux/bpf_verifier.h +14 -0
index 347a155d8e21..b48fcd411903 100644
@@ -662,6 +662,16 @@ struct bpf_loop {
 	bool irreducible;
 };
 
+struct bpf_state_diff {
+	u8 slot;
+	u8 frame;
+	enum {
+		DIFF_REG,
+		DIFF_STACK,
+		DIFF_ARG,
+	} kind;
+};
+
 struct bpf_callchain {
 	u32 insn_idx[MAX_CALL_FRAMES];
 	u32 curframe;
@@ -1631,5 +1641,9 @@ int bpf_fixup_call_args(struct bpf_verifier_env *env);
 int bpf_do_misc_fixups(struct bpf_verifier_env *env);
 
 int bpf_compute_loops(struct bpf_verifier_env *env);
+int bpf_sample_state_diffs(struct bpf_verifier_env *env,
+			   struct bpf_callchain *cc,
+			   struct bpf_state_diff *top_diffs,
+			   int *nr_diffs);
 
 #endif /* _LINUX_BPF_VERIFIER_H */
kernel/bpf/states.c +152 -22

332 lines not on this page · raw message

kernel/bpf/verifier.c +45 -9

103 lines not on this page · raw message

Signature · 1 line
2.53.0
#15 lore raw

Re: [PATCH RFC bpf-next 5/6] bpf: report register diff summary for hot callchains

Can this dereference corrupt memory?
Quoted 4 lines
kernel/bpf/states.c +0 -0
index 877338136009..17b48d9f0c10 100644

[ ... ]

Quoted 44 lines
kernel/bpf/states.c +40 -0
@@ -1588,3 +1627,94 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)
 	list_add(&new_sl->node, head);
 	return 0;
 }
+
+static bool callchain_matches_state(struct bpf_callchain *cc,
+				    struct bpf_verifier_state *st)
+{
+	int i;
+
+	if (st->curframe != cc->curframe)
+		return false;
+	for (i = 0; i < (int)cc->curframe; i++)
+		if (st->frame[i + 1]->callsite != cc->insn_idx[i])
+			return false;
+	return true;
+}
+
+struct state_diff_cnt {
+	struct bpf_state_diff diff;
+	u32 cnt;
+};
+
+static int state_diff_cmp(const void *a, const void *b)
+{
+	return ((struct state_diff_cnt *)b)->cnt - ((struct state_diff_cnt *)a)->cnt;
+}
+
+static bool state_diff_eq(struct bpf_state_diff *a, struct bpf_state_diff *b)
+{
+	return a->frame == b->frame && a->slot == b->slot && a->kind == b->kind;
+}
+
+int bpf_sample_state_diffs(struct bpf_verifier_env *env,
+			   struct bpf_callchain *cc,
+			   struct bpf_state_diff *top_diffs,
+			   int *nr_diffs)
+{
+	struct bpf_verifier_state_list *sl_i, *sl_j;
+	struct state_diff_cnt *diff_cnts = NULL;
+	struct list_head *pos_i, *pos_j, *head;
+	u32 leaf_insn, callsite, hash_idx;
+	int i, cap = 0, nr_locs = 0;
+

kernel/bpf/states.c int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx) · line 1679

Quoted 10 lines
kernel/bpf/states.c +10 -0
+	leaf_insn = cc->insn_idx[cc->curframe];
+	callsite = cc->curframe > 0 ? cc->insn_idx[cc->curframe - 1] : BPF_MAIN_FUNC;
+	hash_idx = (leaf_insn ^ callsite) % env->prog->len;
+	head = &env->explored_states[hash_idx];
+
+	list_for_each(pos_i, head) {
+		sl_i = container_of(pos_i, struct bpf_verifier_state_list, node);
+		if (!callchain_matches_state(cc, &sl_i->state))
+			continue;
+		list_for_each(pos_j, pos_i) {
                                       ^^^^^^

kernel/bpf/states.c int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx) · line 1682

Quoted 3 lines
kernel/bpf/states.c +3 -0
+			struct bpf_state_diff diff = {};
+
+			sl_j = container_of(pos_j, struct bpf_verifier_state_list, node);

Can this dereference corrupt memory?

The inner list_for_each(pos_j, pos_i) walks the list starting from pos_i (an element in the list, not the list head). The env->explored_states array contains standalone list_head anchors (not embedded in bpf_verifier_state_list structures), so when the iteration crosses the anchor, pos_j points to the bare list_head at env->explored_states[hash_idx].

At that point, the container_of() produces an invalid pointer, and the subsequent dereference via &sl_j->state accesses arbitrary memory adjacent to the explored_states array (potentially other hash buckets). This can cause spurious matches or crashes when callchain_matches_state() tries to read sl_j->state.curframe from unrelated memory.

The outer list_for_each(pos_i, head) correctly uses the real anchor as terminator. For the inner loop to iterate "all elements after pos_i to the end of the list," it should terminate at head:

    for (pos_j = pos_i->next; pos_j != head; pos_j = pos_j->next)

or use a helper macro that accepts head as the terminator.

Quoted 42 lines
kernel/bpf/states.c +38 -0
+			if (!callchain_matches_state(cc, &sl_j->state))
+				continue;
+			if (states_equal(env, &sl_i->state, &sl_j->state, NOT_EXACT, &diff))
+				continue;
+			for (i = 0; i < nr_locs; i++) {
+				if (state_diff_eq(&diff_cnts[i].diff, &diff)) {
+					diff_cnts[i].cnt++;
+					goto next;
+				}
+			}
+			if (nr_locs == cap) {
+				int new_cap = cap ? cap * 2 : 16;
+				struct state_diff_cnt *new;
+
+				new = kvrealloc(diff_cnts, new_cap * sizeof(*new),
+						GFP_KERNEL_ACCOUNT);
+				if (!new) {
+					kvfree(diff_cnts);
+					return -ENOMEM;
+				}
+				memset(new + cap, 0, (new_cap - cap) * sizeof(*new));
+				diff_cnts = new;
+				cap = new_cap;
+			}
+			diff_cnts[nr_locs].diff = diff;
+			diff_cnts[nr_locs].cnt = 1;
+			nr_locs++;
+next:;
+		}
+	}
+
+	sort(diff_cnts, nr_locs, sizeof(*diff_cnts), state_diff_cmp, NULL);
+	*nr_diffs = min(nr_locs, *nr_diffs);
+	for (i = 0; i < *nr_diffs; i++)
+		top_diffs[i] = diff_cnts[i].diff;
+	kvfree(diff_cnts);
+	return 0;
+}
kernel/bpf/verifier.c +0 -0
index 8eb8f1ce17c7..7a84eeae395f 100644

[ ... ]

Quoted 53 lines
kernel/bpf/verifier.c +32 -3
@@ -17292,13 +17292,13 @@ static void free_callchain_profile(struct bpf_verifier_env *env)
 	}
 }
 
-static void print_callchain_entry(struct bpf_verifier_env *env,
-				  struct bpf_callchain_entry *entry, int idx)
+static int print_callchain_entry(struct bpf_verifier_env *env,
+				 struct bpf_callchain_entry *entry, int idx)
 {
 	struct bpf_callchain *cc = &entry->cc;
 	const struct bpf_line_info *linfo;
 	struct bpf_subprog_info *sub;
-	int i, insn_idx;
+	int i, err, insn_idx;
 
 	verbose(env, "#%d most visited simulated stacktrace (visited %llu times):\n",
 		idx, entry->count);
@@ -17316,6 +17316,35 @@ static void print_callchain_entry(struct bpf_verifier_env *env,
 				BPF_LINE_INFO_LINE_NUM(linfo->line_col));
 		verbose(env, "\n");
 	}
+
+	insn_idx = cc->insn_idx[cc->curframe];
+	if (bpf_is_force_checkpoint(env, insn_idx)) {
+		struct bpf_state_diff top_diffs[3];
+		int nr_diffs = ARRAY_SIZE(top_diffs);
+
+		err = bpf_sample_state_diffs(env, cc, top_diffs, &nr_diffs);
+		if (err)
+			return err;
+		for (i = 0; i < nr_diffs; i++) {
+			struct bpf_state_diff *d = &top_diffs[i];
+
+			switch (d->kind) {
+			case DIFF_REG:
+				verbose(env, "    Most varying: R%d (frame %d)\n",
+					d->slot, d->frame);
+				break;
+			case DIFF_STACK:
+				verbose(env, "    Most varying: fp-%d (frame %d)\n",
+					(d->slot + 1) * BPF_REG_SIZE, d->frame);
+				break;
+			case DIFF_ARG:
+				verbose(env, "    Most varying: arg#%d (frame %d)\n",
+					d->slot, d->frame);
+				break;
+			}
+		}
+	}
+	return 0;
 }
 
 static void disasm_subprog(struct bpf_verifier_env *env, struct bpf_subprog_info *sub)

[ ... ]

Quoted 20 lines
kernel/bpf/verifier.c +3 -3
@@ -17340,16 +17369,16 @@ static void disasm_subprog(struct bpf_verifier_env *env, struct bpf_subprog_info
  * Print several most visited simulated stack traces,
  * and a disasembly of related subprograms.
  */
-static void print_hotspots(struct bpf_verifier_env *env)
+static int print_hotspots(struct bpf_verifier_env *env)
 {
 	DECLARE_BITMAP(printed_subs, BPF_MAX_SUBPROGS) = {};
 	struct bpf_callchain_entry *top[3] = {};
 	struct bpf_callchain_entry *entry;
 	struct bpf_subprog_info *sub;
-	int i, j, bkt, nr_top = 0;
+	int i, j, err, bkt, nr_top = 0;
 
 	if (!(env->log.level & BPF_LOG_LEVEL))
-		return;
+		return 0;
 
 	/* Collect the hottest callchains */
 	hash_for_each(env->callchain_htab, bkt, entry, node) {

[ ... ]

Quoted 17 lines
kernel/bpf/verifier.c +6 -1
@@ -17388,9 +17417,14 @@ static void print_hotspots(struct bpf_verifier_env *env)
 
 	/* Print the hot callchains */
 	for (i = 0; i < nr_top; i++) {
-		print_callchain_entry(env, top[i], i + 1);
+		err = print_callchain_entry(env, top[i], i + 1);
+		if (err)
+			return err;
+
 		verbose(env, "\n");
 	}
+
+	return 0;
 }
 
 static int do_check_insn(struct bpf_verifier_env *env, bool *do_print_state)

kernel/bpf/verifier.c static int do_check(struct bpf_verifier_env *env) · line 17569

Quoted 10 lines
kernel/bpf/verifier.c +3 -1
@@ -17527,7 +17561,9 @@ static int do_check(struct bpf_verifier_env *env)
 		insn_aux = &env->insn_aux_data[env->insn_idx];
 
 		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
-			print_hotspots(env);
+			err = print_hotspots(env);
+			if (err)
+				return err;
 			verbose(env,
 				"BPF program is too large. Processed %d insn\n",
 				env->insn_processed);

Should diagnostic allocation failures mask the complexity limit verdict?

When the verifier hits BPF_COMPLEXITY_LIMIT_INSNS, do_check() now calls print_hotspots() and returns its error before emitting the standard "BPF program is too large" message.

If bpf_sample_state_diffs() returns -ENOMEM from kvrealloc() during diagnostic printing, do_check() propagates that error to userspace instead of the expected -E2BIG. The program is correctly rejected, but the user-visible error shifts from "program too large" to "out of memory" purely because diagnostic output failed to allocate.

Would it be better to ignore or log-and-discard errors from print_hotspots() so that -E2BIG and the "too large" message are always produced when the complexity limit is reached?

---
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/26444655429

#16 lore raw

Re: [PATCH RFC bpf-next 5/6] bpf: report register diff summary for hot callchains

In reply to Eduard Zingerman
Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

Thank you for your contribution! Sashiko AI review found 3 potential issue(s) to consider:

New issues:
- [High] Misuse of the list_for_each macro in bpf_sample_state_diffs() causes out-of-bounds reads and an eventual kernel panic.
- [Medium] Early returns in states_equal() and func_states_equal() fail to populate the bpf_state_diff output parameter, misleadingly attributing differences to register R0.

Pre-existing issues:
- [High] The printed_subs bitmap in print_hotspots() is undersized, which can lead to a stack buffer overflow. --

commit d10e1bb2745385ee84a9743a4009ae6e95842d64
Author: Eduard Zingerman <[email protected]>

bpf: report register diff summary for hot callchains

This commit modifies the verifier to report a summary of register differences for hot callchains ending at iter_next, may_goto, or callback-calling instructions. It does this by taking the most frequently varying register or stack locations from explored states.

Quoted 4 lines
kernel/bpf/states.c +0 -0
index 8773381360095..17b48d9f0c105 100644

[ ... ]

kernel/bpf/states.c static void reset_idmap_scratch(struct bpf_verifier_env *env) · line 1011

Quoted 10 lines
kernel/bpf/states.c +2 -1
@@ -970,7 +1004,8 @@ static void reset_idmap_scratch(struct bpf_verifier_env *env)
 static bool states_equal(struct bpf_verifier_env *env,
 			 struct bpf_verifier_state *old,
 			 struct bpf_verifier_state *cur,
-			 enum exact_level exact)
+			 enum exact_level exact,
+			 struct bpf_state_diff *diff)
 {
 	u32 insn_idx;
 	int i;

[Severity: Medium]
Since diff is initialized to zero by the caller, will early returns in states_equal() and func_states_equal() (such as mismatches in in_sleepable, callback_depth, or refsafe()) fail to update the diff parameter?

Would this result in falsely attributing state mismatches to register R0 and producing misleading profiling statistics?

[ ... ]

Quoted 1 line
kernel/bpf/states.c +0 -0
@@ -1588,3 +1627,94 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)

[ ... ]

Quoted 5 lines
kernel/bpf/states.c +5 -0
+int bpf_sample_state_diffs(struct bpf_verifier_env *env,
+			   struct bpf_callchain *cc,
+			   struct bpf_state_diff *top_diffs,
+			   int *nr_diffs)
+{

[ ... ]

kernel/bpf/states.c int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx) · line 1683

Quoted 9 lines
kernel/bpf/states.c +9 -0
+	list_for_each(pos_i, head) {
+		sl_i = container_of(pos_i, struct bpf_verifier_state_list, node);
+		if (!callchain_matches_state(cc, &sl_i->state))
+			continue;
+		list_for_each(pos_j, pos_i) {
+			struct bpf_state_diff diff = {};
+
+			sl_j = container_of(pos_j, struct bpf_verifier_state_list, node);
+			if (!callchain_matches_state(cc, &sl_j->state))

[Severity: High]
Does this nested loop traversal result in processing the dummy list head?

Because list_for_each() iterates until the pointer wraps around to its start point (in this case, pos_i), the traversal will inevitably evaluate the dummy head (&env->explored_states[hash_idx]).

When container_of() computes sl_j from this dummy head, won't the subsequent callchain_matches_state() dereference an invalid pointer and cause an out-of-bounds read?

Quoted 3 lines
kernel/bpf/states.c +3 -0
+				continue;
+			if (states_equal(env, &sl_i->state, &sl_j->state, NOT_EXACT, &diff))
+				continue;

[ ... ]

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index 8eb8f1ce17c76..7a84eeae395fa 100644

[ ... ]

kernel/bpf/verifier.c static void disasm_subprog(struct bpf_verifier_env *env, struct bpf_subprog_info · line 17374

Quoted 8 lines
kernel/bpf/verifier.c +1 -1
@@ -17340,16 +17369,16 @@ static void disasm_subprog(struct bpf_verifier_env *env, struct bpf_subprog_info
  * Print several most visited simulated stack traces,
  * and a disasembly of related subprograms.
  */
-static void print_hotspots(struct bpf_verifier_env *env)
+static int print_hotspots(struct bpf_verifier_env *env)
 {
 	DECLARE_BITMAP(printed_subs, BPF_MAX_SUBPROGS) = {};

[Severity: High]
This is a pre-existing issue, but could the printed_subs bitmap be too small here?

The subprog_info array in the verifier environment contains BPF_MAX_SUBPROGS
+ 2 elements to account for fake and exception subprograms.

If a recorded hot callchain includes an exception subprogram, will the offset sub - env->subprog_info evaluate to an index greater than or equal to BPF_MAX_SUBPROGS, causing a stack buffer overflow when __set_bit() is called?

Quoted 3 lines
kernel/bpf/verifier.c +0 -0
 	struct bpf_callchain_entry *top[3] = {};
 	struct bpf_callchain_entry *entry;
 	struct bpf_subprog_info *sub;
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=5
author maintainer
#17 lore raw

Re: [PATCH RFC bpf-next 5/6] bpf: report register diff summary for hot callchains

On Tue, 2026-05-26 at 11:11 +0000, [email protected] wrote:

[...]

Quoted 16 lines

kernel/bpf/states.c static void reset_idmap_scratch(struct bpf_verifier_env *env) · line 1011

Quoted 10 lines
kernel/bpf/states.c +2 -1
@@ -970,7 +1004,8 @@ static void reset_idmap_scratch(struct bpf_verifier_env *env)
  static bool states_equal(struct bpf_verifier_env *env,
  			 struct bpf_verifier_state *old,
  			 struct bpf_verifier_state *cur,
-			 enum exact_level exact)
+			 enum exact_level exact,
+			 struct bpf_state_diff *diff)
  {
  	u32 insn_idx;
  	int i;

[Severity: Medium]
Since diff is initialized to zero by the caller, will early returns in states_equal() and func_states_equal() (such as mismatches in in_sleepable, callback_depth, or refsafe()) fail to update the diff parameter?

Quoted 2 lines

Would this result in falsely attributing state mismatches to register R0 and producing misleading profiling statistics?

Don't expect this to be an issue in loops, but yes. I should add DIFF_OTHER as a reason.

Quoted 22 lines

[ ... ]

Quoted 1 line
(quoted diff) +0 -0
@@ -1588,3 +1627,94 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)

[ ... ]

Quoted 5 lines
kernel/bpf/states.c +5 -0
+int bpf_sample_state_diffs(struct bpf_verifier_env *env,
+			   struct bpf_callchain *cc,
+			   struct bpf_state_diff *top_diffs,
+			   int *nr_diffs)
+{

[ ... ]

kernel/bpf/states.c int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx) · line 1683

Quoted 9 lines
kernel/bpf/states.c +9 -0
+	list_for_each(pos_i, head) {
+		sl_i = container_of(pos_i, struct bpf_verifier_state_list, node);
+		if (!callchain_matches_state(cc, &sl_i->state))
+			continue;
+		list_for_each(pos_j, pos_i) {
+			struct bpf_state_diff diff = {};
+
+			sl_j = container_of(pos_j, struct bpf_verifier_state_list, node);
+			if (!callchain_matches_state(cc, &sl_j->state))

[Severity: High]
Does this nested loop traversal result in processing the dummy list head?

Quoted 7 lines

Because list_for_each() iterates until the pointer wraps around to its start point (in this case, pos_i), the traversal will inevitably evaluate the dummy head (&env->explored_states[hash_idx]).

When container_of() computes sl_j from this dummy head, won't the subsequent callchain_matches_state() dereference an invalid pointer and cause an out-of-bounds read?

Good point. I should iterate starting from the same 'head' and just filter out 'pos_i == pos_j'. Surprising that I didn't see KASAN splats when testing this on scx.

author maintainer
#18 lore raw

RFC PATCH 6/6 selftests/bpf: test budget exhaustion profiling report

In reply to Eduard Zingerman

Add verifier selftests that exhaust the 1M instruction budget and verify that the new profiling report is produced:
- nested function calls with inner loop, check that stack trace is print correctly;
- two loops on the same level, check that both are reported;
- iterator-based loop with non-converging register, check that register is in the report;
- iterator-based loop with non-converging stack slot, check that stack slot is in the report.

---
 tools/testing/selftests/bpf/prog_tests/verifier.c  |   2 +
 .../selftests/bpf/progs/verifier_budget_report.c   | 175 +++++++++++++++++++++
 2 files changed, 177 insertions(+)
tools/testing/selftests/bpf/prog_tests/verifier.c +2 -0
index 35d92d176c1f..61a732a499b0 100644
@@ -14,6 +14,7 @@
 #include "verifier_basic_stack.skel.h"
 #include "verifier_bitfield_write.skel.h"
 #include "verifier_bounds.skel.h"
+#include "verifier_budget_report.skel.h"
 #include "verifier_bounds_deduction.skel.h"
 #include "verifier_bounds_deduction_non_const.skel.h"
 #include "verifier_bounds_mix_sign_unsign.skel.h"
@@ -169,6 +170,7 @@ void test_verifier_bounds(void)               { RUN(verifier_bounds); }
 void test_verifier_bounds_deduction(void)     { RUN(verifier_bounds_deduction); }
 void test_verifier_bounds_deduction_non_const(void)     { RUN(verifier_bounds_deduction_non_const); }
 void test_verifier_bounds_mix_sign_unsign(void) { RUN(verifier_bounds_mix_sign_unsign); }
+void test_verifier_budget_report(void)        { RUN(verifier_budget_report); }
 void test_verifier_bpf_get_stack(void)        { RUN(verifier_bpf_get_stack); }
 void test_verifier_bpf_trap(void)             { RUN(verifier_bpf_trap); }
 void test_verifier_bswap(void)                { RUN(verifier_bswap); }
tools/testing/selftests/bpf/progs/verifier_budget_report.c new file +175 -0

175 lines not on this page · raw message

Signature · 1 line
2.53.0