bpf: fixes and follow-ups for 32-/64-bit scalar evolution
Subsystems (4)
Eduard Zingerman
maintainerv2 cover bpf: fixes and follow-ups for 32-/64-bit scalar evolution
Fixes:
- bpf: avoid false infinite loop reports after changes in SCEV clamping
- bpf: do not intersect with current register range on clamp
- bpf: reject pointer operands for 32-bit recurrences/latches
Follow-ups:
- bpf: (zext32 (zext32 X)) -> (zext32 X) SCEV simplification rule
- bpf: check the iteration count before the predicted exit value
Note: this supersedes [1].
[1] bpf: reject pointer operands for 32-bit recurrences/latches
https://lore.kernel.org/bpf/[email protected]/
There are some veristat improvements after clamping changes and new zext32 simplification rule.
A: master; B: scev-simpler-clamp. Corpora: cilium, meta, scx, selftests. Object exclusions: verifier_scev.bpf.o.
Histogram: selected programs, without the table filters.
Total progs: 8071
-85 .. -75 %: 1 -35 .. -25 %: 3 -25 .. -20 %: 18 -20 .. -10 %: 5 -10 .. 0 %: 13 0 .. 5 %: 8031
Tables: success in both runs; baseline Insns >= 5,000.
Ranked by percentage change, then instruction-count change, file, program. Meta names are anonymized; numbered objects are distinct files.
Top wins
--------
File Program Insns (A) Insns (B) Insns (DIFF) ------------------------- --------------------------------- --------- --------- ---------------- profiler-06.bpf.o on_perf_event 94751 64595 -30156 (-31.83%) profiler-19.bpf.o sched_switch_offcpu 21906 15726 -6180 (-28.21%) profiler-12.bpf.o sched_switch 12105 9015 -3090 (-25.53%) profiler-26.bpf.o handle_cu_mem_address_reserve 12702 9738 -2964 (-23.33%) profiler-26.bpf.o handle_cu_mem_create 12702 9738 -2964 (-23.33%) profiler-26.bpf.o handle_malloc 12702 9738 -2964 (-23.33%) profiler-26.bpf.o handle_cu_mem_map 12900 9936 -2964 (-22.98%) profiler-09.bpf.o on_custom_event_start 12951 9987 -2964 (-22.89%) profiler-09.bpf.o trace_func_entry 12951 9987 -2964 (-22.89%) profiler-19.bpf.o sched_waking 6642 5160 -1482 (-22.31%) profiler-27.bpf.o handle_cuda_launch_exc 6665 5183 -1482 (-22.24%) profiler-27.bpf.o handle_cuda_launch 6678 5196 -1482 (-22.19%) profiler-12.bpf.o on_custom_event_begin 6885 5403 -1482 (-21.53%) profiler-12.bpf.o on_custom_event_end 6889 5407 -1482 (-21.51%) profiler-26.bpf.o handle_mtia_cached_alloc 13870 10906 -2964 (-21.37%) profiler-26.bpf.o handle_mtia_allocate_enter 13931 10967 -2964 (-21.28%) profiler-26.bpf.o handle_pytorch_malloc 14223 11259 -2964 (-20.84%) profiler-19.bpf.o oncpu 7178 5696 -1482 (-20.65%) profiler-12.bpf.o on_task_enqueued 7223 5741 -1482 (-20.52%) profiler-12.bpf.o sched_waking 7258 5776 -1482 (-20.42%) profiler-12.bpf.o on_task_dequeued 7398 5916 -1482 (-20.03%) profiler-12.bpf.o on_request_context_event 7489 6007 -1482 (-19.79%) profiler-12.bpf.o on_pytorch_event 7490 6008 -1482 (-19.79%) profiler-12.bpf.o on_task_stats 7572 6090 -1482 (-19.57%) profiler-12.bpf.o oncpu 7676 6194 -1482 (-19.31%) profiler-12.bpf.o get_crochet_walltime_stacks 22063 18973 -3090 (-14.01%) profiler-24.bpf.o get_task_stacks 64928 61154 -3774 (-5.81%)
Changelog:
v1 -> v2:
- changed series target to bpf.
- change in the bpf_is_state_visited() to avoid infinite loop detection interference for terminating loops.
v1: https://lore.kernel.org/bpf/[email protected]/T/47e07d3ab05
---
Eduard Zingerman (11):
bpf: reject pointer operands for 32-bit recurrences/latches
bpf: do not intersect with current register range on clamp
bpf: avoid false infinite loop reports after changes in SCEV clamping
bpf: check the iteration count before the predicted exit value
bpf: (zext32 (zext32 X)) -> (zext32 X) SCEV simplification rule
bpf: print 32-bit SCEV bounds as 32-bit numbers
selftests/bpf: pointer operands for 32-bit recurrences/latches
selftests/bpf: cases with empty range error under old clamping logic selftests/bpf: cases for SCEV interaction with infinite loop detection selftests/bpf: 32-bit copy of the counter compared at the latch
selftests/bpf: Restore stack pointer subrange pruning coverage
include/linux/bpf_verifier.h | 1 + kernel/bpf/log.c | 8 + kernel/bpf/scev.c | 47 ++-- kernel/bpf/states.c | 36 ++- tools/testing/selftests/bpf/progs/verifier_scev.c | 295 ++++++++++++++++++++- .../selftests/bpf/progs/verifier_stack_ptr.c | 30 ++- 6 files changed, 369 insertions(+), 48 deletions(-)
---
base-commit: 195a3519ff27bff5575e05b5086e38ee92715776
change-id: 20261022-scev-simpler-clamp-4b5486b201d2
Eduard Zingerman
maintainerPATCH v2 1/11 bpf: reject pointer operands for 32-bit recurrences/latches
Avoid inferring loop bounds for the following program shapes:
32-bit latch (A) | 32-bit recurrence (B)
-------------------------+--------------------------
r1 = ... pointer ... | r1 = ... pointer ...
r2 = ... pointer ... | r2 = ... pointer ...
l: r1 += 8 | l: w1 += 8
... | ...
if w1 < w2 goto l | if r1 < r2 goto l(A) Scalar bounds for pointers represent only offsets from their common origin values. The 32-bit operations also depend on the runtime base address: the addresses can wrap at 32 bits without the tracked offsets wrapping. Thus, offsets alone do not determine the iteration count.
(B) 32-bit operations on pointers either prohibited (wX += 1) or convert them to scalars (wX = wX). No need to deal with this at SCEV level.
--- kernel/bpf/scev.c | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-)
kernel/bpf/scev.c +7 -3
@@ -2024,7 +2024,8 @@ static void log_incompatible_scev_values(struct bpf_verifier_env *env, const cha }static bool scev_value_compatible (struct bpf_verifier_env *env,struct bpf_func_state *st, -const struct scev_value *a,const struct scev_value *b) +const struct scev_value *a,const struct scev_value *b, +const struct linear_latch *latch) {const struct bpf_reg_state *ra, *rb;
@@ -2035,7 +2036,7 @@ static bool scev_value_compatible(struct bpf_verifier_env *env, struct bpf_func_ } ra =scev_reg_for_read (env, st, a->ptr_reg); rb =scev_reg_for_read (env, st, b->ptr_reg); -if (ra && rb &&bpf_same_memory_origin (ra, rb)) +if (ra && rb &&bpf_same_memory_origin (ra, rb) && !latch->zext32 && !latch->jmp32)return true; incompatible:
@@ -2267,7 +2268,7 @@ static bool compute_max_iters(struct bpf_verifier_env *env, }return false; } -if (!scev_value_compatible (env, st, &initial_val, &bound_val)) +if (!scev_value_compatible (env, st, &initial_val, &bound_val, latch))return false; initial = initial_val.value;
@@ -2700,6 +2701,9 @@ int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_sta reg =scev_reg_for_linear (cur_func, r);/* If SCEV for r is (linear <reg> <slope>) */ if (reg &&is_simple_linear (scev, r_scev, &coefs) &&is_widenable_reg_type (reg)) { +/* 32-bit ALU operations on pointers convert them to scalars */ +if (coefs.zext32 && reg->type !=SCALAR_VALUE ) + goto cant_widen;/* Spills at varying offsets lose precision */ if (test_bit (r, loop->store_base_regs)) { spill_base = true;
Signature · 1 line
2.56.0
Eduard Zingerman
maintainerPATCH v2 2/11 bpf: do not intersect with current register range on clamp
In reply to Eduard Zingermanscev.c:bpf_clamp_scev_regs() is called each time verifier returns to a loop header via a backedge. It's purpose is to re-establish computed variable ranges for registers with linear SCEVs.
It can be defined as:
- For each register R with linear SCEV compute:
- loop_range(R) := entry_range(R) * iterations_count
- range(R) := range(R) ∩ loop_range(R)
Such formulation is necessary to avoid ranges over-approximation in examples like below:
r1 = 0; SCEVs: r1 = (linear r1 1)
r3 = 0; r3 = (linear r3 1)
loop: r3 += 1;
r1 += 1;
if r1 < 5 goto loop;
r0 = 0;
exit;- At loop entry r3 is widened to be in a range r3 ∈ {0,1,2,3,4}.
- After increment it becomes r3 ∈ {1,2,3,4,5}.
- On a second iteration the bpf_clamp_scev_regs() forces r3 to become r3 ∈ {1,2,3,4}. W/o clamping logic r3 range wouldn't shrink preventing loop from converging in states.c:states_equal().
However, intersection logic might lead to assigning an empty range to a register, as in example below:
r1 = 0; verification
r3 = 0; path
loop: r3 += 1; | <---------.
if r3 != 5 goto +0; | r3 ∈ {5} |
r1 += 1; | |
if r1 != 5 goto loop; '-----------'
r0 = 0;
exit;- At header r3 ∈ {0,1,2,3,4}.
- While exploring the branch if r3 != 5 goto ... with r3 ∈ {5}.
- On a second iteration:
r3 := {0,1,2,3,4} ∩ {5} = ∅Which stops verification with the following error:
verifier bug: scev clamp produced empty range for r3
Technically this means that the current verification path is impossible at runtime and should not be traced further.
This commit mitigates the above by removing the intersection logic, the function is now defined as:
- For each register R with linear SCEV compute:
- range(R) := entry_range(R) * iterations_count
This is still sound, provided that SCEV expressions loop execution counts are correct.
--- kernel/bpf/scev.c | 6 ------ tools/testing/selftests/bpf/progs/verifier_scev.c | 2 +- tools/testing/selftests/bpf/progs/verifier_stack_ptr.c | 7 ++----- 3 files changed, 3 insertions(+), 12 deletions(-)
kernel/bpf/scev.c +0 -6
@@ -2896,12 +2896,6 @@ int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *curcontinue ;linear_bounds (entry_reg, max_header_count, &coefs, &bounds); - bounds.r64 =cnum64_intersect (reg->r64, bounds.r64); - bounds.r32 =cnum32_intersect (reg->r32, bounds.r32); -if (cnum64_is_empty (bounds.r64)) { -verifier_bug (env,"scev clamp produced empty range for r%d" , r); -return -EFAULT ; - }if (log->level &BPF_LOG_LEVEL2 ) {bpf_log (log,"loop header at %d, clamping " , insn_idx);log_reg (env, r);
tools/testing/selftests/bpf/progs/verifier_scev.c +1 -1
@@ -1592,7 +1592,7 @@ __msg_next(" r0=(+ r0 -1) / (linear (+ r0 -1) -1)") __msg("loop header at 1, header_count is 3 ") __msg("loop header at 1, widening r0 to 1..3 step 1") __msg("1: R0=scalar(smin=umin=smin32=umin32=1,smax=umax=smax32=umax32=3,var_off=(0x0; 0x3)) loop_stack=1") -__msg("loop header at 1, clamping r0 to 1..2 (s32 1..2) step 1") +__msg("loop header at 1, clamping r0 to 1..3 step 1") __msg("processed 5 insns")__naked void post_cond_jne_neg_step (void ) {
tools/testing/selftests/bpf/progs/verifier_stack_ptr.c +2 -5
@@ -601,11 +601,8 @@ __flag(BPF_F_TEST_STATE_FREQ)*/ __msg("loop header at 3, widening r7 to -72..-16 step 8")__msg ("R7=fp(smin=smin32=-64,smax=smax32=-8" ) -/* -* back-edge state is clamped to the remaining iterations and pruned -* at the header, because [-64, -16] is within the widened [-72, -16] - */ -__msg("loop header at 3, clamping r7 to -64..-16 (s32 -64..-8) step 8") +/* back-edge state is clamped to the widened range and pruned at the header */ +__msg("loop header at 3, clamping r7 to -72..-16 step 8") __msg("from 5 to 3: safe") __msg("processed 9 insns")__naked void stack_ptr_subrange_in_loop (void )
Signature · 1 line
2.56.0
Eduard Zingerman
maintainerPATCH v2 3/11 bpf: avoid false infinite loop reports after changes in SCEV clamping
In reply to Eduard ZingermanClamping now reproduces the widened range at every back edge, so induction variable ranges no longer vary between iterations. This can produce identical checkpoint states in terminating programs, for example:
int main(...) {
for (int i = 0; i < 10; i++) {
foo(...);
for (int j = 0; j < 3; j++)
...;
}
}
void foo(...) {
...;
}Handle two cases in states.c:bpf_is_state_visited():
- For checkpoints inside foo(), look for active loops in upper frames as well. Otherwise current_loop() returns NULL and an identical callee state can trigger an infinite loop report.
- For checkpoints inside the inner loop, skip the infinite loop check when the current state is inside a terminating loop in any frame. That loop bounds how many times its body is re-executed, so an identical state on a later iteration does not imply nontermination. This covers the inner loop above, re-entered with a fresh entry state on each outer iteration, and inner loops SCEV cannot analyze.
The nested_terminating_prune test still rejects such an outer loop, but now reaches the jump complexity limit instead of reporting an infinite loop. Update its expected message accordingly.
--- kernel/bpf/states.c | 36 ++++++++++++++++++----- tools/testing/selftests/bpf/progs/verifier_scev.c | 2 +- 2 files changed, 29 insertions(+), 9 deletions(-)
kernel/bpf/states.c +28 -8
@@ -1358,13 +1358,33 @@ static bool need_loop_checkpoint(struct bpf_verifier_env *env, int insn_idx)return top->loop_id == insn_idx && top->terminates; } +/* Searches for an innermost loop entry starting from an innermost frame. */ static struct loop_stack_entry *current_loop (struct bpf_verifier_state *st) { -struct bpf_func_state *frame = st->frame[st->curframe]; +struct bpf_func_state *frame; +int fr; -if (frame->loop_stack_cnt ==0 ) -return NULL ; -return &frame->loop_stack[frame->loop_stack_cnt -1 ]; +for (fr = st->curframe; fr >=0 ; fr--) { + frame = st->frame[fr]; +if (frame->loop_stack_cnt) +return &frame->loop_stack[frame->loop_stack_cnt -1 ]; + } +return NULL ; +} + +/* True if any of the loops call chain is currently in terminates. */ +static bool in_a_terminating_loop (struct bpf_verifier_state *st) +{ +struct bpf_func_state *frame; +int l, fr; + +for (fr = st->curframe; fr >=0 ; fr--) { + frame = st->frame[fr]; +for (l = frame->loop_stack_cnt -1 ; l >=0 ; l--) +if (frame->loop_stack[l].terminates) +return true; + } +return false; }int bpf_is_state_visited (struct bpf_verifier_env *env,int insn_idx)
@@ -1528,10 +1548,10 @@ int bpf_is_state_visited(struct bpf_verifier_env *env, int insn_idx)*/ old_loop =current_loop (&sl->state); cur_loop =current_loop (cur); -if (old_loop && cur_loop && - old_loop->terminates && cur_loop->terminates && - old_loop->entry_state == cur_loop->entry_state) { -if (states_equal (env, &sl->state, cur,RANGE_WITHIN )) { +if (old_loop && cur_loop &&in_a_terminating_loop (cur)) { +if (old_loop->terminates && cur_loop->terminates && + old_loop->entry_state == cur_loop->entry_state && +states_equal (env, &sl->state, cur,RANGE_WITHIN )) { loop = true; goto hit; }
tools/testing/selftests/bpf/progs/verifier_scev.c +1 -1
@@ -3351,7 +3351,7 @@ SEC("xdp") __failure __log_level(2) __flag(BPF_F_TEST_STATE_FREQ) -__msg("infinite loop detected at insn 6") +__msg("The sequence of 8193 jumps is too complex.")__naked void nested_terminating_prune (void ) { asm volatile (" \
Signature · 1 line
2.56.0
[email protected]
AI reviewRe: [PATCH bpf v2 03/11] bpf: avoid false infinite loop reports after changes in SCEV clamping
TL;DR: Nit only: the comment above in_a_terminating_loop() is hard to parse and may be missing words; a clearer rewording is suggested. No functional issues raised.
Quoted 1 line
bpf: avoid false infinite loop reports after changes in SCEV clamping
TL;DR: Nit only: the comment above in_a_terminating_loop() is hard to parse and may be missing words; a clearer rewording is suggested. No functional issues raised.
Quoted 4 lines
kernel/bpf/states.c +0
-0
[ ... ]
Quoted 4 lines
kernel/bpf/states.c +0
-0@@ -1358,13 +1358,33 @@ static bool need_loop_checkpoint(struct bpf_verifier_env *env, int insn_idx)return top->loop_id == insn_idx && top->terminates; }
[ ... ]
Quoted 4 lines
kernel/bpf/states.c +4
-0+/* True if any of the loops call chain is currently in terminates. */ +static bool in_a_terminating_loop (struct bpf_verifier_state *st) +{ +struct bpf_func_state *frame;
kernel/bpf/states.c static bool need_loop_checkpoint(struct bpf_verifier_env *env, int insn_idx) · line 1388
Quoted 10 lines
kernel/bpf/states.c +9
-0+int l, fr; + +for (fr = st->curframe; fr >=0 ; fr--) { + frame = st->frame[fr]; +for (l = frame->loop_stack_cnt -1 ; l >=0 ; l--) +if (frame->loop_stack[l].terminates) +return true; + } +return false; }
this isn't a bug, but is the comment above in_a_terminating_loop() missing a word or two? "True if any of the loops call chain is currently in terminates" is hard to parse.
The function returns true when any loop_stack entry, in any frame from st->curframe down to frame 0, has ->terminates set. Would something like the following describe that more directly?
/* True if any loop @st is currently in, in any frame, terminates. */
---
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/40421781646
Eduard Zingerman
maintainerPATCH v2 4/11 bpf: check the iteration count before the predicted exit value
In reply to Eduard ZingermanThe comment before total_change computation:
/*
* compute_backedge_taken_count() guarantees that 'total_change'
* does not overflow in 64-bit domain.
*/
total_change = initial + step * backedge_taken_count;Is not true before the check:
if (backedge_taken_count >= U32_MAX - 1)
return false;Move the check before total_change computation in order to reconcile the code with comments. Old position is not a bug the check was performed either way.
--- kernel/bpf/scev.c | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-)
kernel/bpf/scev.c +8 -11
@@ -2307,11 +2307,15 @@ static bool compute_max_iters(struct bpf_verifier_env *env,if (!compute_backedge_taken_count (op, initial, step, bound, &backedge_taken_count))return false; +/* +* max_header_count is u32 and U32_MAX means "infinite", +* check to avoid overflow below. +*/ +if (backedge_taken_count >=U32_MAX -1 ) +return false; +if (latch->zext32 || latch->jmp32) { -/* -* compute_backedge_taken_count() guarantees that 'total_change' -* does not overflow in 64-bit domain. -*/ +/* total_change is guaranteed not to overflow at this point */ total_change = initial + step * backedge_taken_count;if (latch->jmp32 &&is_signed_op (op)) {if ((s64 )total_change <S32_MIN || (s64 )total_change >S32_MAX )
@@ -2322,13 +2326,6 @@ static bool compute_max_iters(struct bpf_verifier_env *env, } } -/* -* max_header_count is u32 and U32_MAX means "infinite", -* check to avoid overflow below. -*/ -if (backedge_taken_count >=U32_MAX -1 ) -return false; -/* The header executes once on entry and once for each taken backedge, hence +1. */ iters->max_header_count = backedge_taken_count +1 ;/*
Signature · 1 line
2.56.0
Eduard Zingerman
maintainerPATCH v2 5/11 bpf: (zext32 (zext32 X)) -> (zext32 X) SCEV simplification rule
In reply to Eduard ZingermanThe compiler can preserve an induction variable across a call by copying it to a callee-saved register. For example:
w1 = 0;
loop:
w7 = w1;
call foo;
w1 = w7;
w1 += 2;
if w7 < 10 goto loop;When building expressions for the loop body, each 32-bit move adds a zero extension:
w7 = w1; r7 = (zext32 r1)
w1 = w7; r1 = (zext32 (zext32 r1))
w1 += 2; r1 = (zext32 (+ (zext32 (zext32 r1)) 2))The existing ALU32 simplification rules allow recognizing the header SCEV for r1 as:
(zext32 (linear r1 2))
Substituting this SCEV into r7's expression at the latch produces:
(zext32 (zext32 (linear r1 2)))
Add the simplification rule:
(zext32 (zext32 X)) -> (zext32 X)
This allows recognizing the saved induction variable in r7 as a 32-bit linear SCEV and computing the loop iteration bound.
--- kernel/bpf/scev.c | 4 ++++ 1 file changed, 4 insertions(+)
kernel/bpf/scev.c +4 -0
@@ -1502,6 +1502,10 @@ static int simplify(struct scev *scev, u32 id, void *priv)return t; } +/* (zext32 (zext32 X)) -> (zext32 X) */ +if (is_zext32 (scev, id, &a) &&is_zext32 (scev, a, &b)) +return a; +return id; }
Signature · 1 line
2.56.0
Eduard Zingerman
maintainerPATCH v2 6/11 bpf: print 32-bit SCEV bounds as 32-bit numbers
In reply to Eduard Zingerman- Print large 32-bit bounds without sign extension.
- Omit 32-bit bounds when they coincide with 64-bit bounds.
Before:
loop header at ..., widening r0 to 0x80000000..0xffffffff (s32 0xffffffff80000000..-1) step 1 loop header at ..., widening r0 to 0..3 (s32 0..3) step 1
After:
loop header at ..., widening r0 to 0x80000000..0xffffffff (s32 0x80000000..-1) step 1 loop header at ..., widening r0 to 0..3 step 1
--- include/linux/bpf_verifier.h | 1 + kernel/bpf/log.c | 8 ++++++++ kernel/bpf/scev.c | 8 +++++--- tools/testing/selftests/bpf/progs/verifier_scev.c | 2 +- 4 files changed, 15 insertions(+), 4 deletions(-)
include/linux/bpf_verifier.h +1 -0
@@ -1280,6 +1280,7 @@ __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env,u32 insn_off, const char *prefix_fmt, ...);void bpf_verbose_snum (struct bpf_verifier_env *env,s64 num); +void bpf_verbose_snum32 (struct bpf_verifier_env *env,s32 num); #define verifier_bug_if(cond, env, fmt, args...) \ ({ \
kernel/bpf/log.c +8 -0
@@ -535,6 +535,14 @@ void bpf_verbose_snum(struct bpf_verifier_env *env, s64 num)verbose (env,"%#llx" , num); } +void bpf_verbose_snum32 (struct bpf_verifier_env *env,s32 num) +{ +if (is_snum_decimal (num)) +verbose (env,"%d" , num); +else +verbose (env,"%#x" , (u32 )num); +} +int tnum_strn (char *str,size_t size,struct tnum a) {/* print as a constant, if tnum is fully known */
kernel/bpf/scev.c +5 -3
@@ -2456,11 +2456,13 @@ static void log_bounds(struct bpf_verifier_env *env, const struct bounds *boundsbpf_verbose_snum (env,cnum64_smin (bounds->r64));bpf_log (log,".." );bpf_verbose_snum (env,cnum64_smax (bounds->r64)); -if (bounds->r32.size <U32_MAX ) { +if (bounds->r32.size <U32_MAX && + (cnum32_smin (bounds->r32) !=cnum64_smin (bounds->r64) || +cnum32_smax (bounds->r32) !=cnum64_smax (bounds->r64))) {bpf_log (log," (s32 " ); -bpf_verbose_snum (env,cnum32_smin (bounds->r32)); +bpf_verbose_snum32 (env,cnum32_smin (bounds->r32));bpf_log (log,".." ); -bpf_verbose_snum (env,cnum32_smax (bounds->r32)); +bpf_verbose_snum32 (env,cnum32_smax (bounds->r32));bpf_log (log,")" ); }bpf_log (log," step %u" , bounds->step);
tools/testing/selftests/bpf/progs/verifier_scev.c +1 -1
@@ -1771,7 +1771,7 @@ __success __log_level(2) __flag(BPF_F_TEST_STATE_FREQ) __msg("loop header at 1, header_count is 4") -__msg("loop header at 1, widening r0 to 0..3 (s32 0..3) step 1") +__msg("loop header at 1, widening r0 to 0..3 step 1") __msg("loop header at 1, clamping r0") __msg("4: R0=3")__naked void pre_cond_je32 (void )
Signature · 1 line
2.56.0
Eduard Zingerman
maintainerPATCH v2 7/11 selftests/bpf: pointer operands for 32-bit recurrences/latches
In reply to Eduard ZingermanAdd four tests for pointer operands in 32-bit SCEV analysis. Check that loop bounds are not inferred for the following program shapes:
32-bit latch | 32-bit recurrence
-------------------------+--------------------------
r6 = ... pointer ... | r6 = ... pointer ...
r7 = ... pointer ... | r7 = ... pointer ...
l: r6 += 1 | l: w6 += 1
... | ...
if w6 < w7 goto l | if r6 < r7 goto l--- tools/testing/selftests/bpf/progs/verifier_scev.c | 109 ++++++++++++++++++++++ 1 file changed, 109 insertions(+)
tools/testing/selftests/bpf/progs/verifier_scev.c +109 -0
@@ -2971,6 +2971,115 @@ __naked void ptr_stack_other_frame(void) " ::: __clobber_all); } +SEC("xdp") +__success +__log_level(2) +__msg("scev: incompatible latch operands r6 (map_value), r7 (map_value)") +__msg("loop header at 11, can't compute iterations count at 14") +__naked void ptr_map_value_jmp32 (void ) +{ + asmvolatile (" \ +*(u64 *)(r10 - 8) = 0; \ +r2 = r10; \ +r2 += -8; \ +r1 = %[map] ll; \ +call %[bpf_map_lookup_elem]; \ +if r0 == 0 goto 2f; \ +r6 = r0; \ +r7 = r6; \ +r7 += 4; \ +r9 = 0; \ +1:" LIMIT_ITERATIONS \ +" r6 += 1; \ +if w6 < w7 goto 1b; \ +2: r0 = 0; \ +exit; \ +" : + : __imm(bpf_map_lookup_elem), __imm_addr(map) + : __clobber_all); +} + +SEC("xdp") +__failure +__log_level(2) +__msg("loop header at 11, can't compute iterations count") +__msg("R6 32-bit pointer arithmetic prohibited") +__naked void ptr_map_value_alu32_latch (void ) +{ + asmvolatile (" \ +*(u64 *)(r10 - 8) = 0; \ +r2 = r10; \ +r2 += -8; \ +r1 = %[map] ll; \ +call %[bpf_map_lookup_elem]; \ +if r0 == 0 goto 2f; \ +r6 = r0; \ +r7 = r6; \ +r7 += 4; \ +r9 = 0; \ +1:" LIMIT_ITERATIONS \ +" w6 += 1; \ +if r6 < r7 goto 1b; \ +2: r0 = 0; \ +exit; \ +" : + : __imm(bpf_map_lookup_elem), __imm_addr(map) + : __clobber_all); +} + +SEC("xdp") +__success +__log_level(2) +__msg("loop header at 11, can't compute iterations count") +__naked void ptr_map_value_alu32_latch2 (void ) +{ + asmvolatile (" \ +*(u64 *)(r10 - 8) = 0; \ +r2 = r10; \ +r2 += -8; \ +r1 = %[map] ll; \ +call %[bpf_map_lookup_elem]; \ +if r0 == 0 goto 2f; \ +r6 = r0; \ +r7 = r6; \ +r7 += 4; \ +r9 = 0; \ +1:" LIMIT_ITERATIONS \ +" r6 += 1; \ +w8 = w6; \ +if r8 < r7 goto 1b; \ +2: r0 = 0; \ +exit; \ +" : + : __imm(bpf_map_lookup_elem), __imm_addr(map) + : __clobber_all); +} + +SEC("xdp") +__success +__log_level(2) +__msg("loop header at 8, can't widen r0, expr is (zext32 (+ r0 1))") +__naked void ptr_map_value_alu32_non_latch (void ) +{ + asmvolatile (" \ +*(u64 *)(r10 - 8) = 0; \ +r2 = r10; \ +r2 += -8; \ +r1 = %[map] ll; \ +call %[bpf_map_lookup_elem]; \ +if r0 == 0 goto 2f; \ +r1 = 0; \ +1: r1 += 1; \ +w0 = w0; \ +w0 += 1; \ +if r1 < 4 goto 1b; \ +2: r0 = 0; \ +exit; \ +" : + : __imm(bpf_map_lookup_elem), __imm_addr(map) + : __clobber_all); +} +/* Metadata and packet data have different origins. */ SEC ("xdp" ) __success
Signature · 1 line
2.56.0
Eduard Zingerman
maintainerPATCH v2 8/11 selftests/bpf: cases with empty range error under old clamping logic
In reply to Eduard ZingermanA 64-bit and 32-bit examples leading to an empty register range error when scev.c:bpf_clamp_scev_regs() intersected current register state with computed iteration range:
r1 = 0; verification
r3 = 0; path
loop: r3 += 1; | <---------.
if r3 != 5 goto +0; | r3 ∈ {5} |
r1 += 1; | |
if r1 != 5 goto loop; '-----------'
r0 = 0;
exit;- At header r3 ∈ {0,1,2,3,4}.
- After if r3 != 5 goto ... continued with r3 ∈ {5}.
- On a second iteration bpf_clamp_scev_regs() computed:
r3 := {0,1,2,3,4} ∩ {5} = ∅And reported an error:
verifier bug: scev clamp produced empty range for r3
--- tools/testing/selftests/bpf/progs/verifier_scev.c | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+)
tools/testing/selftests/bpf/progs/verifier_scev.c +55 -0
@@ -1604,6 +1604,61 @@ __naked void post_cond_jne_neg_step(void) " ::: __clobber_all); } +/* +* r1 and r3 are widened independently, so the r3 == 5 path reaches the back +* edge with r3 past the last value it takes at the header. +*/ +SEC("socket") +__success +__log_level(2) +__flag(BPF_F_TEST_STATE_FREQ) +__msg("loop header at 2, header_count is 5 ") +__msg("loop header at 2, widening r1 to 0..4 step 1") +__msg("loop header at 2, widening r3 to 0..4 step 1") +__msg("3: (55) if r3 != 0x5 goto pc+1 {{.*}}; R3=5") +__msg("loop header at 2, clamping r3 to 0..4 step 1") +__msg("from 6 to 2: safe") +__naked void clamp_dependent_overshoot (void ) +{ + asmvolatile (" \ +r1 = 0; \ +r3 = 0; \ +1: r3 += 1; \ +if r3 != 5 goto 2f; \ +r2 = 0; \ +2: r1 += 1; \ +if r1 != 5 goto 1b; \ +r0 = 0; \ +exit; \ +" ::: __clobber_all); +} + +/* Same with a 32-bit dependent register, SCEV (zext32 (linear r3 1)) */ +SEC("socket") +__success +__log_level(2) +__flag(BPF_F_TEST_STATE_FREQ) +__msg("loop header at 2, header_count is 5 ") +__msg("loop header at 2, widening r1 to 0..4 step 1") +__msg("loop header at 2, widening r3 to 0..4 step 1") +__msg("3: (56) if w3 != 0x5 goto pc+1 {{.*}}; R3=5") +__msg("loop header at 2, clamping r3 to 0..4 step 1") +__msg("from 6 to 2: safe") +__naked void clamp_dependent_overshoot32 (void ) +{ + asmvolatile (" \ +r1 = 0; \ +w3 = 0; \ +1: w3 += 1; \ +if w3 != 5 goto 2f; \ +r2 = 0; \ +2: r1 += 1; \ +if r1 != 5 goto 1b; \ +r0 = 0; \ +exit; \ +" ::: __clobber_all); +} + SEC("xdp") __success__log_level (2 )
Signature · 1 line
2.56.0
Eduard Zingerman
maintainerPATCH v2 9/11 selftests/bpf: cases for SCEV interaction with infinite loop detection
In reply to Eduard ZingermanAdd three test cases exercising state pruning after loop counter clamping. All turn a 32-bit stack spill into STACK_MISC during the first iteration. This prevents a state match at the outer loop header on the next iteration, while allowing states to match further inside the loop. All are falsely reported as infinite loop w/o changes in patch [1].
- clamp_callee_state_pruning(), a callee overwrites the upper half of the caller's stack slot. States then match at the callee's exit, where the current frame has no active loop.
Verify that current_loop() finds the caller's active loop.
- clamp_nested_loop_state_pruning(), the overwrite happens inside an inner loop. Exercise matching states when the inner loop is entered again on a subsequent outer iteration.
- clamp_nested_unrolled_loop_state_pruning(), same as above, but the inner loop is not recognized by SCEV and is unrolled with a precise counter, so its entries are never marked terminating.
[1] bpf: avoid false infinite loop reports after changes in SCEV clamping
--- tools/testing/selftests/bpf/progs/verifier_scev.c | 98 +++++++++++++++++++++++ 1 file changed, 98 insertions(+)
tools/testing/selftests/bpf/progs/verifier_scev.c +98 -0
@@ -2567,6 +2567,104 @@ __naked void no_widen_any_stack_origin(void) " ::: __clobber_all); } +__naked __noinline __used static int scrub_slot_callee(void) +{ + asmvolatile (" \ +*(u32 *)(r1 + 4) = 1; \ +call %[bpf_get_prandom_u32]; \ +exit; \ +" : + : __imm(bpf_get_prandom_u32) + : __clobber_all); +} + +/* +* The callee turns the caller's fp-8 into misc, so the states at the call site +* differ between the first and the second iteration, while the states inside +* the callee are identical. Verification fails with an infinite loop error if +* states.c:current_loop() does not search upper frames for active loops. +*/ +SEC("socket") +__success +__log_level(2) +__flag(BPF_F_TEST_STATE_FREQ) +__msg("loop header at 3, widening r6 to 0..9 step 1") +__msg("loop header at 3, clamping r6 to 0..9 step 1") +__msg("12: safe") +__naked void clamp_callee_state_pruning (void ) +{ + asmvolatile (" \ +w1 = 1; \ +*(u32 *)(r10 - 8) = r1; \ +r6 = 0; \ +1: r1 = r10; \ +r1 += -8; \ +call scrub_slot_callee; \ +r6 += 1; \ +if r6 < 10 goto 1b; \ +r0 = *(u32 *)(r10 - 8); \ +exit; \ +" ::: __clobber_all); +} + +/* +* The inner loop turns fp-8 from a spill into misc. On the next outer +* iteration, the states inside the inner loop match its first invocation. +*/ +SEC("socket") +__success +__log_level(2) +__flag(BPF_F_TEST_STATE_FREQ) +__msg("loop header at 3, widening r6 to 0..9 step 1") +__msg("loop header at 4, widening r7 to 0..2 step 1") +__msg("loop header at 3, clamping r6 to 0..9 step 1") +__naked void clamp_nested_loop_state_pruning (void ) +{ + asmvolatile (" \ +w1 = 1; \ +*(u32 *)(r10 - 8) = r1; \ +r6 = 0; \ +1: r7 = 0; \ +2: *(u32 *)(r10 - 4) = 1; \ +r7 += 1; \ +if r7 < 3 goto 2b; \ +r6 += 1; \ +if r6 < 10 goto 1b; \ +r0 = *(u32 *)(r10 - 8); \ +exit; \ +" ::: __clobber_all); +} + +/* +* Same as above, but the inner loop is not recognized by SCEV and is unrolled +* with a precise r7. The states at its header still match between the outer +* iterations and must not be reported as an infinite loop: the path between +* them crosses the back edge of the terminating outer loop. +*/ +SEC("socket") +__success +__log_level(2) +__flag(BPF_F_TEST_STATE_FREQ) +__msg("loop header at 3, widening r6 to 0..9 step 1") +__msg("loop header at 5, can't compute iterations count") +__msg("loop header at 3, clamping r6 to 0..9 step 1") +__naked void clamp_nested_unrolled_loop_state_pruning (void ) +{ + asmvolatile (" \ +w1 = 1; \ +*(u32 *)(r10 - 8) = r1; \ +r6 = 0; \ +1: *(u32 *)(r10 - 4) = 1; \ +r7 = 1; \ +2: r7 *= 2; \ +if r7 < 4 goto 2b; \ +r6 += 1; \ +if r6 < 10 goto 1b; \ +r0 = *(u32 *)(r10 - 8); \ +exit; \ +" ::: __clobber_all); +} +/* * r7 starts as 1 + 6*k and invariant r8 as 1 + 9*k (0 <= k <= 3). * The (any r7 r8) union must preserve base 1 and step gcd(6, 9) = 3.
Signature · 1 line
2.56.0
Eduard Zingerman
maintainerPATCH v2 10/11 selftests/bpf: 32-bit copy of the counter compared at the latch
In reply to Eduard ZingermanWhen building SCEV expressions for the loop:
w7 = w1; r7 = (zext32 r1) w1 = w7; r1 = (zext32 (zext32 r1)) w1 += 2; r1 = (zext32 (+ (zext32 (zext32 r1)) 2))
Computed SCEV expression for r1:
(zext32 (linear r1 2))
Substituting this into r7's expression at the latch:
(zext32 (zext32 (linear r1 2)))
Without (zext32 (zext32 X)) -> (zext32 X) simplification rule the latch would not be recognized as linear and header_count won't be computed.
--- tools/testing/selftests/bpf/progs/verifier_scev.c | 27 +++++++++++++++++++++++ 1 file changed, 27 insertions(+)
tools/testing/selftests/bpf/progs/verifier_scev.c +27 -0
@@ -3710,4 +3710,31 @@ __naked void dominating_exit_bounds_count(void) " ::: __clobber_all); } +/* +* The counter is copied to a callee-saved register for the call and the copy is compared. +*/ +SEC("xdp") +__success +__log_level(2) +__flag(BPF_F_TEST_STATE_FREQ) +__msg(" scev at latch 5:") +__msg(" r7=(zext32 r1) / (zext32 (linear r1 2))") +__msg("loop header at 1, header_count is 100 ") +__msg("loop header at 1, widening r1 to 0..198 step 2") +__naked void post_cond_jlt32_copy (void ) +{ + asmvolatile (" \ +w1 = 0; \ +1: w7 = w1; \ +call %[bpf_get_prandom_u32]; \ +w1 = w7; \ +w1 += 2; \ +if w7 < 198 goto 1b; \ +r0 = 0; \ +exit; \ +" : + : __imm(bpf_get_prandom_u32) + : __clobber_all); +} + char _license[] SEC("license") = "GPL";
Signature · 1 line
2.56.0
Eduard Zingerman
maintainerPATCH v2 11/11 selftests/bpf: Restore stack pointer subrange pruning coverage
In reply to Eduard ZingermanAfter the clamping changes, r7 returns to the header with [-72, -16] instead of the narrower [-64, -16], so the test no longer checks subrange pruning. Assign an invariant fp-16 pointer to r7 in the loop, giving r7 an ANY SCEV that is not clamped and restoring strict-subrange coverage.
--- .../selftests/bpf/progs/verifier_stack_ptr.c | 27 +++++++++++++--------- 1 file changed, 16 insertions(+), 11 deletions(-)
tools/testing/selftests/bpf/progs/verifier_stack_ptr.c +16 -11
@@ -588,32 +588,37 @@ __naked void stack_check_size_512_with_may_goto(void)/* * Verify that old PTR_TO_STACK state is considered a super-set of -* new PTR_TO_STACK state when new variable range is a sub-range -* of the old range, e.g. old [-72, -16] vs new [-64, -16]. +* new PTR_TO_STACK state when the new offset is within the old range, +* e.g. old [-72, -16] vs new {-16}. */ SEC("socket") __success __log_level(2) __flag(BPF_F_TEST_STATE_FREQ) /* - * r7 is widened to [-72, -16] at the loop header (insn 3), - * the loop body sees [-64, -8] after 'r7 += 8' + * r7 is widened to [-72, -16] at the loop header (insn 5), + * the loop body sees [-64, -8] after 'r7 += 8'. */ -__msg("loop header at 3, widening r7 to -72..-16 step 8") +__msg("loop header at 5, widening r7 to -72..-16 step 1") __msg("R7=fp(smin=smin32=-64,smax=smax32=-8") -/* back-edge state is clamped to the widened range and pruned at the header */ -__msg("loop header at 3, clamping r7 to -72..-16 step 8") -__msg("from 5 to 3: safe") -__msg("processed 9 insns") +/* 'r7 = r8' sets r7 to fp-16; its ANY SCEV is not clamped. */ +__msg("R7=fp-16 R8=fp-16 loop_stack=5") +__not_msg ("clamping r7" ) +/* back-edge state is pruned because {-16} is within [-72, -16]. */ +__msg("from 8 to 5: safe") +__msg("processed 12 insns")__naked void stack_ptr_subrange_in_loop (void ) { asmvolatile (" \ r7 = r10; \ r7 += -72; \ +r8 = r10; \ +r8 += -16; \ r6 = 0; \ -r7 += 8; \ +1: r7 += 8; \ +r7 = r8; \ r6 += 1; \ -if r6 < 8 goto -3; \ +if r6 < 8 goto 1b; \ r0 = 0; \ exit; \ " ::: __clobber_all);
Signature · 1 line
2.56.0
This series was applied to bpf/bpf.git (master) by Alexei Starovoitov <[email protected]>:
Hello:
This series was applied to bpf/bpf.git (master)
by Alexei Starovoitov <[email protected]>:
Quoted 10 lines · On Mon, 26 Oct 2026 16:38:20 -0700 you wrote:
Fixes:
- bpf: avoid false infinite loop reports after changes in SCEV clamping
- bpf: do not intersect with current register range on clamp
- bpf: reject pointer operands for 32-bit recurrences/latchesFollow-ups:
- bpf: (zext32 (zext32 X)) -> (zext32 X) SCEV simplification rule
- bpf: check the iteration count before the predicted exit value[...]
Here is the summary with links:
- [bpf,v2,01/11] bpf: reject pointer operands for 32-bit recurrences/latches
https://git.kernel.org/bpf/bpf/c/c463b378eae7 - [bpf,v2,02/11] bpf: do not intersect with current register range on clamp https://git.kernel.org/bpf/bpf/c/0c33d612bdd5 - [bpf,v2,03/11] bpf: avoid false infinite loop reports after changes in SCEV clamping https://git.kernel.org/bpf/bpf/c/5dd32c8c1082 - [bpf,v2,04/11] bpf: check the iteration count before the predicted exit value https://git.kernel.org/bpf/bpf/c/86d654957d40 - [bpf,v2,05/11] bpf: (zext32 (zext32 X)) -> (zext32 X) SCEV simplification rule https://git.kernel.org/bpf/bpf/c/abc9a76a888f - [bpf,v2,06/11] bpf: print 32-bit SCEV bounds as 32-bit numbers https://git.kernel.org/bpf/bpf/c/899cbaae6e4c - [bpf,v2,07/11] selftests/bpf: pointer operands for 32-bit recurrences/latches https://git.kernel.org/bpf/bpf/c/88b1da858326 - [bpf,v2,08/11] selftests/bpf: cases with empty range error under old clamping logic https://git.kernel.org/bpf/bpf/c/39cd4e0915c4 - [bpf,v2,09/11] selftests/bpf: cases for SCEV interaction with infinite loop detection https://git.kernel.org/bpf/bpf/c/344c14e8b3d4 - [bpf,v2,10/11] selftests/bpf: 32-bit copy of the counter compared at the latch https://git.kernel.org/bpf/bpf/c/a0137c789774 - [bpf,v2,11/11] selftests/bpf: Restore stack pointer subrange pruning coverage https://git.kernel.org/bpf/bpf/c/8fd732e5a64b
You are awesome, thank you!
Signature · 2 lines
Deet-doot-dot, I am a bot. https://korg.docs.kernel.org/patchwork/pwbot.html