Skip to contentSkip to conversation

bpf: Verify in passes, with equations in the state

PATCH Applied Alexei Starovoitov 5 participants 67 messages Nov 20 – Nov 21 Page 1 of 2

Subsystems (6)
lore
Share & tools
lore
#0 lore raw

v2 cover bpf: Verify in passes, with equations in the state

From: Alexei Starovoitov <[email protected]>

This series replaces the main analysis of the verifier and scev.c. Against bpf-next, the base of the series:

- More valid programs load. The verdict depends less on the code pattern.
- Numbers keep states apart only if an error, or a bound that the program requires, depends on them.
- The work does not grow with the number of iterations of a loop, unless an error needs them one by one.
- The log shows a path to the bug, if the verifier finds one.
- The proof is separate from the guesses. There is less code.

This letter compares three verifiers:

  7.4-rc3    follows one path after another. It has scev.c and no flow.c.
  bpf-next   ea80d2afd285, the base of v1. flow.c joins states.
  series     bpf-next with these patches.

A trip is one iteration of a loop. The sections below explain the other words.

                        7.4-rc3               bpf-next              series
  two states meet       prune or keep apart   guess: join or        join; keep apart after
                                              keep apart            an error
  values that matter    backtrack.c, for      8 tables, before      backward slice from
                        each path             the pass              the error
  related numbers       ids of copies         value numbers of      equations in the state
                                              scev.c, rules
  loop, trip count      scev.c, else each     scev.c, else each     trip index, checked
                        trip                  trip up to a limit
  loop, no trip count   each trip; widen at   each trip up to a     join and widen,
                        may_goto, iterator    limit, then widen     may_goto
                                              and may_goto
  static function       at each call          once for the joined   once for each
                                              calls (*)             instance (*)
  limits                1M insns, 8192 jumps  states, trips         cost, memory

(*) At each call, if the function gets a pointer to the stack.

331763 builds of 6005 programs of other projects load on all three:

  insns, mean           18110                 2716                  1750
  insns, median         585                   397                   384
  time, mean, ms        23.2                  10.3                  5.2
  time, median, ms      1.8                   2.1                   1.0
  peak states, mean     562                   143                   18
  peak states, median   41                    22                    6

Patches 1 and 2 make the analyses before the main pass faster. They give most of the gain in time against bpf-next: with them alone the mean is 6.1 ms, and the median is 1.0 ms.

The problem
===========
Two states meet at a join point of the CFG. The verifier can join them or keep them apart. An example:

state A: i = 0..63 err = 0 --+

                                     +--> join, or keep apart ?
  state B: i = 64..max  err = -22  --+

join cheap, but it can lose "err == 0 means i < 64"
keep apart exact, but n branches can make 2^n states

7.4-rc3 does not join at a branch. It stops ("prunes") a path if an earlier state has all values of the path in the registers that matter ("precise"). Else it keeps the states apart. No fact is lost there, but the paths multiply. The limits are 1M insns and 8192 pending jumps: jumps where one side waits for its check. In loops it can lose facts. scev.c gives each counter its own range. At may_goto, an iterator or a callback a number that is not precise becomes unknown.

bpf-next makes the choice as the states meet. It does not know yet if the join loses a needed fact. So it guesses: 8 tables that tell which values matter, one rule for each code pattern, and limits on states. The guess is final, and it can be wrong in two ways:

  if the states are                   then
  joined, and a needed fact is lost   a valid program is rejected
  kept apart, with no need            the states can grow to the limit

This series decides after the error:

7.4-rc3: each path --> error or limit ? --yes--> REJECT

  bpf-next:   guess --> pass --> error ? --yes--> REJECT

series: join all --> pass --> error ? --no--> ACCEPT

              numbers       ^          | yes
                            |          v
                            +-yes- partition ? --no--> REJECT

A pass checks all functions. An insn whose check fails in a pass is "unproven". A partition keeps more states apart in the next pass (trace partitioning). The first partition makes a backward slice from the unproven insn. It gives two sets of registers and stack slots, the "deps":

data_deps they flow into an operand of the unproven insn
control_deps they flow into a jump that can skip that insn

The join rule looks only at the deps that differ between two states. A "gap" is a value of the join that is in neither state.

  if the deps that differ are      then         example
  not in data_deps                 join         only err differs
  one, in data_deps, no gap        join         i = 0..7 and i = 8..9
  one, in data_deps, with a gap    keep apart   i = 0..1 and i = 100
  two or more, one in data_deps    keep apart   i and err above

If one state has all values of the other in the deps, they are joined. A state that comes back to a loop header is joined. Later partitions keep more apart.

All other numbers stay joined. Two states with different locks, references, or types of a live register stay apart from pass 0.

A pass without errors is a "good pass". It is a complete proof. What a pass keeps apart is its "precision", and it is a guess. A wrong guess costs time, adds a may_goto or a nospec insn that is not needed, or rejects a valid program. It cannot accept an unsafe program. A loop "gets may_goto" if the verifier adds this insn to it. At run time the insn can stop the loop before its end. Then the function returns 0 or, if that is not possible, the code after the loop runs.

What gets better
================
The examples are C, built with clang 21, -O2, -mcpu=v4. barrier_var() is left out. The counts are "insns processed". The verdicts are the same for -mcpu=v2/v3/v4 and -O1/-O2/-O3/-Os, with one exception in example 5. All examples are valid, except MAX = 64 in example 8. "old" is 7.4-rc3 and bpf-next, if they give the same verdict. I also tested 16 variants in which the largest access ends at the last byte. 7.4-rc3 loads 7 of them, bpf-next 1, the series all. If the access can go one byte further, all three reject them.

1. Only the correlated branches in the slice keep states apart
--------------------------------------------------------------

  i = ktime(); err = 0;                 i is any u64
  if (i > 63) err = -22;                err stores the result of i > 63
  c1 = rnd() ? 1 : -1;  ...  cN = ...   N more stored conditions
  if (c1 > 0) cnt[1]++; ...             buf[i] does not depend on them
  if (err) return 0;                    correlated with 'if (i > 63)'
  return buf[i];                        char buf[64]
  N                   4        8        12       24
  7.4-rc3    insns    498      13765    341011   REJECT
             time     0.5 ms   9 ms     213 ms   656 ms
  bpf-next   insns    396      8090     REJECT   REJECT
             time     0.7 ms   60 ms    688 ms   1.5 s
  series     insns    242      470      698      1683
             time     0.4 ms   0.7 ms   1.1 ms   2.6 ms

7.4-rc3 marks c1 .. cN as precise, because they decide a jump. So the paths multiply. With N = 16 it gets to the limit of 1M insns.

bpf-next keeps states apart for each stored condition, because a jump tests it. With N = 12 it gets to its limit on states. It joins all states, and loses the relation between i and err.

The series joins all numbers in pass 0. The join loses the relation, and buf[i] is unproven. i is in data_deps, err is in control_deps. Pass 1 keeps two states
apart: both i and err differ. c1 .. cN are not in the deps and stay joined.

2. The verdict does not depend on the code pattern
--------------------------------------------------
off = 0; len = 64; char buf[64]
if (x) { off = 56; len = 8; }

                                         7.4-rc3   bpf-next          series
  probe_read_kernel(buf + off, len, p)   loads     loads             loads
  buf[off + len - 1]                     loads     REJECT, off=119   loads
  buf[off + len / 2]                     loads     REJECT, off=88    loads
  buf[off * len / 8]                     loads     REJECT, off=448   loads

7.4-rc3 checks the two paths one by one. bpf-next has a table for the first row, and none for the others.

The series has no table. The join finds off = 56 * s, len = 64 - 56 * s, where s is 0 or 1. That proves rows 1, 2 and 3 in pass 0. Row 4 is not linear: it is unproven, and pass 1 keeps the two states apart.

3. The work does not grow with the trip count
---------------------------------------------

  append    for (i = 0; i < N; i++) {
                    n = read_str(big + off, 16);
                    if (n < 0 || n > 16) break;
                    off += n;
            }
  compact   for (i = 0; i < N; i++) if (in[i]) out[n++] = in[i];
  reverse   for (l = 0, r = N - 1; l < r; l++, r--) swap(a[l], a[r]);
  best      for (i = 0; i < N; i++) if (x > max) { max = x; at = i; }  a[at]
  nested    for (j < N) { for (k < N) off += 0..1; off += 0..1; }  a[off]

A trip is one iteration of a loop. Insns processed for each N:

            7.4-rc3                     bpf-next                    series
  N         100      1000     10000     100      1000     10000     each N
  append    1204     12004    REJECT    1104     11004    REJECT    38
  compact   REJECT   REJECT   REJECT    1104     11004    REJECT    37
  reverse   554      5504     55004     554      REJECT   REJECT    38
  best      REJECT   REJECT   REJECT    1108     11008    REJECT    198
  nested    50907    REJECT   REJECT    50907    REJECT   REJECT    55

scev.c has no expression for off, n and at, and no trip count for 'l < r'. So 7.4-rc3 checks the trips one by one, up to 1M insns or 8192 pending jumps. In compact and best a branch in each trip changes a precise value, and the paths multiply.
bpf-next checks the trips one by one, if all trips take 100000 insns or less. With no trip count it stops after 4096 insns. If N is larger, it rejects the program.

The trip index k is the canonical induction variable, and it is a value in the state. The join at the loop header finds the values that are linear in k. One jump bounds all of them:

append: i = k, off = 16 * k + d, d <= 0 'i < N' bounds k

4. A test of one number bounds the related numbers
--------------------------------------------------
a and b are 0..65535
s = a + b;

  if (s > 63) return 0;                      old:      REJECT, off=65535
  buf[a]                                     series:   13 insns
  a is 0..7, b is 8..15                      char big[169]
  for (i = 12 * a; i != 12 * b; i += 12)     old:      REJECT
          big[i]                             series:   34 insns, 15 trips
  n = bpf_get_stack(ctx, buf, 800, 0);       char buf[800]
  if (n < 0) return 0;                       old:      REJECT, off=800 size=800
  bpf_get_stack(ctx, buf + n, 800 - n, 0);   series:   19 insns
  off is 0..63                               char buf[64]
  if (len > 64 - off) return 0;              old:      REJECT, off=63 size=64
  probe_read_kernel(buf + off, len, p);      series:   41 insns

Each state has a table of equations. An insn makes them, a jump uses them, a join guesses them, and a prune checks them. sym0 is a symbolic value:

  r2 = r1                r1 = sym0, r2 = sym0
  r2 <<= 2               r2 = 4 * sym0
  if r1 > 7 goto out     sym0 is 0..7, so r2 is 0..28

The check of a memory argument uses the equations too: offset n plus size 800 - n is 800. test_get_stack_rawtp.c doubles its buffer to pass this check. Patch 45 gives the buffer its real size.

A jump can make an equation: 'len > 64 - off' gives d = len + off - 64 and d <= 0. It does that only if len is in data_deps, so in pass 1.

7.4-rc3 links only copies and 'x + constant', up to 5 at a jump. On bpf-next scev.c has one expression for all paths. An equation holds in one state, so it can differ between paths.

5. Loops without a trip count
-----------------------------
lo = 0; hi = N; 7.4-rc3: REJECT, 1M insns, also for N = 8
while (lo < hi) { (N = 8 loads with -Os)
mid = (lo + hi) / 2; bpf-next: REJECT, also for N = 8
if (a[mid] < key) series: 79 insns, N = 8
lo = mid + 1; 970 insns, N = 1024
else 1596 insns, N = 1M
hi = mid;
}

  while (can_loop) {                 7.4-rc3:  1654 insns
          if (push) {                bpf-next: REJECT
                  if (d == 63)       series:   313 insns
                          break;
                  d++;
          } else {
                  if (!d) break;
                  d--;
          }
          buf[d]

}

7.4-rc3 checks the trips one by one. clang makes two jumps for 'a[mid] < key'. On the path where they disagree, lo and hi do not change, so the paths are long. In the second loop d has 64 values, and may_goto prunes a state that repeats.

If a[mid] or buf[d] is unproven in pass 0, lo, hi and d get into the deps. Then they are "widened": a bound that grows moves to the next constant of the loop. If that is not sufficient, a partition peels only the loop that made one of them
imprecise: its trips are checked one by one. The binary search has no trip count, so it gets may_goto.

6. Calls are context-sensitive
------------------------------
static u64 next(u64 x) { return x + 1; } char buf[64]

  i = next(7);                       7.4-rc3:  18 insns
  sum = next(rnd());                 bpf-next: REJECT, i is any number
  buf[i]                             series:   24 insns

7.4-rc3 checks a static function again at each call, on each path. bpf-next joins the two calls.

The series checks a static function once for each instance. An instance is an entry state, its exit states and its calls. Here next(7) is checked first, and it gets the exit state with 8. If two calls share an instance and this causes an error, the next pass gives each call its own instance. If the function gets a pointer to the stack, bpf-next and the series check it at each call too.

static bool ok(u64 x) { return x < 64; }

if (!ok(x)) return 0; 7.4-rc3: 22 insns
buf[x] bpf-next: REJECT
series: 118 insns

An instance does not know that its argument is x of the caller. If an error depends on such an argument, a partition checks this call with the state of the caller.

7. Arrays of pointers on the stack
----------------------------------

  char *p[2] = { a, b };           old:      REJECT, "invalid mem access"
  return p[i & 1][63];             series:   45 insns
  bpf_for(i, 0, 2)                 old:      REJECT, "invalid mem access"
          sum += p[i][63];         series:   135 insns

A load from one of several stack slots gives a number. If a later insn needs a pointer, the next pass "forks" the state: it does the load once for each slot.

8. The log shows the bug
------------------------
for (i = 0; i < 100000; i++)

          if (rnd() && n < MAX) n++;

buf[n] char buf[64], n is in R6

MAX = 63, valid
7.4-rc3 BPF program is too large. Processed 1000001 insn
bpf-next R6=scalar()
math between map_value pointer and register with unbounded min value is not allowed
series loads, 198 insns

MAX = 64, off by one
7.4-rc3 R6=64, after 899878 insns
invalid access to map value, value_size=64 off=64 size=1
bpf-next the same message as for MAX = 63
series R6=0..64, after 13964 insns
invalid access to map value, value_size=64 off=64 size=1

7.4-rc3 checks the 100000 trips one by one: the first path takes 900k insns. It shows the path to the bug, if it gets there before its limit.

bpf-next prints a joined state. The author cannot tell a bug from a limit of the verifier. The series tries to reproduce the error in a path-sensitive run: one path after another, with no joins. The path on which the check fails is the failing path. The log shows it from insn 0. With a failing path the error is probably real. So the verifier decreases its limit on work, see section 10. "The price" has the exception. R6 has a range on one path, because clang makes 'n += rnd() & 1' with no branch.

9. The proof is separate from the guesses
-----------------------------------------
There are two kinds of code in the verifier:

trusted A bug in it can accept an unsafe program. It is the proof: the
checks of an insn, the compare and the join of states.
guess It selects what to try next, and trusted code checks the result. A
bug in it can reject a valid program or waste time. It cannot accept an unsafe program.

In 7.4-rc3 almost all of this code is trusted. If a bug in backtrack.c misses a register, a path with an error can be pruned. Its guesses are small: which states to keep, and which numbers to widen. bpf-next mixes the two kinds in flow.c ("both"). The series puts the guesses into their own files:

  7.4-rc3      lines  kind      bpf-next   lines  kind      series           lines  kind
  scev.c        2945  trusted   scev.c      5504  trusted   equation.c        2423  trusted
  states.c      1767  trusted   flow.c      3411  both      flow.c            1837  trusted
  backtrack.c   1052  trusted   join.c       627  trusted   join.c             250  trusted
                                states.c     700  trusted   states.c           671  trusted
                                                            precision.c       1784  guess
                                                            equation_join.c   1458  guess
                                                            failing_path.c     269  guess

total 5764 total 10242 total 8692
of them trusted 5181
verifier.c 24331 trusted verifier.c 25361 trusted verifier.c 25971 trusted

So the series has less code than bpf-next, and more than 7.4-rc3.

An example: what a bug in the trip count can do. The bug is invented. This loop makes 34 trips, i is 0, 3, .. 99:

  char a[100];
  i = 0; do { a[i] = 0; i += 3; } while (i < 100);

7.4-rc3 and bpf-next compute the trip count N with a formula of scev.c. The formula has a case for each form of a loop: <, <=, !=, wrap around, 32-bit counters. N gives the range of i at the loop header. Nothing checks N. The state that comes back to the header gets the same range before the compare, so the compare passes.

If the formula is correct, it gives N = 34. The body is checked with i = 0..99.

If the formula has a bug, it can give N = 30. Then the body is checked with i = 0..87 only. After the body i is 3..90, so 'i < 100' looks always true. The verifier removes the exit as dead code, and the program loads. At run time the loop does not end, and it writes past the end of 'a'.

So the formula and each case of it are trusted code.

The series has such a formula too, but it checks the result. The trip index k is 0 in the first trip, and the back edge adds 1. The formula is only a guess for the largest k. 'i = 3 * k' is a guess too. The verifier checks the body for k = 0..guess. Then it compares the state that comes back with the header.

If the formula is correct, the guess is 33. The header has k = 0..33 and i = 3 * k = 0..99. After the body i is 3..102. The test 'i < 100' lets only 3..99 go back, so k = 1..33 comes back. This is inside of 0..33. So all trips are checked, and this is the proof.

If the formula has a bug, the guess can be 29. The header has k = 0..29 and i = 0..87. After the body i is 3..90, and all of it goes back: k = 1..30. This is not inside of 0..29. The guess fails. If another jump of the loop gives a larger guess, the verifier takes it. This loop has none. So k gets no bound, and the loop gets may_goto. The program loads, and all stores are checked.

If k has a bound in the state that comes back, the loop ends, because k grows by 1 in each trip. If k has no bound up to 2^32, the loop has no trip count.

So a bug in the formula costs time, adds a may_goto, or rejects a valid program. It cannot accept an unsafe program. A new case needs tests, not a proof.

10. Two total limits replace the separate limits
------------------------------------------------
7.4-rc3 1M insns processed, 8192 pending jumps, 256 functions, 64 maps,
256 kfuncs, 10000 calls in liveness. For a trip count: 1 back edge, 4 exit tests, 256 exits
bpf-next 1024 states at an insn, 4096 live states + 16 for each insn, 65536
total states + 256 for each insn, 100000 and 4096 insns for the trips of a loop, 8 trips of bpf_loop(), 10000 calls in liveness. For a trip count: 16 back edges with 4 exit tests each, 256 exits of an inner loop
series cost 2^33 and memory 2 GB, for the full load
all three 1M insns in a program, 16 nested loops, 32 frames (7.4-rc3: 16)

bpf-next removed the limits on insns processed, jumps, functions, maps and kfuncs. The series removes the others. Both have a limit on the ids of a state.

A limit on one kind of work rejects a program that needs much of that kind and little else. "Cost" counts work, not time: one step of a scan costs 1, the check of an insn costs 128, a new state costs 512. So the verdict does not depend on the speed or the load of the machine. The heaviest program of the projects below takes 11% of the cost. The largest peak of memory of a program that loads is 751 MB on 7.4-rc3, 304 MB on bpf-next and 265 MB with the series. The fixed tables take 1.2 KB for each insn, as in bpf-next. The passes can add 256 MB, plus 32 KB for each insn, within the 2 GB. So a small program gets less than 2 GB.

After the first error the limit on cost is 2^33 / 3, or two times the cost so far if that is more. One more limit on precision: a state keeps 4 equations such as a + b for each register or slot that has an equation. A loop gets may_goto if k can be above 2^32.

Results
=======
7.4-rc3, bpf-next ea80d2afd285 and the series have the same config. The tests ran on x86-64 and arm64. veristat ran as root on x86-64, in VMs with mitigations=off and 20 loads in parallel. Time is the best of three runs. "peak states" is the largest number of states that the verifier keeps at a time. 7.4-rc3 does not count the states of pending jumps. In the wide tables rc3 is 7.4-rc3, next is bpf-next, new is the series, and "-" is a program that does not load.

Selftests
---------
Against bpf-next:

test_progs no new failure. default: 770 tests, without some network and
perf tests. no_alu32, cpuv4, KASAN: 400 tests of the verifier
test_verifier 793 of 793

veristat on the selftests of 7.4-rc3, 5683 programs. The sums are for the 3958 programs that load on all three:

                                    7.4-rc3     bpf-next    series
  programs that load                3962        3990        3996
  insns, sum                        5.15M       2.13M       600k
  time, sum                         5.1 s       3.3 s       1.5 s
  peak states, sum                  80k         64k         15k

Top gains and top losses, by time against the faster one of the old verifiers:

insns time, ms peak states
rc3 next new rc3 next new rc3 next new

  pyperf600                               258k  151k   39k    1023   366   140     17k  6102   607
  test_verif_scale2                       780k  520k   12k     201   174    25     801  4186     4
  core_kern                               556k  540k   13k     165   184    28     693  4186     4
  pyperf600_nounroll                      466k  184k  1324     359   125   3.4    1141   146    12
  pyperf100                                43k   27k   27k     385   171    71    3216  2042     6
  pyperf180                                74k   44k   22k     334   165    70    5515  3702   367
  call_large_imm_test                      66k   66k   66k     192   258   103       2     6     7
  test_verif_scale1                       547k   51k   12k     143    76    16    2146  8193     6
  test_verif_scale3                       837k   58k   18k     210    81    26    2146  8193     6
  gotol_large_imm                          40k   40k   40k     106   150    54       0     2     1
  res_spin_lock_test_held_lock_max        2356  4088   49k     4.7   7.1   183      62   148   640
  test_tcp_custom_syncookie                19k  5629   13k      21    14    28    1029   259   175
  rbtree_search                           7326  4236  9558     7.7   7.8    13     118   232   532
  profiler2 kprobe_ret__do_file_open      3038  1822  6588     4.0   3.9   7.3      87    40    15
  bpf_loop_iter_limit_nested               624   496  1942    0.74  0.91   3.1      41    90    42
  xdp_synproxy_kern syncookie_xdp          12k  4164  7630      19    11    13    1124   105    36

veristat on the selftests of bpf-next. 5165 programs load on bpf-next and with the series: insns change by -60%, time by -68%. Patches 1 and 2 alone change the time by -21%. 11 more load with the series. The four new files of verifier tests have 271 valid programs. bpf-next rejects 72 of them.

BPF CI builds the selftests in four ways: default, no_alu32, cpuv4, gcc. 16306 programs of these builds load on bpf-next and with the series: insns change by -66%, time by -76%. 60 more load with the series. In these builds and in the selftests above the series rejects one program that bpf-next loads:
stash_rb_nodes, see "The price". Two tests of 7.4-rc3 load only on 7.4-rc3:
private_stack_two_frames and test_arena_member_cb.

Programs of other projects
--------------------------
The series loads all programs that 7.4-rc3 or bpf-next loads. It loads 8908 more than 7.4-rc3 and 2002 more than bpf-next. 1858 load only with the series.

A build is one choice of release, clang (14 .. 20, 24), -mcpu (v1 .. v4), -O level and options of the project. A program counts once for each build. Not all projects have all builds. Some builds are not options of the project:
__always_inline is removed or becomes noinline, or constants of the loader are unknown. These have 27947 programs, 1983 of the 8908 and 232 of the 2002. The 2002 are builds of 168 programs. For 164 of them another build loads on bpf-next. The objects are adapted to load on one kernel, with a patched veristat.

"progs" is the number of all programs. insns, time and peak states are averages for one program, over the programs that load on all three. Patches 1 and 2 alone change the time of bpf-next by -41%, and all patches by -51%.

                               programs that load       insns          time, ms        peak states
  project              progs    rc3   next    new    rc3 next  new    rc3 next  new    rc3 next  new
  all                 385572 331907 338813 340815    18k 2716 1750     23   10  5.2    562  143   18
  alaz                    69     69     69     69   1477  853  846    4.1  4.3  2.1     96   28    9
  bad-bpf                142    122    130    135   8091   77  100    5.6 0.61 0.35     64    6    4
  bcc                   3364   3311   3319   3327    206   98  118   0.53 0.58 0.35     13   10    5
  below                   14     14     14     14   1349  591  591    3.1  2.9  1.4    105   32    4
  bouheki                 53     51     53     53    19k  717  471     39  3.3  1.5   1629   86   12
  bpf-dev-tutorial       772    754    755    766    424   68   69   0.53 0.43 0.23     10    6    3
  bpf-examples           481    470    464    475   8994  928  703    8.2  3.1  2.1     95   92   13
  bpfjailer             1625   1411   1431   1465    16k 3185 5216     38   18   14   1333  104   48
  bpfsnoop                78     75     76     76   2230  488  117    2.6  2.2 0.79     32   23    6
  bpftune                125    113    113    125    475  311  284    1.7  2.0 0.85     31   23    5
  cilium                5496   5490   5490   5490   7914 2023 1714     14   10  6.4    345  160   22
  coolbpf               1178   1107   1156   1156    14k 3184 1752     29  9.9  5.6   1100  114   23
  datadog-agent       234993 190601 192987 193112   2342  732  619    5.3  3.9  1.9    107   40    7
  elastic-ebpf          1079    646    646   1065   3437 1368  561    4.6  3.0  1.2     36   15    7
  falco                38108  37388  37583  37583    17k 1274 1035     18  6.7  2.6    283   53   13
  gala-gopher            215    209    215    215   9241 5172 5114     15   14  7.2    412  196    8
  inspektor-gadget      5422   5165   5402   5419    14k  515  339     19  2.3  1.0    124   22    5
  katran                 238    236    236    236    15k 1630 2426     16  5.3  4.6    279   83   11
  krie                  6930   6922   6908   6924   5080 2010 2007    9.5  7.5  3.1    177   31   15
  kubearmor             1100   1100   1100   1100    57k  12k  12k    117   61   32   2793  554   22
  kubescape node-agent   582    508    517    549   187k 7629 3195    213   20  7.5   1801  187   16
  kubeshark-tracer       264    252    252    264   2239  610  521    3.2  2.7  1.3     88   15    4
  kyanos                 818    818    818    818   8126 1248 1015     13  7.1  3.2    403   80    9
  lightswitch             67     61     63     63    67k 1420  621     51  3.5  3.6    393   63   21
  linux perf             345    335    341    341   8503 1073  286    9.3  1.6 0.62     67   17    6
  linux selftests/net     47     41     41     41   2289 1409  678    4.4  4.5  2.1    122   92    8
  loxilb-ebpf             47     45     45     45   1815 1273  350    1.9  2.1 0.77     66   28    5
  lsmtrace              2375   2337   2359   2359    290  269  270    1.0  1.2 0.50     18    9    4
  netobserv              389    361    373    373   1707  454  319    5.4  4.4  1.9    108   43    7
  opentelemetry obi     3982   3915   3946   3965   5098  846  664    7.4  4.6  2.4    119   40    8
  pulsar                 665    623    616    623   6307 2125 2121     27   12  5.9    423  119   10
  pwru                   302    300    301    302   2600  654  307    5.1  3.9  1.8     69   23    4
  rbperf                  20     20     20     20   4356 3006 3006     25   18  8.9    346  148    5
  retis                   10      9      9     10   2659 2247 2110    8.2  9.6  4.4    210  118   15
  retsnoop               118    118    118    118   3636 1301 1476    7.9  5.6  4.2    157   65   30
  runtime-enforcer        66     66     66     66   1261  732  702    4.6  4.6  2.3    106   52   18
  rust-bpf              1089      8    861    861     25   23   23   0.18 0.22 0.13      2    6    4
  scx                   1272   1163   1165   1165   4681  480  501    8.1  2.7  1.7    215   35   19
  seabee                 511    503    511    511    300  243  250   0.94  1.1 0.61     26   17   10
  skywalking-rover      1310   1310   1310   1310   162k 1870 1241    141  8.4  3.8    547  103   14
  stackrox fact          154     98     98     98   2624  835  633    6.4  6.0  2.5    101   43   11
  systemd                575    541    559    560    12k 4450  790     14  6.4  2.1    312   70   15
  tetragon             40814  37639  39944  40074   101k  15k 7712    117   46   25   3364  854   80
  tracee               22774  20214  20957  22098    24k 3226 2849     34   15  6.4    656  115   24
  tracexec                94     66     66     66   5501 1157 1371     13  5.1  3.7    541   58   27
  wazuh                  183    175    183    183   168k  76k  76k    427  348  183    11k 1729   13
  wprof                  192    192    192    192    11k 3602 5466     15   14   11    288  209   93
  xdp-tools               67     67     67     67    25k 1656  797     19  3.1  2.0     68  143   13

31 more projects 4958 4868 4868 4868 382 241 244 1.2 1.4 0.68 25 15 5

In the 31 more projects the three verifiers load the same programs, and 7.4-rc3 takes less than 1000 insns on average. The number is "progs":

bpflock 250, bpfman 60, bpftop 8, calico 10, cilium/ebpf 122, cloudflare lsm-bpf 27, dynolog 64, ebpf-exporter 581, ecapture 213, ehids-agent 55, facebook dns 15, kubeskoop 184, learning-ebpf 20, libbpf-bootstrap 88, libbpf-rs 149, libbpfgo 77, linux bpftool 24, linux preload 8, linux samples 204, linux selftests/drv 3,
linux selftests/scx 621, pamspy 6, parca-agent 11, portmaster 32, psc 17, ptcpdump 631, retina 25, rezolus 566, strobelight 6, systing 834, teleport 47

- cilium has one build for each week from February to November 2026. tetragon, tracee, falco (libs) and datadog-agent have the main branch and one release of each minor version, from v1.0, v0.12, 0.13 and 7.50.
- rust-bpf is github.com/4ast/rust-bpf: tests of Rust crates and of the Rust library, and scx schedulers in Rust. LLVM with a pending pull request builds them. Most of them need the arena stack, which 7.4-rc3 does not have. So the row shows only 8 of them. For the 861 against bpf-next:
insns -51%, time +2%, peak states +45%.
- Two of the 31 take many more insns than on bpf-next: cloudflare lsm-bpf 52 -> 113, systing 286 -> 355.
- 44757 programs load on no kernel, 41881 of them in datadog-agent. Most of these attach to a function that the kernel config does not have (583 in a sample of 600).

Why the old verifiers reject a program that the series loads:

                                               7.4-rc3    bpf-next
  a bound is not proven                        3069       1959
  an offset of 2^29 or more at a pointer add   739        0
  limit of 1M insns                            2054       no limit
  limit of 8192 pending jumps                  157        no limit
  "infinite loop detected"                     3          0
  limit on states                              no limit   30
  a rule or a feature that came later          2886       13
  total                                        8908       2002

The last error in the log gives the group. On bpf-next a limit can show as a bound that is not proven, see example 1. bpf-next has the same rule for a large offset as 7.4-rc3, and it loads these 739 programs. The last group is not about the main analysis. On bpf-next it has the rules that patches 8 and 38 change. On 7.4-rc3 it has:

  tail call in a function that does not return int   1467
  arena stack                                        840
  32-bit add to a pointer                            328
  arguments on the stack                             126
  more than 256 functions                            13
  others                                             112

Examples of programs that only the series loads, in some -O2 builds with the options of the project:

  tracee             sys_exit_submit, sched_process_exec_signal
  elastic-ebpf       fentry__vfs_rename, fexit__do_file_open
  tetragon           event_execve, generic_retkprobe_event
  datadog-agent      hook_cgroup_procs_write
  obi                obi_packet_extender_find_existing_tp
  bpftune            bpftune_sysctl
  inspektor-gadget   trace_uprobe_mutex_unlock
  systemd            monitor_varlink_socket_sendmsg

144 programs load on 7.4-rc3 and with the series, and not on bpf-next:
datadog-agent 89, krie 16, kubescape node-agent 16, pulsar 7, others 16.

Top gains and top losses
------------------------
The number of programs whose time changes by more than 1 ms or 10 ms:

faster by slower by
load on both 1 ms 10 ms 1 ms 10 ms

  series vs 7.4-rc3          331907    150316     49795       677        89
  series vs bpf-next         338813    175428     31667      4173      1729

Each table has the programs with the largest change of time, one program and one build for each project. Programs below 1000 insns are left out. A program can be in two tables with two builds.

insns time, ms
project program rc3 next new rc3 next new
gains against 7.4-rc3

  datadog-agent    socket__http2_headers_parser           738k  145k  141k     4866  1349   645
  falco            sendmmsg_x                             950k  2249  2090     1630    15   7.1
  tetragon         generic_lsm_actions                    951k  5183  3499     1306    11   8.9
  tracee           trace_security_file_mprotect           866k   11k  8210     1301    55    20
  inspektor-gadget ig_topfile_rd_e                        611k   14k  7615     1219    42    17
  kubescape        tracepoint__x86_fpu_regs_deactivated   600k   13k  7545     1096    40    17
  scx              flow_select_cpu                        293k  1145  1803     1046   5.8   5.8
  krie             perf_event_syscall_table_ticker        865k   54k   27k     1093   156    58
  coolbpf          trace_mremap_exit                      327k   40k   22k     1005    81    65
  skywalking       go_tls_write_ret                       573k  4147  2585      684    19   8.2
  pulsar           sched_switch                            48k   20k   20k      678   151    62
  lightswitch      dwarf_unwind                           721k   12k  2119      594    22    14

gains against bpf-next

  datadog-agent    __x64_sys_openat2_exit                    -   57k  2194        -  2310   9.7
  coolbpf          trace_openat_exit                         -  944k   76k        -   949   213
  falco            dump_task                                 -   44k   26k        -   632    90
  rust-bpf         smol_str_ryu                              -  587k   76k        -   854   435
  tetragon         generic_fexit_event                    291k  109k   29k      496   469   104
  wazuh            path_rename_old_walk                   198k   90k   90k      504   425   188
  systemd          userns_restrict_inode_symlink          301k  149k   819      286   139   2.5
  tracee           uprobe_syscall_table_check             517k  127k   12k      518   150    31
  bpfjailer        test_dyn_map                            63k   18k   11k      217   192    81
  krie             perf_event_syscall_table_ticker        865k   54k   27k     1093   156    58
  pulsar           sched_switch                            26k   20k   20k      672   146    57
  kubearmor        enforce_proc                           201k   30k   27k      291   128    68

losses against 7.4-rc3

  krie             perf_event_syscall_table_ticker        378k     -  455k      664     -   916
  obi              obi_packet_extender_find_existing_tp   157k     -  113k      119     -   237
  wprof            wprof_task_switch                      121k   32k   80k      154   112   202
  datadog-agent    uprobe__http2_tls_filter                84k   33k   44k       87    85   136
  coolbpf          unwind_native                           55k   31k   31k       69    84   113
  bpfjailer        bpfj_remount                           1717  1110   16k      2.5   2.6    32
  tetragon         generic_uprobe_process_event           7153  3856   29k       92   112   109
  retsnoop         retsn_inj_kretprobe                    1378   642  6220      4.4   3.9    15
  scx              layered_runnable                       9827  4457   12k       18    13    27
  bpf-examples     flowmap_cleanup                        1446   423  4032      2.6   2.3    10

losses against bpf-next

  rust-bpf         vec_sort_stable                           -   85k   95k        -   142   547
  wprof            wprof_task_switch                      121k   32k   80k      154   112   202
  coolbpf          trace_mmap_exit                           -   11k   53k        -    30   114
  tetragon         generic_usdt_actions                   245k  4233   41k      156   7.3    85
  kubearmor        enforce_proc                           254k   41k  112k      342   144   220
  datadog-agent    socket__http2_filter                      -   36k   47k        -   100   160
  krie             perf_event_syscall_table_ticker        504k   25k   97k      761    98   154
  obi              parse_dns_response                        -   11k   33k        -    13    63
  tracee           lkm_seeker_kset_tail                   342k   15k   76k      373    78   125
  falco            dump_task                                 -   21k   71k        -    60    91
  bpfjailer        bpfj_remount                           1717  1110   16k      2.5   2.6    32
  scx              layered_runnable                       9827  4457   12k       18    13    27

The price
=========
(35) means patch 35.

- A program that needs more passes takes more insns: the count is the sum of all passes. There is no separate limit on this count, in bpf-next or in the series. In the series each insn adds to the cost, see section 10. Most losses against bpf-next are such programs. 1032 of the 1729 are generic_*_actions of tetragon: 6 -> 38 ms on average (7.4-rc3: 179 ms). The gcc build of the selftest strobemeta is one more: 254k -> 383k insns, 482 -> 1011 ms.

- Time can grow when insns do not. The work on equations and on deps is not in this count. See vec_sort_stable and unwind_native above. 43 of the 89 losses against 7.4-rc3 are of this kind.

- Only a partition peels a loop. So a short loop without a trip count gets may_goto, where the old verifiers check all trips. 7.4-rc3 does not add may_goto. bpf-next adds it to 745 programs of the projects, the series to 290. 170 of the 290 do not load on 7.4-rc3, 30 do not load on bpf-next. The series against bpf-next:

more may_goto 44 programs rust-bpf 16, tracee 14, coolbpf 10,
bpfjailer 4
fewer may_goto 762 programs rust-bpf 264, falco 211, tetragon 152,
datadog-agent 36, obi 34, others 65

- After a join the verifier can fail to see that a path is dead. Then it does not remove the code of that path. Here "size" is the number of insns in the loaded program. The last column is for programs with the same number of may_goto. Most of them are in tetragon. The largest growth is in generic_lsm_process_event, size 4k -> 17k. The row for 7.4-rc3 also has the changes of bpf-next in the fixups.

                         larger   smaller   sum of sizes   larger by 5%
    series vs 7.4-rc3    19209    8650      +0.6%          1853
    series vs bpf-next   7027     7991      +0.5%          346

- If the address of a function is taken and it has a callx, it counts as recursive. Then a program can fail if the function returns a pointer or passes a pointer to the stack. bpf-next does the same, 7.4-rc3 loads it.

- An unsafe program takes longer to reject. The verifier partitions more and looks for a failing path first. These programs fail on each kernel that ran them. Of the projects: those that get to the main analysis of bpf-next.

                            programs  7.4-rc3  bpf-next  series  slowest, series
    selftests of bpf-next   1964      not run  2.9 s     6.8 s   3.3 s
    selftests of 7.4-rc3    1684      3.8 s    1.3 s     0.2 s   0.05 s
    projects                3573      92 s     91 s      280 s   8.0 s

An off-by-one in example 3 takes up to 5 s for the largest N. The log of a failing path through 10000 trips can have 170k lines.

- A valid program can get to the limit on cost or memory. No program of the projects does. These generated programs do. The first four are very large. The last two are small, their states multiply:

                                                     7.4-rc3        bpf-next
    1000 calls with &local, function of 10000 insns  REJECT         35 s
    100k branches with 16 states each                REJECT         19 s, 4 GB
    400k branches with a large stack                 REJECT         39 s, 14 GB
    a loop of 240k insns with a stack of 2 KB        5 s, 2.2 GB    12 s, 2.2 GB
    12 pairs of pointers that can be equal           4 s, 17 MB     REJECT
    12 ring buffer records, each of 8 or 16 bytes    0.4 s          REJECT

- A search with hand-written tests found more valid programs that bpf-next loads and the series rejects. No program of the projects has such a shape:

3 nested loops in 12k insns take two locks in one of the trips a function that callx calls stores an index and a flag for its caller 36 pairs of constants, then 20 branches that add to one of them 16 live pointers, each has a copy on one path that is never read 40 blocks with 10 pointers, each points to one of two members a word of a table of pointers on the stack is added to such a pointer (43) the only exit of a loop is after bpf_throw()
a path that only a join makes tests or uses a sum of 24 optional numbers 900 loops call one function that has 32k constants

- A program is rejected if one call needs two different fixups (10):
bpf_obj_drop() for two types with different special fields, list push with two node offsets. A compiler can make such a call. The fix is __attribute__((nomerge)). stash_rb_nodes needs it (45).

- The path-sensitive run skips trips of a long loop. If the step is not a constant, the skip is a guess, and the failing path can be false (35). Then the limit on cost is not decreased. An example of an unsafe program, and the time to reject it:

    for (i = 0; i < N; i++) sum += i;   N          1000     1000000
    buf[sum]                            7.4-rc3    1.6 ms   0.4 s
                                        bpf-next   1.4 ms   0.1 ms
                                        series     11 ms    7 s

Other changes of behaviour
==========================
Against bpf-next:

- A loop without a trip count gets may_goto, unless it has may_goto or an iterator, or all trips are peeled. If may_goto is not possible (no exit, offload), or its new edge is not safe, the program is rejected. Only a partition peels a loop. There is no trip count without CAP_PERFMON.
- The form of a loop does not matter for the trip count: two entries, many exits, many back edges. The trip index can be up to 2^32. Some loops lose the trip count and get may_goto (44, 45).
- Without bypass_spec_v1 a pointer add that ALU sanitation cannot mask gets a nospec insn (11).
- A pointer that is 2^29 or more away from the object fails at the access, not at the add. An add of a number that can be -2^29 or less still fails. A far load from a flexible array of a BTF object gets a fault handler, and a far load-acquire fails (8).
- Without allow_ptr_leaks a packet pointer is compared with data_end only from -MAX_PACKET_OFF to 2 * MAX_PACKET_OFF (8).
- Without allow_ptr_leaks a store of a pointer at a variable stack offset is rejected (21).
- With CAP_PERFMON a load can take a part of a spilled pointer at a constant offset (8).
- A function can leave a pointer to the stack in r0. The caller cannot read it (38).
- A join can increase a bound that is checked at attach time, such as the size of the context. Such an insn is "pessimized", and it gets a partition in a small budget. One case is not covered: a join hides that a path is dead, and an insn there has constant operands (36).
- Without CAP_BPF there are no equations. Without bypass_spec_v1 a join makes no equations from constants, and pointers and speculative states have none.
- Without CAP_BPF the limits on cost and memory are 1/32.

How to read the series
======================
Start with patch 49. It rewrites Documentation/bpf/verifier.rst, and explains all parts and all words with examples.

Patches 1 and 2 do not need the rest. Patches 3 .. 43 are one change, divided for review. The kernel builds after each patch. After patches 3 .. 36 it has no main pass, and each load fails with -EOPNOTSUPP. Programs load again from patch 37 on. Only 3 lines are temporary, each other line changes in one patch only.

Read the patches in this order:

  49         docs
  37         do_check_all(): the loop of passes
  21-25      compare, unproven insn, deps, join rule, join
  28-29      prune or join, the order of the worklist
  16-20      equations: arithmetic, table, jump, insn, clean-up
  26-27, 32  equations at a prune and at a join: check, guess, join rule
  15, 30-31  loops: peel, trip index, trip count or may_goto
  33-36      instances, partition and undo, failing path, pessimized
  38-43      less work: fewer passes, one check of a loop body, fork
  5-14       small changes that the above needs
  3-4        deletions
  44-48      selftests

Patches with trusted code, see section 9: the checks of an insn (8-14, 19, 38, 42), equation.c (16-20, 26, 30, 41), subsumes and join (7, 21, 25, 30), prune or join and the order (28, 29), peel (15, 28, 31, 35), recovery after an unproven insn (22), cycles get may_goto (31), exits of instances (33), liveness (2, 6), limits (5), passes and snapshots (9, 35-37), the fork (43).

  kernel/bpf and include   +11272   -12028   net -756
  selftests                +10130   -1079    net +9051
  docs                     +1499    -519     net +980

Changes in v2
=============
- The kernel builds after each patch. About 500 lines moved to another patch.
- Fix the build of the selftests with GCC (47), and three warnings of clang (23, 34, 35).
- A far load from a flexible array of a BTF object gets a fault handler (8).
- Valid programs that v1 rejects load now: a trip index that gets to S64_MAX (30), an error in one function of a callx set (33), a recursion with two exit insns (28), an AND that splits a number with a step (12).
- Count the scan of a table of functions and the sort of gotox targets (5). An error in the collection of thresholds does not leak the charge of memory (25).
- A failed speculative state does not bring back a fastcall rewrite (11).
- The log has no false trip count for a loop with an iterator or may_goto (31).
- More selftests (46 .. 48), better comments (7, 8, 17).
- Rebase on bpf-next 82cc2b4383e3. The tables have the numbers of v1. With v2 each program of the projects has the same verdict, and 5 have other insns.
- v1: https://lore.kernel.org/r/[email protected]

Alexei Starovoitov (49):
bpf: Look for bpf_clone_redirect() once in check_recursion()
bpf: Make stack liveness faster
bpf: Delete the old main pass of the verifier
bpf: Delete scalar evolution
bpf: Limit the cost and the memory of a load
bpf: Record what each insn reads and writes
bpf: Name an id after the xreg that has it
bpf: Do not fail a check because a state has fewer values
bpf: Check fixups in the main pass and keep a snapshot of them
bpf: Reject a program with a call that needs two rewrites
bpf: Put a barrier where no mask fits
bpf: Keep more of what is known about a number
bpf: Remember how many bytes of a packet are checked
bpf: Mark a state that no run of the program has
bpf: Peel the first trips of a loop and join the other trips
bpf: Add equations and their arithmetic
bpf: Keep a table of equations in each state
bpf: Refine all related numbers after a jump
bpf: Make equations from ALU, spill, fill and call insns
bpf: Delete the equations that say nothing
bpf: Compare states by join_key, then by value
bpf: Continue a pass after an unproven insn
bpf: Find the xregs that an unproven insn depends on
bpf: Keep two states apart if data and control deps differ
bpf: Join any two states that have the same join_key
bpf: Check the equations when a state is pruned or joined
bpf: Guess the equations of a join
bpf: Prune or join each state that arrives
bpf: Order the pending states and free the states that are done
bpf: Get the trip count from the trip index
bpf: Give a loop a checked trip count or may_goto
bpf: Use the equations in the join rule
bpf: Verify a static function once for each instance
bpf: Partition the states after an error
bpf: Reproduce an error on one path, with no joins
bpf: Do not let a join raise what a program requires
bpf: Verify in passes
bpf: Make a returned pointer to the stack unreadable
bpf: Keep two states apart if a live xreg has two types
bpf: Check the body of a counted loop once
bpf: Refine the copies of a number that AND or OR splits
bpf: Allow a range of offsets for a constant string
bpf: Keep spilled pointers at a range of stack offsets selftests/bpf: Adjust tests to the new log text selftests/bpf: Adjust tests that get another verdict or may_goto selftests/bpf: Test barriers and far pointers selftests/bpf: Test passes, instances, precision and the failing path selftests/bpf: Test equations
bpf, docs: Rewrite verifier.rst

 Documentation/bpf/bpf_design_QA.rst           |    6 +-
 Documentation/bpf/kfuncs.rst                  |    4 +-
 Documentation/bpf/verifier.rst                | 2008 ++++--
 include/linux/bpf.h                           |    8 +-
 include/linux/bpf_verifier.h                  |  952 ++-
 include/linux/cnum.h                          |    3 -
 include/linux/tnum.h                          |    2 -
 kernel/bpf/Makefile                           |    6 +-
 kernel/bpf/btf.c                              |    2 +-
 kernel/bpf/cnum.c                             |   37 -
 kernel/bpf/const_fold.c                       |  285 +-
 kernel/bpf/diagnostics.c                      |   70 +-
 kernel/bpf/diagnostics.h                      |    8 +-
 kernel/bpf/equation.c                         | 2423 ++++++++
 kernel/bpf/equation.h                         |  199 +
 kernel/bpf/equation_join.c                    | 1458 +++++
 kernel/bpf/failing_path.c                     |  269 +
 kernel/bpf/fixups.c                           |  228 +-
 kernel/bpf/flow.c                             | 4108 ++++--------
 kernel/bpf/join.c                             |  753 +--
 kernel/bpf/liveness.c                         |  322 +-
 kernel/bpf/log.c                              |   91 +-
 kernel/bpf/loops.c                            |  416 +-
 kernel/bpf/offload.c                          |    3 +
 kernel/bpf/precision.c                        | 1784 ++++++
 kernel/bpf/precision.h                        |  139 +
 kernel/bpf/scev.c                             | 5504 -----------------
 kernel/bpf/states.c                           |  621 +-
 kernel/bpf/tnum.c                             |   11 -
 kernel/bpf/verifier.c                         | 3598 ++++++-----
 .../selftests/bpf/prog_tests/far_map_value.c  |   38 +
 .../selftests/bpf/prog_tests/log_fixup.c      |    6 +-
 .../selftests/bpf/prog_tests/spin_lock.c      |   12 +-
 .../selftests/bpf/prog_tests/verifier.c       |   12 +-
 .../selftests/bpf/progs/aggregate_ret_func.c  |   10 +-
 .../bpf/progs/compute_live_registers.c        |   10 +-
 .../testing/selftests/bpf/progs/dynptr_fail.c |    6 +-
 tools/testing/selftests/bpf/progs/iters.c     |    4 +-
 .../selftests/bpf/progs/iters_state_safety.c  |    6 +-
 .../selftests/bpf/progs/iters_testmod_seq.c   |    2 +-
 .../selftests/bpf/progs/local_kptr_stash.c    |    3 +
 .../selftests/bpf/progs/map_kptr_fail.c       |    2 +-
 .../testing/selftests/bpf/progs/rbtree_fail.c |    2 +-
 .../bpf/progs/refcounted_kptr_fail.c          |    4 +-
 .../struct_ops_refcounted_fail__ref_leak.c    |    2 +-
 .../bpf/progs/test_get_stack_rawtp.c          |   20 +-
 tools/testing/selftests/bpf/progs/timer.c     |    5 +-
 .../selftests/bpf/progs/timer_failure.c       |    6 +-
 .../selftests/bpf/progs/verifier_align.c      |   12 +-
 .../selftests/bpf/progs/verifier_and.c        |  150 +
 .../selftests/bpf/progs/verifier_arena.c      |    2 +-
 .../bpf/progs/verifier_arena_stack.c          |  105 +
 .../bpf/progs/verifier_array_access.c         |    2 +-
 .../selftests/bpf/progs/verifier_barrier.c    |  849 +++
 .../selftests/bpf/progs/verifier_bounds.c     |   36 +-
 .../bpf/progs/verifier_bounds_deduction.c     |   28 +-
 .../bpf/progs/verifier_bounds_step.c          |   86 +-
 .../bpf/progs/verifier_bpf_fastcall.c         |   33 +
 .../bpf/progs/verifier_btf_array_access.c     |   53 +
 .../selftests/bpf/progs/verifier_budget.c     |   25 +-
 .../bpf/progs/verifier_callx_rodata.c         |  130 +
 .../bpf/progs/verifier_direct_packet_access.c |  185 +-
 .../verifier_direct_stack_access_wraparound.c |   10 +-
 .../bpf/progs/verifier_div_mod_bounds.c       |   28 +
 .../selftests/bpf/progs/verifier_equations.c  | 1583 +++++
 .../bpf/progs/verifier_jumps_ahead.c          |    2 +-
 .../bpf/progs/verifier_linked_scalars.c       |  146 +-
 .../selftests/bpf/progs/verifier_live_stack.c |   10 +-
 .../bpf/progs/verifier_liveness_exp.c         |   52 +-
 .../bpf/progs/verifier_load_acquire.c         |   19 +
 .../selftests/bpf/progs/verifier_loop_as_is.c |   23 +-
 .../bpf/progs/verifier_loop_hierarchy.c       |   13 +-
 .../selftests/bpf/progs/verifier_loop_latch.c |   81 +-
 .../selftests/bpf/progs/verifier_loop_need.c  |   23 +-
 .../selftests/bpf/progs/verifier_loop_walk.c  |   10 +-
 .../selftests/bpf/progs/verifier_map_ptr.c    |   18 +-
 .../bpf/progs/verifier_meta_access.c          |    2 +-
 .../selftests/bpf/progs/verifier_movsx.c      |   20 +
 .../selftests/bpf/progs/verifier_partition.c  | 1555 +++++
 .../selftests/bpf/progs/verifier_passes.c     | 3758 +++++++++++
 .../selftests/bpf/progs/verifier_precision.c  |    2 +-
 .../bpf/progs/verifier_ref_tracking.c         |    7 +-
 .../selftests/bpf/progs/verifier_scalar_ids.c |   12 +-
 .../selftests/bpf/progs/verifier_sock.c       |    4 +-
 .../selftests/bpf/progs/verifier_spill_fill.c |   80 +-
 .../selftests/bpf/progs/verifier_spin_lock.c  |    2 +-
 .../selftests/bpf/progs/verifier_stack_ptr.c  |   14 +-
 .../bpf/progs/verifier_subprog_callers.c      |    2 +-
 .../bpf/progs/verifier_subprog_insn_stats.c   |   14 +
 .../bpf/progs/verifier_subprog_precision.c    |    8 +-
 ...{verifier_scev.c => verifier_trip_count.c} | 1743 +++---
 .../selftests/bpf/progs/verifier_unpriv.c     |    6 +-
 .../bpf/progs/verifier_value_ptr_arith.c      |   66 +-
 .../selftests/bpf/progs/verifier_var_off.c    |   46 +
 tools/testing/selftests/bpf/verifier/calls.c  |    2 +-
 .../testing/selftests/bpf/verifier/map_kptr.c |    2 +-
 96 files changed, 22901 insertions(+), 13626 deletions(-)
 create mode 100644 kernel/bpf/equation.c
 create mode 100644 kernel/bpf/equation.h
 create mode 100644 kernel/bpf/equation_join.c
 create mode 100644 kernel/bpf/failing_path.c
 create mode 100644 kernel/bpf/precision.c
 create mode 100644 kernel/bpf/precision.h
 delete mode 100644 kernel/bpf/scev.c
 create mode 100644 tools/testing/selftests/bpf/prog_tests/far_map_value.c
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_barrier.c
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_equations.c
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_partition.c
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_passes.c
 rename tools/testing/selftests/bpf/progs/{verifier_scev.c => verifier_trip_count.c} (77%)

base-commit: 82cc2b4383e3edfa1026c8612fb4e90a9329ba11

Signature · 1 line
2.55.0
#1 lore raw

PATCH v2 1/49 bpf: Look for bpf_clone_redirect() once in check_recursion()

From: Alexei Starovoitov <[email protected]>

check_recursion() scans all insns of the program for each recursive subprog. There is no limit on subprogs now. So the cost is subprogs x insns, and no signal ends that loop. Scan once.

  100000 static subprogs of 4 insns in one cycle    BPF_PROG_LOAD
  before                                            34 s
  after                                             11 s
Fixes f7e93aa4a34f ("bpf: Remove BPF_MAX_SUBPROGS")
---
 kernel/bpf/verifier.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)
kernel/bpf/verifier.c +2 -1
index 39f1c6eb113..64ad953bbff 100644
@@ -5485,6 +5485,7 @@ static bool bpf_prog_reenters_datapath(const struct bpf_prog *prog);
  */
 static int check_recursion(struct bpf_verifier_env *env, struct bpf_call_graph *cg)
 {
+	bool reenters = bpf_prog_reenters_datapath(env->prog);
 	int j, s;
 
 	for_each_marked_subprog(cg, s, CG_LIVE) {
@@ -5506,7 +5507,7 @@ static int check_recursion(struct bpf_verifier_env *env, struct bpf_call_graph *
 				return -EINVAL;
 			}
 			/* It runs on top of its own frames. The half of the stack is not enough. */
-			if (bpf_prog_reenters_datapath(env->prog)) {
+			if (reenters) {
 				verbose(env, "recursive %s() in a program that calls bpf_clone_redirect()\n",
 					bpf_subprog_name(env, s));
 				return -EINVAL;
Signature · 1 line
2.55.0
#2 lore raw

PATCH v2 2/49 bpf: Make stack liveness faster

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

compute_subprog_args() follows the pointers to the stack. Each round visits all insns and joins all slots, one by one. Most of that work finds no change. Do only what can find a change:

  old                              new
  each round visits all insns      only the insns whose input changed
  first visit: join each slot      memcpy()
  later visit: join each slot      memcmp() first
  half slots to slots: by bits     by words

The fixed point is the same.

load time, ms

  program                       before   after
  pyperf600                     222      124
  pyperf100                     126      64
  strobemeta                    153      116
  profiler1 kprobe__vfs_link    18       8
---
 kernel/bpf/liveness.c | 59 ++++++++++++++++++++++++++++---------------
 1 file changed, 38 insertions(+), 21 deletions(-)
kernel/bpf/liveness.c +38 -21
index cfa416f7620..d78a8ee0bbf 100644
@@ -752,11 +752,19 @@ static int cmp_instances(const void *pa, const void *pb)
 /* OR the 8-byte slots touched by a half-slot (4-byte) mask into @slots. */
 static void half_spis_to_slots(unsigned long *slots, const unsigned long *mask, u32 nbits)
 {
-	u32 slot;
+	unsigned long x;
+	u32 i;
 
-	for (slot = 0; slot < MAX_BPF_STACK_SLOTS && slot * 2 + 1 < nbits; slot++)
-		if (test_bit(slot * 2, mask) || test_bit(slot * 2 + 1, mask))
-			__set_bit(slot, slots);
+	nbits = min(nbits, FRAME_HALF_SPIS);
+	for (i = 0; i < nbits; i += 32) {
+		x = bitmap_read(mask, i, min(nbits - i, 32));
+		x = (x | x >> 1) & 0x55555555;
+		x = (x | x >> 1) & 0x33333333;
+		x = (x | x >> 2) & 0x0f0f0f0f;
+		x = (x | x >> 4) & 0x00ff00ff;
+		x = (x | x >> 8) & 0x0000ffff;
+		slots[BIT_WORD(i / 2)] |= x << (i / 2 % BITS_PER_LONG);
+	}
 }
 
 /*
@@ -858,7 +866,7 @@ static int print_instances(struct bpf_verifier_env *env)
 struct arg_track {
 	union {
 		s16 off[MAX_ARG_OFFSETS]; /* byte offsets; off_cnt says how many */
-		u32 mask;	/* arg bitmask when arg == ARG_IMPRECISE */
+		u64 mask;	/* arg bitmask if ARG_IMPRECISE. As wide as off[] for memcmp() */
 	};
 	s8 frame;	/* absolute frame index, or enum arg_track_state */
 	s8 off_cnt;	/* 0 = offset-imprecise, 1-4 = # of precise offsets */
@@ -912,7 +920,7 @@ static void verbose_arg_track(struct bpf_verifier_env *env, struct arg_track *at
 	switch (at->frame) {
 	case ARG_NONE:      verbose(env, "_");                          break;
 	case ARG_UNVISITED: verbose(env, "?");                          break;
-	case ARG_IMPRECISE: verbose(env, "IMP%x", at->mask);            break;
+	case ARG_IMPRECISE: verbose(env, "IMP%llx", at->mask);          break;
 	default:
 		/* frame >= 0: absolute frame index */
 		if (at->off_cnt == 0) {
@@ -1100,12 +1108,18 @@ static bool arg_track_join_all(struct bpf_verifier_env *env, int idx, int target
 			       const struct arg_track *out, const struct arg_track *stack_out,
 			       u32 nslots)
 {
-	bool changed = false;
+	bool changed = false, same;
 	int r;
 
+	if (!arg_is_visited(&in[BPF_REG_FP])) {
+		memcpy(in, out, MAX_AT_TRACK_REGS * sizeof(*in));
+		memcpy(stack_in, stack_out, nslots * sizeof(*stack_in));
+		return true;
+	}
 	for (r = 0; r < MAX_AT_TRACK_REGS; r++)
 		changed |= arg_track_join(env, idx, target, r, &in[r], out[r]);
-	for (r = 0; r < nslots; r++)
+	same = !memcmp(stack_in, stack_out, nslots * sizeof(*stack_in));
+	for (r = 0; r < nslots && !same; r++)
 		changed |= arg_track_join(env, idx, target, -r - 1, &stack_in[r], stack_out[r]);
 	return changed;
 }
@@ -2078,8 +2092,8 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,
 	struct arg_track at_stack_arg_entry[MAX_STACK_ARG_SLOTS];
 	struct arg_track unvisited = { .frame = ARG_UNVISITED };
 	struct arg_track none = { .frame = ARG_NONE };
-	bool changed;
 	int i, p, r, err = -ENOMEM;
+	unsigned long *changed = NULL;
 
 	at_in = kvmalloc_objs(*at_in, len, BPF_VERIFIER_GFP);
 	if (!at_in)
@@ -2090,7 +2104,8 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,
 		goto err_free;
 
 	at_stack_out = kvmalloc_objs(*at_stack_out, nslots, BPF_VERIFIER_GFP);
-	if (!at_stack_out)
+	changed = kvcalloc(BITS_TO_LONGS(len), sizeof(long), BPF_VERIFIER_GFP);
+	if (!at_stack_out || !changed)
 		goto err_free;
 
 	for (i = 0; i < len; i++) {
@@ -2123,9 +2138,9 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,
 	if (env->log.level & BPF_LOG_LEVEL2)
 		verbose(env, "subprog#%d: analyzing (depth %d)...\n", subprog, depth);
 
-	/* Forward fixed-point iteration in reverse post order */
+	/* Forward fixed-point iteration in reverse post order, over insns whose input changed */
+	__set_bit(0, changed);
 redo:
-	changed = false;
 	for (p = po_end - 1; p >= po_start; p--) {
 		int idx = env->cfg.insn_postorder[p];
 		int i = idx - start;
@@ -2136,17 +2151,17 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,
 		err = -EINTR;
 		if (bpf_must_abort())
 			goto err_free;
-		if (!arg_is_visited(&at_in[i][0]) && !arg_is_visited(&at_in[i][1]))
+		if (!__test_and_clear_bit(i, changed))
 			continue;
 
 		memcpy(at_out, at_in[i], sizeof(at_out));
 		memcpy(at_stack_out, &at_stack_in[(size_t)i * nslots], nslots * sizeof(*at_stack_out));
 
 		ti = bpf_head_guard_target(env, idx) - start;
-		if (ti >= 0)
-			changed |= arg_track_join_all(env, idx, start + ti, at_in[ti],
-						      &at_stack_in[(size_t)ti * nslots],
-						      at_out, at_stack_out, nslots);
+		if (ti >= 0 && arg_track_join_all(env, idx, start + ti, at_in[ti],
+						  &at_stack_in[(size_t)ti * nslots],
+						  at_out, at_stack_out, nslots))
+			__set_bit(ti, changed);
 
 		arg_track_xfer(env, insn, idx, at_out, at_stack_out, nslots,
 			       at_stack_arg_entry, instance, callsites);
@@ -2162,12 +2177,13 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,
 			if (target < start || target >= end)
 				continue;
 			ti = target - start;
-			changed |= arg_track_join_all(env, idx, target, at_in[ti],
-						      &at_stack_in[(size_t)ti * nslots],
-						      at_out, at_stack_out, nslots);
+			if (arg_track_join_all(env, idx, target, at_in[ti],
+					       &at_stack_in[(size_t)ti * nslots],
+					       at_out, at_stack_out, nslots))
+				__set_bit(ti, changed);
 		}
 	}
-	if (changed)
+	if (!bitmap_empty(changed, len))
 		goto redo;
 
 	/* Record memory accesses using converged at_in (RPO skips dead code) */
@@ -2210,6 +2226,7 @@ static noinline_for_stack int compute_subprog_args(struct bpf_verifier_env *env,
 	err = 0;
 
 err_free:
+	kvfree(changed);
 	kvfree(at_stack_out);
 	kvfree(at_stack_in);
 	kvfree(at_in);
Signature · 1 line
2.55.0
#3 lore raw

PATCH v2 3/49 bpf: Delete the old main pass of the verifier

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The main pass decides at each join point if two states become one. It decides before it knows if the join does harm. So it guesses, with one table or one rule for each shape of code:

  what decides             where
  8 tables of "need"       flow_compute_need_const()
  kinds of values          bpf_flow_compute_kinds()
  bounds for widening      flow_compute_rungs()
  rules for two states     flow_join_makes_up(), flow_*_differs()
  walks of loops           flow_try_walk()
  caps on states           1024 at an insn, 256 for each insn, ...

A valid program that no rule fits is rejected, or it runs into a cap.

This series changes the order. Join first, and decide after an error. An insn whose check fails is "unproven". The next run can prove it:

join all states --> error ? --no--> accept
^ | yes
| v
keep apart what the unproven insn depends on

Delete the tables, the rules, the caps, the work list, the join, the walks, the compare of registers and references, and the code that builds the log from kept states. flow.c keeps the order of the insns and the places for may_goto.

What the remaining code uses stays until the patch that replaces it:
do_check(), do_check_all(), check_ids(), regs_exact(), the default case of regsafe(), bpf_loop_rungs, bpf_guard_edge and a part of loop_stack_entry.

There is no main pass until "bpf: Verify in passes". Until then bpf_check() refuses each load with -EOPNOTSUPP. The code after that return is dead, so a call of a function that comes later needs only a prototype. Later patches add static functions before their callers, so -Wunused-function is off until then.

---
 include/linux/bpf_verifier.h |   83 -
 kernel/bpf/Makefile          |    1 +
 kernel/bpf/fixups.c          |    1 -
 kernel/bpf/flow.c            | 3099 ----------------------------------
 kernel/bpf/join.c            |  622 -------
 kernel/bpf/log.c             |   47 -
 kernel/bpf/scev.c            |   15 -
 kernel/bpf/states.c          |  187 --
 kernel/bpf/verifier.c        |  506 +-----
 9 files changed, 4 insertions(+), 4557 deletions(-)
include/linux/bpf_verifier.h +0 -83
index f45c18b3cfa..df72a25764b 100644
@@ -421,7 +421,6 @@ enum bpf_guard_edge {
 
 struct loop_stack_entry {
 	struct bpf_verifier_state *entry_state;
-	u32 min_header_count;
 	u32 max_header_count;
 	u32 loop_id:23;
 	u32 terminates:1;
@@ -434,15 +433,6 @@ struct loop_stack_entry {
 	u32 apart:1;
 	/* max_header_count follows from the state at the entry, not from patience */
 	u32 counted:1;
-	/* the walk goes on for as long as each iteration decides a jump that leaves the loop */
-	u32 probe:1;
-	/* this one did */
-	u32 decided:1;
-	/*
-	 * The state is kept apart from one with the other value of a flag, see
-	 * flow_join_makes_up(). The test of the flag is decided in both, and decides nothing.
-	 */
-	u32 flag_apart:1;
 	/*
 	 * The first iteration of a counted loop is kept apart. The state that comes back
 	 * to the head is made to stand for the rest.
@@ -454,19 +444,6 @@ struct loop_stack_entry {
 	 * the largest number of the states that it is made of.
 	 */
 	u32 trip;
-	/* the number of references that the state had when it entered the loop */
-	u32 refs;
-	/*
-	 * Which of the states that entered the loop this one comes from. What comes back to
-	 * the head is for that state, see flow_merge(). A join has the number of one of the two.
-	 */
-	u32 entry_id;
-	/*
-	 * A walk on patience: which one it is, and how many insns may be looked at in it, see
-	 * env->walk_insns. The size of the loop says nothing about the functions that it calls.
-	 */
-	u32 walk_id;
-	u32 walk_patience;
 	int iv_reg;
 	struct scalar iv_range;
 	int count_insn;
@@ -529,8 +506,6 @@ struct bpf_func_state {
 	 *                           | number of simulations is tracked in frame N
 	 */
 	u32 callback_depth;
-	/* Which of the states that got to the call this one comes from, see flow_merge() */
-	u32 callback_entry_id;
 	/* Instructions processed in this frame and callees on the current path. */
 	u32 insns_subtotal;
 	/*
@@ -828,21 +803,11 @@ struct bpf_loop_exit {
 	int to; /* instruction outside the loop */
 };
 
-/* The places that the table of a loop knows: registers, then stack slots, fp-8 first */
-#define BPF_LOOP_SLOT	64
-#define BPF_LOOP_PLACES	128
-
-/*
- * Where the bounds of the number in @place may come to rest at the head of a loop: the lowest and
- * the highest upper bound, the highest and the lowest lower bound that the jumps of the loop
- * let come back to the head, see flow_compute_rungs().
- */
 struct bpf_loop_rungs {
 	s64 max[2];
 	s64 min[2];
 	bool has_max;
 	bool has_min;
-	u8 place;
 };
 
 struct bpf_loop {
@@ -861,19 +826,9 @@ struct bpf_loop {
 	bool rt_bounded;
 	/* insns in the loop, nested loops included */
 	u32 nr_insns;
-	/*
-	 * a walk on patience whose jumps were all decided, or the two trips of a loop with calls,
-	 * didn't get to the end of the loop: there is no other try
-	 */
-	bool walk_failed;
-	/* functions of the program are called in the loop */
-	bool has_calls;
 	/* not rt_bounded: there are places for may_goto, see guard_to in bpf_insn_aux_data */
 	bool has_guards;
-	/* and it is going to be there, see bpf_flow_loop_gets_guards() */
 	bool guarded;
-	/* a state went through it without the edges of may_goto, see bpf_flow_loop_gets_guards() */
-	bool no_guard_edges;
 	/*
 	 * Loop-entry registers used to compute stack addresses for loads,
 	 * stores and calls requiring fixed stack offsets, in this and nested
@@ -891,10 +846,6 @@ struct bpf_loop {
 	 */
 	unsigned long linear_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
 	unsigned long linear32_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
-	/* the places that insns of the loop write, as far as the insns tell */
-	unsigned long writes[BITS_TO_LONGS(BPF_LOOP_PLACES)];
-	struct bpf_loop_rungs *rungs;
-	u32 rungs_cnt;
 };
 
 struct bpf_insn_aux_data {
@@ -936,9 +887,6 @@ struct bpf_insn_aux_data {
 	DECLARE_BITMAP(may_write_mask, MAX_BPF_STACK_SLOTS);
 	DECLARE_BITMAP(live_stack_before, MAX_BPF_STACK_SLOTS);
 	u16 stack_ptrs; /* bitmask of regs that may hold a frame pointer here (arg_track) */
-	/* regs that hold a number or a pointer to arena; that, or a pointer to a plain map value */
-	u16 plain_regs;
-	u16 value_regs;
 	int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
 	u32 seen; /* this insn was processed by the verifier at env->pass_cnt */
 	u64 nospec:1; /* do not execute this instruction speculatively */
@@ -1310,8 +1258,6 @@ struct bpf_verifier_env {
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
 	bool guards_late;		/* see bpf_flow_loop_gets_guards() */
 	u32 loop_entry_cnt;		/* see loop_stack_entry.entry_id, callback_entry_id */
-	u32 walk_cnt;			/* see loop_stack_entry.walk_id */
-	u32 *walk_insns;		/* the insns that were looked at in each of them */
 	u32 max_arena_stack_depth;	/* of all call chains */
 	struct bpf_verifier_state *cur_state; /* current verifier state */
 	struct bpf_map **used_maps;	/* array of map's used by eBPF program */
@@ -1450,7 +1396,6 @@ struct bpf_verifier_env {
 	struct bpf_leave_cond *leave_conds;
 	struct scev *scev;
 	struct bpf_flow *flow;
-	struct bpf_join_state *join;
 };
 
 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
@@ -1509,15 +1454,6 @@ __printf(2, 3) void bpf_log(struct bpf_verifier_log *log,
 int bpf_vlog_init(struct bpf_verifier_log *log, u32 log_level,
 		  char __user *log_buf, u32 log_size);
 void bpf_vlog_reset(struct bpf_verifier_log *log, u64 new_pos);
-
-/* The end of the log, taken out of it by bpf_vlog_stash() */
-struct bpf_vlog_stash {
-	char *buf;
-	u64 len, lost_start, lost_end;
-};
-
-int bpf_vlog_stash(struct bpf_verifier_log *log, u64 pos, struct bpf_vlog_stash *stash);
-void bpf_vlog_unstash(struct bpf_verifier_log *log, struct bpf_vlog_stash *stash);
 int bpf_vlog_finalize(struct bpf_verifier_log *log, u32 *log_size_actual);
 
 __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env,
@@ -1621,44 +1557,26 @@ int bpf_clean_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_s
 bool bpf_state_subsumes(struct bpf_verifier_env *env, struct bpf_verifier_state *old,
 			struct bpf_verifier_state *cur);
 
-/* join.c */
-int bpf_states_join(struct bpf_verifier_env *env, struct bpf_verifier_state *dst,
-		    const struct bpf_verifier_state *a, const struct bpf_verifier_state *b,
-		    bool widen);
-void bpf_join_free(struct bpf_verifier_env *env);
-
 /* flow.c */
 int bpf_flow_prepare(struct bpf_verifier_env *env);
 void bpf_flow_reset(struct bpf_verifier_env *env);
 void bpf_flow_free(struct bpf_verifier_env *env);
 bool bpf_flow_is_point(struct bpf_verifier_env *env, int insn_idx);
-struct bpf_verifier_state *bpf_flow_keep_state(struct bpf_verifier_env *env,
-					       const struct bpf_verifier_state *st);
 int bpf_flow_deliver(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
 		     int insn_idx, int prev_insn_idx);
 int bpf_flow_guard_edge(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
 			int insn_idx, int prev_insn_idx, enum bpf_guard_edge edge);
 int bpf_flow_next(struct bpf_verifier_env *env, int *prev_insn_idx);
-void bpf_flow_print_way(struct bpf_verifier_env *env, u64 log_pos, int head, int i);
 int bpf_flow_call(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,
 		  struct bpf_verifier_state *entry, int subprog, int call_idx);
 int bpf_flow_exit(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int exit_idx);
 void bpf_flow_next_is_no_bound(struct bpf_verifier_env *env, int insn_idx, int h);
 bool bpf_flow_loops_lost_bound(struct bpf_verifier_env *env);
-void bpf_flow_loop_gets_guards(struct bpf_verifier_env *env, int h);
 void bpf_flow_new_round(struct bpf_verifier_env *env);
 int bpf_flow_place_guards(struct bpf_verifier_env *env);
-int bpf_flow_compute_kinds(struct bpf_verifier_env *env);
-u16 bpf_flow_flag_regs(struct bpf_verifier_env *env, int idx);
-bool bpf_flow_is_needed(struct bpf_verifier_env *env, int idx, u32 r);
-/* verifier.c, for flow.c */
-int bpf_flow_loop_leave(struct bpf_verifier_env *env, bool *enters);
-int bpf_flow_loop_enter(struct bpf_verifier_env *env, bool *backedge, bool *drop, bool *ends_walk);
 int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,
 		    const struct bpf_verifier_state *exit, int call_idx);
 int bpf_insert_loop_guards(struct bpf_verifier_env *env);
-u16 bpf_call_const_arg_regs(struct bpf_verifier_env *env, struct bpf_insn *insn);
-u16 bpf_call_checked_arg_regs(struct bpf_verifier_env *env, struct bpf_insn *insn);
 bool bpf_insn_is_iter_next(struct bpf_verifier_env *env, struct bpf_insn *insn);
 bool bpf_insn_leaves_loop(struct bpf_verifier_env *env, int h, int n);
 int bpf_compute_leave_conds(struct bpf_verifier_env *env);
@@ -2133,7 +2051,6 @@ static inline bool bpf_is_kfunc_sleepable(struct bpf_call_arg_meta *meta)
 	return meta->kfunc_flags & KF_SLEEPABLE;
 }
 bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta);
-bool bpf_is_cast_kfunc(const struct bpf_call_arg_meta *meta);
 struct bpf_iarray *bpf_iarray_realloc(struct bpf_iarray *old, size_t n_elem);
 int bpf_copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off);
 bool bpf_insn_is_cond_jump(u8 code);
kernel/bpf/Makefile +1 -0
index d26c62326e5..e0fb2e01403 100644
@@ -5,6 +5,7 @@ ifneq ($(CONFIG_BPF_JIT_ALWAYS_ON),y)
 cflags-nogcse-$(CONFIG_X86)$(CONFIG_CC_IS_GCC) := -fno-gcse
 endif
 CFLAGS_core.o += -Wno-override-init $(cflags-nogcse-yy)
+ccflags-y += -Wno-unused-function
 
 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 diagnostics.o loops.o scev.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_iter.o
kernel/bpf/fixups.c +0 -1
index 4d9b6798152..aca3c7a53b6 100644
@@ -755,7 +755,6 @@ void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
 	for (i = start; i < end; i++) {
 		if (aux_data[i].loop) {
 			kvfree(aux_data[i].loop->exits);
-			kvfree(aux_data[i].loop->rungs);
 			kvfree(aux_data[i].loop);
 			aux_data[i].loop = NULL;
 		}
kernel/bpf/flow.c +0 -3099

2,797 lines not on this page · raw message

kernel/bpf/join.c +0 -622

622 lines not on this page · raw message

kernel/bpf/log.c +0 -47

47 lines not on this page · raw message

kernel/bpf/scev.c +0 -15
index 5218ce1cafc..abae5fc58ab 100644

Lines of this file are not shown. View the raw message.

kernel/bpf/states.c +0 -187

187 lines not on this page · raw message

kernel/bpf/verifier.c +3 -503

506 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.55.0

Part of the diff is not shown here. View the raw message.

#4 lore raw

PATCH v2 4/49 bpf: Delete scalar evolution

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

scev.c computes an expression for each register at each insn, before the main pass. The expression is the same for all paths. It has three users:

  what                          code
  linked registers at a jump    refine_linked_regs()
  ranges in a loop              bpf_widen_scev_regs(), the clamps
  trip count                    bpf_compute_loop_iters()

The trip count is a proof with a case for each form of a loop:

  compute_backedge_taken_count()  <, <=, >, >=, != and how each wraps
  bound_of_zext32()               a 64-bit jump on a 32-bit counter
  bpf_compute_leave_conds()       a condition is stored, a later

jump tests it and leaves
fresh_regs, mask_regs, ... values that are not linear

Nothing checks the count. If it is too small, the verifier does not check a trip that runs.

Later patches replace all of that with one mechanism: equations in the state. A join guesses them, and a prune checks them. Delete scev.c, its callers, and the helpers that only it uses.

What is not a plain deletion:
- Only scev.c needs all exits and all latches of a loop. The other users need the first one. exit_to replaces exits[], latch replaces latches[]. MAX_LOOP_EXITS and MAX_LATCHES go away.
- find_latch() counts its steps with bpf_add_cost(). The next patch adds the other weights and the limits.

---
 include/linux/bpf_verifier.h |  144 +-
 include/linux/cnum.h         |    3 -
 include/linux/tnum.h         |    2 -
 kernel/bpf/Makefile          |    2 +-
 kernel/bpf/cnum.c            |   37 -
 kernel/bpf/const_fold.c      |  265 +-
 kernel/bpf/fixups.c          |    1 -
 kernel/bpf/flow.c            |   11 +-
 kernel/bpf/liveness.c        |   18 -
 kernel/bpf/log.c             |   18 +-
 kernel/bpf/loops.c           |  267 +-
 kernel/bpf/scev.c            | 5489 ----------------------------------
 kernel/bpf/tnum.c            |   11 -
 kernel/bpf/verifier.c        |  324 +-
 14 files changed, 67 insertions(+), 6525 deletions(-)
 delete mode 100644 kernel/bpf/scev.c
include/linux/bpf_verifier.h +11 -133
index df72a25764b..06429f57c39 100644
@@ -113,8 +113,6 @@ struct bpf_reg_state {
 	 * the dynptr to determine proper reference freeing.
 	 * Similarly to dynptrs, we use ID to track "belonging" of a reference
 	 * to a specific instance of bpf_iter.
-	 * A scalar has no id. The scalars that it is linked to are static: computed before the
-	 * main pass, see bpf_scev_next_linked_reg().
 	 */
 	u32 id;
 	union {
@@ -384,33 +382,6 @@ struct bpf_retval_range {
 	bool return_32bit;
 };
 
-/* SCEV/widening register space: r0..r10 plus every stack slot of a frame. */
-#define BPF_SCEV_REGS_NUM (MAX_BPF_REG + MAX_BPF_STACK_SLOTS)
-
-struct bpf_loop_iters {
-	u32 min_header_count;   /* min number of times header is executed */
-	u32 max_header_count;   /* max number of times header is executed */
-	/* live, changed by the loop, no summary of how: left to the join at the head */
-	unsigned long forget_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
-	/*
-	 * live, made anew in every iteration: the first one tells what it is in the rest.
-	 * Or not set at the entry, and also in forget_regs: the first one sets it.
-	 */
-	unsigned long fresh_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
-	/* [0, max] at the entry, and the loop only clears bits */
-	unsigned long mask_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
-	/*
-	 * The variable that the latches of all back edges test, or -1, and what
-	 * it can be at the loop header: what it is at the entry or what one of
-	 * the latches lets through. A 32-bit latch bounds its low 32 bits only.
-	 */
-	int iv_reg;
-	struct scalar iv_range;
-	/* a jump that counts: it leaves the loop in the last iteration, if not before. Or -1 */
-	int count_insn;
-	/* a pointer to the stack that stores go through moves in the loop */
-	bool spill_base;
-};
 
 /* Where may_goto that the verifier adds goes, see check_loop_guard() */
 enum bpf_guard_edge {
@@ -420,8 +391,6 @@ enum bpf_guard_edge {
 };
 
 struct loop_stack_entry {
-	struct bpf_verifier_state *entry_state;
-	u32 max_header_count;
 	u32 loop_id:23;
 	u32 terminates:1;
 	/* the loop had may_goto when the state entered it, see check_loop_guard() */
@@ -444,9 +413,6 @@ struct loop_stack_entry {
 	 * the largest number of the states that it is made of.
 	 */
 	u32 trip;
-	int iv_reg;
-	struct scalar iv_range;
-	int count_insn;
 };
 
 /* The state is in a walk on patience, which may not get to the end of the loop */
@@ -776,31 +742,11 @@ void bpf_call_graph_free(struct bpf_call_graph *cg);
 	     ___idx++)
 
 #define MAX_BACKEDGES 16
-#define MAX_LOOP_EXITS 256
-
-/* Number of exit conditions dominating a backedge. */
-#define MAX_LATCHES 4
 
 struct bpf_backedge {
 	int from;
-	/*
-	 * Conditional jumps within the loop that dominate 'from' and have
-	 * a successor outside the loop, nearest first. latches[0] is the
-	 * latch; the remaining entries are additional exit conditions.
-	 * After scalar evolution: those that test a counter, see bpf_scev_jump_counts().
-	 * One of them may leave the loop by way of a flag, see bpf_edge_leaves_loop().
-	 * Each usable condition tells iterations in which the back edge is
-	 * not taken, so keeping only a subset is sound.
-	 */
-	int latches[MAX_LATCHES];
-	u8 latches_cnt;
-	/* bit k: the loop is left on the edge of latches[k] that is taken, not on the other one */
-	u8 taken_leaves;
-};
-
-struct bpf_loop_exit {
-	int from; /* instruction inside the loop */
-	int to; /* instruction outside the loop */
+	/* the nearest conditional jump of the loop that dominates 'from' and leaves it, or -1 */
+	int latch;
 };
 
 struct bpf_loop_rungs {
@@ -812,16 +758,10 @@ struct bpf_loop_rungs {
 
 struct bpf_loop {
 	struct bpf_backedge backedges[MAX_BACKEDGES];
-	/* edges exiting from this loop, includes edges from nested loops */
-	struct bpf_loop_exit *exits;
+	int exit_to;		/* where the first edge that leaves the loop goes, or -1 */
 	int backedges_cnt;
-	int exits_cnt;
 	bool irreducible;
 	bool backedges_overflow;
-	/* @exits is cut at MAX_LOOP_EXITS. Only a loop around this one needs all of them. */
-	bool exits_overflow;
-	/* @exits of a loop in this one is cut. Then @exits of this loop can lack exits too. */
-	bool nested_exits_overflow;
 	/* every trip goes through an insn that stops the loop, see flow_is_bound() */
 	bool rt_bounded;
 	/* insns in the loop, nested loops included */
@@ -829,23 +769,6 @@ struct bpf_loop {
 	/* not rt_bounded: there are places for may_goto, see guard_to in bpf_insn_aux_data */
 	bool has_guards;
 	bool guarded;
-	/*
-	 * Loop-entry registers used to compute stack addresses for loads,
-	 * stores and calls requiring fixed stack offsets, in this and nested
-	 * loops.
-	 */
-	unsigned long store_base_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
-	/*
-	 * Loop-entry registers used to compute the operands of conditional jumps, in this and
-	 * nested loops.
-	 */
-	unsigned long tested_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
-	/*
-	 * what gets a constant added in every iteration, in 64 and in 32 bits. A sum that is
-	 * not among tested_regs is taken for that too: nothing stops it either
-	 */
-	unsigned long linear_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
-	unsigned long linear32_regs[BITS_TO_LONGS(BPF_SCEV_REGS_NUM)];
 };
 
 struct bpf_insn_aux_data {
@@ -905,9 +828,6 @@ struct bpf_insn_aux_data {
 	u64 guard_no_unwind:1; /* it cannot unwind from here, at least sometimes */
 	u64 guard_unset_reg:1; /* where it goes a register is read that is not set here */
 	u64 guard_edge_dropped:1; /* an edge of may_goto from here was dropped */
-	u64 need_scev:1;
-	/* a jump in a loop: the edge that is not taken, bit 0, or the other one leaves the loop */
-	u64 edge_leaves:2;
 	u64 alu_state:5; /* used in combination with alu_limit */
 	/* true if STX or LDX instruction is a part of a spill/fill
 	 * pattern for a bpf_fastcall call.
@@ -943,14 +863,12 @@ struct bpf_insn_aux_data {
 	/*
 	 * Bitmask of R0-R9 that hold known values at this instruction.
 	 * const_reg_mask: scalar constants that fit in 32 bits.
-	 * const_reg_wide_mask: scalar constants that don't, there is no val.
 	 * const_reg_map_mask: map pointers, val is map_index into used_maps[].
 	 * const_reg_subprog_mask: subprog pointers, val is subprog number.
 	 * const_reg_vals[i] holds the 32-bit value for register i.
 	 * Populated by compute_const_regs() pre-pass.
 	 */
 	u16 const_reg_mask;
-	u16 const_reg_wide_mask;
 	u16 const_reg_map_mask;
 	u16 const_reg_subprog_mask;
 	u32 const_reg_vals[10];
@@ -1164,7 +1082,6 @@ struct bpf_idmap {
 };
 
 struct bpf_liveness;
-struct scev;
 
 struct bpf_fd_array {
 	union {
@@ -1255,6 +1172,7 @@ struct bpf_verifier_env {
 	bool strict_alignment;		/* perform strict pointer alignment checks */
 	bool test_reg_invariants;	/* fail verification on register invariants violations */
 	bool uses_arena_sp;		/* the program has insns with BPF_REG_ARENA_SP */
+	u64 cost, mem;			/* see bpf_check_limits() */
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
 	bool guards_late;		/* see bpf_flow_loop_gets_guards() */
 	u32 loop_entry_cnt;		/* see loop_stack_entry.entry_id, callback_entry_id */
@@ -1392,9 +1310,6 @@ struct bpf_verifier_env {
 	struct bpf_iarray *succ;
 	struct bpf_iarray *gotox_tmp_buf;
 	int *idoms;
-	/* per insn, while bpf_compute_leave_conds() runs */
-	struct bpf_leave_cond *leave_conds;
-	struct scev *scev;
 	struct bpf_flow *flow;
 };
 
@@ -1459,8 +1374,6 @@ int bpf_vlog_finalize(struct bpf_verifier_log *log, u32 *log_size_actual);
 __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...)						\
 	({											\
@@ -1557,7 +1470,14 @@ int bpf_clean_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_s
 bool bpf_state_subsumes(struct bpf_verifier_env *env, struct bpf_verifier_state *old,
 			struct bpf_verifier_state *cur);
 
+#define BPF_COST_SCAN	1	/* one step of a scan */
+
 /* flow.c */
+static inline void bpf_add_cost(struct bpf_verifier_env *env, u64 cnt, u32 weight)
+{
+	env->cost += cnt * weight;
+}
+
 int bpf_flow_prepare(struct bpf_verifier_env *env);
 void bpf_flow_reset(struct bpf_verifier_env *env);
 void bpf_flow_free(struct bpf_verifier_env *env);
@@ -1579,10 +1499,6 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 int bpf_insert_loop_guards(struct bpf_verifier_env *env);
 bool bpf_insn_is_iter_next(struct bpf_verifier_env *env, struct bpf_insn *insn);
 bool bpf_insn_leaves_loop(struct bpf_verifier_env *env, int h, int n);
-int bpf_compute_leave_conds(struct bpf_verifier_env *env);
-bool bpf_edge_leaves_loop(struct bpf_verifier_env *env, int h, int n, int t);
-int bpf_find_latches(struct bpf_verifier_env *env, bool flags);
-bool bpf_jump_leaves_loop(struct bpf_verifier_env *env, int h, int n);
 int bpf_insert_recursion_checks(struct bpf_verifier_env *env);
 
 int bpf_copy_verifier_state(struct bpf_verifier_state *dst_state,
@@ -1920,7 +1836,6 @@ u32 btf_func_arg_align(const struct btf *btf, const struct btf_type *t);
 
 int bpf_find_subprog(struct bpf_verifier_env *env, int off);
 bool bpf_is_throw_kfunc(struct bpf_insn *insn);
-bool bpf_is_dynptr_slice_rdwr_kfunc(struct bpf_insn *insn);
 int bpf_compute_const_regs(struct bpf_verifier_env *env);
 int bpf_prune_dead_branches(struct bpf_verifier_env *env);
 int bpf_check_cfg(struct bpf_verifier_env *env);
@@ -2085,26 +2000,15 @@ void scalar_set_unknown(struct scalar *s);
 void scalar_set_const(struct scalar *s, u64 imm);
 void scalar_add(struct scalar *dst, const struct scalar *a, const struct scalar *b);
 void scalar_alu(struct scalar *dst, const struct scalar *src, const struct bpf_insn *insn);
-void scalar_zext32(struct scalar *s);
-void scalar_ext(struct scalar *s, u32 bits, bool sign);
 bool scalar_intersect(struct scalar *dst, const struct scalar *src, u32 bits);
 void scalar_union(struct scalar *acc, const struct scalar *src);
-int bpf_set_reg_range(struct bpf_verifier_env *env, struct bpf_reg_state *reg,
-		      const struct scalar *range);
-bool bpf_reg_union_compatible(const struct bpf_reg_state *a, const struct bpf_reg_state *b);
 void scalar_widen(struct scalar *s, const struct scalar *old,
 		  const struct bpf_loop_rungs *rungs, int linear);
-int bpf_reg_union(struct bpf_verifier_env *env, struct bpf_reg_state *acc,
-		  const struct bpf_reg_state *src);
-
 int bpf_stack_liveness_init(struct bpf_verifier_env *env);
 void bpf_stack_liveness_free(struct bpf_verifier_env *env);
 int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
-const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx);
-bool bpf_needs_fixed_stack_off(struct bpf_verifier_env *env, int insn_idx);
 bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 spi);
 bool bpf_stack_slot_filled(struct bpf_verifier_env *env, u32 frameno, u32 spi);
-bool bpf_half_slot_live_before(struct bpf_verifier_env *env, u32 insn_idx, u32 half_spi);
 int bpf_compute_live_registers(struct bpf_verifier_env *env);
 
 #define BPF_MAP_KEY_POISON	(1ULL << 63)
@@ -2241,31 +2145,5 @@ int bpf_compute_loops(struct bpf_verifier_env *env);
 int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx);
 bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header);
 
-int bpf_init_scev(struct bpf_verifier_env *env);
-void bpf_free_scev(struct bpf_verifier_env *env);
-int bpf_compute_scev(struct bpf_verifier_env *env);
-int bpf_scev_jump_counts(struct bpf_verifier_env *env, int header, int n, bool taken_leaves);
-/* What is known about a scalar or about the offset of a pointer. */
-struct scev_value {
-	struct scalar;
-	int ptr_reg;	/* SCEV register identifying the pointer origin, or -1. */
-	u8 bits;	/* The value is known modulo 2^bits. 0: nothing is known. */
-	bool refined;	/* It depends on a register that the jump refined. */
-};
-bool bpf_scev_next_linked_reg(struct bpf_verifier_env *env, struct bpf_func_state *st, int insn_idx,
-			      int next_idx, u16 refined_regs, u32 *pos, u32 *linked_regno,
-			      u32 *fill_off, struct scev_value *val);
-bool bpf_scev_mem_addr(struct bpf_verifier_env *env, int insn_idx, u32 regno, u32 *base_regno,
-		       s64 *off);
-bool bpf_is_widenable_reg_type(const struct bpf_reg_state *reg);
-bool bpf_scev_in_slice_slots(struct bpf_verifier_env *env, int off, u32 size, bool fixed_off);
-
-int bpf_compute_loop_iters(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
-			   struct bpf_loop_iters *iters);
-int bpf_widen_scev_regs(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
-			struct bpf_verifier_state *loop_entry, struct bpf_loop_iters *iters,
-			bool back);
-int bpf_clamp_scev_regs(struct bpf_verifier_env *env, struct bpf_func_state *st, u32 insn_idx,
-			const struct loop_stack_entry *entry, bool behind);
 
 #endif /* _LINUX_BPF_VERIFIER_H */
include/linux/cnum.h +0 -3
index e00148d352e..d31e5fcb2cb 100644
@@ -84,9 +84,6 @@ bool cnum64_is_subset(struct cnum64 outer, struct cnum64 inner);
 
 struct cnum32 cnum32_from_cnum64(struct cnum64 cnum);
 struct cnum64 cnum64_zext32(struct cnum32 cnum);
-struct cnum64 cnum64_sext32(struct cnum32 cnum);
-struct cnum64 cnum64_lshift32(struct cnum32 cnum);
-struct cnum32 cnum32_rshift32(struct cnum64 cnum);
 struct cnum64 cnum64_cnum32_intersect(struct cnum64 a, struct cnum32 b);
 struct cnum64 cnum64_intersect_linear(struct cnum64 in, u16 base, u16 step);
 
include/linux/tnum.h +0 -2
index 16682248f96..ca2cfec8de0 100644
@@ -134,6 +134,4 @@ static inline bool tnum_subreg_is_const(struct tnum a)
 /* Returns the smallest member of t larger than z */
 u64 tnum_step(struct tnum t, u64 z);
 
-u32 tnum_alignment(struct tnum a);
-
 #endif /* _LINUX_TNUM_H */
kernel/bpf/Makefile +1 -1
index e0fb2e01403..5cf89286df9 100644
@@ -7,7 +7,7 @@ endif
 CFLAGS_core.o += -Wno-override-init $(cflags-nogcse-yy)
 ccflags-y += -Wno-unused-function
 
-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 diagnostics.o loops.o scev.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 diagnostics.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/cnum.c +0 -37
index e64c09a37cc..a298753158d 100644
@@ -31,43 +31,6 @@ struct cnum64 cnum64_zext32(struct cnum32 cnum)
 	return cnum64_from_urange(cnum32_umin(cnum), cnum32_umax(cnum));
 }
 
-/*
- * The sign extension of each value of 'cnum'.
- * An arc that crosses S32_MAX/S32_MIN gives [S32_MIN, S32_MAX].
- */
-struct cnum64 cnum64_sext32(struct cnum32 cnum)
-{
-	if (cnum32_is_empty(cnum))
-		return CNUM64_EMPTY;
-	return cnum64_from_srange(cnum32_smin(cnum), cnum32_smax(cnum));
-}
-
-/*
- * The smallest arc with { x << 32 : x in 'cnum' }. The circle of 2^32 numbers is laid on the circle
- * of 2^64 numbers: sums, the order of signed and of unsigned numbers and the places where they wrap
- * stay.
- */
-struct cnum64 cnum64_lshift32(struct cnum32 cnum)
-{
-	if (cnum32_is_empty(cnum))
-		return CNUM64_EMPTY;
-	return (struct cnum64){ .base = (u64)cnum.base << 32, .size = (u64)cnum.size << 32 };
-}
-
-/* { x >> 32 : x in 'cnum' } */
-struct cnum32 cnum32_rshift32(struct cnum64 cnum)
-{
-	u32 base = cnum.base >> 32;
-	u32 size = ((cnum.base + cnum.size) >> 32) - base;
-
-	if (cnum64_is_empty(cnum))
-		return CNUM32_EMPTY;
-	/* less than 1 << 32 numbers are missing, or the arc ends one before its base */
-	if (cnum.size >> 32 == U32_MAX || size == U32_MAX)
-		return CNUM32_UNBOUNDED;
-	return (struct cnum32){ .base = base, .size = size };
-}
-
 /*
  * Suppose 'a' and 'b' are laid out as follows:
  *
kernel/bpf/const_fold.c +3 -262

296 lines not on this page · raw message

kernel/bpf/fixups.c +0 -1
index aca3c7a53b6..bd47a38c7bc 100644
@@ -754,7 +754,6 @@ void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
 
 	for (i = start; i < end; i++) {
 		if (aux_data[i].loop) {
-			kvfree(aux_data[i].loop->exits);
 			kvfree(aux_data[i].loop);
 			aux_data[i].loop = NULL;
 		}
kernel/bpf/flow.c +5 -6
index 060bdff7f29..d2248745fdd 100644
@@ -158,8 +158,7 @@ static void flow_place_guards(struct bpf_verifier_env *env, int h, u32 *seen)
 	 */
 	if (loop->irreducible) {
 		for (i = 0; i < loop->backedges_cnt; i++)
-			if (!loop->backedges[i].latches_cnt ||
-			    loop->backedges[i].latches[0] != loop->backedges[i].from)
+			if (loop->backedges[i].latch != loop->backedges[i].from)
 				goto header;
 		for (i = 0; i < loop->backedges_cnt; i++)
 			flow_set_guard(env, h, loop->backedges[i].from);
@@ -182,10 +181,10 @@ static void flow_place_guards(struct bpf_verifier_env *env, int h, u32 *seen)
 	}
 
 	for (i = 0; i < loop->backedges_cnt; i++)
-		if (!loop->backedges[i].latches_cnt)
+		if (loop->backedges[i].latch < 0)
 			goto header;
 	for (i = 0; i < loop->backedges_cnt; i++)
-		flow_set_guard(env, h, loop->backedges[i].latches[0]);
+		flow_set_guard(env, h, loop->backedges[i].latch);
 	return;
 
 header:
@@ -202,9 +201,9 @@ static void flow_place_guards(struct bpf_verifier_env *env, int h, u32 *seen)
 	for (o = h; aux[o].loop_header >= 0; o = aux[o].loop_header)
 		;
 	/* a loop that has no exit can only be stopped together with the program */
-	if (!aux[o].loop->exits_cnt)
+	t = aux[o].loop->exit_to;
+	if (t < 0)
 		return;
-	t = aux[o].loop->exits[0].to;
 	aux[h].guard_place = true;
 	aux[h].guard_at_header = true;
 	aux[h].guard_to = t;
kernel/bpf/liveness.c +0 -18
index d78a8ee0bbf..711f9da2b26 100644
@@ -795,24 +795,6 @@ static void compute_may_write_masks(struct bpf_verifier_env *env)
 	}
 }
 
-/* live_stack_before of the insn at @insn_idx for one half-slot */
-bool bpf_half_slot_live_before(struct bpf_verifier_env *env, u32 insn_idx, u32 half_spi)
-{
-	struct func_instance *instance;
-	int bkt;
-
-	hash_for_each(env->liveness->func_instances, bkt, instance, hl_node)
-		if (insn_idx - instance->subprog_start < instance->insn_cnt &&
-		    is_live_before(instance, insn_idx, instance->depth, half_spi, FM_LIVE_BEFORE))
-			return true;
-	return false;
-}
-
-const unsigned long *bpf_may_write_mask(struct bpf_verifier_env *env, u32 insn_idx)
-{
-	return env->insn_aux_data[insn_idx].may_write_mask;
-}
-
 /* print use/def slots for all instances ordered by callsite first, then by depth */
 static int print_instances(struct bpf_verifier_env *env)
 {
kernel/bpf/log.c +5 -13
index 20820098c6b..e58202955f1 100644
@@ -527,7 +527,7 @@ static void verbose_unum(struct bpf_verifier_env *env, u64 num)
 		verbose(env, "%#llx", num);
 }
 
-void bpf_verbose_snum(struct bpf_verifier_env *env, s64 num)
+static void verbose_snum(struct bpf_verifier_env *env, s64 num)
 {
 	if (is_snum_decimal(num))
 		verbose(env, "%lld", num);
@@ -535,14 +535,6 @@ 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 */
@@ -617,7 +609,7 @@ static void print_scalar_ranges(struct bpf_verifier_env *env,
 		}
 
 		if (m1->name[0] == 's')
-			bpf_verbose_snum(env, m1->val);
+			verbose_snum(env, m1->val);
 		else
 			verbose_unum(env, m1->val);
 	}
@@ -638,7 +630,7 @@ static void print_reg_state(struct bpf_verifier_env *env,
 
 	t = reg->type;
 	if (t == SCALAR_VALUE && tnum_is_const(reg->var_off)) {
-		bpf_verbose_snum(env, reg->var_off.value);
+		verbose_snum(env, reg->var_off.value);
 		return;
 	}
 
@@ -649,7 +641,7 @@ static void print_reg_state(struct bpf_verifier_env *env,
 		if (state->frameno != reg->frameno)
 			verbose(env, "[%d]", reg->frameno);
 		if (tnum_is_const(reg->var_off)) {
-			bpf_verbose_snum(env, reg->var_off.value);
+			verbose_snum(env, reg->var_off.value);
 			return;
 		}
 	}
@@ -687,7 +679,7 @@ static void print_reg_state(struct bpf_verifier_env *env,
 		/* a pointer register with fixed offset */
 		if (reg->var_off.value) {
 			verbose_a("imm=");
-			bpf_verbose_snum(env, reg->var_off.value);
+			verbose_snum(env, reg->var_off.value);
 		}
 	} else {
 		print_scalar_ranges(env, reg, &sep);
kernel/bpf/loops.c +38 -229

337 lines not on this page · raw message

kernel/bpf/scev.c deleted +0 -5489

1,911 lines not on this page · raw message

kernel/bpf/tnum.c +0 -11
index 1f620facd1b..ec9c310cf5d 100644

Lines of this file are not shown. View the raw message.

kernel/bpf/verifier.c +4 -320

324 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.55.0

Part of the diff is not shown here. View the raw message.

#5 lore raw

Re: [PATCH bpf-next v2 04/49] bpf: Delete scalar evolution

TL;DR: Nit only: a comment on loop_stack_entry's counted bit still mentions max_header_count, a field this patch removes; the comment is only fixed later in the series.
Quoted 1 line

bpf: Delete scalar evolution

TL;DR: Nit only: a comment on loop_stack_entry's counted bit still mentions max_header_count, a field this patch removes; the comment is only fixed later in the series.

Quoted 3 lines
include/linux/bpf_verifier.h +0 -0

[ ... ]

include/linux/bpf_verifier.h enum bpf_guard_edge { · line 395

Quoted 8 lines
include/linux/bpf_verifier.h +0 -2
@@ -420,8 +391,6 @@ enum bpf_guard_edge {
 };
 
 struct loop_stack_entry {
-	struct bpf_verifier_state *entry_state;
-	u32 max_header_count;
 	u32 loop_id:23;
 	u32 terminates:1;

[ ... ]

This isn't a bug, but this hunk removes max_header_count from struct loop_stack_entry (and struct bpf_loop_iters), while the comment documenting the counted bit further down in the same struct is left in place:

	/* max_header_count follows from the state at the entry, not from patience */
	u32 counted:1;

Could that comment be rewritten or dropped together with the field? No field or variable named max_header_count remains in the tree after this patch.

The comment is only rewritten later in the series, in 29203c388956 ("bpf:
Give a loop a checked trip count or may_goto"), so every commit in between keeps the dangling reference.

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

#6 lore raw

PATCH v2 5/49 bpf: Limit the cost and the memory of a load

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The caps on states are gone. Something has to stop a load that takes too long. A cap on one kind of work is a poor tool. It rejects a valid program that needs much of that kind and little else.

Use two limits for the whole load, one on cost and one on memory:

  weight  work
       1  one step of a scan
       4  copy an xreg
      16  clean, compare or join an xreg
     128  check an insn
     512  make, order and free a state

BPF_MAX_COST 1 << 33, BPF_MAX_MEM 2 GB, 1/32 of both without CAP_BPF

The cost counts work, not time. So the verdict does not depend on the speed or the load of the machine. bpf_check_limits() calls bpf_must_abort() too, and replaces it in the loops that add cost. A thaw does not take an abort back, see env->aborted.

A state knows its part of env->mem, so copy and free take env. free_pushed_states() frees the states that an insn pushed. A load from a table of functions pays for the scan and for the set that it makes. gotox pays for the sort of its targets.

The walks up a deep nest of loops are quadratic. Move the check of LOOP_STACK_SIZE to bpf_compute_loops(), before these walks. Stack liveness skips the registers and slots that hold no argument. It copies the stack only for a call that passes a pointer to a stack.

Stack liveness has a cap on one kind of work too. It rejects a program after 10000 calls of functions:

for 12000 times:
call small_func liveness analysis exceeded complexity limit

The program is valid and cheap. Remove the cap. Each call site has an instance, and the hash table of instances has 256 buckets. So 12000 instances make long chains. Use an array with the call site as the index. An entry has one instance for each depth:

by_callsite[insn] -> depth 2 -> depth 1 -> NULL

A list has all instances, for the loops over them.

---
 include/linux/bpf.h          |   4 +-
 include/linux/bpf_verifier.h |  41 +++++++-
 kernel/bpf/const_fold.c      |  15 +--
 kernel/bpf/flow.c            |  39 +++++---
 kernel/bpf/liveness.c        | 188 +++++++++++++++++++----------------
 kernel/bpf/loops.c           |  42 +++++++-
 kernel/bpf/states.c          |   1 +
 kernel/bpf/verifier.c        |  90 ++++++++++++-----
 8 files changed, 282 insertions(+), 138 deletions(-)
include/linux/bpf.h +2 -2
index 971e584c6ef..41f2cb37c19 100644
@@ -2627,8 +2627,8 @@ struct bpf_array {
 int bpf_array_get_next_key(struct bpf_map *map, void *key, void *next_key);
 
 /*
- * the longest program. The verifier limits the number of states, not of
- * processed insns, see BPF_FLOW_MAX_STATES.
+ * the longest program. The verifier limits the cost of a load, not the number
+ * of processed insns, see BPF_MAX_COST.
  */
 #define BPF_COMPLEXITY_LIMIT_INSNS      1000000 /* yes. 1M insns */
 #define MAX_TAIL_CALL_CNT 33
include/linux/bpf_verifier.h +39 -2

78 lines not on this page · raw message

kernel/bpf/const_fold.c +8 -7
index bf81bd54232..50179edbf34 100644
@@ -250,9 +250,10 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 	struct const_arg_info ci_out[MAX_BPF_REG];
 	struct bpf_iarray *succ;
 	bool changed;
-	int i, r, t;
+	int i, r, t, err;
 
 	/* kvzalloc zeroes memory, so all entries start as CONST_ARG_UNVISITED (0) */
+	env->mem += insn_cnt * sizeof(*ci_in);
 	ci_in = kvzalloc_objs(*ci_in, insn_cnt, BPF_VERIFIER_GFP);
 	if (!ci_in)
 		return -ENOMEM;
@@ -278,10 +279,9 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 	}
 
 redo:
-	if (bpf_must_abort()) {
-		kvfree(ci_in);
-		return -EINTR;
-	}
+	err = bpf_add_cost_and_check(env, env->cfg.cur_postorder * 2ULL, BPF_COST_XREG);
+	if (err)
+		goto out;
 	changed = false;
 	for (i = env->cfg.cur_postorder - 1; i >= 0; i--) {
 		int idx = env->cfg.insn_postorder[i];
@@ -334,9 +334,10 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 		aux->const_reg_map_mask = map_mask;
 		aux->const_reg_subprog_mask = subprog_mask;
 	}
-
+out:
+	env->mem -= insn_cnt * sizeof(*ci_in);
 	kvfree(ci_in);
-	return 0;
+	return err;
 }
 
 static int eval_const_branch(u8 opcode, u64 dst_val, u64 src_val)
kernel/bpf/flow.c +23 -16
index d2248745fdd..5a04cf19805 100644
@@ -220,9 +220,11 @@ static bool flow_loop_is_bounded(struct bpf_verifier_env *env, int h)
 	if (loop->backedges_overflow || loop->irreducible)
 		return false;
 	for (i = 0; i < loop->backedges_cnt; i++) {
-		for (n = loop->backedges[i].from; n >= 0 && n != h; n = env->idoms[n])
+		for (n = loop->backedges[i].from; n >= 0 && n != h; n = env->idoms[n]) {
+			bpf_add_cost(env, 1, BPF_COST_SCAN);
 			if (flow_is_bound(env, h, n))
 				break;
+		}
 		if (n < 0 || !flow_is_bound(env, h, n))
 			return false;
 	}
@@ -269,7 +271,7 @@ bool bpf_flow_loops_lost_bound(struct bpf_verifier_env *env)
 int bpf_flow_place_guards(struct bpf_verifier_env *env)
 {
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
-	int len = env->prog->len, h, i, depth, ret = 0;
+	int len = env->prog->len, h, i, ret = 0, err = 0;
 	struct bpf_loop *loop;
 	u32 *seen;
 
@@ -279,27 +281,18 @@ int bpf_flow_place_guards(struct bpf_verifier_env *env)
 
 	for (i = 0; i < len; i++) {
 		aux[i].not_stopped = -1;
-		depth = 0;
-		for (h = bpf_loop_at_index(env, i); h >= 0; h = aux[h].loop_header) {
-			/* the main pass doesn't get that deep */
-			if (++depth > LOOP_STACK_SIZE) {
-				verbose(env, "Too many nested loops at %d\n", i);
-				kvfree(seen);
-				return -E2BIG;
-			}
+		for (h = bpf_loop_at_index(env, i); h >= 0; h = aux[h].loop_header)
 			aux[h].loop->nr_insns++;
-		}
 	}
 
 	for (h = 0; h < len; h++) {
 		loop = aux[h].loop;
 		if (!loop)
 			continue;
-		/* a deep nest of loops takes long */
-		if (bpf_must_abort()) {
-			ret = -EINTR;
+		err = bpf_add_cost_and_check(env, (u64)loop->nr_insns * loop->backedges_cnt,
+					     BPF_COST_COPY);
+		if (err)
 			break;
-		}
 		loop->rt_bounded = flow_loop_is_bounded(env, h);
 		/* also when it's bounded: the main pass may find that it's not */
 		flow_place_guards(env, h, seen);
@@ -307,5 +300,19 @@ int bpf_flow_place_guards(struct bpf_verifier_env *env)
 			ret = 1;
 	}
 	kvfree(seen);
-	return ret;
+	return err ?: ret;
+}
+
+int bpf_check_limits(struct bpf_verifier_env *env)
+{
+	env->aborted |= bpf_must_abort();
+	if (env->aborted)
+		return -EINTR;
+	if (env->cost <= min(env->max_cost, env->pass_max_cost) && env->mem <= env->max_mem &&
+	    !env->over_limit)
+		return 0;
+	verbose(env, "BPF program is too complex: cost %llu of %llu, memory %llu of %llu\n",
+		env->cost, min(env->max_cost, env->pass_max_cost), env->mem, env->max_mem);
+	env->over_limit = true;
+	return -E2BIG;
 }
kernel/bpf/liveness.c +104 -84

420 lines not on this page · raw message

kernel/bpf/loops.c +39 -3

107 lines not on this page · raw message

kernel/bpf/states.c +1 -0
index 73c329ec755..5d78a10dd29 100644
@@ -179,6 +179,7 @@ int bpf_clean_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_s
 {
 	int i, err;
 
+	bpf_add_cost(env, bpf_xreg_cnt(st), BPF_COST_XREG);
 	err = bpf_live_stack_query_init(env, st);
 	if (err)
 		return err;
kernel/bpf/verifier.c +66 -24

231 lines not on this page · raw message

Signature · 1 line
2.55.0
#7 lore raw

PATCH v2 6/49 bpf: Record what each insn reads and writes

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Liveness knows what an insn reads and writes, and drops most of that when it is done. A later patch walks back from an unproven insn and needs the same data. Keep it in bpf_insn_aux_data:

  r2 += r3                   use_regs: r2 r3, def_regs: r2
  r2 = *(u64 *)(r10 - 8)     may_read_mask: fp-8
  *(u64 *)(r1 + 0) = r2      writes_outer, if r1 points to the frame

of a caller

Give registers and stack slots one number, the xreg:

  0 .. 10      11 .. 13            14 ..
  r0 .. r10    hidden registers    fp-8, fp-16, ...

Two sets of reads were too large:
- LD_ABS and LD_IND read all registers and wrote none. They read r6 and the source register, and they clobber r0-r5.
- bpf_timer_set_callback() does not read r3. The verifier sets that argument.

---
 include/linux/bpf_verifier.h | 33 ++++++++++++++++++++++++++++
 kernel/bpf/liveness.c        | 42 ++++++++++++++++++++++++------------
 kernel/bpf/verifier.c        |  1 +
 3 files changed, 62 insertions(+), 14 deletions(-)
include/linux/bpf_verifier.h +33 -0
index 9ae46e3a8d6..7977f8452e9 100644
@@ -382,6 +382,30 @@ struct bpf_retval_range {
 	bool return_32bit;
 };
 
+/*
+ * An xreg is a register or a stack slot of a frame:
+ *
+ *	0 .. 10		11 .. 13		MAX_BPF_EXT_REG ..
+ *	r0 .. r10	hidden registers	fp-8, fp-16, ...
+ *
+ * A state has no value for a hidden register. No mask of xregs has its bit.
+ */
+#define MAX_BPF_XREG (MAX_BPF_EXT_REG + MAX_BPF_STACK_SLOTS)
+
+static inline bool bpf_xreg_is_slot(u32 xregno)
+{
+	return xregno >= MAX_BPF_EXT_REG;
+}
+
+static inline u32 bpf_spi_to_xreg(u32 spi)
+{
+	return MAX_BPF_EXT_REG + spi;
+}
+
+static inline u32 bpf_xreg_to_spi(u32 xregno)
+{
+	return xregno - MAX_BPF_EXT_REG;
+}
 
 /* Where may_goto that the verifier adds goes, see check_loop_guard() */
 enum bpf_guard_edge {
@@ -858,10 +882,19 @@ struct bpf_insn_aux_data {
 	u64 non_stack_access:1; /* instruction can access non-stack memory */
 	/* true if some jump or call instruction targets this instruction */
 	u64 jump_target:1;
+	/* it can read or write the frame of a caller, in a call with a known callee */
+	u32 reads_outer:1;
+	u32 writes_outer:1;
+	DECLARE_BITMAP(may_read_mask, MAX_BPF_STACK_SLOTS);
 
 	unsigned int orig_idx; /* original instruction index, initialized once */
 	/* registers alive before this instruction. */
 	u16 live_regs_before;
+	/*
+	 * Registers that it reads and writes. The arguments of a static function and of callx
+	 * are not in @use_regs. The bits above r10 are not valid.
+	 */
+	u16 use_regs, def_regs;
 	/*
 	 * Bitmask of R0-R9 that hold known values at this instruction.
 	 * const_reg_mask: scalar constants that fit in 32 bits.
kernel/bpf/liveness.c +28 -14

70 lines not on this page · raw message

kernel/bpf/verifier.c +1 -0
index 06bd1cd3d18..1c1aeec4069 100644
@@ -19836,6 +19836,7 @@ bool bpf_get_call_summary(struct bpf_verifier_env *env, struct bpf_insn *call,
 			if (fn->arg_type[i] == ARG_UNUSED)
 				break;
 			cs->arg_slot_cnt++;
+			cs->implicit_slot_cnt += fn->arg_type[i] == ARG_PTR_TO_PROG_AUX;
 		}
 		return true;
 	}
Signature · 1 line
2.55.0
#8 lore raw

Re: [PATCH bpf-next v2 06/49] bpf: Record what each insn reads and writes

TL;DR: Nits only: in bpf_insn_aux_data, may_read_mask may belong beside may_write_mask rather than under the caller-frame flags, and the new 1-bit flags are u32 while neighbours are u64.
Quoted 1 line

bpf: Record what each insn reads and writes

TL;DR: Nits only: in bpf_insn_aux_data, may_read_mask may belong beside may_write_mask rather than under the caller-frame flags, and the new 1-bit flags are u32 while neighbours are u64.

Quoted 3 lines
include/linux/bpf_verifier.h +0 -0

[ ... ]

include/linux/bpf_verifier.h struct bpf_insn_aux_data { · line 888

Quoted 8 lines
include/linux/bpf_verifier.h +4 -0
@@ -858,10 +882,19 @@ struct bpf_insn_aux_data {
 	u64 non_stack_access:1; /* instruction can access non-stack memory */
 	/* true if some jump or call instruction targets this instruction */
 	u64 jump_target:1;
+	/* it can read or write the frame of a caller, in a call with a known callee */
+	u32 reads_outer:1;
+	u32 writes_outer:1;
+	DECLARE_BITMAP(may_read_mask, MAX_BPF_STACK_SLOTS);

This isn't a bug, but could may_read_mask go next to may_write_mask and live_stack_before, under their "stack slots in the current frame" comment?

As written it sits right under the reads_outer/writes_outer comment, which is about the frame of a caller, while compute_may_write_masks() fills may_read_mask only from the top frame of the instruction.

Also, the two new 1-bit flags are declared u32 while the other flags in this group are u64. Is that intentional?

[ ... ]

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

#9 lore raw

PATCH v2 7/49 bpf: Name an id after the xreg that has it

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

An id stands for the set of xregs that have it. Its number depends on the path. Two states with the same sets have other numbers:

  state 1:  r1=ptr(id=17)  r6=ptr(id=17)  r7=ptr(id=4)
  state 2:  r1=ptr(id=3)   r6=ptr(id=3)   r7=ptr(id=9)

So the compare, the join and the return from a function each had a map from one set of ids to another.

bpf_renumber_ids() names each id after the first xreg that has it:

both: r1=ptr(id=r1) r6=ptr(id=r1) r7=ptr(id=r7)

Equal sets have equal ids now, and reg_object_equal() is a memcmp(). If r1 = r6 in one state and r1 is not set in the other, r6 has two names and counts as two objects. The maps saw one object.

The ids are renumbered at the end of a basic block and before the call of a function. The low bits tell the origin:

  bpf_new_id()       an insn of this basic block made it
  BPF_REF_ID()       it is held, named after its index in refs[]
  BPF_XREG_ID()      named after an xreg
  BPF_RETURNED_ID()  a function returned it

A caller and its callee have the same refs[], so they have the same names. inherited_id(), fresh_id() and BPF_MAX_ID go away. check_ids() stays until "bpf: Compare states by join_key, then by value".

The id of a __ref argument is not constant any more. refs[].ctx_arg tells which argument a reference came with. The report of a leak finds the acquire by refs[].diag_id, which is not renumbered. A reference that leaks has no release, so the events of a release go away.

---
 include/linux/bpf.h          |   4 +-
 include/linux/bpf_verifier.h |  57 +++++---
 kernel/bpf/btf.c             |   2 +-
 kernel/bpf/diagnostics.c     |  56 +++-----
 kernel/bpf/diagnostics.h     |   6 +-
 kernel/bpf/states.c          |  79 +++++++++-
 kernel/bpf/verifier.c        | 271 ++++++++++++-----------------------
 7 files changed, 230 insertions(+), 245 deletions(-)
include/linux/bpf.h +2 -2
index 41f2cb37c19..dee0cca907b 100644
@@ -1189,7 +1189,7 @@ struct bpf_insn_access_aux {
 		struct {
 			struct btf *btf;
 			u32 btf_id;
-			u32 ref_id;
+			u32 ref_arg;	/* see struct bpf_ctx_arg_aux */
 		};
 	};
 	u32 mem_size;
@@ -1827,7 +1827,7 @@ struct bpf_ctx_arg_aux {
 	enum bpf_reg_type reg_type;
 	struct btf *btf;
 	u32 btf_id;
-	u32 ref_id;
+	u32 ref_arg;	/* a number for a __ref argument, else 0 */
 	u32 mem_size;
 	bool refcounted;
 };
include/linux/bpf_verifier.h +40 -17

103 lines not on this page · raw message

kernel/bpf/btf.c +1 -1
index 2f28b418a7f..3d278a2c29c 100644
@@ -7645,7 +7645,7 @@ bool btf_ctx_access(int off, int size, enum bpf_access_type type,
 			info->reg_type = ctx_arg_info->reg_type;
 			info->btf = ctx_arg_info->btf ? : btf_vmlinux;
 			info->btf_id = ctx_arg_info->btf_id;
-			info->ref_id = ctx_arg_info->ref_id;
+			info->ref_arg = ctx_arg_info->ref_arg;
 			return true;
 		}
 	}
kernel/bpf/diagnostics.c +18 -38

135 lines not on this page · raw message

kernel/bpf/diagnostics.h +3 -3
index e155d2588a5..f6380137e9a 100644
@@ -77,7 +77,8 @@ void bpf_diag_lock(struct bpf_verifier_env *env, u32 insn_idx, const char *probl
 		   const struct bpf_reference_state *active_lock);
 void bpf_diag_irq(struct bpf_verifier_env *env, u32 insn_idx, const char *problem,
 		  const char *reason, const char *suggestion, u32 depth);
-void bpf_diag_leak(struct bpf_verifier_env *env, u32 ref_id, u32 alloc_insn, u32 fail_insn);
+void bpf_diag_leak(struct bpf_verifier_env *env, const struct bpf_reference_state *ref,
+		   u32 fail_insn);
 void bpf_diag_call_type(struct bpf_verifier_env *env, u32 insn_idx, int argno, int regno,
 			int stack_arg_slot, const char *call_name, const char *arg_name,
 			const char *reason, const char *suggestion);
@@ -104,8 +105,7 @@ void bpf_diag_record_scrub(struct bpf_verifier_env *env, const struct bpf_reg_st
 void bpf_diag_record_scrub_stack(struct bpf_verifier_env *env,
 				 const struct bpf_func_state *state, s16 min_off, s16 max_off,
 				 enum bpf_diag_mod_reason reason);
-void bpf_diag_record_ref_acquire(struct bpf_verifier_env *env, u32 insn_idx, u32 ref_id);
-void bpf_diag_record_ref_release(struct bpf_verifier_env *env, u32 insn_idx, u32 ref_id);
+void bpf_diag_record_ref_acquire(struct bpf_verifier_env *env, struct bpf_reference_state *ref);
 void bpf_diag_record_context(struct bpf_verifier_env *env, u32 insn_idx,
 			     enum bpf_diag_context_kind ctx_kind, bool enter, u32 depth);
 
kernel/bpf/states.c +78 -1

91 lines not on this page · raw message

kernel/bpf/verifier.c +88 -183

557 lines not on this page · raw message

Signature · 1 line
2.55.0
#10 lore raw

PATCH v2 8/49 bpf: Do not fail a check because a state has fewer values

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

More precision must not make the result worse. If an insn is proven in a state, it has to be proven in a state with fewer values too. Else it is proven after a join and unproven without the join. Three checks do not work that way.

1. Pointer arithmetic looks at the smallest offset:

     r1 = 1 << 30            r1 = 0 .. 1 << 30
     r0 += r1   fails        r0 += r1   ok

Allow the add. bpf_blur_far_offset() extends the range of the offset down to BPF_MAX_VAR_OFF - 1. So the offset is not a constant that overflows an int, and an access fails. The same holds far below the object. The number still needs a lower bound.

A flexible array of a BTF object has no end. If a far load from it passes, it gets a fault handler. A far load-acquire fails.

2. A jump can cut a range in two:

                         r8 = -4..3            r8 = any number
     if r8 < 3 goto L    -4..-1, 3 -> -4..3    3..U64_MAX
     if r8 s< 0 goto L   0..3                  3..S64_MAX

The small state has 0..2, the large state does not. cut_range() does the jump two times: for -4..-1 and for 0..3. It does that only if an error depends on the register, see bpf_xreg_in_deps() in a later patch.
'x != 0' is 'x u> 0', so it cuts a range too.

3. A load takes a part of a spilled pointer:

     *(u64 *)(r10 - 16) = ptr
     r1 = r10 - 16 + (0..7)       r1 = r10 - 16 + 3
     r0 = *(u8 *)(r1 + 0)  ok     r0 = *(u8 *)(r1 + 0)  fails

With allow_ptr_leaks the constant offset takes the path of the variable offset: the result is an unknown number. An atomic read-modify-write still needs the whole slot.

do_check() has only a range for a far offset. So const_fold.c does not follow a far pointer to a map value.

A far pointer to the packet can wrap around:
- It gets a new id and loses its range. bpf_blur_far_offset() looks at the source and the result of the add.
- A compare with the end of the packet leaks the address. Without allow_ptr_leaks, compare only offsets from -MAX_PACKET_OFF to 2 * MAX_PACKET_OFF. A header and a 16-bit length fit.

---
 include/linux/bpf_verifier.h |  27 ++++++
 kernel/bpf/const_fold.c      |   3 +
 kernel/bpf/liveness.c        |   6 +-
 kernel/bpf/states.c          |   4 +-
 kernel/bpf/verifier.c        | 182 ++++++++++++++++++++++++-----------
 5 files changed, 163 insertions(+), 59 deletions(-)
include/linux/bpf_verifier.h +27 -0
index d63a522b465..87b4e01cda2 100644
@@ -1227,10 +1227,13 @@ struct bpf_verifier_env {
 	bool strict_alignment;		/* perform strict pointer alignment checks */
 	bool test_reg_invariants;	/* fail verification on register invariants violations */
 	bool uses_arena_sp;		/* the program has insns with BPF_REG_ARENA_SP */
+	bool path_sensitive;		/* no joins, see run_path_sensitive() */
 	u64 cost, mem;			/* see bpf_check_limits() */
 	u64 max_cost, max_mem;
 	u64 pass_max_cost;		/* see bpf_undo_precision() */
 	bool aborted;			/* a thaw does not take it back */
+	int err;			/* the first error */
+	bool imprecise;			/* a state before the first error is imprecise */
 	bool over_limit;		/* see bpf_check_limits() */
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
 	bool guards_late;		/* see bpf_flow_loop_gets_guards() */
@@ -1531,6 +1534,8 @@ bool bpf_state_subsumes(struct bpf_verifier_env *env, struct bpf_verifier_state
 
 int bpf_renumber_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
 
+bool bpf_xreg_in_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+		      u32 fr, u32 xregno);
 /*
  * The two limits of the verifier, for the whole load. The unit of cost is one step of a scan,
  * about a dozen insns of the CPU. Memory is the bytes of states and tables at a time.
@@ -1796,6 +1801,27 @@ static inline bool type_may_be_null(u32 type)
 	return type & PTR_MAYBE_NULL;
 }
 
+/* A number, or a pointer that stands for the offsets in its range */
+static inline bool bpf_reg_has_range(const struct bpf_reg_state *reg)
+{
+	switch (base_type(reg->type)) {
+	case SCALAR_VALUE:
+	case PTR_TO_MAP_KEY:
+	case PTR_TO_MAP_VALUE:
+	case PTR_TO_STACK:
+	case PTR_TO_PACKET:
+	case PTR_TO_PACKET_META:
+	case PTR_TO_MEM:
+	case PTR_TO_BUF:
+	case PTR_TO_TP_BUFFER:
+	case PTR_TO_BTF_ID:
+	case PTR_TO_INSN:
+		return !type_may_be_null(reg->type);
+	default:
+		return false;
+	}
+}
+
 static inline void mark_reg_scratched(struct bpf_verifier_env *env, u32 regno)
 {
 	env->scratched_regs |= 1U << regno;
@@ -2079,6 +2105,7 @@ bpf_global_subprog_stack_access_bytes(struct bpf_verifier_env *env,
 int bpf_compute_subprog_arg_access(struct bpf_verifier_env *env);
 bool bpf_same_memory_origin(const struct bpf_reg_state *reg_a,
 			    const struct bpf_reg_state *reg_b);
+void bpf_blur_far_offset(struct bpf_verifier_env *env, struct bpf_reg_state *reg);
 void bpf_trim_pkt_range(struct bpf_reg_state *reg, s64 smax);
 void scalar_set_unknown(struct scalar *s);
 void scalar_set_const(struct scalar *s, u64 imm);
kernel/bpf/const_fold.c +3 -0
index 50179edbf34..61e22636ff8 100644
@@ -214,6 +214,9 @@ static void const_reg_xfer(struct bpf_verifier_env *env, struct const_arg_info *
 			ci_out[r] = unknown;
 		break;
 	}
+	/* do_check() has only a range for a far offset */
+	if (ci_is_map_value(dst) && abs((s64)dst->val) >= BPF_MAX_VAR_OFF)
+		*dst = unknown;
 }
 
 /* Join function: merge output state into a successor's input state. */
kernel/bpf/liveness.c +3 -3
index 6e6b2c6d88c..78acb620aa7 100644
@@ -596,9 +596,9 @@ bool bpf_stack_slot_alive(struct bpf_verifier_env *env, u32 frameno, u32 half_sp
  * fill a pointer, and a helper, a kfunc or a global subprog that gets a pointer to the stack reads
  * memory. Such a read keeps the bytes of the slot alive, not what the verifier knows about them.
  *
- * A short load at an offset that is known here counts as a fill: the main pass rejects it when it
- * finds a pointer. If only the main pass knows the offset, the load doesn't count. It is rejected
- * too, or it reads unknown bytes if the state was cleaned between the spill and the load.
+ * A short load at an offset that is known here counts as a fill. A NULL check can make the
+ * pointer the number 0, and the load gets a part of it. If only the main pass knows the offset,
+ * the load doesn't count.
  */
 bool bpf_stack_slot_filled(struct bpf_verifier_env *env, u32 frameno, u32 half_spi)
 {
kernel/bpf/states.c +2 -2
index 854db8ee6a2..c05dcab5216 100644
@@ -224,8 +224,8 @@ static void __clean_func_state(struct bpf_verifier_env *env,
 			/*
 			 * Only scalar spills can be degraded to raw stack bytes
 			 * when their high half is dead. Pointer spills need the
-			 * saved spilled_ptr metadata so partial fills keep
-			 * rejecting as non-scalar register fills.
+			 * saved spilled_ptr metadata: without allow_ptr_leaks
+			 * a partial fill is rejected.
 			 * The code above replaces only pointers that no insn ahead can fill.
 			 */
 			if (!hi_live) {
kernel/bpf/verifier.c +128 -54

310 lines not on this page · raw message

Signature · 1 line
2.55.0
#11 lore raw

PATCH v2 9/49 bpf: Check fixups in the main pass and keep a snapshot of them

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The main pass writes fixups for the code that rewrites the program: the type of a pointer at a load, the mask of an add, the depth of a stack. The main pass will run more than once, and a join can make a path that the program does not have:

r7, r8 = 0, 0 or 1, 5 join: r7 = 0..1, r8 = 0..5
if r7 != 0 goto out
if r8 == 0 goto out
call f only the join gets here

The next pass must not see what this path wrote. Put what a pass writes in groups: bpf_insn_fixups and bpf_env_per_pass. save_snapshot() copies them, with subprog_info, func_info_aux, the prog and fields of prog->aux. Each pass starts from the snapshot. The callers of the snapshot and of check_after_pass() come in later patches.

Some checks ran after the main pass. That is too late for another pass. Move them:

to the insn a tail call with two maps, a load of an arena
member and of something else, a missing kfunc, bpf_override_return() and a map of programs
check_after_pass() the depth of the stack, the prologue of an
extension, r12 in a callback that is called too, the slots of stack arguments

The check for room for the arguments of an arena stack entry goes away. The frame is empty at the entry, so R1-R5 wait there.

An insn has one fixup for all states. A second one is an error, see fixups_differ().

---
 include/linux/bpf_verifier.h |  56 +++++----
 kernel/bpf/fixups.c          | 102 ++--------------
 kernel/bpf/verifier.c        | 222 ++++++++++++++++++++++++++++-------
 3 files changed, 224 insertions(+), 156 deletions(-)
include/linux/bpf_verifier.h +32 -24
index 87b4e01cda2..f7c36629e1f 100644
@@ -810,6 +810,8 @@ struct bpf_loop {
 };
 
 struct bpf_insn_aux_data {
+	/* What a pass writes for the rewrite of the insn. Each pass starts from the snapshot. */
+	struct_group_tagged(bpf_insn_fixups, fixups,
 	union {
 		enum bpf_reg_type ptr_type;	/* pointer type for load/store insns */
 		struct bpf_map_ptr_state map_ptr_state;
@@ -841,13 +843,6 @@ struct bpf_insn_aux_data {
 	};
 	struct btf_struct_meta *kptr_struct_meta;
 	u64 map_key_state; /* constant (32 bit) key tracking for maps */
-	/*
-	 * Per-instruction summary of stack slots in the current frame
-	 * that this instruction may write to.
-	 */
-	DECLARE_BITMAP(may_write_mask, MAX_BPF_STACK_SLOTS);
-	DECLARE_BITMAP(live_stack_before, MAX_BPF_STACK_SLOTS);
-	u16 stack_ptrs; /* bitmask of regs that may hold a frame pointer here (arg_track) */
 	int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
 	u32 seen; /* this insn was processed by the verifier at env->pass_cnt */
 	u64 nospec:1; /* do not execute this instruction speculatively */
@@ -859,12 +854,7 @@ struct bpf_insn_aux_data {
 	u64 call_with_percpu_alloc_ptr:1; /* {this,per}_cpu_ptr() with prog percpu alloc */
 	u64 cast_arena:1; /* addr_space_cast of an address in arena */
 	u64 cast_mov:1; /* addr_space_cast of a pointer that is not in arena, it's a move */
-	u64 bb_end:1; /* last instruction of a basic block */
 	u64 loop_guard:1; /* may_goto is added in front of this instruction */
-	u64 guard_place:1; /* it's the place for may_goto if the loop needs one */
-	u64 guard_at_header:1; /* there is no better place than the head of the loop */
-	u64 guard_no_unwind:1; /* it cannot unwind from here, at least sometimes */
-	u64 guard_unset_reg:1; /* where it goes a register is read that is not set here */
 	u64 guard_edge_dropped:1; /* an edge of may_goto from here was dropped */
 	u64 alu_state:5; /* used in combination with alu_limit */
 	/* true if STX or LDX instruction is a part of a spill/fill
@@ -884,20 +874,35 @@ struct bpf_insn_aux_data {
 	u64 arena_member:1;
 	u64 arena_member_nullable:1;
 	u64 non_arena_load:1;
+	u64 indirect_target:1; /* if it is an indirect jump target */
+	u64 non_stack_access:1; /* instruction can access non-stack memory */
+	);
+
+	/* what one pass gives to the next pass, see bpf_flow_new_pass() */
+	u32 guard_no_unwind:1; /* it cannot unwind from here, at least sometimes */
+	u32 guard_unset_reg:1; /* where it goes a register is read that is not set here */
 
 	/* below flags are initialized once */
+	u32 bb_end:1; /* last instruction of a basic block */
+	u32 guard_place:1; /* it is the place for may_goto if the loop needs one */
+	u32 guard_at_header:1; /* there is no better place than the header of the loop */
 	/* true if instruction is a call to a helper function that
 	 * accepts callback function as a parameter.
 	 */
-	u64 calls_callback:1;
-	u64 indirect_target:1; /* if it is an indirect jump target */
-	u64 non_stack_access:1; /* instruction can access non-stack memory */
+	u32 calls_callback:1;
 	/* true if some jump or call instruction targets this instruction */
-	u64 jump_target:1;
+	u32 jump_target:1;
 	/* it can read or write the frame of a caller, in a call with a known callee */
 	u32 reads_outer:1;
 	u32 writes_outer:1;
+	/*
+	 * Per-instruction summary of stack slots in the current frame
+	 * that this instruction may write, may read, and that are live before it.
+	 */
+	DECLARE_BITMAP(may_write_mask, MAX_BPF_STACK_SLOTS);
 	DECLARE_BITMAP(may_read_mask, MAX_BPF_STACK_SLOTS);
+	DECLARE_BITMAP(live_stack_before, MAX_BPF_STACK_SLOTS);
+	u16 stack_ptrs; /* bitmask of regs that may hold a frame pointer here (arg_track) */
 
 	unsigned int orig_idx; /* original instruction index, initialized once */
 	/* registers alive before this instruction. */
@@ -1232,13 +1237,23 @@ struct bpf_verifier_env {
 	u64 max_cost, max_mem;
 	u64 pass_max_cost;		/* see bpf_undo_precision() */
 	bool aborted;			/* a thaw does not take it back */
+	/* What a pass writes. Each pass starts from the snapshot. */
+	struct_group_tagged(bpf_env_per_pass, per_pass,
 	int err;			/* the first error */
 	bool imprecise;			/* a state before the first error is imprecise */
 	bool over_limit;		/* see bpf_check_limits() */
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
 	bool guards_late;		/* see bpf_flow_loop_gets_guards() */
-	u32 loop_entry_cnt;		/* see loop_stack_entry.entry_id, callback_entry_id */
+	bool seen_direct_write;
+	/* a register may point to the stack and is not PTR_TO_STACK, see bpf_reg_state::buf */
+	bool seen_stack_slice;
+	bool seen_exception;
+	bool sleepable_async_cb;
+	u32 id_gen;			/* used to generate unique reg IDs */
+	u32 max_stack_depth;		/* maximum combined stack depth */
 	u32 max_arena_stack_depth;	/* of all call chains */
+	u32 loop_entry_cnt;		/* see loop_stack_entry.entry_id */
+	);
 	struct bpf_verifier_state *cur_state; /* current verifier state */
 	struct bpf_map **used_maps;	/* array of map's used by eBPF program */
 	struct btf_mod_pair *used_btfs;	/* array of BTF's used by BPF program */
@@ -1250,7 +1265,6 @@ struct bpf_verifier_env {
 	u32 used_map_cnt;		/* number of used maps */
 	u32 used_btf_cnt;		/* number of used BTF objects */
 	u32 insn_array_map_cnt;		/* number of used maps of type BPF_MAP_TYPE_INSN_ARRAY */
-	u32 id_gen;			/* used to generate unique reg IDs */
 	u32 hidden_subprog_cnt;		/* number of hidden subprogs */
 	int exception_callback_subprog;
 	bool explore_alu_limits;
@@ -1263,12 +1277,8 @@ struct bpf_verifier_env {
 	bool bpf_capable;
 	bool bypass_spec_v1;
 	bool bypass_spec_v4;
-	bool seen_direct_write;
-	/* a register may point to the stack and is not PTR_TO_STACK, see bpf_reg_state::buf */
-	bool seen_stack_slice;
 	/* a global function is verified for BPF_FUNC_CTX_NO_RCU_LOCK */
 	bool no_rcu_read_lock;
-	bool seen_exception;
 	bool signature;
 	u32 insn_aux_data_len;
 	struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */
@@ -1319,8 +1329,6 @@ struct bpf_verifier_env {
 	u32 subprog_cnt;
 	/* number of instructions analyzed by the verifier */
 	u32 insn_processed;
-	/* maximum combined stack depth */
-	u32 max_stack_depth;
 	/* stack budget of the program, see bpf_prog_stack_limit() */
 	u32 stack_limit;
 	/* total verification time */
kernel/bpf/fixups.c +12 -90

195 lines not on this page · raw message

kernel/bpf/verifier.c +180 -42

342 lines not on this page · raw message

Signature · 1 line
2.55.0
#12 lore raw

PATCH v2 10/49 bpf: Reject a program with a call that needs two rewrites

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Some calls are rewritten with a number and with the special fields of a type: bpf_obj_new(), bpf_obj_drop(), bpf_refcount_acquire(), list push, rbtree add, per_cpu_ptr(). One state sets them for all states. That is wrong if another state has another type:

if (...) p = a; else p = b; a has a kptr, b has none
bpf_obj_drop(p); one btf_struct_meta for both

With the fields of b, the drop of a leaks the kptr. With the fields of a, the drop of b frees a kptr that is not there.

record_call_fixup() notes the number and the fields of the first state. It fails if another state has other ones. Two types with equal fields can share a call, see btf_record_equal(). bpf_refcount_acquire() reads only the offset of the refcount, so only that has to be equal.

This rejects programs that load today. A compiler can make one call of two calls in the source. The fix is __attribute__((nomerge)) on the declaration of the function. A static function can get two types from its callers. The fix is to inline it. The log says so.

---
 include/linux/bpf_verifier.h |  5 ++-
 kernel/bpf/verifier.c        | 73 ++++++++++++++++++++++++++----------
 2 files changed, 58 insertions(+), 20 deletions(-)
include/linux/bpf_verifier.h +4 -1
index f7c36629e1f..eb05063c6d8 100644
@@ -840,6 +840,9 @@ struct bpf_insn_aux_data {
 		u64 obj_new_size;
 		/* remember the offset of node field within type to rewrite */
 		u64 insert_off;
+		/* {this,per}_cpu_ptr() with prog percpu alloc */
+		u64 call_with_percpu_alloc_ptr;
+		u64 call_num;	/* any of these, or the offset of a refcount */
 	};
 	struct btf_struct_meta *kptr_struct_meta;
 	u64 map_key_state; /* constant (32 bit) key tracking for maps */
@@ -851,10 +854,10 @@ struct bpf_insn_aux_data {
 	u64 needs_zext:1; /* alu op needs to clear upper bits */
 	u64 prevent_zext:1; /* alu op cannot be zext (already used with 64-bit scalars) */
 	u64 non_sleepable:1; /* helper/kfunc may be called from non-sleepable context */
-	u64 call_with_percpu_alloc_ptr:1; /* {this,per}_cpu_ptr() with prog percpu alloc */
 	u64 cast_arena:1; /* addr_space_cast of an address in arena */
 	u64 cast_mov:1; /* addr_space_cast of a pointer that is not in arena, it's a move */
 	u64 loop_guard:1; /* may_goto is added in front of this instruction */
+	u64 call_recorded:1; /* see record_call_fixup() */
 	u64 guard_edge_dropped:1; /* an edge of may_goto from here was dropped */
 	u64 alu_state:5; /* used in combination with alu_limit */
 	/* true if STX or LDX instruction is a part of a spill/fill
kernel/bpf/verifier.c +54 -19

141 lines not on this page · raw message

Signature · 1 line
2.55.0
#13 lore raw

PATCH v2 11/49 bpf: Put a barrier where no mask fits

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Without bypass_spec_v1 the offset of 'ptr += reg' is masked. The program is rejected if two paths need two masks, or if no mask is possible. To find such paths, explore_alu_limits keeps all states with other numbers apart. That cannot work in a pass that joins all states.

Allow the insn and put a barrier before it. A mask fits if it passes the largest offset that was checked, and no larger one:

offset 2 or 3, joined to 2..3 mask passes 0..3
two masks, mixed signs, pointer to a packet barrier

A stack pointer with a variable offset is still rejected.

An error in a speculative state is no error. The insn gets a barrier and the path ends, see nospec_ends_path(). What the state noted at the insn is dropped. The barrier has to stop each edge that leads there:

  fall-through, jump, call, return     barrier before the insn
  exit of a callback --> helper        barrier at the exit
  may_goto --> r0 = 0; exit            barrier before r0 = 0
  call --> recursion in frames         barrier at the call
  return --> dead code                 'goto -1' replaces the code

That 'goto -1' takes no zext_dst from the insn that it replaces. A jump that is dead itself is not hard-wired: it is removed later, and the driver of an offloaded program refuses a new target.

A speculative state starts no async callback, and it asks for no slot of a stack argument.

This also fixes two bugs of the old code:
- If many insns replace an insn, the barrier has to go before the first one. In an inlined bpf_loop() it was before the last one, after the callback.
- A speculative path ends after a store to the stack, because a barrier follows the store. It also ended after other writes to the stack: an atomic, a call, a fastcall spill that is removed. No barrier follows them, and the code after them was not checked. Now the path continues.

explore_alu_limits and the REASON_* errors go away. Some unprivileged programs load now.

Rename push_budget_exit() to push_unwind_exit(): the way to stop is 'r0 = 0; unwind_exit'. budget_exit_insn() becomes emit_unwind_exit(), and budget_can_unwind() becomes state_can_unwind(). In the next patches a budget is a limit on the work of the verifier. bpf_insert_loop_guards() uses emit_unwind_exit() too. A later patch sets guard_unwinds. pass_cnt counts the calls of do_check(): rename it to check_cnt.

---
 include/linux/bpf_verifier.h |   7 +-
 kernel/bpf/const_fold.c      |   2 +-
 kernel/bpf/fixups.c          |  97 +++++++++--------
 kernel/bpf/liveness.c        |   2 +-
 kernel/bpf/verifier.c        | 205 +++++++++++++++++------------------
 5 files changed, 157 insertions(+), 156 deletions(-)
include/linux/bpf_verifier.h +4 -3
index eb05063c6d8..63c75a68c99 100644
@@ -847,7 +847,7 @@ struct bpf_insn_aux_data {
 	struct btf_struct_meta *kptr_struct_meta;
 	u64 map_key_state; /* constant (32 bit) key tracking for maps */
 	int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
-	u32 seen; /* this insn was processed by the verifier at env->pass_cnt */
+	u32 seen; /* this insn was processed by the verifier at env->check_cnt */
 	u64 nospec:1; /* do not execute this instruction speculatively */
 	u64 nospec_result:1; /* result is unsafe under speculation, nospec must follow */
 	u64 zext_dst:1; /* this insn zero extends dst reg */
@@ -857,6 +857,7 @@ struct bpf_insn_aux_data {
 	u64 cast_arena:1; /* addr_space_cast of an address in arena */
 	u64 cast_mov:1; /* addr_space_cast of a pointer that is not in arena, it's a move */
 	u64 loop_guard:1; /* may_goto is added in front of this instruction */
+	u64 guard_unwinds:1; /* it leaves the subprog */
 	u64 call_recorded:1; /* see record_call_fixup() */
 	u64 guard_edge_dropped:1; /* an edge of may_goto from here was dropped */
 	u64 alu_state:5; /* used in combination with alu_limit */
@@ -1270,7 +1271,6 @@ struct bpf_verifier_env {
 	u32 insn_array_map_cnt;		/* number of used maps of type BPF_MAP_TYPE_INSN_ARRAY */
 	u32 hidden_subprog_cnt;		/* number of hidden subprogs */
 	int exception_callback_subprog;
-	bool explore_alu_limits;
 	bool allow_ptr_leaks;
 	/* Allow access to uninitialized stack memory. Writes with fixed offset are
 	 * always allowed, so this refers to reads (with fixed or variable offset),
@@ -1283,6 +1283,7 @@ struct bpf_verifier_env {
 	/* a global function is verified for BPF_FUNC_CTX_NO_RCU_LOCK */
 	bool no_rcu_read_lock;
 	bool signature;
+	u8 bug:1;			/* ends the load, see bpf_note_bug() */
 	u32 insn_aux_data_len;
 	struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */
 	struct bpf_patch_list patch_list;
@@ -1328,7 +1329,7 @@ struct bpf_verifier_env {
 	} cfg;
 	/* Per-callsite snapshot of the parent's tracked spill slots for cross-frame fills. */
 	struct spill_snapshot **callsite_at_stack;
-	u32 pass_cnt; /* number of times do_check() was called */
+	u32 check_cnt; /* number of times do_check() was called */
 	u32 subprog_cnt;
 	/* number of instructions analyzed by the verifier */
 	u32 insn_processed;
kernel/bpf/const_fold.c +1 -1
index 61e22636ff8..3310a55afa3 100644
@@ -269,7 +269,7 @@ int bpf_compute_const_regs(struct bpf_verifier_env *env)
 			ci_in[start][r] = unknown;
 		/*
 		 * The subprog gets there from where it is out of budget too, see
-		 * push_budget_exit(). That is not an edge of the graph.
+		 * push_unwind_exit(). That is not an edge of the graph.
 		 */
 		for (r = 0; r < MAX_BPF_REG && env->subprog_info[i].bail_insn >= 0; r++)
 			ci_in[env->subprog_info[i].bail_insn][r] = unknown;
kernel/bpf/fixups.c +50 -47

169 lines not on this page · raw message

kernel/bpf/liveness.c +1 -1
index 78acb620aa7..4cc29334a69 100644
@@ -2975,7 +2975,7 @@ int bpf_compute_live_registers(struct bpf_verifier_env *env)
 		 */
 		insn_aux[i].zext_dst = def32 >= 0 && (mask_hi(out) & BIT(def32));
 	}
-	/* the exit that stands for 'r0 = 0; exit' may be dead code, see push_budget_exit() */
+	/* the exit that stands for 'r0 = 0; exit' may be dead code, see push_unwind_exit() */
 	for (i = 0; i < env->subprog_cnt; i++)
 		if (env->subprog_info[i].bail_insn >= 0)
 			insn_aux[env->subprog_info[i].bail_insn].live_regs_before |=
kernel/bpf/verifier.c +101 -104

410 lines not on this page · raw message

Signature · 1 line
2.55.0
#14 lore raw

PATCH v2 12/49 bpf: Keep more of what is known about a number

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Six transfer functions lose what is known. Scalar evolution hid a part of that: it had expressions for extensions and for partial spills. Fix the functions.

1. An AND that clears no bit is a move: the old ranges hold too. If the AND splits the state, the step goes away, and a part that has no value gets only the new ranges.

     r0 = 1..16; w0 &= 255             was 0..16, now 1..16

2. A sign extension does not change the low bits. The other bits are copies of the sign. If the low 32 bits fit, they give the range.

     w6 = -100..100; r7 = (s32)r6      was any s32, now -100..100

3. A fill can be larger than the spill. On little endian the low bytes are from the spill.

     *(u32 *)(r10 - 8) = 5; r1 = *(u64 *)(r10 - 8)      w1 is 5

4. A write above the low bytes of a spill does not change them. Keep them as a narrow spill. Zero bytes next to it stay zero.

     struct { u32 i; u32 flag; } s; s.i = r6; s.flag = 1;

5. A range that crosses S64_MAX has no signed bounds. A later patch makes such ranges. The known bits can have signed bounds, so a signed shift takes the tighter ones.

     r7 = 0..0xf0 << 56; r7 s>>= 56    -128..112, not -128..127

6. A number can have a step: 0, 12, 24, ... The known bits tell only a power of two. A later patch counts a loop by the distance of the counter to its bound:

     for (i = 12 * a; i != 12 * b; i += 12)

     distance = i - 12 * b     ..., -24, -12, 0
     distance != 0             ..., -24, -12     with the step
                               ..., -2, -1       without it

Without the step, 'i += 12' goes past the bound. Keep it:

     -3 * (3 * a + 1)          step 9: a negative factor
     3 * a + 6 * b             step 3: the gcd of the two steps
     step 3 and step 6         step 6: one is a multiple of the other

As before, a result that can wrap has no step.

---
 include/linux/bpf_verifier.h |   1 +
 kernel/bpf/verifier.c        | 142 +++++++++++++++++++++++------------
 2 files changed, 94 insertions(+), 49 deletions(-)
include/linux/bpf_verifier.h +1 -0
index 63c75a68c99..2efb9d61501 100644
@@ -2121,6 +2121,7 @@ void bpf_blur_far_offset(struct bpf_verifier_env *env, struct bpf_reg_state *reg
 void bpf_trim_pkt_range(struct bpf_reg_state *reg, s64 smax);
 void scalar_set_unknown(struct scalar *s);
 void scalar_set_const(struct scalar *s, u64 imm);
+void scalar_step_scale(struct scalar *dst, s64 amount);
 void scalar_add(struct scalar *dst, const struct scalar *a, const struct scalar *b);
 void scalar_alu(struct scalar *dst, const struct scalar *src, const struct bpf_insn *insn);
 bool scalar_intersect(struct scalar *dst, const struct scalar *src, u32 bits);
kernel/bpf/verifier.c +93 -49

313 lines not on this page · raw message

Signature · 1 line
2.55.0
#15 lore raw

PATCH v2 13/49 bpf: Remember how many bytes of a packet are checked

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The range of a packet pointer is lost when the number that is added can be negative:

if (data + 54 > data_end) return;

  p = data + 20;       range 54
  p += -4..4;          range 0
  *p                   fails, but the offset is 16..24

The check of 54 bytes holds for the packet, wherever the pointer goes. Keep that number in pkt_min_len. If the largest offset of the pointer is below pkt_min_len, the range is at least pkt_min_len.

A join takes the smaller number. A state with the larger number does not subsume a state with the smaller number. The join rule does not look at the number: each trip of a scan loop checks one byte more, so all exits of the loop would stay apart.

Equations will let a jump refine a pointer that has any offset, and they bring a far pointer back:

  r9 = data + r2                  r2 is 0..255, 8 bytes are checked
  r8 = r9 + 0x7fffffffffffffc0    the largest offset wraps
  if r2 > 100 goto out            refines r2, r9 and r8
  r8 -= 0x7fffffffffffffc0        r8 is r9 again

An earlier patch has the rule for that: an id and a range hold only within BPF_MAX_VAR_OFF of the start. So r8 has no range, and pointers with one id are all near, or they are copies of one far pointer.

smax can go from S64_MAX to -3, and the difference does not fit in s64. bpf_trim_pkt_range() computes it in u64.

---
 include/linux/bpf_verifier.h | 11 ++++++++++-
 kernel/bpf/log.c             |  2 ++
 kernel/bpf/verifier.c        | 31 ++++++++++++++++++++-----------
 3 files changed, 32 insertions(+), 12 deletions(-)
include/linux/bpf_verifier.h +10 -1
index 2efb9d61501..f110909413b 100644
@@ -117,7 +117,10 @@ struct bpf_reg_state {
 	u32 id;
 	union {
 		/* valid when type == PTR_TO_PACKET */
-		int range;
+		struct {
+			int range;
+			int pkt_min_len;	/* see pkt_min_len() */
+		};
 		/*
 		 * Valid when type == PTR_TO_STACK. Inside the callee two registers
 		 * can be both PTR_TO_STACK like R1=fp-8 and R2=fp-8, but one of them
@@ -2270,6 +2273,12 @@ int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx);
 bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header);
 
 
+/* How many bytes are checked from the start of the packet, wherever the pointer is */
+static inline int pkt_min_len(const struct bpf_reg_state *reg)
+{
+	return reg->r64.size ? reg->pkt_min_len : max(reg->range, reg->pkt_min_len);
+}
+
 static inline u32 bpf_xreg_cnt(const struct bpf_verifier_state *st)
 {
 	u32 fr, nr = 0;
kernel/bpf/log.c +2 -0
index e58202955f1..0d381e31421 100644
@@ -666,6 +666,8 @@ static void print_reg_state(struct bpf_verifier_env *env,
 	if (type_is_pkt_pointer(t)) {
 		verbose_a("r=");
 		verbose_unum(env, reg->range);
+		if (pkt_min_len(reg) && pkt_min_len(reg) != reg->range)
+			verbose_a("min_len=%d", pkt_min_len(reg));
 	}
 	if (base_type(t) == PTR_TO_MEM) {
 		verbose_a("sz=");
kernel/bpf/verifier.c +20 -11
index d67f6d6780b..8d90ed783d0 100644
@@ -16524,7 +16524,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn
 	u8 opcode = BPF_OP(insn->code);
 	u32 dst = insn->dst_reg;
 	const char *reason;
-	int ret, bounds_ret;
+	int ret, bounds_ret, min_len;
 	bool to_scalar;
 	s64 smax;
 
@@ -16655,6 +16655,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn
 	 * constraints violations.
 	 */
 	__mark_scalar32_unbounded(scalar_of(dst_reg));
+	min_len = pkt_min_len(ptr_reg);
 
 	switch (opcode) {
 	case BPF_ADD:
@@ -16684,7 +16685,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn
 			 */
 			if (dst_reg->range < 0 ||
 			    (!known && (smin_val < 0 || reg_umax(dst_reg) >= dst_reg->range)))
-				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
+				dst_reg->range = 0;
 		}
 		break;
 	case BPF_SUB:
@@ -16730,7 +16731,7 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn
 			 * prior comparison as arithmetic invalidates them.
 			 */
 			if ((!known && smin_val < 0) || dst_reg->range < 0)
-				memset(&dst_reg->raw, 0, sizeof(dst_reg->raw));
+				dst_reg->range = 0;
 		}
 		scalar_step_reset(scalar_of(dst_reg));
 		break;
@@ -16770,14 +16771,15 @@ static int adjust_ptr_min_max_vals(struct bpf_verifier_env *env, struct bpf_insn
 	 * step tell about it (alignment, umin). No other pointer has its id, so
 	 * it is enough that its range loses what its umax loses.
 	 */
+	smax = reg_smax(dst_reg);
 	if (reg_is_pkt_pointer(dst_reg) &&
-	    (known || (opcode == BPF_SUB && dst_reg->range > 0))) {
+	    (known || (opcode == BPF_SUB && dst_reg->range > 0)))
 		__update_scalar32_bounds(scalar_of(dst_reg));
-	} else {
-		smax = reg_smax(dst_reg);
+	else
 		reg_bounds_sync(dst_reg);
-		bpf_trim_pkt_range(dst_reg, smax);
-	}
+	if (reg_is_pkt_pointer(dst_reg))
+		dst_reg->pkt_min_len = min_len;
+	bpf_trim_pkt_range(dst_reg, smax);
 	bpf_blur_far_offset(env, dst_reg);
 	bounds_ret = sanitize_check_bounds(env, insn, dst_reg);
 	if (bounds_ret == -EACCES)
@@ -17883,12 +17885,19 @@ bool bpf_same_memory_origin(const struct bpf_reg_state *reg_a,
  * 'range - smax' bytes from a packet pointer are in the packet. reg_bounds_sync() can make smax
  * smaller than @smax: with a step of 8, or with 3 zero bits in var_off, 58 becomes 56. Make the
  * range smaller by the same number, so that the number of bytes does not grow. umax is not
- * sufficient: it is U64_MAX when the offset can be negative.
+ * sufficient: it is U64_MAX when the offset can be negative. A jump can take smax from S64_MAX
+ * to -3: the difference does not fit in s64. If smax is larger than @smax the range is lost.
+ * If smax is below pkt_min_len, the range is at least pkt_min_len.
  */
 void bpf_trim_pkt_range(struct bpf_reg_state *reg, s64 smax)
 {
-	if (type_is_pkt_pointer(reg->type) && reg->range > 0)
-		reg->range = max_t(s64, reg->range - (smax - reg_smax(reg)), 0);
+	u64 lost = (u64)smax - reg_smax(reg);
+
+	if (!type_is_pkt_pointer(reg->type) || reg->range < 0)
+		return;
+	reg->range = lost < reg->range ? reg->range - lost : 0;
+	if (reg->pkt_min_len > reg_smax(reg))
+		reg->range = max(reg->range, reg->pkt_min_len);
 }
 
 /*
Signature · 1 line
2.55.0
#16 lore raw

PATCH v2 14/49 bpf: Mark a state that no run of the program has

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A jump can leave an xreg without a value: the ranges and the known bits have no number in common. No run of the program has such a state.

jump -> range is empty -> infeasible -> a pass: continues
a run without joins: drops it

---
 include/linux/bpf_verifier.h | 2 ++
 kernel/bpf/verifier.c        | 7 ++++++-
 2 files changed, 8 insertions(+), 1 deletion(-)
include/linux/bpf_verifier.h +2 -0
index f110909413b..8b8f999de26 100644
@@ -560,6 +560,8 @@ struct bpf_verifier_state {
 	struct bpf_reference_state *refs;
 	u32 insn_idx;
 	u32 curframe;
+	/* an xreg has no value: unreachable. Only a path-sensitive run drops such a state. */
+	bool infeasible;
 
 	struct_group(held,
 	void *active_lock_ptr;
kernel/bpf/verifier.c +6 -1
index 8d90ed783d0..3c027b19551 100644
@@ -1808,6 +1808,7 @@ int bpf_copy_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_st
 	dst_state->unwound = src->unwound;
 	dst_state->changed_pkt_data = src->changed_pkt_data;
 	dst_state->flow_entry = src->flow_entry;
+	dst_state->infeasible = src->infeasible;
 	dst_state->insn_idx = src->insn_idx;
 	dst_state->curframe = src->curframe;
 	dst_state->last_insn_idx = src->last_insn_idx;
@@ -2437,6 +2438,7 @@ static int reg_bounds_sanity_check(struct bpf_verifier_env *env,
 		reg->base, reg->step);
 	if (env->test_reg_invariants)
 		return -EFAULT;
+	env->cur_state->infeasible = true;
 	__mark_scalar_unbounded(s);
 	scalar_step_reset(s);
 	return 0;
@@ -19013,6 +19015,7 @@ static int refine_live_branch(struct bpf_verifier_env *env, struct bpf_insn *ins
 			      struct bpf_reg_state *reg1, struct bpf_reg_state *reg2)
 {
 	struct bpf_reg_state *regs = cur_regs(env);
+	bool empty;
 	int err;
 
 	/* is_branch_taken() knew the branch before it refined anything */
@@ -19023,7 +19026,9 @@ static int refine_live_branch(struct bpf_verifier_env *env, struct bpf_insn *ins
 	 * The fall-through branch of JSET forgets the ranges. Or this branch is dead too: the path
 	 * is infeasible. The registers are left as they are.
 	 */
-	if (BPF_OP(insn->code) == BPF_JSET || reg_is_empty(reg1) || reg_is_empty(reg2))
+	empty = reg_is_empty(reg1) || reg_is_empty(reg2);
+	env->cur_state->infeasible |= empty;
+	if (BPF_OP(insn->code) == BPF_JSET || empty)
 		return 0;
 	err = reg_bounds_sanity_check(env, reg1, "live_reg1");
 	err = err ?: reg_bounds_sanity_check(env, reg2, "live_reg2");
Signature · 1 line
2.55.0
#17 lore raw

PATCH v2 15/49 bpf: Peel the first trips of a loop and join the other trips

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A loop can be verified trip by trip, or with one state for all trips. The first way is precise and too long for a long loop. The second way is short and loses what differs between trips:

char buf[64]; off = 255; ok = 0; trip 0 is different
for (...) { if (ok) buf[off] = 0; off = x & 63; ok = 1; }

Use both. A loop has peeled trips and a leftover:

entry -> [0] -> [1] -> ... -> [d-1] -> +----------+ <--+

           peeled trips, kept apart      | LEFTOVER |    |
                                         |  widened |----+
                                         +----------+

Pass 0 peels nothing. A later pass peels if an error asks for it, see try_peel_trip(). bpf_flow_loop_enter() keeps the loop stack of a frame.

The calls of a callback and recursive calls go around like the body of a loop. One struct bpf_loop describes the three:

  kind                 header
  BPF_LOOP_JUMPS       the target of the back edge
  BPF_LOOP_CALLBACK    the call of the helper
  BPF_LOOP_RECURSION   the start of the first function of the cycle

What is held has no join. A loop that acquires in each trip makes new states without end. check_held_in_leftover() stops it: a reference that is in no xreg is a leak, and the peeled trips limit the locks.

check_loop_guard() still reads the old members of loop_stack_entry. They go away with "bpf: Give a loop a checked trip count or may_goto". Later patches also start the leftover at a back edge, note the error of check_held_in_leftover() and leave the loop of a callback.

The log has the innermost loop. Level 2 has all loops for each block.

---
 include/linux/bpf_verifier.h |  80 ++++++++-
 kernel/bpf/fixups.c          |  15 +-
 kernel/bpf/flow.c            |  17 ++
 kernel/bpf/log.c             |  18 +-
 kernel/bpf/loops.c           |   1 +
 kernel/bpf/verifier.c        | 316 ++++++++++++++++++++++++++++++++---
 6 files changed, 411 insertions(+), 36 deletions(-)
include/linux/bpf_verifier.h +75 -5
index 8b8f999de26..b15dc67f0bf 100644
@@ -93,6 +93,8 @@ struct scalar {
 	 */
 	u16 base;
 	u16 step;
+	/* Not a part of the value: it grew once at a loop header, see join_range() */
+	bool grew_once;
 };
 
 /* The struct scalar that is an anonymous member of *@p */
@@ -427,7 +429,16 @@ enum bpf_guard_edge {
 	BPF_GUARD_LEAVES_LOOP,
 };
 
+/*
+ * A state in a loop, see bpf_flow_loop_enter()
+ *
+ * entry -> [0] -> [1] -> ... -> [d-1] -> +----------+ <--+
+ *          peeled trips, kept apart      | LEFTOVER |    |
+ *                                        |  widened |----+
+ *                                        +----------+
+ */
 struct loop_stack_entry {
+	struct bpf_loop *loop;
 	u32 loop_id:23;
 	u32 terminates:1;
 	/* the loop had may_goto when the state entered it, see check_loop_guard() */
@@ -444,12 +455,12 @@ struct loop_stack_entry {
 	 * to the head is made to stand for the rest.
 	 */
 	u32 first:1;
-	/*
-	 * How many times the state came back to the head of the loop. With @apart that is
-	 * the iteration that it is in. A state that stands for many iterations is a join, and has
-	 * the largest number of the states that it is made of.
-	 */
+	/* How many times the state came back to the header. A join has the larger number. */
 	u32 trip;
+	/* The state that entered the loop. What comes back to the header is for that state. */
+	u32 entry_id;
+	u32 held_cnt;		/* when the state entered the loop */
+	bool peeled;		/* in a peeled trip, not in the leftover */
 };
 
 /* The state is in a walk on patience, which may not get to the end of the loop */
@@ -562,6 +573,11 @@ struct bpf_verifier_state {
 	u32 curframe;
 	/* an xreg has no value: unreachable. Only a path-sensitive run drops such a state. */
 	bool infeasible;
+	/* an error only in a leftover, see check_held_in_leftover() */
+	bool holds_too_much;
+	u32 max_held_cnt;	/* when it first held too much */
+	/* the loops that made an xreg of data_deps imprecise, see bpf_loop.suspect_bit */
+	u64 suspect_loops;
 
 	struct_group(held,
 	void *active_lock_ptr;
@@ -792,6 +808,23 @@ struct bpf_backedge {
 	int latch;
 };
 
+/* Calls of a callback and recursive calls go around like the body of a loop does */
+enum bpf_loop_kind {
+	BPF_LOOP_JUMPS,
+	BPF_LOOP_CALLBACK,	/* the header is the call of the helper */
+	/* the header is the first insn of the first function of the cycle */
+	BPF_LOOP_RECURSION,
+};
+
+/* What a pass finds about a loop */
+struct bpf_loop_per_pass {
+	bool has_leftover;	/* the peeled trips were not enough */
+	/* a check failed in a state that the loop kept apart, with no other suspect */
+	bool has_unproven;
+	u32 peeled_cnt;		/* trips that the pass peeled */
+	u64 cost;		/* for the states that the loop keeps apart */
+};
+
 struct bpf_loop_rungs {
 	s64 max[2];
 	s64 min[2];
@@ -800,6 +833,10 @@ struct bpf_loop_rungs {
 };
 
 struct bpf_loop {
+	enum bpf_loop_kind kind;
+	u32 header;
+	/* in bpf_verifier_state.suspect_loops. Loops with the same bit are suspects together. */
+	u64 suspect_bit;
 	struct bpf_backedge backedges[MAX_BACKEDGES];
 	int exit_to;		/* where the first edge that leaves the loop goes, or -1 */
 	int backedges_cnt;
@@ -811,9 +848,30 @@ struct bpf_loop {
 	u32 nr_insns;
 	/* not rt_bounded: there are places for may_goto, see guard_to in bpf_insn_aux_data */
 	bool has_guards;
+
+	/* What one pass gives to the next pass */
+	struct_group_tagged(bpf_loop_precision, precision,
+	u32 peel_cnt;		/* trips before the leftover */
+	/* while bpf_loop_per_pass.cost is not above @budget: */
+	u64 budget;
+	u32 max_peel_cnt;	/* peel up to this trip */
+	);
+	bool partitioned;	/* the last partition was for this loop */
+	struct bpf_loop_per_pass this_pass;
 	bool guarded;
 };
 
+static inline bool bpf_loop_has_budget(const struct bpf_loop *loop)
+{
+	return loop->this_pass.cost <= loop->budget;
+}
+
+/* A partition for a loop ends when a state that it kept apart is unproven */
+static inline bool bpf_loop_partition_is_active(const struct bpf_loop *loop)
+{
+	return bpf_loop_has_budget(loop) && !(loop->partitioned && loop->this_pass.has_unproven);
+}
+
 struct bpf_insn_aux_data {
 	/* What a pass writes for the rewrite of the insn. Each pass starts from the snapshot. */
 	struct_group_tagged(bpf_insn_fixups, fixups,
@@ -947,6 +1005,8 @@ struct bpf_insn_aux_data {
 	s32 guard_to;
 	/* additional information about the loop if this instruction is a loop header */
 	struct bpf_loop *loop;
+	/* the call of a callback, or the first insn of a recursive function */
+	struct bpf_loop *callback_loop, *recursion_loop;
 };
 
 /*
@@ -1043,6 +1103,7 @@ struct bpf_subprog_info {
 	u16 stack_depth; /* max. stack depth used by this function */
 	u16 stack_extra;
 	u16 arena_stack_depth; /* size of the frame in the stack in arena */
+	u32 cycle; /* the first subprog of its cycle of the call graph, 0 if it is on none */
 	u32 insns_total;
 	u32 insns_self;
 	/* offsets in range [stack_depth .. fastcall_stack_off)
@@ -1597,6 +1658,9 @@ void bpf_flow_next_is_no_bound(struct bpf_verifier_env *env, int insn_idx, int h
 bool bpf_flow_loops_lost_bound(struct bpf_verifier_env *env);
 void bpf_flow_new_round(struct bpf_verifier_env *env);
 int bpf_flow_place_guards(struct bpf_verifier_env *env);
+/* verifier.c, for flow.c */
+int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge_loop,
+			bool *starts_leftover);
 #define BPF_EXIT_NEEDS_CALLER	1	/* verify the call in the frames of the caller */
 int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,
 		    const struct bpf_verifier_state *exit, int call_idx);
@@ -2281,6 +2345,12 @@ static inline int pkt_min_len(const struct bpf_reg_state *reg)
 	return reg->r64.size ? reg->pkt_min_len : max(reg->range, reg->pkt_min_len);
 }
 
+/* The loop that the frame is in, or NULL */
+static inline struct loop_stack_entry *bpf_top_loop(const struct bpf_func_state *frame)
+{
+	return frame->loop_stack_cnt ? &frame->loop_stack[frame->loop_stack_cnt - 1] : NULL;
+}
+
 static inline u32 bpf_xreg_cnt(const struct bpf_verifier_state *st)
 {
 	u32 fr, nr = 0;
kernel/bpf/fixups.c +11 -4
index 3be90ed308c..2fa6065b0d9 100644
@@ -749,6 +749,13 @@ int bpf_insert_recursion_checks(struct bpf_verifier_env *env)
 	return 0;
 }
 
+static void free_loop(struct bpf_loop *loop)
+{
+	if (!loop)
+		return;
+	kvfree(loop);
+}
+
 /* Clean up dynamically allocated fields of aux data for instructions [start, ...] */
 void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
 {
@@ -757,10 +764,10 @@ void bpf_clear_insn_aux_data(struct bpf_verifier_env *env, int start, int len)
 	int i;
 
 	for (i = start; i < end; i++) {
-		if (aux_data[i].loop) {
-			kvfree(aux_data[i].loop);
-			aux_data[i].loop = NULL;
-		}
+		free_loop(aux_data[i].loop);
+		free_loop(aux_data[i].callback_loop);
+		free_loop(aux_data[i].recursion_loop);
+		aux_data[i].loop = aux_data[i].callback_loop = aux_data[i].recursion_loop = NULL;
 	}
 }
 
kernel/bpf/flow.c +17 -0
index 5a04cf19805..5d86792025f 100644
@@ -316,3 +316,20 @@ int bpf_check_limits(struct bpf_verifier_env *env)
 	env->over_limit = true;
 	return -E2BIG;
 }
+
+static struct bpf_loop *flow_new_call_loop(struct bpf_verifier_env *env, enum bpf_loop_kind kind,
+					   int header, int func)
+{
+	struct bpf_loop *loop = kvzalloc_obj(*loop, BPF_VERIFIER_GFP);
+
+	env->mem += sizeof(*loop);
+	if (!loop)
+		return NULL;
+	loop->kind = kind;
+	loop->header = header;
+	/* the helper stops, the function checks the stack, see check_recursion_guard() */
+	loop->rt_bounded = true;
+	loop->nr_insns = func < 0 ? 1 :
+			 env->subprog_info[func + 1].start - env->subprog_info[func].start;
+	return loop;
+}
kernel/bpf/log.c +11 -7
index 0d381e31421..7b1390d9054 100644
@@ -702,7 +702,7 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie
 {
 	const struct bpf_func_state *state = vstate->frame[frameno];
 	const struct bpf_reg_state *reg;
-	int i;
+	int i, first;
 
 	if (state->frameno)
 		verbose(env, " frame%d:", state->frameno);
@@ -789,15 +789,19 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie
 		verbose(env, " cb");
 	if (state->in_async_callback_fn)
 		verbose(env, " async_cb");
-	/* the iterations of the loops in which they are kept apart */
-	for (i = 0; i < state->loop_stack_cnt; i++)
-		if (state->loop_stack[i].apart)
-			verbose(env, " iter(%d)=%u", state->loop_stack[i].loop_id,
+	/* The innermost loop. Level 2 has all loops, once for each block. */
+	first = print_all && (env->log.level & BPF_LOG_LEVEL2) ? 0 :
+		max(state->loop_stack_cnt, 1U) - 1;
+	/* the peeled trips */
+	for (i = first; i < state->loop_stack_cnt; i++)
+		if (state->loop_stack[i].peeled)
+			verbose(env, " iter(%d)=%u", state->loop_stack[i].loop->header,
 				state->loop_stack[i].trip);
 	if (state->loop_stack_cnt) {
 		verbose(env, " loop_stack=");
-		for (i = 0; i < state->loop_stack_cnt; i++)
-			verbose(env, "%s%d", i ? "," : "", state->loop_stack[i].loop_id);
+		for (i = first; i < state->loop_stack_cnt; i++)
+			verbose(env, "%s%d", i > first ? "," : "",
+				state->loop_stack[i].loop->header);
 	}
 	verbose(env, "\n");
 	if (!print_all)
kernel/bpf/loops.c +1 -0
index e1f39629f60..f8b2f8befa6 100644
@@ -251,6 +251,7 @@ static int mark_as_header(struct bpf_verifier_env *env, int h)
 		if (!aux[h].loop)
 			return -ENOMEM;
 		env->mem += sizeof(struct bpf_loop);
+		aux[h].loop->header = h;
 	}
 	return 0;
 }
kernel/bpf/verifier.c +296 -20

447 lines not on this page · raw message

Signature · 1 line
2.55.0
#18 lore raw

PATCH v2 16/49 bpf: Add equations and their arithmetic

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A state has a range for each xreg. It does not have the relation of two xregs:

r2 = r1
r2 <<= 2
if r1 > 7 goto out r2 is 0..28, but nothing says so

An equation relates two or three numbers. A sym is a number that the program had or could have had. There are three kinds:

  xreg = coef * sym + off                       r2 = 4 * sym0 + 8
  sym  = coef * sym + coef * sym + off    sum   sym2 = sym0 + sym1
  sym  = what an insn makes of two exprs  op    sym3 = sym2 & 0xf8

All equations hold mod 2^64, as the registers do. Add the types and the arithmetic on ranges that the next patches use:

  scalar_scale()          sym0 = 0..7          ->  4 * sym0 = 0..28
  refine_from_product()   4 * sym0 = 8..20     ->  sym0 = 2..5
  bpf_expr_div_exact()    (4 * sym0 + 8) / 4   ->  sym0 + 2
  bpf_find_next_diff()    sym2 - sym0          ->  sym1

If the product can wrap, the range tells nothing. A power of two still tells the low bits. If a range becomes empty, the equations cannot
hold: the state is infeasible.

---
 include/linux/bpf_verifier.h |  14 +++
 kernel/bpf/Makefile          |   1 +
 kernel/bpf/equation.c        | 232 +++++++++++++++++++++++++++++++++++
 kernel/bpf/equation.h        | 112 +++++++++++++++++
 kernel/bpf/states.c          |   8 +-
 kernel/bpf/verifier.c        |   2 +-
 6 files changed, 366 insertions(+), 3 deletions(-)
 create mode 100644 kernel/bpf/equation.c
 create mode 100644 kernel/bpf/equation.h
include/linux/bpf_verifier.h +14 -0
index b15dc67f0bf..5256f48723b 100644
@@ -564,6 +564,18 @@ struct bpf_func_state {
 #define BPF_ID_MAP_SIZE ((MAX_BPF_REG + MAX_BPF_STACK_SLOTS + MAX_STACK_ARG_SLOTS) * \
 			 MAX_CALL_FRAMES)
 
+/* See equation.c */
+struct bpf_equations {
+	struct bpf_xreg_equation *xreg_equations;	/* the three tables are one allocation */
+	struct bpf_sym_equation *sym_equations;
+	struct scalar *syms;
+	u32 xreg_equation_cnt, sym_equation_cnt, sym_cnt;
+	u32 xreg_equation_cap, sym_equation_cap, sym_cap;
+	bool normalized;	/* see normalize_equations() */
+	bool infeasible;	/* the equations cannot hold: the program does not get here */
+	bool needs_refine;	/* widened: the equations are not applied, see bpf_flow_next() */
+};
+
 struct bpf_verifier_state {
 	/* call stack tracking */
 	struct bpf_func_state *frame[MAX_CALL_FRAMES];
@@ -2338,6 +2350,8 @@ int bpf_compute_loops(struct bpf_verifier_env *env);
 int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx);
 bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header);
 
+void scalar_bounds_sync(struct scalar *s);
+bool scalar_subsumes(const struct scalar *old, const struct scalar *cur);
 
 /* How many bytes are checked from the start of the packet, wherever the pointer is */
 static inline int pkt_min_len(const struct bpf_reg_state *reg)
kernel/bpf/Makefile +1 -0
index 5cf89286df9..f05ccfce45c 100644
@@ -13,6 +13,7 @@ obj-$(CONFIG_BPF_SYSCALL) += hashtab.o arraymap.o percpu_freelist.o bpf_lru_list
 obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_insn_array.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o
 obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o check_btf.o flow.o join.o
+obj-$(CONFIG_BPF_SYSCALL) += equation.o
 obj-${CONFIG_BPF_LSM}	  += bpf_inode_storage.o
 obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o
 obj-$(CONFIG_BPF_JIT) += trampoline.o
kernel/bpf/equation.c new file +232 -0

232 lines not on this page · raw message

kernel/bpf/equation.h new file +112 -0

112 lines not on this page · raw message

kernel/bpf/states.c +6 -2
index c05dcab5216..b3d4301ff8d 100644
@@ -6,8 +6,7 @@
 #include <linux/filter.h>
 
 /* check %cur's range satisfies %old's */
-static bool range_within(const struct bpf_reg_state *old,
-			 const struct bpf_reg_state *cur)
+static bool range_within(const struct scalar *old, const struct scalar *cur)
 {
 	if (!cnum64_is_subset(old->r64, cur->r64) ||
 	    !cnum32_is_subset(old->r32, cur->r32))
@@ -35,6 +34,11 @@ static bool range_within(const struct bpf_reg_state *old,
 	       (cur->base - old->base) % old->step == 0;
 }
 
+bool scalar_subsumes(const struct scalar *old, const struct scalar *cur)
+{
+	return range_within(old, cur) && tnum_in(old->var_off, cur->var_off);
+}
+
 static void renumber_id(struct bpf_verifier_env *env, u32 *id, u32 new_id)
 {
 	struct bpf_idmap *map = &env->idmap_scratch;
kernel/bpf/verifier.c +1 -1
index e7da78986aa..c3d33960fba 100644
@@ -2310,7 +2310,7 @@ static void __update_bounds_from_step(struct scalar *s)
 
 static bool range_bounds_violation(const struct scalar *s);
 
-static void scalar_bounds_sync(struct scalar *s)
+void scalar_bounds_sync(struct scalar *s)
 {
 	/* If the input reg_state is invalid, we can exit early */
 	if (range_bounds_violation(s))
Signature · 1 line
2.55.0
#19 lore raw

PATCH v2 17/49 bpf: Keep a table of equations in each state

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

What holds on one path has to be in the state of that path. Give each state a table of equations. The state says: there are numbers for the syms, in their ranges, for which all equations hold.

  xreg equations    sym equations         syms
  r1 = sym0         sym2 = sym0 + sym1    sym0  0..7
  r2 = 4 * sym0                           sym1  0..255
  fp-8 = sym2                             sym2  0..262

The three arrays are one allocation. It is copied, freed and charged with the state. An insn deletes the sym equations of its earlier visit. The clean-up of a later patch limits the size of the table.

Each scan of a table adds to the cost. At the limit a scan does not start, see over_limit(). The work on equations stops half way then, and the pass proves nothing. The last state can get there after the last test of the limits. So the new do_check() of a later patch tests them again when it ends.

An equation does not outlive its xreg. bpf_find_var_bounds() has no bounds for a register that is not set, or for a slot without a spill. A pointer that became a scalar is another number.

The trip index of a loop is an xreg too. A later patch counts it.

The number in a pointer is its offset. The cpu can speculate past the jump that refines it, so pointers need bypass_spec_v1. There are no equations without CAP_BPF.

The log has the table: 0:r2=4*sym0+0 sym0=[0,+7]

---
 include/linux/bpf_verifier.h |  22 ++
 kernel/bpf/equation.c        | 439 +++++++++++++++++++++++++++++++++++
 kernel/bpf/equation.h        |  58 +++++
 kernel/bpf/flow.c            |   2 +
 kernel/bpf/log.c             |   3 +
 kernel/bpf/verifier.c        |  10 +-
 6 files changed, 533 insertions(+), 1 deletion(-)
include/linux/bpf_verifier.h +22 -0
index 5256f48723b..d4fba11a891 100644
@@ -115,6 +115,7 @@ struct bpf_reg_state {
 	 * the dynptr to determine proper reference freeing.
 	 * Similarly to dynptrs, we use ID to track "belonging" of a reference
 	 * to a specific instance of bpf_iter.
+	 * A scalar has no id, see struct bpf_equations.
 	 */
 	u32 id;
 	union {
@@ -422,6 +423,13 @@ static inline u32 bpf_xreg_to_spi(u32 xregno)
 	return xregno - MAX_BPF_EXT_REG;
 }
 
+/* The trip index of a loop is an xreg too. The loops of a frame come after its slots. */
+#define BPF_XREG_TRIP MAX_BPF_XREG
+static inline u64 bpf_xreg(u32 frameno, u32 xregno)
+{
+	return (u64)frameno << 32 | xregno;
+}
+
 /* Where may_goto that the verifier adds goes, see check_loop_guard() */
 enum bpf_guard_edge {
 	BPF_NO_GUARD_EDGE,
@@ -461,6 +469,8 @@ struct loop_stack_entry {
 	u32 entry_id;
 	u32 held_cnt;		/* when the state entered the loop */
 	bool peeled;		/* in a peeled trip, not in the leftover */
+	/* an xreg: how many times the program came back to the header */
+	struct scalar trip_index;
 };
 
 /* The state is in a walk on patience, which may not get to the end of the loop */
@@ -577,6 +587,7 @@ struct bpf_equations {
 };
 
 struct bpf_verifier_state {
+	struct bpf_equations equations;
 	/* call stack tracking */
 	struct bpf_func_state *frame[MAX_CALL_FRAMES];
 	/* Acquired reference states */
@@ -1319,6 +1330,7 @@ struct bpf_verifier_env {
 	u64 max_cost, max_mem;
 	u64 pass_max_cost;		/* see bpf_undo_precision() */
 	bool aborted;			/* a thaw does not take it back */
+	bool no_mem;			/* a table cannot grow, see bpf_check_limits() */
 	/* What a pass writes. Each pass starts from the snapshot. */
 	struct_group_tagged(bpf_env_per_pass, per_pass,
 	int err;			/* the first error */
@@ -1462,6 +1474,7 @@ struct bpf_verifier_env {
 	struct bpf_iarray *succ;
 	struct bpf_iarray *gotox_tmp_buf;
 	int *idoms;
+	struct bpf_equation_env *eq_env;
 	struct bpf_flow *flow;
 };
 
@@ -2169,6 +2182,7 @@ static inline bool bpf_is_kfunc_sleepable(struct bpf_call_arg_meta *meta)
 	return meta->kfunc_flags & KF_SLEEPABLE;
 }
 bool bpf_is_kfunc_pkt_changing(struct bpf_call_arg_meta *meta);
+bool bpf_grow_array(struct bpf_verifier_env *env, void *array, u32 *cap, u32 cnt, size_t size);
 struct bpf_iarray *bpf_iarray_realloc(struct bpf_iarray *old, size_t n_elem);
 int bpf_copy_insn_array_uniq(struct bpf_map *map, u32 start, u32 end, u32 *off);
 bool bpf_insn_is_cond_jump(u8 code);
@@ -2350,6 +2364,14 @@ int bpf_compute_loops(struct bpf_verifier_env *env);
 int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx);
 bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header);
 
+/* equation.c */
+int bpf_equation_env_init(struct bpf_verifier_env *env);
+void bpf_equation_env_free(struct bpf_verifier_env *env);
+int bpf_equations_copy(struct bpf_verifier_env *env, struct bpf_equations *dst,
+		       const struct bpf_equations *src);
+void bpf_equations_free(struct bpf_equations *eqs);
+void bpf_equations_print(struct bpf_verifier_env *env, const struct bpf_verifier_state *st);
+u32 bpf_equations_bytes(const struct bpf_equations *eqs);
 void scalar_bounds_sync(struct scalar *s);
 bool scalar_subsumes(const struct scalar *old, const struct scalar *cur);
 
kernel/bpf/equation.c +439 -0

442 lines not on this page · raw message

kernel/bpf/equation.h +58 -0

72 lines not on this page · raw message

kernel/bpf/flow.c +2 -0
index 5d86792025f..f8e8ea7b05a 100644
@@ -308,6 +308,8 @@ int bpf_check_limits(struct bpf_verifier_env *env)
 	env->aborted |= bpf_must_abort();
 	if (env->aborted)
 		return -EINTR;
+	if (env->no_mem)
+		return -ENOMEM;
 	if (env->cost <= min(env->max_cost, env->pass_max_cost) && env->mem <= env->max_mem &&
 	    !env->over_limit)
 		return 0;
kernel/bpf/log.c +3 -0
index 7b1390d9054..8a905f4df9b 100644
@@ -803,6 +803,9 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie
 			verbose(env, "%s%d", i > first ? "," : "",
 				state->loop_stack[i].loop->header);
 	}
+	/* one table for all frames */
+	if (print_all && frameno == vstate->curframe)
+		bpf_equations_print(env, vstate);
 	verbose(env, "\n");
 	if (!print_all)
 		mark_verifier_state_clean(env);
kernel/bpf/verifier.c +9 -1
index c3d33960fba..5cd1d83d0c0 100644
@@ -1748,6 +1748,7 @@ void bpf_charge_state(struct bpf_verifier_env *env, struct bpf_verifier_state *s
 	u32 bytes = 2 * sizeof(*st) + ksize(st->refs), fr;
 	struct bpf_func_state *f;
 
+	bytes += bpf_equations_bytes(&st->equations);
 	for (fr = 0; fr <= st->curframe && (f = st->frame[fr]); fr++)
 		bytes += kmalloc_size_roundup(sizeof(*f)) + ksize(f->stack) +
 			 ksize(f->stack_arg_regs) + ksize(f->loop_stack);
@@ -1767,6 +1768,7 @@ void bpf_free_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_s
 		state->frame[i] = NULL;
 	}
 	kfree(state->refs);
+	bpf_equations_free(&state->equations);
 	if (free_self)
 		kfree(state);
 }
@@ -1800,7 +1802,8 @@ int bpf_copy_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_st
 		free_func_state(dst_state->frame[i]);
 		dst_state->frame[i] = NULL;
 	}
-	err = copy_reference_state(dst_state, src);
+	err = copy_reference_state(dst_state, src) ?:
+	      bpf_equations_copy(env, &dst_state->equations, &src->equations);
 	if (err)
 		return err;
 	bpf_add_cost(env, bpf_xreg_cnt(src) + src->acquired_refs, BPF_COST_COPY);
@@ -24907,6 +24910,10 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (env->log.level & BPF_LOG_LEVEL2)
 		log_program(env);
 
+	ret = bpf_equation_env_init(env);
+	if (ret < 0)
+		goto skip_full_check;
+
 	ret = bpf_flow_prepare(env);
 	if (ret < 0)
 		goto skip_full_check;
@@ -25048,6 +25055,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	kvfree(env->used_index.slots);
 	kvfree(env->kfunc_index.slots);
 	kvfree(env->insn_array_maps);
+	bpf_equation_env_free(env);
 	bpf_flow_free(env);
 	bpf_stack_liveness_free(env);
 	kvfree(env->cfg.postorder_nums);
Signature · 1 line
2.55.0
#20 lore raw

PATCH v2 18/49 bpf: Refine all related numbers after a jump

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A jump refines its operands. Take that through the equations:

xreg -> its sym -> the other syms -> their xregs

r1 = sym0, r2 = 4 * sym0
if r1 > 7 goto out r1 0..7 -> sym0 0..7 -> r2 0..28

propagate_bounds() keeps the refined syms in a queue, and links the equations that use a sym. A sym propagates once, so the work is linear in the size of the table. A sum refines all of its syms. An op refines only its result: run_op() runs scalar_alu() on the new operands.

A jump that compares two numbers compares their difference with 0:

end = p + sym0
if (p != end) sym0 != 0

A 32-bit test for equal does that for the numbers before a truncation too, see skip_truncation(): w1 += 1; if w1 != w2

Code with no 32-bit insns can test the carry of a sum, see refine_carry():

r5 = r2; r5 <<= 32; r5 >>= 32
if r5 != r2 goto carry if the jump is taken, r2 is above U32_MAX

Packet pointers that share an id move together, see refine_ptr().

The two branches can get other bounds for one pointer. The test for the end of the packet takes the operands of one branch for both. So bpf_equations_jump() is last in check_cond_jmp_op().

If the equations cannot hold, the state ends after the next conditional jump. The removal of dead code deletes an edge only from such a jump: a call or a goto has to keep its target. The cpu can speculate past the jump, so that needs bypass_spec_v1. See infeasible_state_ends().

Two pointers to one object have the order of their offsets:

for (p = buf; p < end; p++)

          *p = 0;

The jump refines both offsets, and is_branch_taken() decides it. This holds if no address wraps, so both offsets have to be near the object. It is off without bypass_spec_v1.

This replaces refine_linked_regs().

---
 include/linux/bpf_verifier.h |  12 +
 kernel/bpf/equation.c        | 440 +++++++++++++++++++++++++++++++++++
 kernel/bpf/equation.h        |   6 +
 kernel/bpf/verifier.c        |  49 +++-
 4 files changed, 503 insertions(+), 4 deletions(-)
include/linux/bpf_verifier.h +12 -0
index d4fba11a891..39d79f0c1cb 100644
@@ -2370,10 +2370,22 @@ void bpf_equation_env_free(struct bpf_verifier_env *env);
 int bpf_equations_copy(struct bpf_verifier_env *env, struct bpf_equations *dst,
 		       const struct bpf_equations *src);
 void bpf_equations_free(struct bpf_equations *eqs);
+void bpf_equations_refine_all(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
+void bpf_equations_jump(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int idx,
+			bool taken);
 void bpf_equations_print(struct bpf_verifier_env *env, const struct bpf_verifier_state *st);
 u32 bpf_equations_bytes(const struct bpf_equations *eqs);
 void scalar_bounds_sync(struct scalar *s);
 bool scalar_subsumes(const struct scalar *old, const struct scalar *cur);
+bool scalars_fit_in_bits(const struct scalar *a, const struct scalar *b, u32 bits);
+void scalars_refine_cond_op(struct scalar *a, struct scalar *b, u8 opcode, bool is_jmp32);
+
+static inline u8 bpf_signed_opcode(u8 op)
+{
+	if (op == BPF_JLT || op == BPF_JLE)
+		return op + BPF_JSLT - BPF_JLT;
+	return op == BPF_JGT || op == BPF_JGE ? op + BPF_JSGT - BPF_JGT : op;
+}
 
 /* How many bytes are checked from the start of the packet, wherever the pointer is */
 static inline int pkt_min_len(const struct bpf_reg_state *reg)
kernel/bpf/equation.c +440 -0

446 lines not on this page · raw message

kernel/bpf/equation.h +6 -0
index db1f9fe3776..4e9b83ba419 100644
@@ -46,6 +46,9 @@ struct sym_scratch {
 	u32 use_cnt;		/* equations that use it */
 	/* propagate_bounds(): the sweep that has to look at its equations */
 	u32 refined_sweep;
+	/* propagate_bounds(): not of this sym. The queue of refined syms. */
+	u32 queued_sym;
+	u32 first_use;		/* see link_sym_equations() */
 	u32 new_symno;
 	bool determined, by_op;
 	const struct bpf_sym_equation *op;	/* that makes it */
@@ -57,6 +60,9 @@ struct bpf_equation_env {
 	u32 *use_links;
 	u32 scratch_cap, use_link_cap, refined_cnt;
 	bool has_expr[2], is_ptr[2], equation_added, divided;
+	/* the operand of a jump and its bounds, see refine_from_reg() */
+	struct expr jump_expr;
+	struct scalar jump_bounds;
 	/* equation_join.c */
 	struct bpf_verifier_state join_state;	/* it has equations and no frames */
 	struct join_phi *phis;
kernel/bpf/verifier.c +45 -4

126 lines not on this page · raw message

Signature · 1 line
2.55.0
#21 lore raw

PATCH v2 19/49 bpf: Make equations from ALU, spill, fill and call insns

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

An insn deletes the equations of the registers that it writes, see def_regs. The result gets a new equation:

  r2 = r1             r1 = sym0, r2 = sym0
  r2 += 8             r2 = sym0 + 8
  r2 <<= 2            r2 = 4 * sym0 + 32
  r2 += r3            r2 = sym2, sum: sym2 = 4 * sym0 + sym1 + 32
  r1 >>= 3            r1 = quot, sum: rem = sym0 - 8 * quot
  w4 = w1             r4 = low,  sum: low = sym0 - 2^32 * high
  r1 ^= 5             r1 = sym3, op:  sym3 = sym0 ^ 5
  *(fp - 8) = r1      fp-8 = sym0, and a fill reads it back
  call                r1-r5 go to the frame of the callee
  exit                r0 goes to the frame of the caller

A number gets a sym only when a second xreg needs it.

A truncation is a sum for the low bits. Compilers test one truncation and use another one:

w2 = w1; w2 += -1; w2 &= 255; if w2 > 99 goto out; use (u8)r1

expr_low_bits() looks for a number with the same low bits before it makes a new sym. 'w1 <<= 24; w1 s>>= 24' is a truncation to 8 bits. An op that reads only the low bits gets them from a truncation, also if the test of the truncation was earlier:

w2 = w1; w2 &= 0xff; if w2 > 0xdf goto out; w1 &= 0xf0 0..0xd0

find_same_op() finds an op with the same operands. So two insns that compute one number get one sym.

A call uses the equations of its arguments before it deletes them. The largest offset and the largest size do not have to go together:

read(buf + off, 64 - off) r1 = buf + sym0, r2 = 64 - sym0

size_at_max_offset() gives the check the size that is left at the largest offset. It can be 0 for a call that touches memory. So check_stack_access_within_bounds() tests the range, not the size.

A speculative state gets no equations.

---
 include/linux/bpf_verifier.h |   9 +
 kernel/bpf/equation.c        | 534 +++++++++++++++++++++++++++++++++++
 kernel/bpf/equation.h        |   9 +
 kernel/bpf/verifier.c        |  44 ++-
 4 files changed, 591 insertions(+), 5 deletions(-)
include/linux/bpf_verifier.h +9 -0
index 39d79f0c1cb..5ed2bed1622 100644
@@ -2370,6 +2370,15 @@ void bpf_equation_env_free(struct bpf_verifier_env *env);
 int bpf_equations_copy(struct bpf_verifier_env *env, struct bpf_equations *dst,
 		       const struct bpf_equations *src);
 void bpf_equations_free(struct bpf_equations *eqs);
+s64 bpf_equations_max_sum(struct bpf_verifier_env *env, int regno1, int regno2);
+void bpf_equations_before_insn(struct bpf_verifier_env *env);
+int bpf_equations_after_insn(struct bpf_verifier_env *env);
+void bpf_equations_forget_xreg(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+			       u64 xreg);
+void bpf_equations_spill(struct bpf_verifier_env *env, struct bpf_func_state *frame, int spi,
+			 int regno);
+void bpf_equations_fill(struct bpf_verifier_env *env, struct bpf_func_state *frame, int spi,
+			int size);
 void bpf_equations_refine_all(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
 void bpf_equations_jump(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int idx,
 			bool taken);
kernel/bpf/equation.c +534 -0

540 lines not on this page · raw message

kernel/bpf/equation.h +9 -0
index 4e9b83ba419..8a247451a15 100644
@@ -59,7 +59,16 @@ struct bpf_equation_env {
 	struct sym_scratch *scratch;
 	u32 *use_links;
 	u32 scratch_cap, use_link_cap, refined_cnt;
+	/* the insn that is checked and its operands */
+	s32 insn_idx;
+	struct expr operand_expr[2];
+	struct scalar operand_bounds[2];
 	bool has_expr[2], is_ptr[2], equation_added, divided;
+	/* the arguments of a call */
+	struct expr arg_expr[BPF_REG_5 + 1];
+	u8 has_arg_expr;
+	u64 fill_xreg;
+	u32 fill_bits;
 	/* the operand of a jump and its bounds, see refine_from_reg() */
 	struct expr jump_expr;
 	struct scalar jump_bounds;
kernel/bpf/verifier.c +39 -5

110 lines not on this page · raw message

Signature · 1 line
2.55.0
#22 lore raw

PATCH v2 20/49 bpf: Delete the equations that say nothing

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Insns add syms, and registers die. Without a clean-up the table grows, and two states with the same facts have tables that do not compare.

  if                      then
  sym0 is 5               put 5 into the equations
  sym1 = sym0 + 8         replace sym1
  r1 = sym0, only use     delete, the range of r1 says the same
  no xreg holds sym0      eliminate it:
    p = sym0 + len, sym0 = 8 * trip + sym1  ->  p = 8 * trip + sym2

The result can be a second equation for the same sum, often with a smaller range than the guess of a join. refine_same_sum() gives the range to the first equation and deletes the second one. Two sums can also become the same when a sym is replaced.

The new range needs a sym to hold it. If the equation has no sym with one use, the sym of the deleted equation holds it:

x = m + d, m = 2 * k + 41 * j, k is dead -> x = 41 * j + d'

normalize_equations() also sets the order: each equation has at most one sym that the xregs and the earlier equations do not determine. A later patch needs that order to check a table in one walk.

A state keeps 2 * SUMS_PER_XREG sym equations for each xreg equation. That cuts a chain such as 'x += k; x += k; ...'. A pass that is over its budget drops all equations. So does a speculative state.

A state without an equation has more values. So it is always safe to delete an equation.

The clean-up runs when a state is cleaned, and when the number of syms doubles.

---
 include/linux/bpf_verifier.h |   2 +
 kernel/bpf/equation.c        | 427 +++++++++++++++++++++++++++++++++++
 kernel/bpf/equation.h        |   3 +
 kernel/bpf/states.c          |   1 +
 4 files changed, 433 insertions(+)
include/linux/bpf_verifier.h +2 -0
index 5ed2bed1622..e7322f0aece 100644
@@ -584,6 +584,7 @@ struct bpf_equations {
 	bool normalized;	/* see normalize_equations() */
 	bool infeasible;	/* the equations cannot hold: the program does not get here */
 	bool needs_refine;	/* widened: the equations are not applied, see bpf_flow_next() */
+	u32 clean_sym_cnt;	/* after the last bpf_equations_clean() */
 };
 
 struct bpf_verifier_state {
@@ -2370,6 +2371,7 @@ void bpf_equation_env_free(struct bpf_verifier_env *env);
 int bpf_equations_copy(struct bpf_verifier_env *env, struct bpf_equations *dst,
 		       const struct bpf_equations *src);
 void bpf_equations_free(struct bpf_equations *eqs);
+void bpf_equations_clean(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
 s64 bpf_equations_max_sum(struct bpf_verifier_env *env, int regno1, int regno2);
 void bpf_equations_before_insn(struct bpf_verifier_env *env);
 int bpf_equations_after_insn(struct bpf_verifier_env *env);
kernel/bpf/equation.c +427 -0

445 lines not on this page · raw message

kernel/bpf/equation.h +3 -0
index 8a247451a15..5a2d7f24658 100644
@@ -9,6 +9,9 @@
 #define VAR_NONE	U64_MAX
 #define NO_SYM		U32_MAX
 
+/* For each xreg a state keeps twice that many sums and ops in total, see normalize_equations() */
+#define SUMS_PER_XREG	2
+
 /* coef * var + off. A constant has no var and coef == 0. */
 struct expr {
 	s64 coef;
kernel/bpf/states.c +1 -0
index b3d4301ff8d..c7630a50e62 100644
@@ -270,6 +270,7 @@ int bpf_clean_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_s
 
 		__clean_func_state(env, st->frame[i], live_regs, i);
 	}
+	bpf_equations_clean(env, st);
 	return bpf_renumber_ids(env, st);
 }
 
Signature · 1 line
2.55.0
#23 lore raw

PATCH v2 21/49 bpf: Compare states by join_key, then by value

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The compare and the join of two states start with the same question:
can they be one state at all? Each had its own list of fields. Put the fields in one group, the join_key:

  what is held    references, locks, dynptrs, iterators, irq flags
  where it is     the call chain, the instance of the function
  which trip      the peeled trip, or the leftover

The group is compared and hashed as bytes, so it has no padding. States with two join_keys never meet. bpf_state_subsumes() looks only at values.

regsafe() had a case for each type. All say the same: the type and the object are equal, and the number is within. bpf_same_type_and_object() answers the first part, also for the join.

Two rules are new. A later patch joins such values:
- Pointers to the packet are compared by the bytes that are left:

smin smax range

    |-- offsets ---|-- bytes left ---|

Pointers that share an id have to keep their distance. The pairs of ids are in env->pkt_pairs, which grows on demand.
- stacksafe() knows the bytes that a join makes. An unreadable spill subsumes a written byte, misc subsumes a spilled number, zero subsumes a spilled 0.

This also fixes a leak in the old code. A store of a pointer at a variable stack offset makes a number of it. With the mitigations off that needed no CAP_PERFMON. Reject it: a join of two offsets makes such a store too.

This replaces check_ids(), regs_exact(), refsafe() and stack_arg_safe(). async_entry_cnt goes away: states of an async callback are joined.

---
 include/linux/bpf_verifier.h | 105 +++++++---
 kernel/bpf/states.c          | 362 ++++++++++++++++++++---------------
 kernel/bpf/verifier.c        |  15 +-
 3 files changed, 292 insertions(+), 190 deletions(-)
include/linux/bpf_verifier.h +78 -27
index e7322f0aece..bded3a774be 100644
@@ -395,7 +395,7 @@ struct bpf_reference_state {
 struct bpf_retval_range {
 	s32 minval;
 	s32 maxval;
-	bool return_32bit;
+	u32 return_32bit;	/* no padding, see bpf_same_join_key() */
 };
 
 /*
@@ -486,6 +486,8 @@ static inline bool bpf_loop_walk_may_give_up(const struct loop_stack_entry *entr
  */
 struct bpf_func_state {
 	struct bpf_reg_state regs[MAX_BPF_REG];
+	/* equal in states that have a join, see bpf_same_join_key() */
+	struct_group(join_key,
 	/* index of call instruction that called into this func */
 	int callsite;
 	/* stack frame number of this function state from pov of
@@ -493,32 +495,36 @@ struct bpf_func_state {
 	 * 0 = main function, 1 = first callee.
 	 */
 	u32 frameno;
-	/*
-	 * Unique diagnostic identity for this function invocation. Frame depth is
-	 * reused after returns, while this ID is preserved across state clones.
-	 */
-	u32 diag_frame_id;
-	/* parent_id of the args that are gone when this frame returns */
-	u32 frame_id;
 	/* subprog number == index within subprog_info
 	 * zero == main subprog
 	 */
 	u32 subprogno;
 	/*
-	 * The frame of an async callback has the count of frame 0 of the state
-	 * that sets the callback plus one. Frames that differ in it are not joined.
+	 * What was held at the entry of the frame and is still held. For references these are
+	 * the first entry_refs of refs[]. What is released and acquired again does not count.
+	 * This frame must release all the rest.
 	 */
-	u32 async_entry_cnt;
+	u32 entry_refs;
+	u32 entry_rcu_locks;
+	u32 entry_preempt_locks;
 	struct bpf_retval_range callback_ret_range;
 	bool in_callback_fn;
 	bool in_async_callback_fn;
 	bool in_exception_callback_fn;
-	bool no_stack_arg_load;
 	/*
 	 * The helper invokes this callback under rcu_read_lock(), so the
 	 * callback and its callees run in an RCU read-side critical section.
 	 */
 	bool in_rcu_callback_fn;
+	/* parent_id of the args that are gone when this frame returns */
+	u32 frame_id;
+	);
+	bool no_stack_arg_load;
+	/*
+	 * Unique diagnostic identity for this function invocation. Frame depth is
+	 * reused after returns, while this ID is preserved across state clones.
+	 */
+	u32 diag_frame_id;
 	/* For callback calling functions that limit number of possible
 	 * callback executions (e.g. bpf_loop) keeps track of current
 	 * simulated iteration number.
@@ -537,14 +543,6 @@ struct bpf_func_state {
 	 * subprogram (loops never cross subprogram boundaries).
 	 */
 	u32 loop_stack_cnt;
-	/*
-	 * How much of what was held when the frame was entered is held ever since. For
-	 * references that is the first entry_refs of refs[]. What is released and taken again
-	 * doesn't count. More than that is for this frame to release.
-	 */
-	u32 entry_refs;
-	u32 entry_rcu_locks;
-	u32 entry_preempt_locks;
 
 	/* The following fields should be last. See copy_func_state() */
 	/* The state of the stack. Each element of the array describes BPF_REG_SIZE
@@ -594,7 +592,7 @@ struct bpf_verifier_state {
 	/* Acquired reference states */
 	struct bpf_reference_state *refs;
 	u32 insn_idx;
-	u32 curframe;
+	bool speculative;
 	/* an xreg has no value: unreachable. Only a path-sensitive run drops such a state. */
 	bool infeasible;
 	/* an error only in a leftover, see check_held_in_leftover() */
@@ -603,6 +601,8 @@ struct bpf_verifier_state {
 	/* the loops that made an xreg of data_deps imprecise, see bpf_loop.suspect_bit */
 	u64 suspect_loops;
 
+	/* equal in states that have a join, see bpf_same_join_key(). No holes. */
+	struct_group(join_key,
 	struct_group(held,
 	void *active_lock_ptr;
 	u32 acquired_refs;
@@ -611,9 +611,8 @@ struct bpf_verifier_state {
 	u32 active_rcu_locks;
 	u32 active_irq_id;
 	u32 active_lock_id;
-
-	bool speculative;
 	);
+	u32 curframe;
 	bool in_sleepable;
 	/* a global function or an extension, and what it calls: exit of frame 0 is not the end */
 	bool callers_unknown;
@@ -629,6 +628,9 @@ struct bpf_verifier_state {
 	 * state at its entry came from, see bpf_flow_call().
 	 */
 	u32 flow_entry;
+	);
+	/* Not zero in a function that is verified on its own, see bpf_flow_call() */
+	u32 instance_id;
 
 	/* The insn that the state comes from, -1 if no instructions have been executed yet. */
 	u32 last_insn_idx;
@@ -683,6 +685,16 @@ static inline bool bpf_stack_args_are_incoming(const struct bpf_func_state *fram
 	return !frame->frameno && !frame->no_stack_arg_load;
 }
 
+/* Stack argument @i of @frame to compare with @other or NULL: incoming ones are not outgoing */
+static inline const struct bpf_reg_state *
+bpf_stack_arg(const struct bpf_func_state *frame, const struct bpf_func_state *other, u32 i)
+{
+	if (i >= frame->out_stack_arg_cnt ||
+	    (bpf_stack_args_are_incoming(frame) && !bpf_stack_args_are_incoming(other)))
+		return NULL;
+	return &frame->stack_arg_regs[i];
+}
+
 /* Iterate over 'frame', setting 'reg' to either NULL or a spilled register. */
 #define bpf_for_each_spilled_reg(iter, frame, reg, mask)			\
 	for (iter = 0, reg = bpf_get_spilled_reg(iter, frame, mask);		\
@@ -1230,6 +1242,16 @@ static inline bool bpf_id_is_xreg(u32 id)
 	return id & 2;
 }
 
+/* pointers to the packet with id @old are those with id @cur moved by @delta */
+struct bpf_pkt_pair {
+	u32 old;
+	u32 cur;
+	u64 delta;
+	/* for a join */
+	u32 type;
+	u32 id;
+};
+
 struct bpf_idmap {
 	u32 cnt;
 	struct bpf_id_pair map[BPF_ID_MAP_SIZE];
@@ -1329,6 +1351,7 @@ struct bpf_verifier_env {
 	bool path_sensitive;		/* no joins, see run_path_sensitive() */
 	u64 cost, mem;			/* see bpf_check_limits() */
 	u64 max_cost, max_mem;
+	u64 hash_seed;			/* see bpf_hash_join_key() */
 	u64 pass_max_cost;		/* see bpf_undo_precision() */
 	bool aborted;			/* a thaw does not take it back */
 	bool no_mem;			/* a table cannot grow, see bpf_check_limits() */
@@ -1403,6 +1426,8 @@ struct bpf_verifier_env {
 	} *callx_edges;
 	struct bpf_index callx_index;
 	struct bpf_idmap idmap_scratch;
+	struct bpf_pkt_pair *pkt_pairs;	/* of the two states that are compared or joined */
+	u32 pkt_pair_cnt, pkt_pair_cap;
 	struct {
 		int *insn_state;
 		int *insn_stack;
@@ -1633,9 +1658,15 @@ void bpf_free_kfunc_btf_tab(struct bpf_kfunc_btf_tab *tab);
 
 
 int bpf_clean_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
-bool bpf_state_subsumes(struct bpf_verifier_env *env, struct bpf_verifier_state *old,
-			struct bpf_verifier_state *cur);
-
+bool bpf_add_pkt_pair(struct bpf_verifier_env *env, const struct bpf_pkt_pair *pair);
+bool bpf_state_subsumes(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
+			const struct bpf_verifier_state *cur);
+bool bpf_scalar_subsumes(const struct bpf_reg_state *old, const struct bpf_reg_state *cur);
+bool bpf_same_type_and_object(struct bpf_verifier_env *env, const struct bpf_reg_state *a,
+			      const struct bpf_reg_state *b);
+bool bpf_same_join_key(const struct bpf_verifier_state *a, const struct bpf_verifier_state *b);
+u64 bpf_hash64(const void *p, size_t len, u64 hash);
+u64 bpf_hash_join_key(const struct bpf_verifier_env *env, const struct bpf_verifier_state *st);
 int bpf_renumber_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
 
 bool bpf_xreg_in_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
@@ -1745,7 +1776,7 @@ static inline struct bpf_func_state *bpf_func(struct bpf_verifier_env *env,
 }
 
 /* Return IP for a given frame in a call stack */
-static inline u32 bpf_frame_insn_idx(struct bpf_verifier_state *st, u32 frame)
+static inline u32 bpf_frame_insn_idx(const struct bpf_verifier_state *st, u32 frame)
 {
 	return frame == st->curframe
 	       ? st->insn_idx
@@ -2398,12 +2429,25 @@ static inline u8 bpf_signed_opcode(u8 op)
 	return op == BPF_JGT || op == BPF_JGE ? op + BPF_JSGT - BPF_JGT : op;
 }
 
+/* True if pkt_bytes_left() is valid */
+static inline bool pkt_has_bytes_left(const struct bpf_reg_state *reg)
+{
+	return reg->range >= 0 && reg_smin(reg) >= -MAX_PACKET_OFF &&
+	       reg_smax(reg) <= MAX_PACKET_OFF;
+}
+
 /* How many bytes are checked from the start of the packet, wherever the pointer is */
 static inline int pkt_min_len(const struct bpf_reg_state *reg)
 {
 	return reg->r64.size ? reg->pkt_min_len : max(reg->range, reg->pkt_min_len);
 }
 
+/* How many bytes are checked after a pointer to the packet */
+static inline s64 pkt_bytes_left(const struct bpf_reg_state *reg)
+{
+	return reg->range - reg_smax(reg);
+}
+
 /* The loop that the frame is in, or NULL */
 static inline struct loop_stack_entry *bpf_top_loop(const struct bpf_func_state *frame)
 {
@@ -2419,4 +2463,11 @@ static inline u32 bpf_xreg_cnt(const struct bpf_verifier_state *st)
 	return nr;
 }
 
+static inline bool bpf_slot_is_held(const struct bpf_stack_state *slot)
+{
+	u8 t = slot->slot_type[BPF_REG_SIZE - 1];
+
+	return t == STACK_DYNPTR || t == STACK_ITER || t == STACK_IRQ_FLAG;
+}
+
 #endif /* _LINUX_BPF_VERIFIER_H */
kernel/bpf/states.c +205 -157

470 lines not on this page · raw message

kernel/bpf/verifier.c +9 -6
index e0c829745b2..3edc91b8852 100644
@@ -29,6 +29,7 @@
 #include <linux/keyctl.h>
 #include <linux/btf_ids.h>
 #include <linux/poison.h>
+#include <linux/random.h>
 #include <linux/module.h>
 #include <linux/cpumask.h>
 #include <linux/cnum.h>
@@ -1808,16 +1809,12 @@ int bpf_copy_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_st
 		return err;
 	bpf_add_cost(env, bpf_xreg_cnt(src) + src->acquired_refs, BPF_COST_COPY);
 	dst_state->speculative = src->speculative;
-	dst_state->in_sleepable = src->in_sleepable;
-	dst_state->callers_unknown = src->callers_unknown;
-	dst_state->unwound = src->unwound;
-	dst_state->changed_pkt_data = src->changed_pkt_data;
 	dst_state->flow_entry = src->flow_entry;
 	dst_state->infeasible = src->infeasible;
 	dst_state->max_held_cnt = src->max_held_cnt;
 	dst_state->suspect_loops = src->suspect_loops;
+	dst_state->join_key = src->join_key;
 	dst_state->insn_idx = src->insn_idx;
-	dst_state->curframe = src->curframe;
 	dst_state->last_insn_idx = src->last_insn_idx;
 	for (i = 0; i <= src->curframe; i++) {
 		dst = dst_state->frame[i];
@@ -3788,6 +3785,11 @@ static int check_stack_write_var_off(struct bpf_verifier_env *env,
 	max_off = reg_smax(ptr_reg) + off + size;
 	if (value_regno >= 0)
 		value_reg = &cur->regs[value_regno];
+	/* no slot remembers the pointer, a load gets it as a number */
+	if (value_reg && __is_pointer_value(env->allow_ptr_leaks, value_reg)) {
+		verbose(env, "R%d leaks addr into stack\n", value_regno);
+		return -EACCES;
+	}
 	if ((value_reg && bpf_register_is_null(value_reg)) ||
 	    (!value_reg && is_bpf_st_mem(insn) && insn->imm == 0))
 		writing_zero = true;
@@ -11418,7 +11420,6 @@ static int push_callback_call(struct bpf_verifier_env *env, struct bpf_insn *ins
 		if (is_async_cb_sleepable(env, insn))
 			env->sleepable_async_cb = true;
 		callee = async_cb->frame[0];
-		callee->async_entry_cnt = state->frame[0]->async_entry_cnt + 1;
 
 		/* Convert bpf_timer_set_callback() args into timer callback args */
 		err = set_callee_state_cb(env, caller, callee, insn_idx);
@@ -24790,6 +24791,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	env->max_cost = BPF_MAX_COST >> (is_priv ? 0 : BPF_LIMITS_SHIFT_UNPRIV);
 	env->pass_max_cost = U64_MAX;
 	env->max_mem = BPF_MAX_MEM >> (is_priv ? 0 : BPF_LIMITS_SHIFT_UNPRIV);
+	env->hash_seed = get_random_u64();
 	env->signature = attr->signature;
 
 	/* user could have requested verbose verifier output
@@ -25137,6 +25139,7 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	kvfree(env->cfg.insn_postorder);
 	kvfree(env->succ);
 	kvfree(env->gotox_tmp_buf);
+	kvfree(env->pkt_pairs);
 	kvfree(env->callx_edges);
 	kvfree(env->callx_index.slots);
 	kvfree(env->func_ptrs);
Signature · 1 line
2.55.0
#24 lore raw

Re: [PATCH bpf-next v2 21/49] bpf: Compare states by join_key, then by value

TL;DR: join_key has 4 bytes of tail padding on 64-bit, despite the "no holes" claim. Its memcmp/hash could differ for equal states, possibly blocking pruning and joining (precision/complexity loss…
Quoted 1 line

bpf: Compare states by join_key, then by value

TL;DR: join_key has 4 bytes of tail padding on 64-bit, despite the "no holes" claim. Its memcmp/hash could differ for equal states, possibly blocking pruning and joining (precision/complexity loss, not safety).

Quoted 3 lines
include/linux/bpf_verifier.h +0 -0

[ ... ]

Quoted 20 lines
include/linux/bpf_verifier.h +3 -2
@@ -603,6 +601,8 @@ struct bpf_verifier_state {
 	/* the loops that made an xreg of data_deps imprecise, see bpf_loop.suspect_bit */
 	u64 suspect_loops;
 
+	/* equal in states that have a join, see bpf_same_join_key(). No holes. */
+	struct_group(join_key,
 	struct_group(held,
 	void *active_lock_ptr;
 	u32 acquired_refs;
@@ -611,9 +611,8 @@ struct bpf_verifier_state {
 	u32 active_rcu_locks;
 	u32 active_irq_id;
 	u32 active_lock_id;
-
-	bool speculative;
 	);
+	u32 curframe;
 	bool in_sleepable;
 	/* a global function or an extension, and what it calls: exit of frame 0 is not the end */
 	bool callers_unknown;

[ ... ]

include/linux/bpf_verifier.h struct bpf_verifier_state { · line 633

Quoted 4 lines
include/linux/bpf_verifier.h +3 -0
 	u32 flow_entry;
+	);
+	/* Not zero in a function that is verified on its own, see bpf_flow_call() */
+	u32 instance_id;

Is the "No holes" comment accurate on 64-bit?

The members of join_key add up to 44 bytes:

    held (void * plus six u32)    0..31
    curframe                      32
    in_sleepable..changed_pkt_data   36..39
    flow_entry                    40..43

The void * gives the group 8-byte alignment, so sizeof(st->join_key) is 48 and bytes 44..47 are tail padding. The commit message also says "The group is compared and hashed as bytes, so it has no padding."

Both users read those bytes:

    bpf_same_join_key(): memcmp(&a->join_key, &b->join_key, sizeof(a->join_key))
    bpf_hash_join_key(): bpf_hash64(&st->join_key, sizeof(st->join_key), ...)

The padding is zero in practice, since states come from kzalloc_obj() or '= {}', and bpf_copy_verifier_state() copies the group with 'dst_state->join_key = src->join_key'. But C does not require a struct assignment to copy padding. If two states with equal fields ever had different padding, they would compare unequal and hash to different values, and would never be pruned or joined. That costs precision and complexity rather than safety.

This is the same problem that is avoided for struct bpf_retval_range by turning return_32bit into a u32. Would it make sense to move flow_entry out of the group (or add a 4-byte member), and add a BUILD_BUG_ON() on the size of the group so the "No holes" claim is enforced?

The later commit 699ddfe056ce ("bpf: Verify a static function once for each instance") removes flow_entry, which leaves a 40 byte group with no padding. The commits in between, for example eddb572e724e ("bpf: Join any two states that have the same join_key") and 8514cc01b0e8 ("bpf: Prune or join each state that arrives"), use the padded layout.

[ ... ]

Quoted 3 lines
kernel/bpf/states.c +0 -0

[ ... ]

kernel/bpf/states.c static bool stacksafe(struct bpf_verifier_env *env, struct bpf_func_state *old, · line 520

Quoted 10 lines
kernel/bpf/states.c +10 -0
+bool bpf_same_join_key(const struct bpf_verifier_state *a, const struct bpf_verifier_state *b)
+{
+	const struct bpf_stack_state *sa, *sb;
+	const struct loop_stack_entry *ea, *eb;
+	const struct bpf_func_state *fa, *fb;
+	u32 fr, i;
+
+	if (memcmp(&a->join_key, &b->join_key, sizeof(a->join_key)) ||
+	    a->instance_id != b->instance_id || !same_refs(a, b))
+		return false;

This is the same padding question from the struct definition: the memcmp() of sizeof(a->join_key) covers the 4 bytes of tail padding on 64-bit, and bpf_hash_join_key() hashes the same range. Equal join_keys with different padding would not match or hash alike, so such states would never be pruned or joined. Could flow_entry be moved out of the group, or a BUILD_BUG_ON() added on the size of the group, until 699ddfe056ce removes flow_entry?

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

#25 lore raw

PATCH v2 22/49 bpf: Continue a pass after an unproven insn

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A pass stops at its first error. A program with many insns that need precision then takes one pass for each insn. Let the pass find all of them:

  r0 = *(u64 *)(r2 + 0)    unproven; r0 = unknown, from_unproven
  r4 = *(u8 *)(r0 + 0)     unproven because of r0: not a new error
  r5 = *(u8 *)(r7 + 0)     unproven: noted too

skip_unproven_insn() continues as if the insn is proven. Such a pass accepts nothing: env->err keeps the first error, and the log ends there. If the insn is a call that changes what is held, the path ends.

bpf_note_unproven_insn() notes what the next pass needs: the insn, the calls that lead to it, and the suspect loops of the state. A loop is a suspect if it made a value imprecise. The pass ends early when all unproven insns of the last pass are unproven again.

Two errors have no state that caused them:

fixups differ The first state is gone. The insn remembers the
suspect loops of its states. If a speculative state was first, the insn gets a barrier.
check_after_pass() bpf_find_unproven_after_pass() takes the calls
and the insns that set the depth of a stack.

Small fixes that this needs:
- A join can make an unset stack argument: -EINVAL, not -EFAULT.
- An unproven call does not mark a global function as unreliable.
- The log does not skip a slot if it starts at the main dynptr slot.

---
 include/linux/bpf_verifier.h |  25 ++++-
 kernel/bpf/Makefile          |   1 +
 kernel/bpf/log.c             |   3 +-
 kernel/bpf/precision.c       | 142 +++++++++++++++++++++++
 kernel/bpf/precision.h       |  39 +++++++
 kernel/bpf/verifier.c        | 211 +++++++++++++++++++++++++++++++----
 6 files changed, 397 insertions(+), 24 deletions(-)
 create mode 100644 kernel/bpf/precision.c
 create mode 100644 kernel/bpf/precision.h
include/linux/bpf_verifier.h +23 -2
index bded3a774be..3b1ff5cb61c 100644
@@ -95,6 +95,8 @@ struct scalar {
 	u16 step;
 	/* Not a part of the value: it grew once at a loop header, see join_range() */
 	bool grew_once;
+	/* The value comes from an unproven insn (its check failed), see skip_unproven_insn() */
+	bool from_unproven;
 };
 
 /* The struct scalar that is an anonymous member of *@p */
@@ -646,7 +648,7 @@ static inline u32 bpf_stack_nr_slots(const struct bpf_func_state *frame)
 
 /*
  * Stack slot @spi of @frame, covering bytes [fp - (spi + 1) * 8, fp - spi * 8).
- * The caller must ensure spi < bpf_stack_nr_slots(frame), see bpf_grow_stack_state().
+ * The caller must ensure spi < bpf_stack_nr_slots(frame), see grow_stack_state().
  */
 static inline struct bpf_stack_state *bpf_stack_slot(const struct bpf_func_state *frame, u32 spi)
 {
@@ -891,6 +893,7 @@ struct bpf_loop {
 	/* while bpf_loop_per_pass.cost is not above @budget: */
 	u64 budget;
 	u32 max_peel_cnt;	/* peel up to this trip */
+	bool disjoint_apart;	/* disjoint values in data_deps stay apart, also in the leftover */
 	);
 	bool partitioned;	/* the last partition was for this loop */
 	struct bpf_loop_per_pass this_pass;
@@ -944,6 +947,7 @@ struct bpf_insn_aux_data {
 		u64 call_num;	/* any of these, or the offset of a refcount */
 	};
 	struct btf_struct_meta *kptr_struct_meta;
+	u64 suspect_loops; /* of the states that got here */
 	u64 map_key_state; /* constant (32 bit) key tracking for maps */
 	int ctx_field_size; /* the ctx field size for load insn, maybe 0 */
 	u32 seen; /* this insn was processed by the verifier at env->check_cnt */
@@ -957,7 +961,9 @@ struct bpf_insn_aux_data {
 	u64 cast_mov:1; /* addr_space_cast of a pointer that is not in arena, it's a move */
 	u64 loop_guard:1; /* may_goto is added in front of this instruction */
 	u64 guard_unwinds:1; /* it leaves the subprog */
+	u64 speculative_first:1; /* a speculative state came to it first */
 	u64 call_recorded:1; /* see record_call_fixup() */
+	u64 pessimized:1; /* see bpf_partition_for_pessimized() */
 	u64 guard_edge_dropped:1; /* an edge of may_goto from here was dropped */
 	u64 alu_state:5; /* used in combination with alu_limit */
 	/* true if STX or LDX instruction is a part of a spill/fill
@@ -984,6 +990,7 @@ struct bpf_insn_aux_data {
 	/* what one pass gives to the next pass, see bpf_flow_new_pass() */
 	u32 guard_no_unwind:1; /* it cannot unwind from here, at least sometimes */
 	u32 guard_unset_reg:1; /* where it goes a register is read that is not set here */
+	u32 non_speculative_first:1; /* speculative states end here, their fixups did not fit */
 
 	/* below flags are initialized once */
 	u32 bb_end:1; /* last instruction of a basic block */
@@ -1136,6 +1143,7 @@ struct bpf_subprog_info {
 	u32 exit_idx;
 	u32 callx_edge; /* 1 + the first of its env->callx_edges, 0 if none */
 	struct bpf_iarray *jt; /* jump table shared by all gotox of this subprogram */
+	u32 deepest_insn; /* the insn that set stack_depth */
 	u16 stack_depth; /* max. stack depth used by this function */
 	u16 stack_extra;
 	u16 arena_stack_depth; /* size of the frame in the stack in arena */
@@ -1349,6 +1357,8 @@ struct bpf_verifier_env {
 	bool test_reg_invariants;	/* fail verification on register invariants violations */
 	bool uses_arena_sp;		/* the program has insns with BPF_REG_ARENA_SP */
 	bool path_sensitive;		/* no joins, see run_path_sensitive() */
+	bool for_log;			/* the verdict is known, see do_check_all() */
+	struct bpf_precision *precision;
 	u64 cost, mem;			/* see bpf_check_limits() */
 	u64 max_cost, max_mem;
 	u64 hash_seed;			/* see bpf_hash_join_key() */
@@ -1358,10 +1368,13 @@ struct bpf_verifier_env {
 	/* What a pass writes. Each pass starts from the snapshot. */
 	struct_group_tagged(bpf_env_per_pass, per_pass,
 	int err;			/* the first error */
+	u32 err_insn;
 	bool imprecise;			/* a state before the first error is imprecise */
 	bool over_limit;		/* see bpf_check_limits() */
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
 	bool guards_late;		/* see bpf_flow_loop_gets_guards() */
+	bool extra_values;		/* a state can have constants that no run has */
+	bool new_linear_xreg;		/* see bpf_same_insns_unproven() */
 	bool seen_direct_write;
 	/* a register may point to the stack and is not PTR_TO_STACK, see bpf_reg_state::buf */
 	bool seen_stack_slice;
@@ -1671,6 +1684,13 @@ int bpf_renumber_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st
 
 bool bpf_xreg_in_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 		      u32 fr, u32 xregno);
+void bpf_note_reads_from_unproven(struct bpf_verifier_env *env, u32 idx);
+void bpf_note_unproven_insn(struct bpf_verifier_env *env,
+			    const struct bpf_verifier_state *st, u32 idx);
+bool bpf_insn_is_unproven(struct bpf_verifier_env *env);
+void bpf_note_fixups_differ(struct bpf_verifier_env *env);
+void bpf_find_unproven_after_pass(struct bpf_verifier_env *env);
+bool bpf_same_insns_unproven(struct bpf_verifier_env *env);
 /*
  * The two limits of the verifier, for the whole load. The unit of cost is one step of a scan,
  * about a dozen insns of the CPU. Memory is the bytes of states and tables at a time.
@@ -1718,6 +1738,8 @@ int bpf_flow_place_guards(struct bpf_verifier_env *env);
 /* verifier.c, for flow.c */
 int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge_loop,
 			bool *starts_leftover);
+int bpf_flow_edge_unproven(struct bpf_verifier_env *env, struct bpf_verifier_state *st, u32 idx,
+			   int err);
 #define BPF_EXIT_NEEDS_CALLER	1	/* verify the call in the frames of the caller */
 int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,
 		    const struct bpf_verifier_state *exit, int call_idx);
@@ -1735,7 +1757,6 @@ void bpf_mark_reg_not_init(const struct bpf_verifier_env *env,
 			   struct bpf_reg_state *reg);
 void bpf_mark_reg_known_scalar(struct bpf_reg_state *reg, u64 imm);
 void bpf_mark_reg_unknown(struct bpf_reg_state *reg);
-int bpf_grow_stack_state(struct bpf_verifier_env *env, struct bpf_func_state *state, int size);
 
 static inline int bpf_get_spi(s32 off)
 {
kernel/bpf/Makefile +1 -0
index f05ccfce45c..bb2841387d4 100644
@@ -14,6 +14,7 @@ obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_in
 obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o
 obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o check_btf.o flow.o join.o
 obj-$(CONFIG_BPF_SYSCALL) += equation.o
+obj-$(CONFIG_BPF_SYSCALL) += precision.o
 obj-${CONFIG_BPF_LSM}	  += bpf_inode_storage.o
 obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o
 obj-$(CONFIG_BPF_JIT) += trampoline.o
kernel/bpf/log.c +2 -1
index 8a905f4df9b..dfe40d86677 100644
@@ -751,7 +751,8 @@ void print_verifier_state(struct bpf_verifier_env *env, const struct bpf_verifie
 			break;
 		case STACK_DYNPTR:
 			/* skip to main dynptr slot */
-			i += BPF_DYNPTR_NR_SLOTS - 1;
+			if (!reg->dynptr.first_slot)
+				i += BPF_DYNPTR_NR_SLOTS - 1;
 			reg = &bpf_stack_slot(state, i)->spilled_ptr;
 
 			verbose(env, " fp%d", (-i - 1) * BPF_REG_SIZE);
kernel/bpf/precision.c new file +142 -0

142 lines not on this page · raw message

kernel/bpf/precision.h new file +39 -0
new file mode 100644
index 00000000000..23980622006
@@ -0,0 +1,39 @@
+/* SPDX-License-Identifier: GPL-2.0-only */
+/* What precision.c and failing_path.c share */
+#ifndef __BPF_PRECISION_H
+#define __BPF_PRECISION_H
+
+#include <linux/bpf_verifier.h>
+
+/* What a pass finds about its errors */
+struct precision_per_pass {
+	/* bitmaps of insns */
+	unsigned long *unproven_insns;
+	unsigned long *call_insns;		/* lead to unproven insns, or write what is held */
+	unsigned long *bad_read_insns;		/* unproven because of an unreadable xreg */
+	unsigned long *unproven_funcs;		/* of functions */
+	u64 suspect_loops, first_suspect_loops;	/* of the unproven states, of the first one */
+};
+
+struct bpf_precision {
+	/* this pass, and the last pass whose partition was kept */
+	struct precision_per_pass this_pass, last_pass;
+	unsigned long *bad_value_insns;		/* unproven, its value is possibly the cause */
+	unsigned long *last_unproven_insns;	/* in the last pass */
+	unsigned long *bad_read_insns_done;
+	u32 last_unproven_left;		/* last_unproven_insns whose check did not fail again */
+	bool new_nospec;
+
+	/* The path-sensitive run */
+	unsigned long *err_insns;		/* insns at which the failing path can end */
+};
+
+static inline bool bpf_calls_function(struct bpf_verifier_env *env, int idx)
+{
+	struct bpf_insn *insn = &env->prog->insnsi[idx];
+
+	return bpf_pseudo_call(insn) || bpf_is_callx(insn) ||
+	       env->insn_aux_data[idx].calls_callback || bpf_is_async_callback_calling_insn(insn);
+}
+
+#endif
kernel/bpf/verifier.c +190 -21

334 lines not on this page · raw message

Signature · 1 line
2.55.0
#26 lore raw

Re: [PATCH bpf-next v2 22/49] bpf: Continue a pass after an unproven insn

TL;DR: - Possible NULL env->precision dereference on any rejected program, a kernel oops that breaks bisection until a later patch - note_error() zeroes log level, so failed-load logs and stats may…
Quoted 1 line

bpf: Continue a pass after an unproven insn

TL;DR:
- Possible NULL env->precision dereference on any rejected program, a kernel oops that breaks bisection until a later patch
- note_error() zeroes log level, so failed-load logs and stats may be lost
- Early return may skip noting an unproven insn

Quoted 3 lines
kernel/bpf/precision.c +0 -0

[ ... ]

kernel/bpf/precision.c line 142

Quoted 8 lines
kernel/bpf/precision.c +8 -0
+bool bpf_same_insns_unproven(struct bpf_verifier_env *env)
+{
+	struct bpf_precision *prec = env->precision;
+
+	return env->for_log || (prec->last_unproven_left == 1 && !env->new_linear_xreg &&
+				test_bit(env->insn_idx, prec->last_unproven_insns) &&
+				!test_bit(env->insn_idx, prec->this_pass.unproven_insns));
+}

Can this dereference a NULL prec? Nothing in this commit assigns env->precision, and env comes from kvzalloc_obj() in bpf_check(), so the pointer stays NULL. env->for_log and env->path_sensitive are not written either, so both stay false.

A rejected program then reaches the new code in do_check_block():

kernel/bpf/precision.c

Quoted 4 lines
kernel/bpf/precision.c +4 -0
+		} else if (error_is_recoverable(err) && !env->path_sensitive) {
+			env->insn_idx = prev_insn_idx;
+			if (bpf_same_insns_unproven(env))
+				return err;

For example a socket filter with r0 = *(u32 *)(r1 + 0xffff) returns -EACCES from do_check_insn(), and bpf_same_insns_unproven() reads prec->last_unproven_left through NULL. Before this patch the load was rejected with the error.

The same NULL pointer is used by these paths:

note_error() -> bpf_note_unproven_insn()
__set_bit(..., prec->this_pass.unproven_funcs) (reached from do_check_common() for any error of a state, e.g. -EFAULT)

check_held_in_leftover() -> bpf_same_insns_unproven()

fixups_differ() -> bpf_note_fixups_differ() -> suspect_loops_of_insn()
env->precision->this_pass.suspect_loops |= ...
(reached before the nospec_ends_path() check, so a speculative state that hits "same insn cannot be used with different pointers" also crashes, where it used to be accepted with a nospec)

Any user who can load BPF programs can trigger this.

The allocation is added later in the series: bpf_precision_init() in 61b3482f7d0f ("bpf: Partition the states after an error"), first called from do_check_all() in 02e7abee2ca0 ("bpf: Verify in passes"). The commits from this one up to that point oops on any rejected program, which breaks bisection. Should the allocation, or a NULL check on env->precision, be part of this commit?

The commit message also says check_after_pass() uses bpf_find_unproven_after_pass(), but nothing calls that function until 02e7abee2ca0.

Also, in this commit do_check_common() and do_check_main() still return "ret". If env->precision were valid, a program with a failed check would be skipped past by skip_unproven_insn() and could be accepted with ret == 0, although the commit message says "Such a pass accepts nothing".

Quoted 3 lines
kernel/bpf/verifier.c +0 -0

[ ... ]

kernel/bpf/verifier.c static bool is_error_of_state(struct bpf_verifier_env *env, int err) · line 21278

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+/* The pass has an error. The log ends with the first error. */
+static void note_error(struct bpf_verifier_env *env, int err)
+{
+	if (!is_error_of_state(env, err))
+		return;
+	if (!env->err) {
+		env->err = err;
+		env->err_insn = env->insn_idx;
+		env->log.level = 0;
+	}

Is the user's log level restored before bpf_check() calls bpf_log_attr_finalize()? bpf_vlog_finalize() treats level 0 as "no log":

    *log_size_actual = 0;
    if (!log || log->level == 0 || log->level == BPF_LOG_KERNEL)
        return 0;

For a failed load with a log buffer this means:

- log_true_size is reported as 0 instead of the needed size
- a log that wrapped in the default rotating mode is not rotated back
- a truncated log no longer returns -ENOSPC
- print_verification_stats() checks env->log.level, so the "processed N insns" and stats lines are no longer printed for a failing program

At this commit the NULL env->precision dereference in the bpf_note_unproven_insn() call below happens first. At 61b3482f7d0f the problem is visible, because the level is still not restored. 92146e43b75d ("bpf: Reproduce an error on one path, with no joins") saves and restores env->log.level later in the series. Could this commit restore the level before the log is finalized?

[ ... ]

kernel/bpf/verifier.c static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx) · line 21542

Quoted 12 lines
kernel/bpf/verifier.c +8 -0
@@ -21380,12 +21532,29 @@ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
 			need_nospec(env, prev_insn_idx);
 			free_pushed_states(env);
 			goto process_bpf_exit;
+		} else if (error_is_recoverable(err) && !env->path_sensitive) {
+			env->insn_idx = prev_insn_idx;
+			if (bpf_same_insns_unproven(env))
+				return err;
+			if (from_unproven)
+				bpf_note_reads_from_unproven(env, prev_insn_idx);
+			else
+				note_error(env, err);

When bpf_same_insns_unproven() is true this returns before note_error(), so the insn that ends the pass is never set in precision->this_pass.unproven_insns. The fallback in do_check_common() does not help once another insn has already failed in the pass:

    if (ret && !env->err)
        note_error(env, ret);

check_held_in_leftover() has the same shape: it returns -EINVAL before note_error() when bpf_same_insns_unproven() is true. bpf_flow_edge_unproven() handles this differently: it computes "last" with bpf_same_insns_unproven(), calls note_error() anyway, and only then returns.

At the series tip, bpf_partition_more() swaps this_pass into last_pass, copies last_pass.unproven_insns into last_unproven_insns and ANDs err_insns with it. The lost insn is dropped from the next pass's set and from the insns where the failing path can end.

A concrete case: pass N has unproven insns {X, Y}, with X as err_insn. In pass N+1, Y fails first and is noted, so last_unproven_left drops from 2 to 1. Then X fails:

last_unproven_left == 1
X in last_unproven_insns
X not in this_pass.unproven_insns

so do_check_block() returns without noting X. partition_helped() then evaluates !test_bit(first_unproven_insn, this_pass.unproven_insns) as true even though X failed again, and the partition is reported as helpful. The path-sensitive run that follows cannot end at X, because X was masked out of err_insns.

The verdict stays safe since a pass with env->err set accepts nothing, but the partitions kept, the number of passes and the failing path that is logged can differ. Should note_error() be called before this early return, as bpf_flow_edge_unproven() does?

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

#27 lore raw

PATCH v2 23/49 bpf: Find the xregs that an unproven insn depends on

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

After an error the next pass has to keep some states apart. To keep all apart is too costly. Find the xregs that the unproven insn depends on, the deps:

data_deps their value flows into an operand of the insn
control_deps their value flows into a jump that can skip the insn

bpf_compute_deps() makes a backward slice. It is the analysis of liveness with other seeds:

                                        data     control
   1: r6 = ctx->idx                     r1       -
   2: r7 = 0                            r6       -
   3: if r6 <= 7 goto 5                 r6       r7
   4: r7 = -22                          r6       -
   5: if r7 != 0 goto exit  join point  r6       r7    <- seed
   6: r3 = map value                    r6       -
   7: r3 += r6                          r6 r3    -
   8: r0 = *(u8 *)(r3 + 0)              r3       -     <- seed

It follows values through calls, returns and the frames of callers. What a helper stores is not known. But the address and the size decide which slots it keeps.
A store through a join of two addresses forgets the slots between them. So may_write_mask has these slots too.
What is held is tracked like an xreg: the insns that acquire or release write it. find_control_seeds() finds the jumps with one edge that leads to the insn and one edge that does not.

bpf_flow_is_bb_start() comes in a later patch. It tells where a basic block starts.

The masks are a guess. They select where a pass does more work. A wrong mask cannot make the verifier accept an unsafe program.

---
 include/linux/bpf_verifier.h |   5 +
 kernel/bpf/liveness.c        |   4 +-
 kernel/bpf/precision.c       | 541 +++++++++++++++++++++++++++++++++++
 kernel/bpf/precision.h       |  55 ++++
 kernel/bpf/verifier.c        |   7 +-
 5 files changed, 609 insertions(+), 3 deletions(-)
include/linux/bpf_verifier.h +5 -0
index 3b1ff5cb61c..db18d451070 100644
@@ -991,6 +991,8 @@ struct bpf_insn_aux_data {
 	u32 guard_no_unwind:1; /* it cannot unwind from here, at least sometimes */
 	u32 guard_unset_reg:1; /* where it goes a register is read that is not set here */
 	u32 non_speculative_first:1; /* speculative states end here, their fixups did not fit */
+	u32 acquires:1; /* a reference or a lock */
+	u32 releases:1;
 
 	/* below flags are initialized once */
 	u32 bb_end:1; /* last instruction of a basic block */
@@ -1722,6 +1724,7 @@ static inline int bpf_add_cost_and_check(struct bpf_verifier_env *env, u64 cnt,
 int bpf_flow_prepare(struct bpf_verifier_env *env);
 void bpf_flow_reset(struct bpf_verifier_env *env);
 void bpf_flow_free(struct bpf_verifier_env *env);
+bool bpf_flow_is_bb_start(struct bpf_verifier_env *env, int insn_idx);
 bool bpf_flow_is_point(struct bpf_verifier_env *env, int insn_idx);
 int bpf_flow_deliver(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
 		     int insn_idx, int prev_insn_idx);
@@ -2417,6 +2420,8 @@ int bpf_compute_loops(struct bpf_verifier_env *env);
 int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx);
 bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header);
 
+int bpf_insn_callee(struct bpf_verifier_env *env, int idx);
+
 /* equation.c */
 int bpf_equation_env_init(struct bpf_verifier_env *env);
 void bpf_equation_env_free(struct bpf_verifier_env *env);
kernel/bpf/liveness.c +3 -1
index 4cc29334a69..7b00e17cab2 100644
@@ -1665,7 +1665,9 @@ static int record_stack_access_off(struct func_instance *instance, const struct
 			return err;
 	}
 	if (info.may_write) {
-		err = mark_stack_may_write(instance, frame, insn_idx, slot_lo, slot_hi);
+		/* A join of the offsets is a range. A write forgets the slots between them. */
+		err = mark_stack_may_write(instance, frame, insn_idx, slot_lo,
+					   (-arg->off[0] - 1) / STACK_SLOT_SZ);
 		if (err)
 			return err;
 	}
kernel/bpf/precision.c +541 -0

554 lines not on this page · raw message

kernel/bpf/precision.h +55 -0

84 lines not on this page · raw message

kernel/bpf/verifier.c +5 -2
index 6da1a0f5b44..ce26d681bb0 100644
@@ -21403,6 +21403,7 @@ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
 	struct bpf_insn *insns = env->prog->insnsi;
 	int insn_cnt = env->prog->len;
 	bool do_print_state = true, from_unproven;
+	u32 held;
 
 	for (;;) {
 		struct bpf_insn *insn;
@@ -21518,9 +21519,12 @@ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
 			return err;
 
 		bpf_equations_before_insn(env);
+		held = held_cnt(state);
 		from_unproven = reads_from_unproven(env);
 		fixups = insn_aux->fixups;
 		err = do_check_insn(env, &do_print_state) ?: bpf_equations_after_insn(env);
+		insn_aux->releases |= held_cnt(state) < held && err != PROCESS_BPF_EXIT;
+		insn_aux->acquires |= held_cnt(state) > held;
 		if (nospec_ends_path(env, state, err)) {
 			/* Prevent this speculative path from ever reaching the
 			 * insn that would have been unsafe to execute.
@@ -25164,13 +25168,12 @@ int bpf_check(struct bpf_prog **prog, union bpf_attr *attr, bpfptr_t uattr,
 	if (ret < 0)
 		goto skip_full_check;
 
-	bpf_free_subprog_jts(env);
-
 	ret = mark_fastcall_patterns(env);
 	if (ret < 0)
 		goto skip_full_check;
 
 	ret = do_check_all(env);
+	bpf_free_subprog_jts(env);
 	/* while the calls are what they are in the program */
 	if (env->log.level & BPF_LOG_STATS)
 		add_insns_of_callees(env);
Signature · 1 line
2.55.0
#28 lore raw

Re: [PATCH bpf-next v2 23/49] bpf: Find the xregs that an unproven insn depends on

TL;DR: - Possible NULL env->precision dereference in bpf_xreg_in_deps() via cut_range() on ordinary programs, breaking bisection - New functions have no callers, so unused-function warnings may fail…
Quoted 1 line

bpf: Find the xregs that an unproven insn depends on

TL;DR:
- Possible NULL env->precision dereference in bpf_xreg_in_deps() via cut_range() on ordinary programs, breaking bisection
- New functions have no callers, so unused-function warnings may fail -Werror builds

Quoted 3 lines
kernel/bpf/precision.c +0 -0

[ ... ]

kernel/bpf/precision.c line 50

Quoted 8 lines
kernel/bpf/precision.c +8 -0
+bool bpf_xreg_in_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+		      u32 fr, u32 xregno)
+{
+	unsigned long data_deps[XREG_WORDS], control_deps[XREG_WORDS];
+
+	if (!env->precision->data_deps ||
+	    xregno >= bpf_frame_mask(env, env->precision->data_deps, st, fr, data_deps))
+		return false;

Can env->precision be NULL here? At this commit nothing allocates it:
env is created with kvzalloc_obj() in bpf_check() and no code assigns env->precision. env->path_sensitive is never set either, so cut_range() always reaches this call:

    if (!env->path_sensitive && !bpf_xreg_in_deps(env, st, st->curframe, regno))
            return 0;

The path is bpf_check() -> do_check_all() -> do_check_block() -> do_check_insn() -> check_cond_jmp_op() -> cut_range() -> bpf_xreg_in_deps(). It runs for an undecided conditional jump on a scalar whose range wraps the end of the compare order, for example a sign-extended byte in [-128, 127] compared with an unsigned 'if r1 > 10'. That would dereference NULL + offsetof(struct bpf_precision, data_deps) while loading an ordinary program.

The parent commit 71c3255177f2 ("bpf: Continue a pass after an unproven insn") added the cut_range() call without a definition, so it does not link. This commit adds the definition, which turns the link failure into a runtime NULL dereference.

env->precision is allocated by bpf_precision_init() added in 61b3482f7d0f ("bpf: Partition the states after an error"), but nothing calls it until 02e7abee2ca0 ("bpf: Verify in passes"), 14 commits after this one. Every commit in between can oops in the verifier, which breaks bisection.

Should env->precision be allocated (or checked for NULL) in this patch, or should the cut_range() call move to the patch that allocates it?

[ ... ]

Quoted 2 lines
kernel/bpf/precision.c +2 -0
+static int find_calls_to_unproven(struct bpf_verifier_env *env)
+{

[ ... ]

Quoted 2 lines
kernel/bpf/precision.c +2 -0
+static int compute_deps_of_unproven(struct bpf_verifier_env *env)
+{

[ ... ]

kernel/bpf/precision.c bool bpf_same_insns_unproven(struct bpf_verifier_env *env) · line 632

Quoted 2 lines
kernel/bpf/precision.c +2 -0
+static int alloc_masks(struct bpf_verifier_env *env)
+{

This isn't a bug at runtime, but find_calls_to_unproven(), compute_deps_of_unproven() and alloc_masks() have no callers in the tree at this commit. Won't each of them give a 'defined but not used [-Wunused-function]' warning from precision.c?

With CONFIG_WERROR=y (the default under COMPILE_TEST, so allmodconfig), those warnings are errors and kernel/bpf/precision.c would not build.

find_blocks(), find_control_seeds(), add_control_deps(), may_not_return() and add_masks() are reachable only from these unused functions. That seems to be the only reason the call to bpf_flow_is_bb_start() (declared here, first defined in 8514cc01b0e8 "bpf: Prune or join each state that arrives") does not fail at link time.

The commit message mentions the late bpf_flow_is_bb_start() but not the missing callers. The callers arrive ten commits later in 61b3482f7d0f ("bpf: Partition the states after an error"), which adds
'ret = prec->data_deps ? 0 : alloc_masks(env);' and
'return find_calls_to_unproven(env) ?: partition_next(env);' in bpf_partition_more(), and calls compute_deps_of_unproven() from add_deps() and add_transitive_deps().

Could these functions be moved into 61b3482f7d0f, the commit that first calls them?

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

#29 lore raw

PATCH v2 24/49 bpf: Keep two states apart if data and control deps differ

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Two states meet at a join point. The join does harm if it makes a pair of values that no path has, and the unproven insn depends on the pair:

                r6 (data)    r7 (control)
   ok_state     0..7         0
   err_state    8..max       -22
   join         0..max       -22..0     has r6 = 8 with r7 = 0

One rule decides at all join points, bpf_must_keep_apart():

  what differs               action
  data dep and control dep   keep apart
  two data deps              keep apart
  one data dep, with a gap   keep apart   (0..1 and 100)
  one data dep, no gap       join         (0..7 and 8..9)
  control deps only          join
  other regs only            join

In pass 0 the masks are empty, so all states are joined.

At the header of a loop only a type or an object keeps states apart, else the loop has no end. If the join is imprecise, the loop is a suspect, also if the other state entered the loop at another time. At the first insn of a function a difference in data_deps is sufficient.

The hash functions and bpf_range_of_data_dep() let the table of states skip states that the rule keeps apart. They can skip more: two constants that differ by 2 or more, or a value and an unreadable xreg.

This rule replaces all flow_*_differs() rules and their tables.

---
 include/linux/bpf_verifier.h |  14 ++
 kernel/bpf/precision.c       | 390 +++++++++++++++++++++++++++++++++++
 kernel/bpf/precision.h       |  15 ++
 3 files changed, 419 insertions(+)
include/linux/bpf_verifier.h +14 -0
index db18d451070..f2fea1985ab 100644
@@ -893,9 +893,11 @@ struct bpf_loop {
 	/* while bpf_loop_per_pass.cost is not above @budget: */
 	u64 budget;
 	u32 max_peel_cnt;	/* peel up to this trip */
+	bool peeled_apart;	/* the join rule holds for states that start a peeled trip */
 	bool disjoint_apart;	/* disjoint values in data_deps stay apart, also in the leftover */
 	);
 	bool partitioned;	/* the last partition was for this loop */
+	bool peeled_joined;	/* at the start of a peeled trip, against the join rule */
 	struct bpf_loop_per_pass this_pass;
 	bool guarded;
 };
@@ -1684,6 +1686,18 @@ u64 bpf_hash64(const void *p, size_t len, u64 hash);
 u64 bpf_hash_join_key(const struct bpf_verifier_env *env, const struct bpf_verifier_state *st);
 int bpf_renumber_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
 
+/* precision.c, failing_path.c */
+enum bpf_join_point { BPF_JOIN_POINT, BPF_JOIN_POINT_HEADER, BPF_JOIN_POINT_CALLS };
+bool bpf_must_keep_apart(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
+			 struct bpf_verifier_state *new, enum bpf_join_point kind,
+			 const struct loop_stack_entry *entry);
+bool bpf_values_grew_in_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
+			     const struct bpf_verifier_state *new);
+u64 bpf_hash_apart_xregs(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			 u64 hash, bool consts);
+u64 bpf_hash_args(struct bpf_verifier_env *env, const struct bpf_verifier_state *st, u64 hash);
+void bpf_range_of_data_dep(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			   u32 *first, u32 *last);
 bool bpf_xreg_in_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 		      u32 fr, u32 xregno);
 void bpf_note_reads_from_unproven(struct bpf_verifier_env *env, u32 idx);
kernel/bpf/precision.c +390 -0

396 lines not on this page · raw message

kernel/bpf/precision.h +15 -0
index 63869360160..e057e452ec1 100644
@@ -21,6 +21,7 @@ struct precision_per_pass {
 	unsigned long *bad_read_insns;		/* unproven because of an unreadable xreg */
 	unsigned long *unproven_funcs;		/* of functions */
 	u64 suspect_loops, first_suspect_loops;	/* of the unproven states, of the first one */
+	bool disjoint_joined;			/* disjoint values in data_deps were joined */
 };
 
 /* callx calls one of the functions whose address is taken. They count as one function. */
@@ -55,6 +56,7 @@ struct bpf_precision {
 	bool new_nospec;
 
 	u16 *apart_xregno;	/* per insn, see bpf_range_of_data_dep() */
+
 	/* The path-sensitive run */
 	unsigned long *err_insns;		/* insns at which the failing path can end */
 	u32 *hops_to_err, *hops_to_exit;	/* per insn, see compute_hops() */
@@ -63,8 +65,21 @@ struct bpf_precision {
 	unsigned long loop_carried[XREG_WORDS];
 };
 
+struct state_cmp {
+	struct bpf_reg_state tmp[2];
+	u32 all, data_deps, cnt;
+	u32 disjoint_xregno;		/* an xreg of data_deps in the top frame, plus one */
+	u32 disjoint_apart;		/* what differs in these xregs */
+};
+
 u32 bpf_frame_mask(struct bpf_verifier_env *env, unsigned long *masks,
 		   const struct bpf_verifier_state *st, u32 fr, unsigned long *out);
+const struct bpf_reg_state *bpf_xreg_value(struct bpf_verifier_env *env,
+					   const struct bpf_func_state *f, u32 xregno,
+					   struct bpf_reg_state *tmp);
+void bpf_compare_states(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
+			const struct bpf_verifier_state *new, unsigned long *only,
+			const struct bpf_loop *iv_loop, struct state_cmp *cmp);
 int bpf_compute_deps(struct bpf_verifier_env *env, unsigned long *masks,
 		     const unsigned long *seed_insns);
 
Signature · 1 line
2.55.0
#30 lore raw

PATCH v2 25/49 bpf: Join any two states that have the same join_key

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The old join could fail: a pointer and a number had no join, and the states stayed apart. So the number of states had no bound but the caps. The new join is total:

map ptr | scalar -> unreadable -+
two objects -> unreadable -+-> a use is unproven
p+1, p+2, ... at header -> p+unknown -+ -> next pass keeps apart

If nothing uses the value, the join costs nothing. An unreadable xreg can hold a pointer, so __is_pointer_value() is true for it.

A number can grow in each trip of a leftover. The first growth is a join. After that the bound that moves goes to a threshold:

do { a[i] = 0; i += 3; } while (i < 30); 29
while (i < 30) { a[i] = 0; i += 3; } 32

The thresholds are the constants of the loop and of the functions that it calls, one less, and one step more. They apply to the deps. Other xregs stop at 0, S32_MAX, U32_MAX or S32_MIN. A threshold is a
guess: the state that comes back is compared with it. bpf_flow_insn_after() walks the insns of a loop.

The old join compared its result with both inputs on each call. The new one changes dst in place. It compares the result only with src, and only with BPF_F_TEST_REG_INVARIANTS.

---
 include/linux/bpf_verifier.h |  24 ++--
 kernel/bpf/fixups.c          |   1 +
 kernel/bpf/flow.c            |  12 +-
 kernel/bpf/join.c            | 243 +++++++++++++++++++++++++++++++++++
 kernel/bpf/loops.c           | 108 ++++++++++++++++
 kernel/bpf/verifier.c        |  59 ++++-----
 6 files changed, 399 insertions(+), 48 deletions(-)
include/linux/bpf_verifier.h +14 -10
index f2fea1985ab..1a42a5e1ab2 100644
@@ -863,13 +863,6 @@ struct bpf_loop_per_pass {
 	u64 cost;		/* for the states that the loop keeps apart */
 };
 
-struct bpf_loop_rungs {
-	s64 max[2];
-	s64 min[2];
-	bool has_max;
-	bool has_min;
-};
-
 struct bpf_loop {
 	enum bpf_loop_kind kind;
 	u32 header;
@@ -899,6 +892,10 @@ struct bpf_loop {
 	bool partitioned;	/* the last partition was for this loop */
 	bool peeled_joined;	/* at the start of a peeled trip, against the join rule */
 	struct bpf_loop_per_pass this_pass;
+	/* sorted constants of the loop, the largest and the smallest constant that an insn adds */
+	s64 *thresholds;
+	u32 threshold_cnt, threshold_cap;
+	s32 max_step, min_step;
 	bool guarded;
 };
 
@@ -1686,6 +1683,11 @@ u64 bpf_hash64(const void *p, size_t len, u64 hash);
 u64 bpf_hash_join_key(const struct bpf_verifier_env *env, const struct bpf_verifier_state *st);
 int bpf_renumber_ids(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
 
+/* join.c */
+int bpf_states_join(struct bpf_verifier_env *env, struct bpf_verifier_state *dst,
+		    const struct bpf_verifier_state *src, struct bpf_loop *leftover_loop,
+		    bool widen);
+
 /* precision.c, failing_path.c */
 enum bpf_join_point { BPF_JOIN_POINT, BPF_JOIN_POINT_HEADER, BPF_JOIN_POINT_CALLS };
 bool bpf_must_keep_apart(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
@@ -2291,8 +2293,8 @@ void scalar_add(struct scalar *dst, const struct scalar *a, const struct scalar
 void scalar_alu(struct scalar *dst, const struct scalar *src, const struct bpf_insn *insn);
 bool scalar_intersect(struct scalar *dst, const struct scalar *src, u32 bits);
 void scalar_union(struct scalar *acc, const struct scalar *src);
-void scalar_widen(struct scalar *s, const struct scalar *old,
-		  const struct bpf_loop_rungs *rungs, int linear);
+void scalar_widen(struct scalar *s, const struct scalar *old, s64 min_threshold, s64 max_threshold);
+
 int bpf_stack_liveness_init(struct bpf_verifier_env *env);
 void bpf_stack_liveness_free(struct bpf_verifier_env *env);
 int bpf_live_stack_query_init(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
@@ -2432,8 +2434,10 @@ u8 bpf_rev_opcode(u8 opcode);
 int bpf_compute_idoms(struct bpf_verifier_env *env);
 int bpf_compute_loops(struct bpf_verifier_env *env);
 int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx);
+int bpf_flow_insn_after(struct bpf_verifier_env *env, int idx);
 bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header);
-
+u32 bpf_loop_thresholds_below(const struct bpf_loop *loop, s64 k);
+int bpf_loop_collect_thresholds(struct bpf_verifier_env *env, struct bpf_loop *loop);
 int bpf_insn_callee(struct bpf_verifier_env *env, int idx);
 
 /* equation.c */
kernel/bpf/fixups.c +1 -0
index 2fa6065b0d9..bd26c6f563e 100644
@@ -753,6 +753,7 @@ static void free_loop(struct bpf_loop *loop)
 {
 	if (!loop)
 		return;
+	kvfree(loop->thresholds);
 	kvfree(loop);
 }
 
kernel/bpf/flow.c +11 -1
index f8e8ea7b05a..0d9bd4652bb 100644
@@ -16,6 +16,7 @@ struct flow_kept {
 struct bpf_flow {
 	/* computed once */
 	u32 *pos;			/* place of the insn in the order */
+	s32 *insn_after;		/* the next insn in the order, or -1 */
 };
 
 /*
@@ -32,7 +33,7 @@ struct bpf_flow {
 static int flow_compute_order(struct bpf_verifier_env *env, struct bpf_flow *flow)
 {
 	struct bpf_insn_aux_data *aux = env->insn_aux_data;
-	int len = env->prog->len, i, s, n, h, top, depth;
+	int len = env->prog->len, i, s, n, h, top, depth, prev = -1;
 	int *next, *head, *tail, *stack;
 	unsigned long *linked;
 	u32 pos = 0;
@@ -82,6 +83,10 @@ static int flow_compute_order(struct bpf_verifier_env *env, struct bpf_flow *flo
 				continue;
 			}
 			flow->pos[n] = pos++;
+			flow->insn_after[n] = -1;
+			if (prev >= 0)
+				flow->insn_after[prev] = n;
+			prev = n;
 			if (aux[n].loop && head[n] >= 0) {
 				stack[depth++] = n;
 				n = head[n];
@@ -100,6 +105,11 @@ static int flow_compute_order(struct bpf_verifier_env *env, struct bpf_flow *flo
 	return err;
 }
 
+int bpf_flow_insn_after(struct bpf_verifier_env *env, int idx)
+{
+	return env->flow->insn_after[idx];
+}
+
 /* Does the insn at @idx stop the loop @h? */
 static bool flow_is_bound(struct bpf_verifier_env *env, int h, int idx)
 {
kernel/bpf/join.c +243 -0

248 lines not on this page · raw message

kernel/bpf/loops.c +108 -0

117 lines not on this page · raw message

kernel/bpf/verifier.c +22 -37

104 lines not on this page · raw message

Signature · 1 line
2.55.0
#31 lore raw

PATCH v2 26/49 bpf: Check the equations when a state is pruned or joined

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Ranges do not show that a state has a relation:

old: r1 0..7, r2 0..7, r1 == r2
cur: r1 0..7, r2 0..7 old does not subsume cur

check_equations() looks for a value in cur for each sym of old:

  old:  r1 = sym0       r2 = 4 * sym0 + 8     sym0 0..7
  cur:  r1 = sym5 + 1   r2 = 4 * sym5 + 12    sym5 0..3

r1: sym0 is sym5 + 1, and 1..4 is in 0..7
r2: (4 * sym5 + 12 - 8) / 4 is sym5 + 1 too

A join needs equations that hold in both states. The next patch guesses them. This patch checks the guess with the same function:

guess -> check in dst and in src -> delete what fails -> check again

The worst guess gives no equation.

A widened state is saved as it is. Its equations are applied to the copy that runs, see needs_refine. Else the state at the header can get smaller again, and the loop has no fixpoint.

An infeasible state ends after the next jump. It does not subsume a state that is feasible.

---
 include/linux/bpf_verifier.h |   7 ++
 kernel/bpf/equation.c        | 180 +++++++++++++++++++++++++++++++++++
 kernel/bpf/join.c            |   2 +
 kernel/bpf/states.c          |   2 +-
 4 files changed, 190 insertions(+), 1 deletion(-)
include/linux/bpf_verifier.h +7 -0
index 1a42a5e1ab2..a2e8844f291 100644
@@ -2459,7 +2459,14 @@ void bpf_equations_fill(struct bpf_verifier_env *env, struct bpf_func_state *fra
 void bpf_equations_refine_all(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
 void bpf_equations_jump(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int idx,
 			bool taken);
+bool bpf_equations_subsume(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
+			   const struct bpf_verifier_state *cur);
 void bpf_equations_print(struct bpf_verifier_env *env, const struct bpf_verifier_state *st);
+void bpf_equations_pre_join(struct bpf_verifier_env *env, struct bpf_verifier_state *dst,
+			    const struct bpf_verifier_state *src, struct bpf_loop *leftover_loop,
+			    bool widen);
+void bpf_equations_post_join(struct bpf_verifier_env *env, struct bpf_verifier_state *dst,
+			     const struct bpf_verifier_state *src);
 u32 bpf_equations_bytes(const struct bpf_equations *eqs);
 void scalar_bounds_sync(struct scalar *s);
 bool scalar_subsumes(const struct scalar *old, const struct scalar *cur);
kernel/bpf/equation.c +180 -0

186 lines not on this page · raw message

kernel/bpf/join.c +2 -0
index 9b9cddfa124..caaf711570a 100644
@@ -235,9 +235,11 @@ int bpf_states_join(struct bpf_verifier_env *env, struct bpf_verifier_state *dst
 	env->pkt_pair_cnt = 0;
 	env->imprecise |= !env->err;
 	dst->suspect_loops |= src->suspect_loops;
+	bpf_equations_pre_join(env, dst, src, leftover_loop, leftover_loop && widen);
 	for (j.fr = 0; j.fr <= dst->curframe; j.fr++)
 		join_func(&j, dst->frame[j.fr], src->frame[j.fr],
 			  env->insn_aux_data[bpf_frame_insn_idx(dst, j.fr)].live_regs_before);
+	bpf_equations_post_join(env, dst, src);
 	dst->max_held_cnt = max(dst->max_held_cnt, src->max_held_cnt);
 	/* no equation is found over a limit */
 	if (env->test_reg_invariants && !bpf_state_subsumes(env, dst, src) &&
kernel/bpf/states.c +1 -1
index fa21a9174f6..23e3adb9822 100644
@@ -640,5 +640,5 @@ bool bpf_state_subsumes(struct bpf_verifier_env *env, const struct bpf_verifier_
 				       bpf_frame_insn_idx(old, i)))
 			return false;
 
-	return true;
+	return bpf_equations_subsume(env, old, cur);
 }
Signature · 1 line
2.55.0
#32 lore raw

PATCH v2 27/49 bpf: Guess the equations of a join

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A join of ranges forgets what moves together. A phi is a sym of the join. It has one value in each state:

               trip   r1         r2             r3
   old state   0      0          p              0..9
   new state   1      4          p + 8          1..9
   join        sym0   4 * sym0   p + 8 * sym0   sym0 + (0..9)

join_expr() looks for a phi that gives both values. If there is none, it makes one. The sums and ops of the two states are translated to the phis. A sym can become two phis. Each of them is tried.

The phi that is 0 in the old state and 1 in the new state is the selector. It can be a stored condition:

c = 0, len = 0..8 | c = 1, len = 64..72
join: len - 64 * c = 0..8

A number gets a phi if its two ranges are disjoint, in 64 bits or in the low 32 bits. A helper returns an int, and the high bits are not known:

w9 = 0; if w0 s> -1 goto L; w9 = -155; L: ...; if w0 s< 0 goto err

A phi that grows is widened to a threshold, and keeps its step. The low 32 bits go around their own circle, so an int can go through 0:

int i = -5; do { ... } while (++i != 3); 0xfffffffb .. 0 .. 2

It terminates. From the third join around a cycle only the equations of the old state are kept, and an equation can only get weaker.

The cpu can speculate past the test of c. So a constant makes no phi without bypass_spec_v1.

A number can grow in a loop and in the loop around it:

  for (j = 0; j < 13; j++) {
          for (k = 0; k < 20; k++)
                  off += 0..2;
          off += 0..1;
  }
  buf[off]                      off is 0..533

The second outer trip enters the inner loop again. Each state shows one trip index, the other one is 0:

  old state   j = 0   off = 2 * k + d
  new state   k = 0   off = 41 * j + d

No equation holds in both, so off has no bound, and all trips have to be peeled. Make a sym for the two parts:

join m = 2 * k + 41 * j, off = m + d

All of this file is a guess, see the previous patch.

insns processed

  program                 bpf-next   without m   with m
  strobemeta_nounroll1    10658      48984       1127
  strobemeta_nounroll2    22116      52061       1127
  strobemeta_subprogs     10829      45634       1007
---
 include/linux/bpf_verifier.h |   3 +
 kernel/bpf/Makefile          |   1 +
 kernel/bpf/equation.c        |   1 +
 kernel/bpf/equation.h        |   5 +
 kernel/bpf/equation_join.c   | 541 +++++++++++++++++++++++++++++++++++
 kernel/bpf/fixups.c          |   1 +
 6 files changed, 552 insertions(+)
 create mode 100644 kernel/bpf/equation_join.c
include/linux/bpf_verifier.h +3 -0
index a2e8844f291..065ffac5ffd 100644
@@ -473,6 +473,7 @@ struct loop_stack_entry {
 	bool peeled;		/* in a peeled trip, not in the leftover */
 	/* an xreg: how many times the program came back to the header */
 	struct scalar trip_index;
+	bool trip_widened;	/* it was moved to a threshold, or it does not grow */
 };
 
 /* The state is in a walk on patience, which may not get to the end of the loop */
@@ -891,6 +892,8 @@ struct bpf_loop {
 	);
 	bool partitioned;	/* the last partition was for this loop */
 	bool peeled_joined;	/* at the start of a peeled trip, against the join rule */
+	struct bpf_iv_threshold *iv_thresholds;	/* where an iv can stop, see equation_join.c */
+	u32 iv_threshold_cnt, iv_threshold_cap;
 	struct bpf_loop_per_pass this_pass;
 	/* sorted constants of the loop, the largest and the smallest constant that an insn adds */
 	s64 *thresholds;
kernel/bpf/Makefile +1 -0
index bb2841387d4..575c7d0ff4e 100644
@@ -14,6 +14,7 @@ obj-$(CONFIG_BPF_SYSCALL) += local_storage.o queue_stack_maps.o ringbuf.o bpf_in
 obj-$(CONFIG_BPF_SYSCALL) += bpf_local_storage.o bpf_task_storage.o
 obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o check_btf.o flow.o join.o
 obj-$(CONFIG_BPF_SYSCALL) += equation.o
+obj-$(CONFIG_BPF_SYSCALL) += equation_join.o
 obj-$(CONFIG_BPF_SYSCALL) += precision.o
 obj-${CONFIG_BPF_LSM}	  += bpf_inode_storage.o
 obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o
kernel/bpf/equation.c +1 -0
index 2e182636094..041311f0d56 100644
@@ -2158,6 +2158,7 @@ void bpf_equations_pre_join(struct bpf_verifier_env *env, struct bpf_verifier_st
 		/* what enters the loop can break the equations that keep the xregs small */
 		if (enters && dst->equations.needs_refine)
 			bpf_equations_refine_all(env, dst);
+		bpf_guess_equations(env, dst, src, leftover_loop, widen);
 		normalize_equations(env, &env->eq_env->join_state);
 		while (!check_equations(env, eqs, dst, eqs) || !check_equations(env, eqs, src, eqs))
 			normalize_equations(env, &env->eq_env->join_state);
kernel/bpf/equation.h +5 -0
index 5a2d7f24658..564ff6e5e6c 100644
@@ -79,6 +79,7 @@ struct bpf_equation_env {
 	struct bpf_verifier_state join_state;	/* it has equations and no frames */
 	struct join_phi *phis;
 	u32 *phi_index;
+	u32 phi_cap, phi_index_cap;
 };
 
 #define for_each_sym_equation(env, eqs, pos)						\
@@ -185,4 +186,8 @@ bool bpf_find_next_diff(struct bpf_verifier_env *env, const struct bpf_equations
 void bpf_eval_diff(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 		   const struct expr *a, const struct expr *b, struct scalar *bounds);
 
+/* equation_join.c */
+void bpf_guess_equations(struct bpf_verifier_env *env, const struct bpf_verifier_state *dst,
+			 const struct bpf_verifier_state *src, struct bpf_loop *leftover_loop,
+			 bool widen);
 #endif
kernel/bpf/equation_join.c new file +541 -0

541 lines not on this page · raw message

kernel/bpf/fixups.c +1 -0
index bd26c6f563e..9f816e2818d 100644
@@ -754,6 +754,7 @@ static void free_loop(struct bpf_loop *loop)
 	if (!loop)
 		return;
 	kvfree(loop->thresholds);
+	kvfree(loop->iv_thresholds);
 	kvfree(loop);
 }
 
Signature · 1 line
2.55.0
#33 lore raw

PATCH v2 28/49 bpf: Prune or join each state that arrives

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Add the table of states of the main pass. All states go one way:

              +---------+   next    +-------------------+
        +---->| pending |---------->| check basic block |
        |     +---------+           +---------+---------+
        | new                                 v
        |                           +-------------------+   subsumed
        +---------------------------|    join point     |-----> prune
          joined, or kept apart     +-------------------+

bpf_flow_deliver() cleans the state and updates its loop stack. flow_prune_or_join() compares it with the states that have the same join_key:

  if bpf_must_keep_apart()   look at the next state
  if old subsumes new        prune new
  if new subsumes old        free old, but widen in a leftover
  else                       join, and compare the join again

What the calls of a function already have is joined, it is not replaced. Else the result of a recursion with two exit insns is never widened. An exit state has no equations, because the calls do not get them.

There is no cap on the states at an insn. A list makes n states cost n * n. So one interval tree sorts all states by the hash of the join_key, then by the range of one xreg of data_deps, see flow_find().

The hash has kernel addresses, such as the address of a map. If it has 32 bits, two of 2048 states at one insn collide in 1 of 2000 loads, and that can change the result. So it has 64 bits. The tree has room for 32 bits. A state that collides only there is skipped.

@again is for an insn that is checked once more with a part of the
state: one function of a set, one part of a range. It meets no other state at that insn, see FLOW_AGAIN. The parts meet at the next insn.

bpf_flow_start_leftover() starts the leftover after the states that enter it are joined. The next patch makes a state pending.

---
 include/linux/bpf_verifier.h |   6 +-
 kernel/bpf/diagnostics.c     |   5 +
 kernel/bpf/diagnostics.h     |   1 +
 kernel/bpf/flow.c            | 604 ++++++++++++++++++++++++++++++++++-
 kernel/bpf/verifier.c        |  33 +-
 5 files changed, 632 insertions(+), 17 deletions(-)
include/linux/bpf_verifier.h +2 -4
index 065ffac5ffd..bf27d751966 100644
@@ -1744,11 +1744,8 @@ int bpf_flow_prepare(struct bpf_verifier_env *env);
 void bpf_flow_reset(struct bpf_verifier_env *env);
 void bpf_flow_free(struct bpf_verifier_env *env);
 bool bpf_flow_is_bb_start(struct bpf_verifier_env *env, int insn_idx);
-bool bpf_flow_is_point(struct bpf_verifier_env *env, int insn_idx);
 int bpf_flow_deliver(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
-		     int insn_idx, int prev_insn_idx);
-int bpf_flow_guard_edge(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
-			int insn_idx, int prev_insn_idx, enum bpf_guard_edge edge);
+		     int insn_idx, int prev_insn_idx, bool again);
 int bpf_flow_next(struct bpf_verifier_env *env, int *prev_insn_idx);
 int bpf_flow_call(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,
 		  struct bpf_verifier_state *entry, int subprog, int call_idx);
@@ -1760,6 +1757,7 @@ int bpf_flow_place_guards(struct bpf_verifier_env *env);
 /* verifier.c, for flow.c */
 int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge_loop,
 			bool *starts_leftover);
+int bpf_flow_start_leftover(struct bpf_verifier_env *env);
 int bpf_flow_edge_unproven(struct bpf_verifier_env *env, struct bpf_verifier_state *st, u32 idx,
 			   int err);
 #define BPF_EXIT_NEEDS_CALLER	1	/* verify the call in the frames of the caller */
kernel/bpf/diagnostics.c +5 -0
index 25d7982327d..2cb9eceb408 100644
@@ -392,6 +392,11 @@ static u32 log_pos(const struct bpf_diag_log *log, u32 idx)
 	return pos < log->cap ? pos : pos - log->cap;
 }
 
+u64 bpf_diag_event_log_save(struct bpf_verifier_env *env)
+{
+	return env->diag ? log_end(&env->diag->log) : 0;
+}
+
 void bpf_diag_event_log_restore(struct bpf_verifier_env *env, u64 log_pos)
 {
 	struct bpf_diag *diag = env->diag;
kernel/bpf/diagnostics.h +1 -0
index f6380137e9a..cb255218c41 100644
@@ -53,6 +53,7 @@ const char *bpf_diag_fmt(struct bpf_verifier_env *env, const char *fmt, ...) __p
 const char *bpf_diag_fmt_btf_type(struct bpf_verifier_env *env, const struct btf *btf, u32 type_id);
 const char *bpf_diag_reg_type_plain(struct bpf_verifier_env *env, enum bpf_reg_type type);
 const char *bpf_diag_arg_type_plain(enum bpf_arg_type type);
+u64 bpf_diag_event_log_save(struct bpf_verifier_env *env);
 void bpf_diag_event_log_restore(struct bpf_verifier_env *env, u64 log_pos);
 u32 bpf_diag_irq_depth(const struct bpf_verifier_state *state);
 void bpf_diag_free(struct bpf_verifier_env *env);
kernel/bpf/flow.c +602 -2

632 lines not on this page · raw message

kernel/bpf/verifier.c +22 -11
index e72a58d34f5..43c4e7b2c8d 100644
@@ -196,7 +196,6 @@ struct bpf_verifier_stack_elem {
 	struct bpf_verifier_state st;
 	int insn_idx;
 	int prev_insn_idx;
-	/* it goes there only if may_goto in front of prev_insn_idx does, see check_loop_guard() */
 	enum bpf_guard_edge guard_edge;
 	bool again;	/* see bpf_flow_deliver() */
 	struct bpf_verifier_stack_elem *next;
@@ -11949,6 +11948,7 @@ static int split_func_set(struct bpf_verifier_env *env, int regno)
 		branch = push_stack(env, env->insn_idx, env->insn_idx, false);
 		if (IS_ERR(branch))
 			return PTR_ERR(branch);
+		env->head->again = true;
 	}
 	return 0;
 }
@@ -11974,6 +11974,7 @@ static int check_func_callx_set(struct bpf_verifier_env *env, int regno, int *in
 			branch = push_stack(env, *insn_idx, *insn_idx, false);
 			if (IS_ERR(branch))
 				return PTR_ERR(branch);
+			env->head->again = true;
 			continue;
 		}
 		copy = kzalloc_obj(*copy, BPF_VERIFIER_GFP);
@@ -20993,6 +20994,13 @@ static int enter_callback(struct bpf_verifier_env *env, bool back, struct bpf_lo
 	return err;
 }
 
+/* The current state is at the header of a loop and starts its leftover */
+int bpf_flow_start_leftover(struct bpf_verifier_env *env)
+{
+	leave_peeled_trips(env, bpf_top_loop(cur_func(env)));
+	return enter_callback(env, false, NULL);
+}
+
 /*
  * The current state gets to env->insn_idx. Leave the loops that the insn is not in. Enter
  * the loops that it is in. Returns 1 if the state ends here.
@@ -21219,12 +21227,9 @@ static int flow_drain(struct bpf_verifier_env *env)
 
 	while ((elem = env->head)) {
 		env->head = elem->next;
-		if (!err && elem->guard_edge)
-			err = bpf_flow_guard_edge(env, &elem->st, elem->insn_idx,
-						  elem->prev_insn_idx, elem->guard_edge);
-		else if (!err)
+		if (!err)
 			err = bpf_flow_deliver(env, &elem->st, elem->insn_idx,
-					       elem->prev_insn_idx);
+					       elem->prev_insn_idx, elem->again);
 		bpf_free_verifier_state(env, &elem->st, false);
 		kfree(elem);
 	}
@@ -21385,11 +21390,14 @@ static void free_pushed_states(struct bpf_verifier_env *env)
 static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
 {
 	struct bpf_verifier_state *state = env->cur_state;
+	struct bpf_verifier_stack_elem *elem;
 	struct bpf_insn *insns = env->prog->insnsi;
 	int insn_cnt = env->prog->len;
 	bool do_print_state = true, from_unproven;
+	bool again = prev_insn_idx == env->insn_idx;
 	u32 held;
 
+	mark_verifier_state_scratched(env);
 	for (;;) {
 		struct bpf_insn *insn;
 		struct bpf_insn_aux_data *insn_aux;
@@ -21552,20 +21560,23 @@ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
 		    bpf_is_mem_insn(insn) && BPF_MODE(insn->code) == BPF_MEM) {
 process_bpf_exit:
 			account_current_path(env);
-			mark_verifier_state_scratched(env);
 			bpf_free_verifier_state(env, state, false);
 			memset(state, 0, sizeof(*state));
 			return flow_drain(env);
 		}
 
+		/* if the insn pushed a part, the current state is a part too */
+		for (elem = env->head; elem; elem = elem->next)
+			again |= elem->again;
 		err = flow_drain(env);
 		if (err)
 			return err;
 
-		if (env->insn_idx < insn_cnt && bpf_flow_is_point(env, env->insn_idx)) {
+		/* the parts of a state meet at the next insn */
+		if (env->insn_idx < insn_cnt &&
+		    (again || bpf_flow_is_bb_start(env, env->insn_idx))) {
 			account_current_path(env);
-			mark_verifier_state_scratched(env);
-			return bpf_flow_deliver(env, state, env->insn_idx, prev_insn_idx);
+			return bpf_flow_deliver(env, state, env->insn_idx, prev_insn_idx, false);
 		}
 	}
 }
@@ -21582,7 +21593,7 @@ static int do_check(struct bpf_verifier_env *env)
 	u64 log_pos = env->log.end_pos;
 	int prev_insn_idx, err;
 
-	err = bpf_flow_deliver(env, env->cur_state, env->insn_idx, -1);
+	err = bpf_flow_deliver(env, env->cur_state, env->insn_idx, -1, false);
 	while (!err) {
 		err = bpf_flow_next(env, &prev_insn_idx);
 		if (err == -ENOENT)
Signature · 1 line
2.55.0
#34 lore raw

PATCH v2 29/49 bpf: Order the pending states and free the states that are done

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The order decides how often an insn is checked. A join point has to get all its states before it runs:

if (c) x = 1; else x = 2; both branches first,
use(x); then one check with x = 1..2

flow_set_pending() sets the order:
1. a function that a call waits for,
2. callers, so that the calls of a function meet before it is checked,
3. the trip and the position in each frame: a trip is complete before the next trip, a loop before the code after it,
4. exit states last.

With this order most states can meet no later state. They are freed when their turn comes. flow_keep() keeps a state at a join point
- in the leftover of a loop, until the states leave the loop,
- at the start of a peeled trip (0, 1, 2, 4, 8, ...), to find a trip that repeats a state,
- at the entry of a function, or while a call can get more exit states,
- in an async callback, because it can start again.

Without that the memory grows with the number of peeled trips.

do_check() takes the next state and checks its basic block.

---
 include/linux/bpf_verifier.h |  11 +-
 kernel/bpf/flow.c            | 281 +++++++++++++++++++++++++++++++++++
 kernel/bpf/verifier.c        |  23 +--
 3 files changed, 305 insertions(+), 10 deletions(-)
include/linux/bpf_verifier.h +10 -1
index bf27d751966..6ccac5dff96 100644
@@ -482,6 +482,12 @@ static inline bool bpf_loop_walk_may_give_up(const struct loop_stack_entry *entr
 	return entry->apart && entry->terminates && !entry->counted && !entry->first;
 }
 
+/* The states of trip 0, 1, 2, 4, 8, ... are saved. A compare with them finds any period. */
+static inline bool bpf_trip_is_saved(const struct loop_stack_entry *entry)
+{
+	return !(entry->trip & (entry->trip - 1));
+}
+
 #define LOOP_STACK_SIZE 16
 
 /* state of the program:
@@ -860,6 +866,7 @@ struct bpf_loop_per_pass {
 	bool has_leftover;	/* the peeled trips were not enough */
 	/* a check failed in a state that the loop kept apart, with no other suspect */
 	bool has_unproven;
+	u32 last_peeled_trip;	/* see flow_keep_peeled() */
 	u32 peeled_cnt;		/* trips that the pass peeled */
 	u64 cost;		/* for the states that the loop keeps apart */
 };
@@ -1362,10 +1369,12 @@ struct bpf_verifier_env {
 	bool uses_arena_sp;		/* the program has insns with BPF_REG_ARENA_SP */
 	bool path_sensitive;		/* no joins, see run_path_sensitive() */
 	bool for_log;			/* the verdict is known, see do_check_all() */
+	bool fallthrough_first;		/* see find_failing_path() */
 	struct bpf_precision *precision;
 	u64 cost, mem;			/* see bpf_check_limits() */
 	u64 max_cost, max_mem;
 	u64 hash_seed;			/* see bpf_hash_join_key() */
+	u64 failing_path_budget, failing_path_max_cost;	/* see find_failing_path() */
 	u64 pass_max_cost;		/* see bpf_undo_precision() */
 	bool aborted;			/* a thaw does not take it back */
 	bool no_mem;			/* a table cannot grow, see bpf_check_limits() */
@@ -1746,7 +1755,7 @@ void bpf_flow_free(struct bpf_verifier_env *env);
 bool bpf_flow_is_bb_start(struct bpf_verifier_env *env, int insn_idx);
 int bpf_flow_deliver(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
 		     int insn_idx, int prev_insn_idx, bool again);
-int bpf_flow_next(struct bpf_verifier_env *env, int *prev_insn_idx);
+int bpf_flow_next(struct bpf_verifier_env *env, int *prev_insn_idx, u64 *log_pos, u64 *diag_pos);
 int bpf_flow_call(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,
 		  struct bpf_verifier_state *entry, int subprog, int call_idx);
 int bpf_flow_exit(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int exit_idx);
kernel/bpf/flow.c +281 -0

302 lines not on this page · raw message

kernel/bpf/verifier.c +14 -9
index 43c4e7b2c8d..f8779c51cf7 100644
@@ -21589,26 +21589,31 @@ static bool round_is_dropped(struct bpf_verifier_env *env)
 
 static int do_check(struct bpf_verifier_env *env)
 {
-	bool level1 = (env->log.level & BPF_LOG_LEVEL) == BPF_LOG_LEVEL1;
-	u64 log_pos = env->log.end_pos;
+	bool level2 = env->log.level & BPF_LOG_LEVEL2;
+	u64 log_pos = env->log.end_pos, diag_pos = 0;
 	int prev_insn_idx, err;
 
 	err = bpf_flow_deliver(env, env->cur_state, env->insn_idx, -1, false);
-	while (!err) {
-		err = bpf_flow_next(env, &prev_insn_idx);
+	while (!err && !(env->path_sensitive && env->cost >= env->failing_path_max_cost)) {
+		err = bpf_flow_next(env, &prev_insn_idx, &log_pos, &diag_pos);
+		/* at the limit the work on equations is not complete, such a pass proves nothing */
 		if (err == -ENOENT)
-			return 0;
+			return bpf_check_limits(env);
 		if (err)
 			break;
-		/* What is known about how the state came to be is not kept with it. */
-		bpf_diag_event_log_restore(env, 0);
-		/* Neither is the text: the level 1 log has one basic block at a time. */
-		if (level1) {
+		/* A pass logs one basic block at a time. A path-sensitive run logs a full path. */
+		bpf_diag_event_log_restore(env, diag_pos);
+		if (!level2) {
 			bpf_vlog_reset(&env->log, log_pos);
 			env->prev_linfo = NULL;
 		}
 		err = do_check_block(env, prev_insn_idx);
+		if (env->bug)
+			return -EFAULT;
 	}
+	/* bpf_flow_edge_unproven() noted it with the state that failed */
+	if (err && !bpf_insn_is_unproven(env))
+		note_error(env, err);
 	return err;
 }
 
Signature · 1 line
2.55.0
#35 lore raw

PATCH v2 30/49 bpf: Get the trip count from the trip index

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A loop needs a trip count or may_goto. The trip index k is an xreg. It is 0 at the entry, and each back edge adds 1. The join at the header finds what moves with k. A jump that tests such an xreg refines k.

for (i = 0; i < 100; i += 4)

    join        i = 4 * k
    threshold   'i < 100' holds up to k = 24: widen k to 0..25
    jump        i < 100  ->  k 0..24
    back edge   k + 1 is 1..25, the header state subsumes it

This is the proof: k grows in each trip and stays in 0..25. The next patch checks that. No jump has to test p here, its equation limits it:

  for (i = 0, p = buf; i < 8; i++, p += 8)      p = buf + 8 * k
          *p = 0;

A threshold is a guess, see bpf_collect_iv_thresholds(). If it is too small, k grows to the next one, and at last to S64_MAX. No run makes 2^63 trips, so a state with k = S64_MAX ends at the back edge.

Two states can enter a loop with two bounds. So each entry has the trip index at which its jumps leave the loop, see exit_threshold:

(n, size) = (1 << 18, 4) or (1 << 17, 8)
for (i = 0; i != n; i++)
buf[i * size]; 1 << 18 is too much for size 8

- The trip count is known only when the pass ends. So pass 0 takes the edges of may_goto in all loops. After it only the loops that need may_goto keep them.
- 'i != n' with two ranges: add_distance_equation() makes a sym for i - n in the first trip. It does that for two pointers into one object too: for (p = t + 0..3; p != t + 4..7; p++)
- A test against the rest of a buffer gets a sym for the difference too, in a loop or not:

    if (len > 64 - off) return; read(buf + off, len);
  An equation has a cost, so len has to be in data_deps. If it is not,
  the pass is imprecise, and a later pass makes the sym.
- With -mcpu=v1 and v2 clang can count down and test the carry:
    x = (u32)x + 0xffffffff; if (x != (u32)x) continue;

The two operands have one step. If the carry is set in the first trips, the jump gives the threshold of 'x > U32_MAX'.
- A distance of two truncated numbers can have a range of 2^31 after a widening. clamp_diff_start() takes the ranges of the two numbers.
- bpf_note_linear_xregs() notes the xregs that are linear in k, and those that are linear only at first: i = (i + 1) & 63
- A leftover is walked more than once. The new walk makes all values again. So flow_is_stale() frees a state of an earlier walk.
- With may_goto k has no bound. trip_index_safe() lets it start again from a smaller number, so the states can be pruned. loop_stack_safe() calls it for each loop of a frame.

---
 include/linux/bpf_verifier.h |  20 ++-
 kernel/bpf/equation.c        | 130 +++++++++++++++++
 kernel/bpf/equation.h        |   5 +
 kernel/bpf/equation_join.c   | 276 +++++++++++++++++++++++++++++++++++
 kernel/bpf/flow.c            |  24 +++
 kernel/bpf/precision.c       |  10 ++
 kernel/bpf/states.c          |  35 ++++-
 kernel/bpf/verifier.c        |  19 +++
 8 files changed, 514 insertions(+), 5 deletions(-)
include/linux/bpf_verifier.h +19 -1
index 6ccac5dff96..1ae2f57311c 100644
@@ -427,6 +427,9 @@ static inline u32 bpf_xreg_to_spi(u32 xregno)
 
 /* The trip index of a loop is an xreg too. The loops of a frame come after its slots. */
 #define BPF_XREG_TRIP MAX_BPF_XREG
+/* A loop that can make more trips gets may_goto */
+#define BPF_MAX_TRIPS BIT_ULL(32)
+
 static inline u64 bpf_xreg(u32 frameno, u32 xregno)
 {
 	return (u64)frameno << 32 | xregno;
@@ -474,6 +477,7 @@ struct loop_stack_entry {
 	/* an xreg: how many times the program came back to the header */
 	struct scalar trip_index;
 	bool trip_widened;	/* it was moved to a threshold, or it does not grow */
+	u64 exit_threshold;	/* by the jumps that the state passed and that leave the loop */
 };
 
 /* The state is in a walk on patience, which may not get to the end of the loop */
@@ -863,6 +867,7 @@ enum bpf_loop_kind {
 
 /* What a pass finds about a loop */
 struct bpf_loop_per_pass {
+	bool needs_guard;	/* see bpf_flow_needs_guard() */
 	bool has_leftover;	/* the peeled trips were not enough */
 	/* a check failed in a state that the loop kept apart, with no other suspect */
 	bool has_unproven;
@@ -897,16 +902,22 @@ struct bpf_loop {
 	bool peeled_apart;	/* the join rule holds for states that start a peeled trip */
 	bool disjoint_apart;	/* disjoint values in data_deps stay apart, also in the leftover */
 	);
+	struct bpf_loop_per_pass last_pass;	/* the last pass whose partition was kept */
 	bool partitioned;	/* the last partition was for this loop */
 	bool peeled_joined;	/* at the start of a peeled trip, against the join rule */
+	bool guarded;		/* states take the edges of may_goto */
 	struct bpf_iv_threshold *iv_thresholds;	/* where an iv can stop, see equation_join.c */
 	u32 iv_threshold_cnt, iv_threshold_cap;
+	u32 leftover_epoch;	/* how many leftovers started */
+	u64 exit_trip;		/* the trip in which the loop can end, 0 if it is not known */
+	/* they move with the trip index, or only at first, see bpf_note_linear_xregs() */
+	DECLARE_BITMAP(linear_xregs, MAX_BPF_XREG);
+	DECLARE_BITMAP(nonlinear_xregs, MAX_BPF_XREG);
 	struct bpf_loop_per_pass this_pass;
 	/* sorted constants of the loop, the largest and the smallest constant that an insn adds */
 	s64 *thresholds;
 	u32 threshold_cnt, threshold_cap;
 	s32 max_step, min_step;
-	bool guarded;
 };
 
 static inline bool bpf_loop_has_budget(const struct bpf_loop *loop)
@@ -1026,6 +1037,8 @@ struct bpf_insn_aux_data {
 	u16 stack_ptrs; /* bitmask of regs that may hold a frame pointer here (arg_track) */
 
 	unsigned int orig_idx; /* original instruction index, initialized once */
+	u32 thresholds_epoch;	/* see bpf_collect_iv_thresholds() */
+	u8 iv_operand;		/* the operand of the jump that tests the iv, + 1 */
 	/* registers alive before this instruction. */
 	u16 live_regs_before;
 	/*
@@ -1712,6 +1725,8 @@ u64 bpf_hash_apart_xregs(struct bpf_verifier_env *env, const struct bpf_verifier
 u64 bpf_hash_args(struct bpf_verifier_env *env, const struct bpf_verifier_state *st, u64 hash);
 void bpf_range_of_data_dep(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 			   u32 *first, u32 *last);
+bool bpf_xreg_in_data_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			   u32 fr, u32 xregno);
 bool bpf_xreg_in_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 		      u32 fr, u32 xregno);
 void bpf_note_reads_from_unproven(struct bpf_verifier_env *env, u32 idx);
@@ -2469,6 +2484,8 @@ void bpf_equations_fill(struct bpf_verifier_env *env, struct bpf_func_state *fra
 void bpf_equations_refine_all(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
 void bpf_equations_jump(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int idx,
 			bool taken);
+void bpf_equations_next_trip(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+			     u32 depth);
 bool bpf_equations_subsume(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
 			   const struct bpf_verifier_state *cur);
 void bpf_equations_print(struct bpf_verifier_env *env, const struct bpf_verifier_state *st);
@@ -2478,6 +2495,7 @@ void bpf_equations_pre_join(struct bpf_verifier_env *env, struct bpf_verifier_st
 void bpf_equations_post_join(struct bpf_verifier_env *env, struct bpf_verifier_state *dst,
 			     const struct bpf_verifier_state *src);
 u32 bpf_equations_bytes(const struct bpf_equations *eqs);
+void bpf_collect_iv_thresholds(struct bpf_verifier_env *env);
 void scalar_bounds_sync(struct scalar *s);
 bool scalar_subsumes(const struct scalar *old, const struct scalar *cur);
 bool scalars_fit_in_bits(const struct scalar *a, const struct scalar *b, u32 bits);
kernel/bpf/equation.c +130 -0

158 lines not on this page · raw message

kernel/bpf/equation.h +5 -0
index 564ff6e5e6c..0b39d99c9b7 100644
@@ -190,4 +190,9 @@ void bpf_eval_diff(struct bpf_verifier_env *env, const struct bpf_verifier_state
 void bpf_guess_equations(struct bpf_verifier_env *env, const struct bpf_verifier_state *dst,
 			 const struct bpf_verifier_state *src, struct bpf_loop *leftover_loop,
 			 bool widen);
+void bpf_note_linear_xregs(struct bpf_verifier_env *env, const struct bpf_verifier_state *dst,
+			   const struct bpf_equations *join);
+u64 bpf_guess_trip_threshold(struct bpf_verifier_env *env, const struct bpf_verifier_state *dst,
+			     const struct loop_stack_entry *e, u64 xreg);
+
 #endif
kernel/bpf/equation_join.c +276 -0

285 lines not on this page · raw message

kernel/bpf/flow.c +24 -0
index fbd81c1447d..856d38cc973 100644
@@ -110,6 +110,7 @@ struct bpf_flow {
 	unsigned long *bb_starts;	/* insn starts a basic block */
 	unsigned long *join_points;	/* more than one edge leads to the insn */
 	struct bpf_loop call_loop;	/* from the exit of a function to its next call */
+	u32 start_cnt;			/* of passes and of path-sensitive runs */
 
 	/* of the pass */
 	u64 *cost;			/* per function */
@@ -416,6 +417,8 @@ int bpf_flow_place_guards(struct bpf_verifier_env *env)
 		loop->rt_bounded = flow_loop_is_bounded(env, h);
 		/* also when it's bounded: the main pass may find that it's not */
 		flow_place_guards(env, h, seen);
+		/* pass 0 does not know the trip count before it ends */
+		loop->guarded = loop->has_guards && !bpf_prog_is_offloaded(env->prog->aux);
 		if (aux[h].guard_at_header)
 			ret = 1;
 	}
@@ -973,6 +976,22 @@ static bool flow_same_entry(struct bpf_loop *loop, const struct flow_state *t,
 	       flow_loop_entry(&t->st, loop)->entry_id == flow_loop_entry(&s->st, loop)->entry_id;
 }
 
+/* @t is from an earlier walk over a leftover. The header state of @s subsumes that of @t. */
+static bool flow_is_stale(const struct flow_state *t, const struct flow_state *s)
+{
+	const struct loop_stack_entry *a, *b;
+	u32 fr, i;
+
+	for (fr = 0; !t->pending && fr <= s->st.curframe; fr++) {
+		a = t->st.frame[fr]->loop_stack;
+		b = s->st.frame[fr]->loop_stack;
+		for (i = 0; i < s->st.frame[fr]->loop_stack_cnt; i++, a++, b++)
+			if (a->entry_id == b->entry_id && a->trip < b->trip)
+				return true;
+	}
+	return false;
+}
+
 /*
  * All states arrive here. @s is
  * - pruned, if a state subsumes it,
@@ -1029,9 +1048,14 @@ static int flow_prune_or_join(struct bpf_verifier_env *env, struct flow_state *s
 			joined = true;
 			continue;
 		}
+		if (!leftover_loop && s->kind == FLOW_AT && flow_is_stale(t, s)) {
+			flow_free_state(env, t);
+			continue;
+		}
 		joined = true;
 		widened = leftover_loop;
 		s->returned |= widened;
+		/* what enters did not grow in this loop */
 		widen = !t->pending && !enters;
 		flow_unlink(env, t);
 		err = bpf_states_join(env, &t->st, &s->st, leftover_loop, widen);
kernel/bpf/precision.c +10 -0
index efee61c4e08..84090f9a8e3 100644
@@ -40,6 +40,16 @@ u32 bpf_frame_mask(struct bpf_verifier_env *env, unsigned long *masks,
 	return words * BITS_PER_LONG;
 }
 
+bool bpf_xreg_in_data_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			   u32 fr, u32 xregno)
+{
+	unsigned long data_deps[XREG_WORDS];
+
+	return env->precision->data_deps &&
+	       xregno < bpf_frame_mask(env, env->precision->data_deps, st, fr, data_deps) &&
+	       test_bit(xregno, data_deps);
+}
+
 bool bpf_xreg_in_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 		      u32 fr, u32 xregno)
 {
kernel/bpf/states.c +31 -4
index 23e3adb9822..d8026295644 100644
@@ -583,6 +583,34 @@ u64 bpf_hash_join_key(const struct bpf_verifier_env *env, const struct bpf_verif
 	return hash;
 }
 
+/*
+ * If may_goto or an iterator stops the loop, its trip index can start again from a smaller
+ * number, never from a larger one: see bpf_equations_next_trip().
+ */
+static bool trip_index_safe(const struct loop_stack_entry *old, const struct loop_stack_entry *cur)
+{
+	u64 min = cnum64_umin(old->trip_index.r64);
+	struct scalar first;
+
+	if (old->peeled || scalar_subsumes(&old->trip_index, &cur->trip_index))
+		return true;
+	if (!old->loop->rt_bounded && !old->loop->this_pass.needs_guard)
+		return false;
+	scalar_set_const(&first, min);
+	return min <= cnum64_umin(cur->trip_index.r64) &&
+	       scalar_subsumes(&old->trip_index, &first);
+}
+
+static bool loop_stack_safe(struct bpf_func_state *old, struct bpf_func_state *cur)
+{
+	u32 i;
+
+	for (i = 0; i < old->loop_stack_cnt; i++)
+		if (!trip_index_safe(&old->loop_stack[i], &cur->loop_stack[i]))
+			return false;
+	return true;
+}
+
 /* compare two verifier states
  *
  * The state that gets to an insn doesn't have to be looked at when there is
@@ -603,10 +631,9 @@ static bool func_states_equal(struct bpf_verifier_env *env, struct bpf_func_stat
 	u16 live_regs = env->insn_aux_data[insn_idx].live_regs_before;
 	u16 i;
 
-	if (old->callback_depth > cur->callback_depth)
-		return false;
-
-	if (!old->no_stack_arg_load && cur->no_stack_arg_load)
+	if (old->callback_depth > cur->callback_depth ||
+	    (!old->no_stack_arg_load && cur->no_stack_arg_load) ||
+	    !loop_stack_safe(old, cur))
 		return false;
 
 	for (i = 0; i < MAX_BPF_REG; i++)
kernel/bpf/verifier.c +19 -0
index f8779c51cf7..b6de3447b08 100644
@@ -19253,6 +19253,7 @@ static int check_cond_jmp_op(struct bpf_verifier_env *env,
 	env->false_reg2 = *src_reg;
 	env->true_reg1 = *dst_reg;
 	env->true_reg2 = *src_reg;
+	bpf_collect_iv_thresholds(env);
 	pred = is_branch_taken(env, dst_reg, src_reg, opcode, is_jmp32);
 	if (pred == 1) {
 		/* Only follow the goto, ignore fall-through. If needed, push
@@ -20747,7 +20748,9 @@ static struct loop_stack_entry *push_loop(struct bpf_verifier_env *env,
 		.held_cnt = held_cnt(env->cur_state),
 		.entry_id = ++env->loop_entry_cnt,
 		.peeled = true,
+		.exit_threshold = U64_MAX,
 	};
+	scalar_set_const(&frame->loop_stack[cnt].trip_index, 0);
 	frame->loop_stack_cnt++;
 	return &frame->loop_stack[cnt];
 }
@@ -20768,10 +20771,17 @@ static void leave_peeled_trips(struct bpf_verifier_env *env, struct loop_stack_e
 {
 	struct bpf_func_state *frame;
 	struct bpf_reg_state *reg;
+	u32 i;
 
 	entry->peeled = false;
 	entry->loop->this_pass.has_leftover = true;
+	entry->loop->leftover_epoch++;
+	/* the leftover of the last pass had no trip count */
+	entry->loop->guarded |= entry->loop->last_pass.needs_guard && !env->cur_state->speculative;
+	entry->trip_index.grew_once = entry->trip_widened = false;
 	bpf_for_each_reg_in_vstate(env->cur_state, frame, reg, reg->grew_once = false);
+	for (i = 0; i < env->cur_state->equations.sym_cnt; i++)
+		env->cur_state->equations.syms[i].grew_once = false;
 }
 
 /*
@@ -20864,6 +20874,8 @@ static void loop_stack_pop(struct bpf_verifier_env *env)
 				verbose(env, "exiting loop %d\n",
 					frame->loop_stack[i].loop->header);
 	frame->loop_stack_cnt = new_cnt;
+	if (new_cnt != cnt)
+		bpf_equations_clean(env, env->cur_state);
 }
 
 static bool xreg_has_id(struct bpf_verifier_state *st, u32 id)
@@ -20938,6 +20950,13 @@ static int next_trip(struct bpf_verifier_env *env, struct loop_stack_entry *entr
 		     bool *starts_leftover)
 {
 	entry->trip++;
+	if (entry->loop->kind != BPF_LOOP_RECURSION) {
+		bpf_equations_next_trip(env, env->cur_state, entry - cur_func(env)->loop_stack);
+		/* No run makes 2^63 trips. The header is not dead code: a trip started there. */
+		if (infeasible_state_ends(env) ||
+		    (env->bypass_spec_v1 && cnum64_is_empty(entry->trip_index.r64)))
+			return 1;
+	}
 	if (!entry->peeled)
 		return check_held_in_leftover(env, entry);
 	return 0;
Signature · 1 line
2.55.0
#36 lore raw

PATCH v2 31/49 bpf: Give a loop a checked trip count or may_goto

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A fixpoint proves that each insn is safe. It does not prove that a loop ends. A state that is pruned by its own ancestor closes a cycle:

t --> ... --> header --> ... --> s
^ |
`----------- subsumes -----------'

All pruned states go through flow_check_trip_counts(). If s made more trips than t, look at the trip index k of s:

if k <= BPF_MAX_TRIPS (2^32) the loop has a trip count, no may_goto
else the loop gets may_goto

A loop that has may_goto or an iterator needs nothing. There is no trip count without CAP_PERFMON, as before.

may_goto is there for all states at run time. If a state went through the loop without its edges, the pass starts again. bpf_flow_drop_guards() removes may_goto that no state needed.

A peeled trip that an earlier trip subsumes is pruned for the price of may_goto, see flow_prune_peeled(). bpf_flow_trip_is_new() tells if one more peeled trip can help. bpf_guard_edge and the old members of loop_stack_entry go away.

may_goto at a header skips the body. So a slot that is live at its target is live at the header.

bpf_loop_spine_end() finds the insns that dominate all back edges. It replaces the counters in flow_place_guards().

If both edges of a jump are dead, no run gets to the jump. It becomes 'goto -1'.

---
 include/linux/bpf_verifier.h |  56 +++------
 kernel/bpf/fixups.c          |   3 +
 kernel/bpf/flow.c            | 233 +++++++++++++++++++++++++++++++----
 kernel/bpf/liveness.c        |   3 +
 kernel/bpf/loops.c           |  10 ++
 kernel/bpf/verifier.c        |  84 ++++++-------
 6 files changed, 282 insertions(+), 107 deletions(-)
include/linux/bpf_verifier.h +17 -39
index 1ae2f57311c..4ed4efcd45f 100644
@@ -435,13 +435,6 @@ static inline u64 bpf_xreg(u32 frameno, u32 xregno)
 	return (u64)frameno << 32 | xregno;
 }
 
-/* Where may_goto that the verifier adds goes, see check_loop_guard() */
-enum bpf_guard_edge {
-	BPF_NO_GUARD_EDGE,
-	BPF_GUARD_LEAVES_SUBPROG,
-	BPF_GUARD_LEAVES_LOOP,
-};
-
 /*
  * A state in a loop, see bpf_flow_loop_enter()
  *
@@ -452,22 +445,6 @@ enum bpf_guard_edge {
  */
 struct loop_stack_entry {
 	struct bpf_loop *loop;
-	u32 loop_id:23;
-	u32 terminates:1;
-	/* the loop had may_goto when the state entered it, see check_loop_guard() */
-	u32 guarded:1;
-	/*
-	 * The iterations are kept apart: states with different @trip are not
-	 * joined for as long as they are in the loop.
-	 */
-	u32 apart:1;
-	/* max_header_count follows from the state at the entry, not from patience */
-	u32 counted:1;
-	/*
-	 * The first iteration of a counted loop is kept apart. The state that comes back
-	 * to the head is made to stand for the rest.
-	 */
-	u32 first:1;
 	/* How many times the state came back to the header. A join has the larger number. */
 	u32 trip;
 	/* The state that entered the loop. What comes back to the header is for that state. */
@@ -480,12 +457,6 @@ struct loop_stack_entry {
 	u64 exit_threshold;	/* by the jumps that the state passed and that leave the loop */
 };
 
-/* The state is in a walk on patience, which may not get to the end of the loop */
-static inline bool bpf_loop_walk_may_give_up(const struct loop_stack_entry *entry)
-{
-	return entry->apart && entry->terminates && !entry->counted && !entry->first;
-}
-
 /* The states of trip 0, 1, 2, 4, 8, ... are saved. A compare with them finds any period. */
 static inline bool bpf_trip_is_saved(const struct loop_stack_entry *entry)
 {
@@ -868,7 +839,9 @@ enum bpf_loop_kind {
 /* What a pass finds about a loop */
 struct bpf_loop_per_pass {
 	bool needs_guard;	/* see bpf_flow_needs_guard() */
+	bool no_guard_edges;	/* a state did not take the edges of may_goto */
 	bool has_leftover;	/* the peeled trips were not enough */
+	bool peel_pruned;	/* see flow_prune_peeled() */
 	/* a check failed in a state that the loop kept apart, with no other suspect */
 	bool has_unproven;
 	u32 last_peeled_trip;	/* see flow_keep_peeled() */
@@ -901,11 +874,14 @@ struct bpf_loop {
 	u32 max_peel_cnt;	/* peel up to this trip */
 	bool peeled_apart;	/* the join rule holds for states that start a peeled trip */
 	bool disjoint_apart;	/* disjoint values in data_deps stay apart, also in the leftover */
+	bool no_peel_prune;	/* a larger earlier trip does not prune, see flow_prune_peeled() */
 	);
 	struct bpf_loop_per_pass last_pass;	/* the last pass whose partition was kept */
 	bool partitioned;	/* the last partition was for this loop */
 	bool peeled_joined;	/* at the start of a peeled trip, against the join rule */
+	bool changed;		/* see flow_forget_loop() */
 	bool guarded;		/* states take the edges of may_goto */
+	bool infinite;		/* see failing_path_trip() */
 	struct bpf_iv_threshold *iv_thresholds;	/* where an iv can stop, see equation_join.c */
 	u32 iv_threshold_cnt, iv_threshold_cap;
 	u32 leftover_epoch;	/* how many leftovers started */
@@ -984,7 +960,6 @@ struct bpf_insn_aux_data {
 	u64 speculative_first:1; /* a speculative state came to it first */
 	u64 call_recorded:1; /* see record_call_fixup() */
 	u64 pessimized:1; /* see bpf_partition_for_pessimized() */
-	u64 guard_edge_dropped:1; /* an edge of may_goto from here was dropped */
 	u64 alu_state:5; /* used in combination with alu_limit */
 	/* true if STX or LDX instruction is a part of a spill/fill
 	 * pattern for a bpf_fastcall call.
@@ -1398,7 +1373,7 @@ struct bpf_verifier_env {
 	bool imprecise;			/* a state before the first error is imprecise */
 	bool over_limit;		/* see bpf_check_limits() */
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
-	bool guards_late;		/* see bpf_flow_loop_gets_guards() */
+	bool guards_late;		/* see bpf_flow_needs_guard() */
 	bool extra_values;		/* a state can have constants that no run has */
 	bool new_linear_xreg;		/* see bpf_same_insns_unproven() */
 	bool seen_direct_write;
@@ -1767,15 +1742,19 @@ static inline int bpf_add_cost_and_check(struct bpf_verifier_env *env, u64 cnt,
 int bpf_flow_prepare(struct bpf_verifier_env *env);
 void bpf_flow_reset(struct bpf_verifier_env *env);
 void bpf_flow_free(struct bpf_verifier_env *env);
+bool bpf_flow_trip_is_new(struct bpf_verifier_env *env, struct loop_stack_entry *entry);
 bool bpf_flow_is_bb_start(struct bpf_verifier_env *env, int insn_idx);
 int bpf_flow_deliver(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
 		     int insn_idx, int prev_insn_idx, bool again);
 int bpf_flow_next(struct bpf_verifier_env *env, int *prev_insn_idx, u64 *log_pos, u64 *diag_pos);
+int bpf_flow_needs_guard(struct bpf_verifier_env *env, struct bpf_loop *loop);
 int bpf_flow_call(struct bpf_verifier_env *env, struct bpf_verifier_state *caller,
 		  struct bpf_verifier_state *entry, int subprog, int call_idx);
 int bpf_flow_exit(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int exit_idx);
 void bpf_flow_next_is_no_bound(struct bpf_verifier_env *env, int insn_idx, int h);
 bool bpf_flow_loops_lost_bound(struct bpf_verifier_env *env);
+void bpf_flow_new_pass(struct bpf_verifier_env *env);
+void bpf_flow_drop_guards(struct bpf_verifier_env *env);
 void bpf_flow_new_round(struct bpf_verifier_env *env);
 int bpf_flow_place_guards(struct bpf_verifier_env *env);
 /* verifier.c, for flow.c */
@@ -2099,18 +2078,16 @@ struct bpf_iarray *bpf_insn_successors(struct bpf_verifier_env *env, u32 idx);
 
 /*
  * Where the program goes from may_goto and from the checks that the verifier adds:
- * - May_goto in front of a jump goes where the jump goes, with the registers and the stack
- *   as they are in front of the jump. bpf_insn_successors() has that edge.
+ * - May_goto before a jump goes where the jump goes, with the registers and the stack
+ *   as they are before the jump. bpf_insn_successors() has that edge.
  * - A subprog that is out of budget goes to bail_insn, an exit. No such edge.
- * - May_goto in front of the head of a loop goes to where the loops around it are left: from
+ * - May_goto before the header of a loop goes to where the loops around it are left: from
  *   @idx to what is returned here, -1 if there is none. No such edge either. The registers
- *   and the stack are what they are in front of @idx.
+ *   and the stack are what they are before @idx.
  *
  * The main pass looks at the states that go there. What is computed from the graph before
- * the main pass has to take these edges into account where the main pass believes it:
- * - Against the direction of the edges, liveness: a register that is live at the target is
- *   live at @idx. Stack that is dead at @idx stays dead: a read of it at the target is
- *   rejected.
+ * the main pass has to take these edges into account where the main pass relies on it:
+ * - Against the direction of the edges, liveness: what is live at the target is live at @idx.
  * - In the direction of the edges, bpf_compute_const_regs() and compute_subprog_args(): what
  *   holds on all edges of the graph to the target doesn't hold on this one.
  */
@@ -2459,6 +2436,7 @@ u8 bpf_rev_opcode(u8 opcode);
 int bpf_compute_idoms(struct bpf_verifier_env *env);
 int bpf_compute_loops(struct bpf_verifier_env *env);
 int bpf_loop_at_index(struct bpf_verifier_env *env, u32 idx);
+int bpf_loop_spine_end(struct bpf_verifier_env *env, const struct bpf_loop *loop);
 int bpf_flow_insn_after(struct bpf_verifier_env *env, int idx);
 bool bpf_is_nested_loop(struct bpf_verifier_env *env, int inner_header, int outer_header);
 u32 bpf_loop_thresholds_below(const struct bpf_loop *loop, s64 k);
kernel/bpf/fixups.c +3 -0
index 9f816e2818d..4c9f63e096d 100644
@@ -826,6 +826,9 @@ void bpf_opt_hard_wire_dead_code_branches(struct bpf_verifier_env *env)
 		if (bpf_prog_is_offloaded(env->prog->aux))
 			bpf_prog_offload_replace_insn(env, i, &ja);
 
+		/* If both edges are dead, no run gets here. The driver keeps the old target. */
+		if (!aux_data[i + 1 + ja.off].seen)
+			ja.off = -1;
 		memcpy(insn, &ja, sizeof(ja));
 	}
 }
kernel/bpf/flow.c +210 -23

299 lines not on this page · raw message

kernel/bpf/liveness.c +3 -0
index 7b00e17cab2..23a66b22393 100644
@@ -418,6 +418,7 @@ static inline bool update_insn(struct bpf_verifier_env *env, struct func_instanc
 	unsigned long *may_read, *must_write, *live_before;
 	struct frame_masks *fm = instance->frames[frame];
 	u32 rel = relative_idx(instance, insn_idx);
+	int t = bpf_head_guard_target(env, insn_idx);
 	struct bpf_iarray *succ;
 	bool changed = false;
 	u32 s, w;
@@ -445,6 +446,8 @@ static inline bool update_insn(struct bpf_verifier_env *env, struct func_instanc
 	for (w = 0; w < fm->words; w++) {
 		unsigned long new_before = (new_after[w] & ~must_write[w]) | may_read[w];
 
+		if (t >= 0)
+			new_before |= rel_mask(fm, relative_idx(instance, t), before)[w];
 		if (new_before != live_before[w]) {
 			live_before[w] = new_before;
 			changed = true;
kernel/bpf/loops.c +10 -0
index bb8cb4fedc5..fafef3dec49 100644
@@ -310,6 +310,16 @@ static int check_loop_depth(struct bpf_verifier_env *env, int idx)
 	return 0;
 }
 
+/* The last insn that dominates all back edges of @loop */
+int bpf_loop_spine_end(struct bpf_verifier_env *env, const struct bpf_loop *loop)
+{
+	int i, n = loop->backedges[0].from;
+
+	for (i = 1; i < loop->backedges_cnt; i++)
+		n = idoms_intersect(env, n, loop->backedges[i].from);
+	return n;
+}
+
 /*
  * The backedge->from and its latch can reside in an inner loop of @h, e.g.:
  *
kernel/bpf/verifier.c +39 -45

139 lines not on this page · raw message

Signature · 1 line
2.55.0
#37 lore raw

PATCH v2 32/49 bpf: Use the equations in the join rule

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The join rule compares the ranges of the deps. Two cases need the equations.

1. State 1 has all ranges of state 2, but only state 1 has a relation:

                r1 (data)    r6 (control)
     state 1    0..99        0..99        r1 == r6
     state 2    0..7         0..99
     join       0..99        0..99        a test of r6 tells nothing

bpf_equations_join_forgets() finds such a pair. It counts as two xregs that differ, so the states stay apart. One xreg has to be in
data_deps: the rule joins what differs in control_deps only.

2. LOOP_DISJOINT_APART keeps disjoint values apart at the header. A counter has another value in each trip, so it keeps all trips apart:

     for (i = 0; i < 400; i++) if (x > best) { best = x; at = i; }

The join has i = trip index and keeps i. So an xreg that moves with the trip index keeps no trips of one entry apart. bpf_note_linear_xregs() notes these xregs. If a pass notes a new one, it does not stop at the errors of the last pass. Later trips can show that the xreg moves with the trip index only at first.

---
 include/linux/bpf_verifier.h |  5 +++++
 kernel/bpf/equation.h        |  1 +
 kernel/bpf/equation_join.c   | 30 ++++++++++++++++++++++++++++++
 kernel/bpf/precision.c       | 11 +++++++++++
 4 files changed, 47 insertions(+)
include/linux/bpf_verifier.h +5 -0
index 4ed4efcd45f..c5793f48ad3 100644
@@ -2473,6 +2473,11 @@ void bpf_equations_pre_join(struct bpf_verifier_env *env, struct bpf_verifier_st
 void bpf_equations_post_join(struct bpf_verifier_env *env, struct bpf_verifier_state *dst,
 			     const struct bpf_verifier_state *src);
 u32 bpf_equations_bytes(const struct bpf_equations *eqs);
+/* equation_join.c */
+bool bpf_equations_join_forgets(struct bpf_verifier_env *env, const struct bpf_verifier_state *a,
+				const struct bpf_verifier_state *b, u32 fr,
+				const unsigned long *data_deps, const unsigned long *xregs,
+				u32 bits);
 void bpf_collect_iv_thresholds(struct bpf_verifier_env *env);
 void scalar_bounds_sync(struct scalar *s);
 bool scalar_subsumes(const struct scalar *old, const struct scalar *cur);
kernel/bpf/equation.h +1 -0
index 0b39d99c9b7..2142869092c 100644
@@ -54,6 +54,7 @@ struct sym_scratch {
 	u32 first_use;		/* see link_sym_equations() */
 	u32 new_symno;
 	bool determined, by_op;
+	bool forgotten, in_data_deps;	/* bpf_equations_join_forgets() */
 	const struct bpf_sym_equation *op;	/* that makes it */
 	struct expr cur_expr;	/* check_equations(): its value in the other state */
 };
kernel/bpf/equation_join.c +30 -0
index 84a866e960e..93ebf337e4c 100644
@@ -591,6 +591,36 @@ void bpf_note_linear_xregs(struct bpf_verifier_env *env, const struct bpf_verifi
 	}
 }
 
+/* An xreg of @data_deps and an xreg of @xregs in frame @fr have one sym in @a and not in @b */
+bool bpf_equations_join_forgets(struct bpf_verifier_env *env, const struct bpf_verifier_state *a,
+				const struct bpf_verifier_state *b, u32 fr,
+				const unsigned long *data_deps, const unsigned long *xregs,
+				u32 bits)
+{
+	const struct bpf_xreg_equation *xreg_eq;
+	struct sym_scratch *sym;
+	struct expr expr;
+	bool is_ptr;
+
+	for_each_xreg_equation(env, &a->equations, xreg_eq)
+		env->eq_env->scratch[xreg_eq->sym] = (struct sym_scratch){};
+	for_each_xreg_equation(env, &a->equations, xreg_eq) {
+		if (xreg_eq->xreg >> 32 != fr || (u32)xreg_eq->xreg >= bits ||
+		    !test_bit((u32)xreg_eq->xreg, xregs))
+			continue;
+		sym = &env->eq_env->scratch[xreg_eq->sym];
+		if (bpf_xreg_expr(env, b, xreg_eq->xreg, &expr, &is_ptr)) {
+			sym->forgotten |= sym->determined && expr.var != sym->cur_expr.var;
+			sym->determined = true;
+			sym->cur_expr = expr;
+		}
+		sym->in_data_deps |= test_bit((u32)xreg_eq->xreg, data_deps);
+		if (sym->forgotten && sym->in_data_deps)
+			return true;
+	}
+	return false;
+}
+
 /* Thresholds */
 
 /*
kernel/bpf/precision.c +11 -0
index 84090f9a8e3..29966b2d80d 100644
@@ -336,6 +336,13 @@ void bpf_compare_states(struct bpf_verifier_env *env, const struct bpf_verifier_
 		bitmap_or(all, all, deps, bits);
 		bitmap_or(deps, deps, data_deps, bits);
 		bpf_add_cost(env, 4 + bitmap_weight(all, bits), BPF_COST_COPY);
+		/* r1 == r6 in one state only: two xregs differ, count both */
+		flags = (bpf_equations_join_forgets(env, old, new, fr, data_deps, deps, bits) ?
+			 CMP_NEW : 0) |
+			(bpf_equations_join_forgets(env, new, old, fr, data_deps, deps, bits) ?
+			 CMP_OLD : 0);
+		note_cmp(cmp, flags, true, true);
+		note_cmp(cmp, flags, true, true);
 		for_each_set_bit(xregno, all, bits) {
 			if (xregno == XREG_STACK_ARGS) {
 				arg_cnt = max(fa->out_stack_arg_cnt, fb->out_stack_arg_cnt);
@@ -355,6 +362,10 @@ void bpf_compare_states(struct bpf_verifier_env *env, const struct bpf_verifier_
 			} else {
 				flags = compare_slots(env, cmp, fa, fb, bpf_xreg_to_spi(xregno));
 			}
+			if (iv_loop && fr == old->curframe && !(flags & CMP_TYPE) &&
+			    test_bit(xregno, iv_loop->linear_xregs) &&
+			    !test_bit(xregno, iv_loop->nonlinear_xregs))
+				flags &= ~(CMP_DISJOINT | CMP_GAP);
 			note_cmp(cmp, flags, test_bit(xregno, data_deps), test_bit(xregno, deps));
 			if (fr == old->curframe && (flags & CMP_DISJOINT) &&
 			    test_bit(xregno, data_deps))
Signature · 1 line
2.55.0
#38 lore raw

PATCH v2 33/49 bpf: Verify a static function once for each instance

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A chain of calls multiplies the work if each call is verified in the frames of its caller. 18 levels with 2 calls each are 1 << 18 chains. A function that cannot get to the frames of its callers is verified on its own. The old pass united two calls if their states met anywhere in the function. Then each call got the results of both. Now the states of two calls meet only at the first insn:

call1 f(0) --+
call2 f(1) --+--> first insn

  in pass 0                join         -> one instance
  if r1 is in data_deps    keep apart   -> two instances

An instance is an entry state, its exit states and the calls that wait for them. So the result of a call goes with its arguments. An instance that has started does not grow. The join starts a new instance:

  call1 f(0)  instance 1: f(0)     exits 1 -> call1
  call2 f(1)  instance 2: f(0..1)  exits 1 -> call2, call3  at once
  call3 f(2)              f(0..2)  exits 2 -> call2, call3  later

A call waits if it has no exit state to continue with, or if it is in a peeled trip.

Instances can multiply too. The functions that have more than one instance divide a budget. When a function has used its part, the next calls are joined, see flow_may_add_instance().

A function can test a reference of its caller for NULL and return it. bpf_flow_return() then marks the copies in the caller as not NULL. Else 'if (!n)' drops the reference, and copy still has its id:

  copy = throw_if_null(n);  if (!n) return copy->a;

callx of a set checks each function with a copy of the state. After an error do_check_block() has to see that copy.

A speculative call gets an instance too. flow_end_instance() frees the calls that have all exit states.

---
 include/linux/bpf_verifier.h |   7 +-
 kernel/bpf/flow.c            | 313 +++++++++++++++++++++++++++++++++++
 kernel/bpf/verifier.c        |  23 ++-
 3 files changed, 334 insertions(+), 9 deletions(-)
include/linux/bpf_verifier.h +2 -5
index c5793f48ad3..54a11c71374 100644
@@ -607,11 +607,6 @@ struct bpf_verifier_state {
 	 * and their packet pointers are not in the state, see bpf_flow_return().
 	 */
 	bool changed_pkt_data;
-	/*
-	 * Not zero in a function that is verified on its own: the call that the
-	 * state at its entry came from, see bpf_flow_call().
-	 */
-	u32 flow_entry;
 	);
 	/* Not zero in a function that is verified on its own, see bpf_flow_call() */
 	u32 instance_id;
@@ -1143,6 +1138,7 @@ struct bpf_subprog_info {
 	u32 callx_edge; /* 1 + the first of its env->callx_edges, 0 if none */
 	struct bpf_iarray *jt; /* jump table shared by all gotox of this subprogram */
 	u32 deepest_insn; /* the insn that set stack_depth */
+	u32 first_exit; /* see bpf_flow_exit() */
 	u16 stack_depth; /* max. stack depth used by this function */
 	u16 stack_extra;
 	u16 arena_stack_depth; /* size of the frame in the stack in arena */
@@ -1374,6 +1370,7 @@ struct bpf_verifier_env {
 	bool over_limit;		/* see bpf_check_limits() */
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
 	bool guards_late;		/* see bpf_flow_needs_guard() */
+	bool calls_joined;		/* see flow_may_add_instance() */
 	bool extra_values;		/* a state can have constants that no run has */
 	bool new_linear_xreg;		/* see bpf_same_insns_unproven() */
 	bool seen_direct_write;
kernel/bpf/flow.c +313 -0

375 lines not on this page · raw message

kernel/bpf/verifier.c +19 -4
index fac44fceccf..58a483fed88 100644
@@ -1809,11 +1809,11 @@ int bpf_copy_verifier_state(struct bpf_verifier_env *env, struct bpf_verifier_st
 		return err;
 	bpf_add_cost(env, bpf_xreg_cnt(src) + src->acquired_refs, BPF_COST_COPY);
 	dst_state->speculative = src->speculative;
-	dst_state->flow_entry = src->flow_entry;
 	dst_state->infeasible = src->infeasible;
 	dst_state->max_held_cnt = src->max_held_cnt;
 	dst_state->suspect_loops = src->suspect_loops;
 	dst_state->join_key = src->join_key;
+	dst_state->instance_id = src->instance_id;
 	dst_state->insn_idx = src->insn_idx;
 	dst_state->last_insn_idx = src->last_insn_idx;
 	for (i = 0; i <= src->curframe; i++) {
@@ -10931,7 +10931,7 @@ static void clear_all_pkt_pointers(struct bpf_verifier_env *env)
 			mark_reg_invalid(env, reg);
 		}
 	}));
-	if (env->cur_state->flow_entry)
+	if (env->cur_state->instance_id)
 		env->cur_state->changed_pkt_data = true;
 }
 
@@ -11515,7 +11515,7 @@ static bool func_is_on_its_own(struct bpf_verifier_env *env, struct bpf_verifier
 	if (sub->changes_pkt_data || sub->has_tail_call || sub->has_ld_abs ||
 	    sub->is_cb || sub->is_async_cb || sub->is_exception_cb)
 		return false;
-	if (state->speculative)
+	if (env->path_sensitive)
 		return false;
 	if (sub->releases_inherited &&
 	    (state->acquired_refs || state->active_rcu_locks || state->active_preempt_locks))
@@ -11560,6 +11560,7 @@ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int i
 	if (!callee)
 		return -ENOMEM;
 	entry.frame[0] = callee;
+	entry.speculative = state->speculative;
 	entry.in_sleepable = state->in_sleepable;
 	entry.suspect_loops = state->suspect_loops;
 	entry.callers_unknown = state->callers_unknown;
@@ -11628,6 +11629,8 @@ static int exit_func_on_its_own(struct bpf_verifier_env *env)
 	return err ?: PROCESS_BPF_EXIT;
 }
 
+static void mark_ptr_or_null_regs(struct bpf_verifier_state *vstate, u32 regno, bool is_null);
+
 static u32 returned_id(u32 id)
 {
 	return bpf_id_is_xreg(id) ? BPF_RETURNED_ID(id) : id;
@@ -11646,6 +11649,7 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 	struct bpf_reg_state *reg;
 	int err;
 
+	caller->speculative |= exit->speculative;
 	/*
 	 * Keep only what the function held all the time. The state at its exit looks the same if
 	 * the function released a lock and acquired it again. Else verify the function in the
@@ -11676,6 +11680,8 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 	 * the packet pointers of the caller is found out in the context of the caller.
 	 */
 	if (exit->changed_pkt_data) {
+		if (exit->speculative)
+			return -EACCES;
 		env->subprog_info[callee->subprogno].changes_pkt_data = true;
 		return BPF_EXIT_NEEDS_CALLER;
 	}
@@ -11700,6 +11706,9 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 		reg->id = returned_id(reg->id);
 		reg->parent_id = returned_id(reg->parent_id);
 		reg->map_uid = returned_id(reg->map_uid);
+		/* the function saw that a reference of the caller is not NULL */
+		if (reg->id && !type_may_be_null(reg->type))
+			mark_ptr_or_null_regs(caller, ret_regs[i], false);
 	}
 	return 0;
 }
@@ -11984,6 +11993,9 @@ static int check_func_callx_set(struct bpf_verifier_env *env, int regno, int *in
 			env->cur_state = copy;
 			err = check_func_callx_one(env, set->subprog[i], insn_idx);
 			env->cur_state = cur;
+			/* do_check_block() looks at the state that failed */
+			if (err < 0)
+				swap(*cur, *copy);
 		}
 		bpf_free_verifier_state(env, copy, true);
 		if (err == PROCESS_BPF_EXIT)
@@ -20331,7 +20343,7 @@ static int process_bpf_exit_full(struct bpf_verifier_env *env,
 {
 	struct bpf_func_state *cur_frame = cur_func(env);
 
-	if (!exception_exit && !env->cur_state->curframe && env->cur_state->flow_entry)
+	if (!exception_exit && !env->cur_state->curframe && env->cur_state->instance_id)
 		return exit_func_on_its_own(env);
 
 	/* We must do check_reference_leak here before
@@ -21529,6 +21541,9 @@ static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
 		from_unproven = reads_from_unproven(env);
 		fixups = insn_aux->fixups;
 		err = do_check_insn(env, &do_print_state) ?: bpf_equations_after_insn(env);
+		/* a call or an exit gave the state to the flow, the error is from there */
+		if (err < 0 && !state->frame[0])
+			return err;
 		insn_aux->releases |= held_cnt(state) < held && err != PROCESS_BPF_EXIT;
 		insn_aux->acquires |= held_cnt(state) > held;
 		if (nospec_ends_path(env, state, err)) {
Signature · 1 line
2.55.0
#39 lore raw

Re: [PATCH bpf-next v2 33/49] bpf: Verify a static function once for each instance

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider: - [Medium] bpf: uncharged instance cost in flow_grow_instance() after first instance - [Medium] bpf: missing…

Thank you for your contribution! Sashiko AI review found 3 potential issues to consider:
- [Medium] bpf: uncharged instance cost in flow_grow_instance() after first instance
- [Medium] bpf: missing FLOW_AGAIN kind on re-queued call state in flow_apply_exit()
- [Medium] bpf: missed non-NULL marking for returned parent_id in bpf_flow_return()
--

commit 086da59f5b2496a96c0c9a8141af31c675e376ed
Author: Alexei Starovoitov <[email protected]>

bpf: Verify a static function once for each instance

This commit verifies static subprograms that do not depend on caller frames once per instance, joining call states only at the subprogram entry point and dividing a verification budget among functions with multiple instances.

Quoted 4 lines
kernel/bpf/flow.c +0 -0
index c10fa54cdf91b..b5d65dd2d07a2 100644

[ ... ]

Quoted 19 lines
kernel/bpf/flow.c +15 -0
@@ -1345,6 +1358,301 @@ int bpf_flow_deliver(struct bpf_verifier_env *env, struct bpf_verifier_state *st
 	return flow_add(env, s, false);
 }
 
+/* @x is an exit state of the instance of the call @w. @w can leave the instance. */
+static int flow_apply_exit(struct bpf_verifier_env *env, struct flow_state *w,
+			   struct flow_state *x)
+{
+	int call_idx = w->st.insn_idx, err;
+	struct bpf_verifier_state st = {};
+
+	err = bpf_copy_verifier_state(env, &st, &w->st) ?:
+	      bpf_flow_return(env, &st, &x->st, call_idx);
+	if (!err)
+		err = bpf_flow_deliver(env, &st, call_idx + 1, call_idx, false);
+	else if (err < 0 && st.speculative)
+		err = min(bpf_flow_edge_unproven(env, &st, call_idx + 1, err), 0);
+	else if (err < 0)
+		err = min(bpf_flow_edge_unproven(env, &x->st, x->prev_insn_idx, err), 0);

kernel/bpf/flow.c int bpf_flow_deliver(struct bpf_verifier_env *env, struct bpf_verifier_state *st · line 1385

Quoted 10 lines
kernel/bpf/flow.c +10 -0
+	bpf_free_verifier_state(env, &st, false);
+	if (err <= 0)
+		return err;
+
+	/* The call is checked again in the frames of the caller */
+	flow_unlink(env, w);
+	flow_find(env, w);
+	flow_link(env, w);
+	return 0;
+}

[Severity: Medium]
Should flow_apply_exit() set w->kind = FLOW_AGAIN before re-linking w, the same way bpf_flow_deliver() does when again is true?

w was allocated with w->kind == FLOW_AT after passing pre-instruction join and flow_keep() handling at call_idx, and after do_check_insn() mutated the state for the call (such as check_func_callx_set() clearing reg->func_set and setting reg->subprogno to one subprogram from the set). When bpf_flow_return() returns BPF_EXIT_NEEDS_CALLER and w is re-inserted into state_tree as FLOW_AT at a join point, flow_prune_or_join() can join w with other states at call_idx (clobbering a split callx target register to NOT_INIT) and flow_keep() does not take its FLOW_AGAIN early return, re-running flow_keep_peeled() if call_idx is a peeled loop header.

[ ... ]

Quoted 4 lines
kernel/bpf/flow.c +4 -0
+/* @s gets to the first insn. @t is there and does not subsume @s. */
+static int flow_grow_instance(struct bpf_verifier_env *env, struct flow_state *t,
+			      struct flow_state *s, struct bpf_loop *leftover_loop)
+{

kernel/bpf/flow.c int bpf_flow_deliver(struct bpf_verifier_env *env, struct bpf_verifier_state *st · line 1439

Quoted 10 lines
kernel/bpf/flow.c +10 -0
+	u64 args = flow_readable_args(t->st.frame[0]);
+	struct flow_instance *old = t->started_instance, *instance = old;
+	int err;
+
+	if (!old->entry_state) {
+		instance = flow_new_instance(env, t);
+		if (!instance)
+			return -ENOMEM;
+		instance->cost = old->cost;
+	}

[Severity: Medium]
Does copying instance->cost = old->cost leave the new instance uncharged when old is the first instance of the subprogram?

In bpf_flow_call(), the first instance is free, so (*cost)++ increments env->flow->cost[subprog] from 0 to 1 while leaving t->started_instance->cost as NULL. When that first instance has already started (!old->entry_state) and a later call grows it into a second instance here, instance->cost is also set to NULL and budget_func_cnt is not incremented, so bpf_flow_next() never charges the cost of the grown instances to env->flow->cost[subprog] and flow_may_add_instance() never throttles them.

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index fac44fceccfbf..58a483fed88be 100644

[ ... ]

kernel/bpf/verifier.c int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal · line 11714

Quoted 10 lines
kernel/bpf/verifier.c +3 -0
@@ -11700,6 +11706,9 @@ int bpf_flow_return(struct bpf_verifier_env *env, struct bpf_verifier_state *cal
 		reg->id = returned_id(reg->id);
 		reg->parent_id = returned_id(reg->parent_id);
 		reg->map_uid = returned_id(reg->map_uid);
+		/* the function saw that a reference of the caller is not NULL */
+		if (reg->id && !type_may_be_null(reg->type))
+			mark_ptr_or_null_regs(caller, ret_regs[i], false);
 	}
 	return 0;
 }

[Severity: Medium]
What if the callee checks a caller reference n for NULL and returns a non-NULL child pointer derived from it, where reg->parent_id carries n's reference ID and reg->id is 0?

For example, a recursive static subprogram verified on its own can take an inherited PTR_MAYBE_NULL reference n, check if (!n) bpf_throw(), and return a PTR_TRUSTED member loaded from n (which sets reg->parent_id to n's reference ID in check_ptr_to_btf_access() while reg->id is 0). Because only reg->id is checked here, n in the caller keeps PTR_MAYBE_NULL; if the caller then tests if (!n), mark_ptr_or_null_regs() drops n from caller->refs[] via release_reference_nomark() without invalidating the returned child register whose parent_id still refers to n.

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

PATCH v2 34/49 bpf: Partition the states after an error

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

If a pass has an error, what does the next pass keep apart? This is trace partitioning. More precision costs more, so take the cheap steps first. bpf_partition_more() takes the first line that adds something:

  ADD_DEPS             the deps of the unproven insns
  PEEL                 suspect loops: one trip, then what a budget pays
  PEELED_APART         suspect loops: the join rule holds at the start
                       of a peeled trip
  TRANSITIVE_DEPS      data_deps |= control_deps; add the jumps that can
                       skip their writes
  DISJOINT_APART       disjoint values in data_deps stay apart
  LOOP_DISJOINT_APART  suspect loops: the same at the header
  PEEL_MORE            suspect loops: 4, 16, 64, ... trips; no prune of

a peeled trip if the last pass pruned one
IN_FRAMES calls with an argument that is in the deps and
has an equation: if (!ok(x)) return; buf[x]

A step can be the wrong one, and use up the limit of the load: to peel a loop of 100000 trips does not help if the error needs control_deps. So each step but the first has a budget, and can be undone:

            +-----------------+   in the budget, or it helped
       +--->| partition, pass |------------------------------> keep
       |    +--------+--------+
       |             | over its part of the budget
       |             v
       +--- undo, take the next line
       |             | no line left, one was too costly
       |             v
       +--- budget *= 4, undo all since one helped

If a step was too costly for a loop, a later step is a second choice. It is undone when the budget grows, also if it helped:
LOOP_DISJOINT_APART makes each later peel much more costly.

The first budget is two times the cost of a pass. charge_loops() gives the cost of a state to the loops that keep it apart.

---
 include/linux/bpf_verifier.h |  23 ++
 kernel/bpf/equation.c        |  12 +
 kernel/bpf/flow.c            |   1 +
 kernel/bpf/precision.c       | 503 +++++++++++++++++++++++++++++++++++
 kernel/bpf/precision.h       |  20 ++
 kernel/bpf/verifier.c        |  36 ++-
 6 files changed, 594 insertions(+), 1 deletion(-)
include/linux/bpf_verifier.h +23 -0
index 54a11c71374..22afe110d43 100644
@@ -839,6 +839,7 @@ struct bpf_loop_per_pass {
 	bool peel_pruned;	/* see flow_prune_peeled() */
 	/* a check failed in a state that the loop kept apart, with no other suspect */
 	bool has_unproven;
+	bool starves, starved;	/* see charge_loops() */
 	u32 last_peeled_trip;	/* see flow_keep_peeled() */
 	u32 peeled_cnt;		/* trips that the pass peeled */
 	u64 cost;		/* for the states that the loop keeps apart */
@@ -871,7 +872,12 @@ struct bpf_loop {
 	bool disjoint_apart;	/* disjoint values in data_deps stay apart, also in the leftover */
 	bool no_peel_prune;	/* a larger earlier trip does not prune, see flow_prune_peeled() */
 	);
+	struct bpf_loop_precision undo;	/* before the last partition */
+	struct bpf_loop_precision kept;	/* see keep_precision() */
 	struct bpf_loop_per_pass last_pass;	/* the last pass whose partition was kept */
+	/* to peel all trips, estimated from a partition that was over its budget */
+	u64 full_peel_cost;
+	u16 tried;		/* bits of PARTITION_*, with this budget */
 	bool partitioned;	/* the last partition was for this loop */
 	bool peeled_joined;	/* at the start of a peeled trip, against the join rule */
 	bool changed;		/* see flow_forget_loop() */
@@ -1351,9 +1357,11 @@ struct bpf_verifier_env {
 	bool strict_alignment;		/* perform strict pointer alignment checks */
 	bool test_reg_invariants;	/* fail verification on register invariants violations */
 	bool uses_arena_sp;		/* the program has insns with BPF_REG_ARENA_SP */
+	bool replay;			/* the good pass, once more for the driver */
 	bool path_sensitive;		/* no joins, see run_path_sensitive() */
 	bool for_log;			/* the verdict is known, see do_check_all() */
 	bool fallthrough_first;		/* see find_failing_path() */
+	u32 pass;			/* number of the pass, see do_check_all() */
 	struct bpf_precision *precision;
 	u64 cost, mem;			/* see bpf_check_limits() */
 	u64 max_cost, max_mem;
@@ -1697,6 +1705,8 @@ u64 bpf_hash_apart_xregs(struct bpf_verifier_env *env, const struct bpf_verifier
 u64 bpf_hash_args(struct bpf_verifier_env *env, const struct bpf_verifier_state *st, u64 hash);
 void bpf_range_of_data_dep(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 			   u32 *first, u32 *last);
+bool bpf_call_needs_frames(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			   u16 args);
 bool bpf_xreg_in_data_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 			   u32 fr, u32 xregno);
 bool bpf_xreg_in_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
@@ -1708,6 +1718,15 @@ bool bpf_insn_is_unproven(struct bpf_verifier_env *env);
 void bpf_note_fixups_differ(struct bpf_verifier_env *env);
 void bpf_find_unproven_after_pass(struct bpf_verifier_env *env);
 bool bpf_same_insns_unproven(struct bpf_verifier_env *env);
+int bpf_partition_more(struct bpf_verifier_env *env);
+bool bpf_undo_precision(struct bpf_verifier_env *env);
+void bpf_precision_new_pass(struct bpf_verifier_env *env);
+u64 bpf_pass_max_cost(struct bpf_verifier_env *env);
+u64 bpf_precision_budget(struct bpf_verifier_env *env);
+u64 bpf_precision_first_budget(struct bpf_verifier_env *env);
+int bpf_precision_init(struct bpf_verifier_env *env);
+void bpf_precision_free(struct bpf_verifier_env *env);
+
 /*
  * The two limits of the verifier, for the whole load. The unit of cost is one step of a scan,
  * about a dozen insns of the CPU. Memory is the bytes of states and tables at a time.
@@ -1719,6 +1738,9 @@ bool bpf_same_insns_unproven(struct bpf_verifier_env *env);
 #define BPF_COST_STATE	512	/* make, order and free a state */
 #define BPF_MAX_COST	(1ULL << 33)
 #define BPF_MAX_MEM	(1ULL << 31)
+/* The floors of the cost after the first error, and of the budget of a partition */
+#define BPF_PARTITION_BUDGET	(BPF_MAX_COST / 3)
+#define BPF_MIN_BUDGET	(BPF_MAX_COST >> 12)
 /* Without CAP_BPF programs are small, and their loads wait for each other */
 #define BPF_LIMITS_SHIFT_UNPRIV	5
 
@@ -2459,6 +2481,7 @@ void bpf_equations_fill(struct bpf_verifier_env *env, struct bpf_func_state *fra
 void bpf_equations_refine_all(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
 void bpf_equations_jump(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int idx,
 			bool taken);
+u16 bpf_args_with_equation(const struct bpf_verifier_state *st);
 void bpf_equations_next_trip(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
 			     u32 depth);
 bool bpf_equations_subsume(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
kernel/bpf/equation.c +12 -0
index 76c04e33da9..387156696ee 100644
@@ -1217,6 +1217,18 @@ static void add_distance_equation(struct bpf_verifier_env *env, const struct bpf
 			env->insn_idx, a.off - b.off });
 }
 
+/* At a call bpf_equations_before_insn() moves the equations of r1-r5 to the next frame */
+u16 bpf_args_with_equation(const struct bpf_verifier_state *st)
+{
+	u16 args = 0;
+	u32 r;
+
+	for (r = BPF_REG_1; r <= BPF_REG_5; r++)
+		if (bpf_find_xreg_equation(&st->equations, bpf_xreg(st->curframe + 1, r)))
+			args |= BIT(r);
+	return args;
+}
+
 /* Note the operands. Delete the equations of the registers that the insn writes. */
 void bpf_equations_before_insn(struct bpf_verifier_env *env)
 {
kernel/bpf/flow.c +1 -0
index b5d65dd2d07..cce3f88f916 100644
@@ -423,6 +423,7 @@ void bpf_flow_new_pass(struct bpf_verifier_env *env)
 	int i;
 
 	memset(flow->cost, 0, env->subprog_cnt * sizeof(*flow->cost));
+	flow->budget = bpf_precision_budget(env);
 	flow->budget_func_cnt = 0;
 	flow->start_cnt++;
 	for (i = 0; i < env->prog->len; i++, aux++) {
kernel/bpf/precision.c +503 -0

518 lines not on this page · raw message

kernel/bpf/precision.h +20 -0
index e057e452ec1..7b27c27c8d9 100644
@@ -22,6 +22,8 @@ struct precision_per_pass {
 	unsigned long *unproven_funcs;		/* of functions */
 	u64 suspect_loops, first_suspect_loops;	/* of the unproven states, of the first one */
 	bool disjoint_joined;			/* disjoint values in data_deps were joined */
+	bool over_budget, calls_joined;
+	bool arg_lost_equation;			/* see bpf_call_needs_frames() */
 };
 
 /* callx calls one of the functions whose address is taken. They count as one function. */
@@ -51,8 +53,18 @@ struct bpf_precision {
 	unsigned long *bad_value_insns;		/* unproven, its value is possibly the cause */
 	unsigned long *last_unproven_insns;	/* in the last pass */
 	unsigned long *bad_read_insns_done;
+	unsigned long *earlier_unproven_insns;	/* in an earlier pass */
 	unsigned long *control_seeds, *controlled_insns, *controlled_insns_done, *def_insns;
+	u32 first_unproven_insn;	/* of the last pass */
 	u32 last_unproven_left;		/* last_unproven_insns whose check did not fail again */
+	struct bpf_loop **loops;
+	u32 loop_cnt;
+	u64 start_cost, pass_cost;	/* env->cost before the pass, the cost of a pass */
+	/* the cost that a partition can add to it, and that this one can add */
+	u64 budget, budget_left;
+	u8 partitioned_by, too_costly;	/* bits of PARTITION_* */
+	bool failing_path_due;		/* see bpf_failing_path_is_due() */
+	bool budget_grew;		/* see partition_next() */
 	bool new_nospec;
 
 	u16 *apart_xregno;	/* per insn, see bpf_range_of_data_dep() */
@@ -60,6 +72,7 @@ struct bpf_precision {
 	/* The path-sensitive run */
 	unsigned long *err_insns;		/* insns at which the failing path can end */
 	u32 *hops_to_err, *hops_to_exit;	/* per insn, see compute_hops() */
+	u64 *seen;				/* hash set, see bpf_failing_path_was_here() */
 	unsigned long *loop_control_deps;	/* see bpf_jumps_see_same() */
 	u32 loop_carried_at;
 	unsigned long loop_carried[XREG_WORDS];
@@ -72,6 +85,13 @@ struct state_cmp {
 	u32 disjoint_apart;		/* what differs in these xregs */
 };
 
+enum {
+	PARTITION_ADD_DEPS, PARTITION_PEEL, PARTITION_PEELED_APART, PARTITION_TRANSITIVE_DEPS,
+	PARTITION_DISJOINT_APART, PARTITION_LOOP_DISJOINT_APART, PARTITION_PEEL_MORE,
+	PARTITION_IN_FRAMES,
+	PARTITION_TOO_COSTLY,	/* in bpf_loop.tried */
+};
+
 u32 bpf_frame_mask(struct bpf_verifier_env *env, unsigned long *masks,
 		   const struct bpf_verifier_state *st, u32 fr, unsigned long *out);
 const struct bpf_reg_state *bpf_xreg_value(struct bpf_verifier_env *env,
kernel/bpf/verifier.c +35 -1
index 58a483fed88..4f73bcf6c57 100644
@@ -11540,7 +11540,7 @@ static bool func_is_on_its_own(struct bpf_verifier_env *env, struct bpf_verifier
 		if (arg_needs_caller(env, state, sub, &caller->stack_arg_regs[i]))
 			return false;
 	}
-	return true;
+	return sub->recursive || !bpf_call_needs_frames(env, state, live);
 }
 
 static int enter_recursion(struct bpf_verifier_env *env, struct bpf_func_state *callee);
@@ -21290,6 +21290,7 @@ static void note_error(struct bpf_verifier_env *env, int err)
 		env->err = err;
 		env->err_insn = env->insn_idx;
 		env->log.level = 0;
+		env->pass_max_cost = min(env->pass_max_cost, bpf_pass_max_cost(env));
 	}
 	if (!env->path_sensitive)
 		bpf_note_unproven_insn(env, env->cur_state, env->insn_idx);
@@ -21615,10 +21616,41 @@ static bool round_is_dropped(struct bpf_verifier_env *env)
 	return (env->restart && bpf_flow_loops_lost_bound(env)) || env->guards_late;
 }
 
+/*
+ * The loops that keep the current state apart pay for the work since the last state, but not
+ * a loop that the state enters. A trip that is peeled on the budget of a loop belongs to that
+ * loop. Such trips can use up the budget of an inner loop.
+ */
+static void charge_loops(struct bpf_verifier_env *env, u64 cost)
+{
+	const struct bpf_verifier_state *st = env->cur_state;
+	const struct loop_stack_entry *e;
+	struct bpf_loop *starved_loop = NULL;
+	int fr, i;
+
+	for (fr = st->curframe; env->pass && fr >= 0; fr--) {
+		for (i = st->frame[fr]->loop_stack_cnt - 1; i >= 0; i--) {
+			e = &st->frame[fr]->loop_stack[i];
+			if ((e->peeled || e->loop->disjoint_apart) &&
+			    (e->trip || e->loop->header != st->insn_idx))
+				e->loop->this_pass.cost += cost;
+			if (e->peeled && e->trip >= e->loop->peel_cnt) {
+				if (starved_loop && e->loop->partitioned)
+					starved_loop->this_pass.starved =
+						e->loop->this_pass.starves = true;
+				return;
+			}
+			if (e->loop->partitioned && !bpf_loop_has_budget(e->loop))
+				starved_loop = e->loop;
+		}
+	}
+}
+
 static int do_check(struct bpf_verifier_env *env)
 {
 	bool level2 = env->log.level & BPF_LOG_LEVEL2;
 	u64 log_pos = env->log.end_pos, diag_pos = 0;
+	u64 cost = env->cost;
 	int prev_insn_idx, err;
 
 	err = bpf_flow_deliver(env, env->cur_state, env->insn_idx, -1, false);
@@ -21629,6 +21661,8 @@ static int do_check(struct bpf_verifier_env *env)
 			return bpf_check_limits(env);
 		if (err)
 			break;
+		charge_loops(env, env->cost - cost);
+		cost = env->cost;
 		/* A pass logs one basic block at a time. A path-sensitive run logs a full path. */
 		bpf_diag_event_log_restore(env, diag_pos);
 		if (!level2) {
Signature · 1 line
2.55.0
#41 lore raw

Re: [PATCH bpf-next v2 34/49] bpf: Partition the states after an error

TL;DR: - bpf_undo_precision() may drop -ENOMEM/-E2BIG from partition_next(), so the load fails with the wrong error - charge_loops() may skip charging outer loops on entering a peeled inner loop…
Quoted 1 line

bpf: Partition the states after an error

TL;DR:
- bpf_undo_precision() may drop -ENOMEM/-E2BIG from partition_next(), so the load fails with the wrong error
- charge_loops() may skip charging outer loops on entering a peeled inner loop
- IN_FRAMES may change nothing for callx sets
- stale return comments

Quoted 3 lines
kernel/bpf/equation.c +0 -0

[ ... ]

kernel/bpf/equation.c static void add_distance_equation(struct bpf_verifier_env *env, const struct bpf · line 1230

Quoted 11 lines
kernel/bpf/equation.c +11 -0
+/* At a call bpf_equations_before_insn() moves the equations of r1-r5 to the next frame */
+u16 bpf_args_with_equation(const struct bpf_verifier_state *st)
+{
+	u16 args = 0;
+	u32 r;
+
+	for (r = BPF_REG_1; r <= BPF_REG_5; r++)
+		if (bpf_find_xreg_equation(&st->equations, bpf_xreg(st->curframe + 1, r)))
+			args |= BIT(r);
+	return args;
+}

Can IN_FRAMES take effect for a callx through a function set?

The first time do_check_block() checks the callx, bpf_equations_before_insn() runs before do_check_insn() and moves the equations of r1-r5 from frame fr to frame fr+1, deleting the ones in frame fr:

    if (r && (bpf_pseudo_call(insn) || bpf_is_callx(insn)))
        copy_xreg_equation(env, eqs, bpf_xreg(fr + 1, r), bpf_xreg(fr, r));
    bpf_equations_forget_xreg(env, st, bpf_xreg(fr, r));

With in_frames set, check_func_callx_set() sees func_is_on_its_own() return false for a member and re-queues the same insn:

    if (!func_is_on_its_own(env, cur, set->subprog[i])) {
        branch = push_stack(env, *insn_idx, *insn_idx, false);
        ...
        env->head->again = true;

push_stack() copies the state after before_insn(), so frame fr+1 has the argument equations and frame fr has none.

When that copy comes back to do_check_block() at the callx, bpf_equations_before_insn() runs again. The BPF_CALL branch drops the fr+1 equations, and copy_xreg_equation() then copies from frame fr, which is now empty.

On the re-check, func_is_on_its_own() -> bpf_call_needs_frames() computes args &= bpf_args_with_equation(st), which is 0, so it returns false and func_is_on_its_own() returns true as it did before the partition.

So for a callx through a function set the IN_FRAMES partition seems to change
nothing: the pass repeats the same error and spends budget. Is that intended, or should callx sets be excluded from IN_FRAMES (or the equations kept across the second before_insn())?

[ ... ]

Quoted 3 lines
kernel/bpf/verifier.c +0 -0

[ ... ]

Quoted 14 lines
kernel/bpf/verifier.c +14 -0
+/*
+ * The loops that keep the current state apart pay for the work since the last state, but not
+ * a loop that the state enters. A trip that is peeled on the budget of a loop belongs to that
+ * loop. Such trips can use up the budget of an inner loop.
+ */
+static void charge_loops(struct bpf_verifier_env *env, u64 cost)
+{
+	const struct bpf_verifier_state *st = env->cur_state;
+	const struct loop_stack_entry *e;
+	struct bpf_loop *starved_loop = NULL;
+	int fr, i;
+
+	for (fr = st->curframe; env->pass && fr >= 0; fr--) {
+		for (i = st->frame[fr]->loop_stack_cnt - 1; i >= 0; i--) {

kernel/bpf/verifier.c static bool round_is_dropped(struct bpf_verifier_env *env) · line 21642

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+			e = &st->frame[fr]->loop_stack[i];
+			if ((e->peeled || e->loop->disjoint_apart) &&
+			    (e->trip || e->loop->header != st->insn_idx))
+				e->loop->this_pass.cost += cost;
+			if (e->peeled && e->trip >= e->loop->peel_cnt) {
+				if (starved_loop && e->loop->partitioned)
+					starved_loop->this_pass.starved =
+						e->loop->this_pass.starves = true;
+				return;
+			}

The header test correctly skips the charge for a loop the state has just entered, but the early return below it also fires for that loop.

Consider an inner loop I with peel_cnt == 0 that is being peeled on its budget, nested in an outer loop O that keeps the state apart. When the state reaches I's header, I is on the loop stack with trip 0 and charge_loops() is called with the cost of the block just run in O's body:

- I is not charged (trip == 0 and header == insn_idx), as the comment says
- e->peeled && e->trip >= e->loop->peel_cnt is true && 0 >= 0, so the function returns
- O is never visited, so the cost of that block is charged to no loop

This repeats on every entry into I, once per trip of O. O's this_pass.cost then reads lower than the work done in the states it keeps apart, which feeds bpf_loop_has_budget(O), bpf_loop_partition_is_active(O), the over_budget test in bpf_undo_precision() and the full_peel_cost estimate in undo_loop().

When a state has just entered a budget-peeled inner loop at trip 0, should the return be skipped so that the outer loops still pay for the block before the inner loop?

[ ... ]

Quoted 3 lines
kernel/bpf/precision.c +0 -0

[ ... ]

Quoted 3 lines
kernel/bpf/precision.c +3 -0
+/* The pass is over its budget. Returns true if another partition replaces the last one. */
+bool bpf_undo_precision(struct bpf_verifier_env *env)
+{

[ ... ]

Quoted 2 lines
kernel/bpf/precision.c +2 -0
+	env->over_limit = false;
+	memcpy(prec->data_deps, prec->undo, 5 * prec->words * sizeof(long));

[ ... ]

kernel/bpf/precision.c static int alloc_masks(struct bpf_verifier_env *env) · line 1421

Quoted 4 lines
kernel/bpf/precision.c +4 -0
+	if (partition_by[__ffs(prec->partitioned_by)] != partition_suspect_loops && !again)
+		prec->too_costly |= prec->partitioned_by;
+	return partition_next(env) > 0;
+}

Can this drop an error from partition_next()?

partition_next() always runs add_deps() first, which reaches compute_deps_of_unproven() -> add_control_deps() -> find_control_seeds() and bpf_compute_deps(). These use kvmalloc_array() and kvcalloc() with BPF_VERIFIER_GFP (which includes __GFP_RETRY_MAYFAIL), so they can return -ENOMEM without setting env->no_mem. bpf_add_cost_and_check() on the same path can also return -E2BIG or -EINTR.

The "> 0" test turns any of these into false, after the partition has already been undone (data_deps restored, undo_loop() called, env->over_limit cleared). With do_check_all() as wired up in 02e7abee2ca0 ("bpf: Verify in passes"):

- If the pass had no error and only ran over its budget (env->err == 0), the caller computes limit = !env->err and rejects the load with the pass's -E2BIG instead of -ENOMEM.
- If the pass had an error, the caller goes on to bpf_partition_more() on a pass whose partition is already undone, which swaps this_pass into last_pass and may call keep_precision(). The retry repeats the same allocations, and env->aborted is sticky but -ENOMEM is not, so -ENOMEM is the error that gets lost.

bpf_partition_more() returns its errors as an int and the caller handles them with "if (more < 0 && more != -E2BIG) err = more;". The same "return partition_next(env) > 0;" is still present at the end of the series.

Could bpf_undo_precision() return int, as bpf_partition_more() does, so that do_check_all() can stop with the real error?

[ ... ]

Quoted 3 lines

+ * Returns 1 if more is kept apart.
+ */
+int bpf_partition_more(struct bpf_verifier_env *env)

This isn't a bug, but the return value comments don't match the code.

When no partition is left, partition_next() returns "wait":

    wait = wait && prec->budget < env->max_cost - env->cost;
    prec->budget_left = prec->budget = min(4 * prec->budget, env->max_cost - env->cost);
    prec->failing_path_due = prec->budget_grew = true;
    return wait;

so bpf_partition_more() can return 1 when nothing more is kept apart; the next pass then undoes to the last keep with a larger budget. The function can also return a negative error (from alloc_masks(), find_calls_to_unproven() or a partition step), which the comment does not mention, although the driver depends on it (last |= more != 1).

Similarly, the comment above bpf_undo_precision() says "Returns true if another partition replaces the last one", but it also returns true when only the budget grows (partitioned_by = 0). It also says "The pass is over its budget", yet the function is called after every pass and returns false at once when !env->over_limit. Could these comments be updated?

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

#42 lore raw

PATCH v2 35/49 bpf: Reproduce an error on one path, with no joins

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

After a join a pass cannot tell a real error from a false one. If the error is real, more passes are wasted work, and the log of the joined state does not show the bug:

R6=scalar(smin=0,smax=max) R7=scalar(smin=-22,smax=0)

find_failing_path() tries to reproduce the error. It checks one path after another until the check of an insn in err_insns fails. This is a path-sensitive run. It has the same checks as a pass, and goes depth first, the shortest way first:
- There are no joins. A call stays in the frames of its caller. Each trip is peeled.
- A state is dropped if a state with the same values in the deps was at the insn.
- If only the jump on the iv of a loop depends on the xregs that moved, the path skips trips, see below.
- If the jumps of a loop see the same values in two trips, the loop is infinite. The path continues where may_goto leaves it.
- A run that is cut by its budget starts again, fall-through edge first. If it is cut again, or by its limit on trips, it starts again with the next limit on trips.

The path on which the check fails is the failing path. If the run made no guess, see below, the passes that are left get a small budget. So a wrong program is rejected fast. And the log has the full path. Only log level 2 has the paths that the run dropped.

A path can have errors that do not end it: in a speculative state, or in the BTF check of the arguments of a static function. Such an error gets no "Verification failed" report, see env->no_report. A missing stack argument ends the path, so report it at the first check.

The paths that continue from a header share a copy of the state there, see bpf_header_state. leave_loops() drops the copy. check_funcs() checks all functions from a snapshot. A pass uses it too.

A path has to get through a long loop to an error after it:

  for (i = 0; i < 100000; i++) { if (rnd() && n < 8) n++; }
  a[n] = 0;

It makes no joins, so it has no equation for the trip index. Two trips give the step:

trip 3: the jump sees i = 3 step 1
trip 4: the jump sees i = 4 99996 trips left

failing_path_trip() compares the state with the saved state of an earlier trip. If the other jumps do not depend on the xregs that moved, bpf_fast_forward_xregs() moves them to the last trips.

The nonlinear_xregs of the loop are not moved: the step of two trips does not tell where '(i + 1) & 63' is after 99996 trips.

Two paths can have the same ranges, and only one of them has r1 == r6. The other one can be the path that fails. So the hash of a state has the xregs that share a sym, see bpf_equations_hash().

Three guesses of the run can make a path that the program cannot take. If such a path cuts the budget, a valid program can be rejected. So a guess sets env->run_has_guess, and the budget is not cut.

1. The skip. Two trips show a step also for 'sum += i':

for (i = 0; i < 1000; i++) sum += i;
buf[sum - 499500] valid, this is buf[0]

trip i sum real sum
2 2 1 1 saved
4 4 6 6 since trip 2: i +2, sum +5
skip 998 2491 497503 497 times: (996 left - 1) / 2
exit 1000 4488 499500 buf[-495012] fails

bpf_steps_are_constant() looks at the xregs that move and at the operands of the jump on the iv, such as 'i < n / i'. A copy has to have the step of its source.

2. "The loop is infinite". Two trips give more than 2^32 trips also for this loop of 512 trips:

     u64 i = 600; do { i = (i + 1) & 1023; } while (i != 88);

The next runs keep this answer. So it is also a guess if the run made a guess before it.

3. The target of may_goto. All states have the same one. A state that only a join makes can hold a lock. Then the target is the code after the loop, also for a path with no lock.

The run accepts nothing. It is not the verdict either: a path has ranges too, and it can fail at an insn that a pass proves.

---
 include/linux/bpf_verifier.h |  36 +++++
 kernel/bpf/Makefile          |   1 +
 kernel/bpf/diagnostics.c     |   2 +-
 kernel/bpf/equation_join.c   | 202 +++++++++++++++++++++++++++
 kernel/bpf/failing_path.c    | 261 +++++++++++++++++++++++++++++++++++
 kernel/bpf/flow.c            |  62 ++++++++-
 kernel/bpf/precision.c       |   4 +
 kernel/bpf/precision.h       |   2 +
 kernel/bpf/verifier.c        | 235 ++++++++++++++++++++++++++++++-
 9 files changed, 801 insertions(+), 4 deletions(-)
 create mode 100644 kernel/bpf/failing_path.c
include/linux/bpf_verifier.h +36 -0
index 22afe110d43..74cc3e2fbc7 100644
@@ -445,6 +445,7 @@ static inline u64 bpf_xreg(u32 frameno, u32 xregno)
  */
 struct loop_stack_entry {
 	struct bpf_loop *loop;
+	struct bpf_header_state *header_state;	/* see failing_path_trip() */
 	/* How many times the state came back to the header. A join has the larger number. */
 	u32 trip;
 	/* The state that entered the loop. What comes back to the header is for that state. */
@@ -455,6 +456,9 @@ struct loop_stack_entry {
 	struct scalar trip_index;
 	bool trip_widened;	/* it was moved to a threshold, or it does not grow */
 	u64 exit_threshold;	/* by the jumps that the state passed and that leave the loop */
+	/* Path-sensitive run: the jump that tests the iv, the value it saw, the trips left */
+	u32 iv_jump_idx;
+	u64 iv_prev, trips_left;
 };
 
 /* The states of trip 0, 1, 2, 4, 8, ... are saved. A compare with them finds any period. */
@@ -632,6 +636,12 @@ static inline struct bpf_stack_state *bpf_stack_slot(const struct bpf_func_state
 	return &frame->stack[spi];
 }
 
+/* The state in which a path started a trip, see failing_path_trip() */
+struct bpf_header_state {
+	struct bpf_verifier_state st;
+	u32 refcnt;
+};
+
 static inline struct bpf_reg_state *
 bpf_get_spilled_reg(int slot, struct bpf_func_state *frame, u32 mask)
 {
@@ -882,7 +892,9 @@ struct bpf_loop {
 	bool peeled_joined;	/* at the start of a peeled trip, against the join rule */
 	bool changed;		/* see flow_forget_loop() */
 	bool guarded;		/* states take the edges of may_goto */
+	bool was_infinite;	/* at the start of the last path-sensitive run */
 	bool infinite;		/* see failing_path_trip() */
+	bool infinite_is_guess;	/* see fast_forward_trips() */
 	struct bpf_iv_threshold *iv_thresholds;	/* where an iv can stop, see equation_join.c */
 	u32 iv_threshold_cnt, iv_threshold_cap;
 	u32 leftover_epoch;	/* how many leftovers started */
@@ -1361,6 +1373,9 @@ struct bpf_verifier_env {
 	bool path_sensitive;		/* no joins, see run_path_sensitive() */
 	bool for_log;			/* the verdict is known, see do_check_all() */
 	bool fallthrough_first;		/* see find_failing_path() */
+	bool run_has_guess;		/* see run_path_sensitive() */
+	u32 failing_path_budget_shift;	/* see func_failing_path_budget() */
+	u32 failing_path_max_trips;	/* see failing_path_trip() */
 	u32 pass;			/* number of the pass, see do_check_all() */
 	struct bpf_precision *precision;
 	u64 cost, mem;			/* see bpf_check_limits() */
@@ -1376,6 +1391,8 @@ struct bpf_verifier_env {
 	u32 err_insn;
 	bool imprecise;			/* a state before the first error is imprecise */
 	bool over_limit;		/* see bpf_check_limits() */
+	bool too_deep;			/* see failing_path_trip() */
+	bool run_over_budget;		/* in one of its functions, see find_failing_path() */
 	bool restart;			/* see bpf_flow_next_is_no_bound() */
 	bool guards_late;		/* see bpf_flow_needs_guard() */
 	bool calls_joined;		/* see flow_may_add_instance() */
@@ -1521,6 +1538,7 @@ struct bpf_verifier_env {
 	int *idoms;
 	struct bpf_equation_env *eq_env;
 	struct bpf_flow *flow;
+	bool no_report;		/* an error does not end the path, see diag_write() */
 };
 
 static inline struct bpf_func_info_aux *subprog_aux(struct bpf_verifier_env *env, int subprog)
@@ -1724,6 +1742,14 @@ void bpf_precision_new_pass(struct bpf_verifier_env *env);
 u64 bpf_pass_max_cost(struct bpf_verifier_env *env);
 u64 bpf_precision_budget(struct bpf_verifier_env *env);
 u64 bpf_precision_first_budget(struct bpf_verifier_env *env);
+bool bpf_failing_path_is_due(struct bpf_verifier_env *env);
+int bpf_failing_path_prepare(struct bpf_verifier_env *env, bool repeat);
+bool bpf_failing_path_may_end_at(struct bpf_verifier_env *env, u32 idx);
+u32 bpf_failing_path_hops(struct bpf_verifier_env *env, const struct bpf_verifier_state *st);
+int bpf_failing_path_was_here(struct bpf_verifier_env *env, const struct bpf_verifier_state *st);
+int bpf_jumps_see_same(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
+		       const struct bpf_verifier_state *new, int iv_jump_idx,
+		       const unsigned long *iv_xregs);
 int bpf_precision_init(struct bpf_verifier_env *env);
 void bpf_precision_free(struct bpf_verifier_env *env);
 
@@ -1763,6 +1789,8 @@ void bpf_flow_reset(struct bpf_verifier_env *env);
 void bpf_flow_free(struct bpf_verifier_env *env);
 bool bpf_flow_trip_is_new(struct bpf_verifier_env *env, struct loop_stack_entry *entry);
 bool bpf_flow_is_bb_start(struct bpf_verifier_env *env, int insn_idx);
+int bpf_flow_save_header_state(struct bpf_verifier_env *env, struct loop_stack_entry *entry);
+void bpf_flow_put_header_state(struct loop_stack_entry *entry);
 int bpf_flow_deliver(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
 		     int insn_idx, int prev_insn_idx, bool again);
 int bpf_flow_next(struct bpf_verifier_env *env, int *prev_insn_idx, u64 *log_pos, u64 *diag_pos);
@@ -2216,6 +2244,7 @@ struct bpf_call_arg_meta {
 
 	/* Only set by subprog */
 	bool subprog_may_change_pkt;
+	bool subprog_is_static;
 
 	/* Only set by kfunc */
 	bool r0_rdonly;
@@ -2498,7 +2527,14 @@ bool bpf_equations_join_forgets(struct bpf_verifier_env *env, const struct bpf_v
 				const struct bpf_verifier_state *b, u32 fr,
 				const unsigned long *data_deps, const unsigned long *xregs,
 				u32 bits);
+u32 bpf_equations_hash(struct bpf_verifier_env *env, const struct bpf_verifier_state *st, u32 fr,
+		       const unsigned long *xregs, u32 bits);
 void bpf_collect_iv_thresholds(struct bpf_verifier_env *env);
+bool bpf_steps_are_constant(struct bpf_verifier_env *env, const struct loop_stack_entry *entry,
+			    const unsigned long *iv_xregs, bool infinite);
+void bpf_fast_forward_xregs(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
+			    struct bpf_verifier_state *cur, u64 factor, unsigned long *iv_xregs);
+
 void scalar_bounds_sync(struct scalar *s);
 bool scalar_subsumes(const struct scalar *old, const struct scalar *cur);
 bool scalars_fit_in_bits(const struct scalar *a, const struct scalar *b, u32 bits);
kernel/bpf/Makefile +1 -0
index 575c7d0ff4e..389e78b0bc4 100644
@@ -16,6 +16,7 @@ obj-$(CONFIG_BPF_SYSCALL) += fixups.o cfg.o states.o check_btf.o flow.o join.o
 obj-$(CONFIG_BPF_SYSCALL) += equation.o
 obj-$(CONFIG_BPF_SYSCALL) += equation_join.o
 obj-$(CONFIG_BPF_SYSCALL) += precision.o
+obj-$(CONFIG_BPF_SYSCALL) += failing_path.o
 obj-${CONFIG_BPF_LSM}	  += bpf_inode_storage.o
 obj-$(CONFIG_BPF_SYSCALL) += disasm.o mprog.o
 obj-$(CONFIG_BPF_JIT) += trampoline.o
kernel/bpf/diagnostics.c +1 -1
index 2cb9eceb408..0e12078ffe1 100644
@@ -372,7 +372,7 @@ static void diag_write(struct bpf_verifier_env *env, const char *fmt, ...)
 {
 	va_list args;
 
-	if (!bpf_diag_enabled(env))
+	if (!bpf_diag_enabled(env) || env->no_report)
 		return;
 
 	va_start(args, fmt);
kernel/bpf/equation_join.c +202 -0

238 lines not on this page · raw message

kernel/bpf/failing_path.c new file +261 -0

261 lines not on this page · raw message

kernel/bpf/flow.c +61 -1

128 lines not on this page · raw message

kernel/bpf/precision.c +4 -0
index a24cea7ee79..bcbc89655ed 100644
@@ -1491,6 +1491,10 @@ int bpf_partition_more(struct bpf_verifier_env *env)
 	if (prec->partitioned_by <= BIT(PARTITION_ADD_DEPS))
 		prec->budget = max(prec->budget, bpf_precision_first_budget(env));
 	swap(prec->this_pass, prec->last_pass);
+	/* only the unproven insns of this pass: no check failed at the other ones */
+	bitmap_or(prec->last_unproven_insns, prec->last_pass.unproven_insns,
+		  prec->last_pass.bad_read_insns, env->prog->len);
+	bitmap_and(prec->err_insns, prec->err_insns, prec->last_unproven_insns, env->prog->len);
 	bitmap_copy(prec->last_unproven_insns, prec->last_pass.unproven_insns, env->prog->len);
 	if (helped)
 		keep_precision(prec, true);
kernel/bpf/precision.h +2 -0
index 7b27c27c8d9..39284d1df97 100644
@@ -73,7 +73,9 @@ struct bpf_precision {
 	unsigned long *err_insns;		/* insns at which the failing path can end */
 	u32 *hops_to_err, *hops_to_exit;	/* per insn, see compute_hops() */
 	u64 *seen;				/* hash set, see bpf_failing_path_was_here() */
+	u32 seen_cnt, seen_bits;
 	unsigned long *loop_control_deps;	/* see bpf_jumps_see_same() */
+	u32 loop_control_deps_for, new_data_deps_for;
 	u32 loop_carried_at;
 	unsigned long loop_carried[XREG_WORDS];
 };
kernel/bpf/verifier.c +233 -2

384 lines not on this page · raw message

Signature · 1 line
2.55.0
#43 lore raw

Re: [PATCH bpf-next v2 35/49] bpf: Reproduce an error on one path, with no joins

TL;DR: - Loop-trip skip may build impossible states with no guess flagged, so valid programs could be rejected - State hash may conflate r6==r1 with r6==r1+1, missing the failing path…
Quoted 1 line

bpf: Reproduce an error on one path, with no joins

TL;DR:
- Loop-trip skip may build impossible states with no guess flagged, so valid programs could be rejected
- State hash may conflate r6==r1 with r6==r1+1, missing the failing path
- find_failing_path() unused here: possible -Werror build break

Quoted 3 lines
kernel/bpf/equation_join.c +0 -0

[ ... ]

kernel/bpf/equation_join.c static u64 compute_trip_count(s64 step, u64 *x, u8 op, bool jmp32, struct scalar · line 758

Quoted 13 lines
kernel/bpf/equation_join.c +13 -0
+/* A path-sensitive run has no equations for the trip index. Two trips give the step. */
+static void note_trips_left(struct bpf_verifier_env *env, struct loop_stack_entry *e,
+			    const struct scalar *x, u8 op, bool jmp32, const struct scalar *bound,
+			    bool is_body_jump)
+{
+	u64 value = jmp32 ? x->r32.base : x->r64.base, far_end;
+	s64 step = jmp32 ? (s32)(value - e->iv_prev) : value - e->iv_prev;
+
+	if (e->iv_jump_idx && e->iv_jump_idx != env->insn_idx)
+		return;
+	far_end = value + (step < 0 ? 0 : jmp32 ? x->r32.size : x->r64.size);
+	if (e->iv_jump_idx)
+		e->trips_left = step ? compute_trip_count(step, &far_end, op, jmp32, *bound) : 0;

Can this skip a path the program cannot take without setting run_has_guess? note_trips_left() takes the step from the iv operand alone (value - e->iv_prev) and passes the other operand's current value to compute_trip_count() as a fixed bound. Nothing checks that the bound stays put between trips.

bpf_fast_forward_xregs() then moves every xreg that changed into iv_xregs, the bound register included. bpf_jumps_see_same() leaves out the iv jump and drops iv_xregs from loop_carried, so the moving bound is never compared. bpf_steps_are_constant() only asks whether the operands of the iv jump have a constant step, and a bound such as 'n--' has one, so it returns true.

For example:

  for (i = 0; i < n; i++) if (rnd()) n--;

The passes do not treat n as an iv because it moves only on some paths, so bpf_collect_iv_thresholds() sets aux->iv_operand = 1. On the path that takes the n-- edge on every trip with n = 100000, trips_left is computed as n - i (about 99994), but the real count is (n - i) / 2. The skip moves i by +99992 and n by -99992, and the loop exits with i = 99996 and n = 4, while every real execution of that path exits with i == n == 50000.

That state is impossible and no guess is recorded. Once 02e7abee2ca0 ("bpf: Verify in passes") wires up find_failing_path(), a check after the loop that depends on n or i can fail on this false path. The program is then rejected with that path's error and log, and 'if (path_err && !guess)' cuts env->max_cost. Isn't that the case run_has_guess is meant to prevent ("If such a path cuts the budget, a valid program can be rejected")?

Would it work to count the trips from the step of the difference of the two operands, or to treat a bound operand that is in iv_xregs as a guess (or refuse the skip)?

[ ... ]

kernel/bpf/equation_join.c static bool insn_is_in_loop(struct bpf_verifier_env *env, const struct bpf_loop · line 834

Quoted 12 lines
kernel/bpf/equation_join.c +12 -0
+/* If the operand has a constant step, the result has one too. @prev: in the same block. */
+static bool keeps_constant_step(const struct bpf_insn *insn, const struct bpf_insn *prev,
+				bool infinite)
+{
+	u8 class = BPF_CLASS(insn->code), op = BPF_OP(insn->code);
+
+	if (bpf_is_ldimm64(insn))
+		return true;
+	if (class != BPF_ALU64 && (class != BPF_ALU || infinite))
+		return false;
+	if (op == BPF_MOV)
+		return !insn->off || (!infinite && insn->off == 32);

Is it correct to treat 32-bit ALU insns as keeping a constant step whenever !infinite? Here, when trips_left <= 2^32, keeps_constant_step() accepts BPF_ALU insns, 'w = w' zero extension, movsx32 and the '<<= 32; >>= 32' idiom. bpf_steps_are_constant() does the same for 4-byte fills ('!infinite || BPF_SIZE(insn->code) == BPF_DW').

The comment '@infinite: above 2^32 trips. Only the jump counts, and 32-bit insns wrap.' assumes a 32-bit result cannot wrap in fewer than 2^32 trips. That holds only for a step of +-1 that starts from 0. A 32-bit value wraps once start + trips * step crosses 2^32. For 'w7 += 0x10000' in a 100000-trip loop that happens after 65536 trips, and for a hash constant such as 0x9e3779b9 it happens every other trip.

move_bounds() then adds the 64-bit delta times factor through scalar_add(). For:

  u32 h = 0; for (i = 0; i < 100000; i++) h += 0x10000;

the skip sets r64 of the zero-extended register to 0x1869F0000 (r32 = 0x869F0000), but the real register is 0x869F0000. Any 64-bit use after the loop (a 64-bit jump, a shift, an index added to a pointer) sees a value no execution has. bpf_steps_are_constant() still returns true, so run_has_guess is not set, and the result is a false failing path with no guess, as above.

The 'i += 1; x = (u32)i; yes' example in the bpf_steps_are_constant() comment has the same problem when i does not start near 0 or the step is not 1.

[ ... ]

kernel/bpf/equation_join.c static bool insn_is_in_loop(struct bpf_verifier_env *env, const struct bpf_loop · line 903

Quoted 6 lines
kernel/bpf/equation_join.c +6 -0
+			slot = slot_of_insn(env, insn);
+			has_step = !slot ? keeps_constant_step(insn, prev, infinite) :
+				   test_bit(bpf_xreg_to_spi(slot),
+					    aux[loop->header].live_stack_before) &&
+				   !test_bit(slot, not_linear) &&
+				   (!infinite || BPF_SIZE(insn->code) == BPF_DW);

Can stores that move with the iv be lost by the skip without being counted as a guess? bpf_fast_forward_xregs() moves only the registers and spilled slots of the current frame whose bounds differ between the saved trip and this one. Stores that the skipped trips make at addresses that move with the iv are not reproduced.

Take a fill loop such as:

  u64 arr[N] = {}; for (p = arr; p < arr + N; p++) *p = f(i);

Here 'p' (PTR_TO_STACK) and 'i' move with a constant step. The store '*(u64 *)(r1 + 0) = r6' has a base that is not BPF_REG_FP, so slot_of_insn() returns 0 and keeps_constant_step() returns false for BPF_STX. A store has no def_regs, though, so the miss changes neither no_step nor new_step, and bpf_steps_are_constant() returns true. bpf_jumps_see_same() does not see the stored slots either: they are not live at the header, so they are not in loop_carried, and no control seed depends on them.

After the skip, the path state lacks every store from the skipped trips. arr[k] for the skipped k still holds its value from before the loop (STACK_ZERO here, STACK_INVALID without the '= {}'). A check after the loop that reads such an element, for example buf[arr[50]], sees a value no execution has. It can fail at the insn where the joined pass failed, with run_has_guess false. Once find_failing_path() is wired up, that false path becomes the reported error and log, and the budget of the passes that could peel the loop and prove the program is cut.

The commit message lists three guesses (non-constant steps, 'infinite', the may_goto target). This case is none of them, yet it also "can make a path that the program cannot take". Should it be a guess too?

Quoted 4 lines
kernel/bpf/failing_path.c new file +0 -0
new file mode 100644

[ ... ]

Quoted 4 lines
kernel/bpf/failing_path.c new file +4 -0
+static u64 hash_state(struct bpf_verifier_env *env, const struct bpf_verifier_state *st)
+{
+	unsigned long all[XREG_WORDS], control_deps[XREG_WORDS];
+	u64 hash = bpf_hash_join_key(env, st);

[ ... ]

kernel/bpf/failing_path.c line 131

Quoted 2 lines
kernel/bpf/failing_path.c new file +2 -0
+		bpf_add_cost(env, 2 * bitmap_weight(all, bits), BPF_COST_XREG);
+		hash += bpf_equations_hash(env, st, fr, all, bits);

Can this hash tell r6 == r1 apart from r6 == r1 + 1? hash_state() is the dedup key of the path-sensitive run: bpf_failing_path_was_here() drops a state at a join point when another state with the same hash got there first. The only relational part of the key is bpf_equations_hash(), which hashes the pairs (first xreg, xreg) of xregs that map to the same sym:

	first = &env->eq_env->scratch[xreg_eq->sym].new_symno;
	if (*first != U32_MAX)
		hash = jhash_2words(*first, xreg_eq->xreg, hash);

It does not hash xreg_eq->coef or xreg_eq->off. An xreg equation is 'xreg = coef * sym + off', so r6 = sym0 and r6 = sym0 + 1 give the same key when r1 = sym0 in both states. alu_add() keeps the sym for an added
constant: bpf_find_next_diff() returns make_expr(1, sym0, 1) when the operand is a constant.

The commit message gives this hash a job: "Two paths can have the same ranges, and only one of them has r1 == r6. The other one can be the path that fails. So the hash of a state has the xregs that share a sym".

  r1 = *(u64 *)(r7 + 0)    // full 64-bit range
  r6 = r1                  // r1 = sym0, r6 = sym0
  if r3 != 0 goto join     // path A: jumps to join
  r6 += 1                  // path B: r6 = sym0 + 1, range still full

join:
if r6 == r1 goto out // A always jumps, B never does
<check that fails> // only path B gets here

At 'join' both states have the same join_key, the same bytes in r1 and r6 (an unbounded scalar plus 1 is still unbounded) and the same pair (r1, r6) in bpf_equations_hash(). Path A is delivered to 'join' straight from the jump, and flow_add() calls bpf_failing_path_was_here() at delivery, so A goes into prec->seen before B has run 'r6 += 1'. When B gets to 'join', bpf_failing_path_was_here() returns 1 and flow_add() frees it. So the run cannot reproduce this error, whatever order it picks. The same happens for r6 = 15 - r1 (coef -1, off 15) with r1 in [0, 15], where both registers get range [0, 15] and tnum (0; 0xf).

The verdict does not change, since the passes still reject the program. But find_failing_path() returns 0, so the budget is not cut and the log gets no failing path. This is reachable once 02e7abee2ca0 ("bpf: Verify in passes") calls find_failing_path() from do_check_all(), and bpf_equations_hash() and hash_state() stay the same through 2b5f274b69fe.

Would hashing coef and off for each xreg in 'all', relative to the first xreg of its sym, keep these states apart?

Quoted 3 lines
kernel/bpf/verifier.c +0 -0

[ ... ]

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

Quoted 7 lines

+ * A function gets half of the budget that is left. @last: the budget is twice the cost so far.
+ */

kernel/bpf/verifier.c +5 -0
+static int find_failing_path(struct bpf_verifier_env *env, struct bpf_snapshot *initial, bool last)
+{
+	u32 trips;
+	u64 start;
+	int ret;

Is it intended that find_failing_path() has no caller in this commit? A grep of the tree at this commit finds only its definition, and do_check_all() still runs the old bpf_flow_new_round() / round_is_dropped() loop. This should give a '-Wunused-function' warning ('find_failing_path' defined but not used), and with CONFIG_WERROR=y (the default under COMPILE_TEST) the build would break. run_path_sensitive() and check_funcs() are reached only from find_failing_path(), so the whole path-sensitive run and every env->path_sensitive branch added here is dead code at this commit.

The commit message and the new comments also describe behaviour that this commit does not have yet:

"If the run made no guess, see below, the passes that are left get a small budget. So a wrong program is rejected fast."

"check_funcs() checks all functions from a snapshot. A pass uses it too."

run_path_sensitive(): "If the error of a pass is real, do_check_all() limits the next passes and logs a path to it."

At this commit no pass calls check_funcs(), and do_check_all() never calls find_failing_path(), so it neither cuts the budget nor logs a failing path.

The first caller arrives two commits later, in 02e7abee2ca0 ("bpf: Verify in passes"), via 'path_err = find_failing_path(env, initial, last);' in do_check_all(). Could find_failing_path() be wired up here, or moved together with the claims about passes and budgets into "bpf: Verify in passes", so that each step builds cleanly and the description stays accurate?

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

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

#44 lore raw

PATCH v2 36/49 bpf: Do not let a join raise what a program requires

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A pass can have no error and still ask for too much:

(off, len) = (0, 64) or (56, 8) each path needs 64 bytes
join: off = 0..56, len = 8..64 the pass asks for 120 bytes

Such bounds are checked at attach time or at run time. The program loads, and then it cannot attach or run.

Mark the insn as pessimized if it raises such a bound after an imprecise join, and an operand has a range. See struct prog_requirements. A barrier and a lost fastcall pattern count too. The verifier then keeps a snapshot of the pass and partitions more as for an unproven insn, in a small budget. If a later pass has an error, the snapshot is the result.

r0 = *(u64 *)(ctx + 8) no range, a join cannot change it
read(ctx + off, len) a join can add values to off and len

One case is not covered: a join makes a dead path reachable, and an insn on that path has constant operands. The bound stays larger.

kprobe_override and the bounds on buffers that a tail call sets move to the main pass, so they are compared too.

The driver of an offloaded program cannot forget what it saw. So it sees only a pass without errors: that pass runs once more for the driver (env->replay). Before that, each insn after an imprecise join is pessimized. An insn that the driver refuses is unproven. prepare() now runs before each pass for the driver, and destroy() between two such passes. An offloaded program gets no fastcall rewrite.

---
 include/linux/bpf_verifier.h |  4 ++
 kernel/bpf/fixups.c          |  6 ---
 kernel/bpf/offload.c         |  3 ++
 kernel/bpf/precision.c       | 44 ++++++++++++++++
 kernel/bpf/precision.h       |  1 +
 kernel/bpf/verifier.c        | 97 ++++++++++++++++++++++++++++++++----
 6 files changed, 139 insertions(+), 16 deletions(-)
include/linux/bpf_verifier.h +4 -0
index 74cc3e2fbc7..8c5eecf7501 100644
@@ -884,6 +884,7 @@ struct bpf_loop {
 	);
 	struct bpf_loop_precision undo;	/* before the last partition */
 	struct bpf_loop_precision kept;	/* see keep_precision() */
+	struct bpf_loop_precision good;	/* see bpf_restore_precision() */
 	struct bpf_loop_per_pass last_pass;	/* the last pass whose partition was kept */
 	/* to peel all trips, estimated from a partition that was over its budget */
 	u64 full_peel_cost;
@@ -1389,6 +1390,7 @@ struct bpf_verifier_env {
 	struct_group_tagged(bpf_env_per_pass, per_pass,
 	int err;			/* the first error */
 	u32 err_insn;
+	bool pessimized;		/* see bpf_partition_for_pessimized() */
 	bool imprecise;			/* a state before the first error is imprecise */
 	bool over_limit;		/* see bpf_check_limits() */
 	bool too_deep;			/* see failing_path_trip() */
@@ -1735,6 +1737,8 @@ void bpf_note_unproven_insn(struct bpf_verifier_env *env,
 bool bpf_insn_is_unproven(struct bpf_verifier_env *env);
 void bpf_note_fixups_differ(struct bpf_verifier_env *env);
 void bpf_find_unproven_after_pass(struct bpf_verifier_env *env);
+int bpf_partition_for_pessimized(struct bpf_verifier_env *env);
+void bpf_restore_precision(struct bpf_verifier_env *env);
 bool bpf_same_insns_unproven(struct bpf_verifier_env *env);
 int bpf_partition_more(struct bpf_verifier_env *env);
 bool bpf_undo_precision(struct bpf_verifier_env *env);
kernel/bpf/fixups.c +0 -6
index 4c9f63e096d..3bec52051a9 100644
@@ -2629,8 +2629,6 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 			prog->dst_needed = 1;
 		if (insn->imm == BPF_FUNC_get_prandom_u32)
 			bpf_user_rnd_init_once();
-		if (insn->imm == BPF_FUNC_override_return)
-			prog->kprobe_override = 1;
 		if (insn->imm == BPF_FUNC_tail_call) {
 			/* If we tail call into other programs, we
 			 * cannot make any assumptions since they can
@@ -2641,10 +2639,6 @@ int bpf_do_misc_fixups(struct bpf_verifier_env *env)
 			if (!bpf_allow_tail_call_in_subprogs(env))
 				prog->aux->stack_depth = MAX_BPF_STACK;
 			prog->aux->max_pkt_offset = MAX_PACKET_OFF;
-			prog->aux->max_rdonly_access = U32_MAX;
-			prog->aux->max_rdwr_access = U32_MAX;
-			if (prog->type == BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE)
-				prog->aux->max_tp_access = U32_MAX;
 
 			/* mark bpf_tail_call as different opcode to avoid
 			 * conditional branch in the interpreter for every normal
kernel/bpf/offload.c +3 -0
index f7bfff1760c..572d828a478 100644
@@ -315,6 +315,9 @@ int bpf_prog_offload_verifier_prep(struct bpf_prog *prog)
 	down_read(&bpf_devs_lock);
 	offload = prog->aux->offload;
 	if (offload) {
+		/* the driver starts again, see do_check_all() */
+		if (offload->dev_state)
+			offload->offdev->ops->destroy(prog);
 		ret = offload->offdev->ops->prepare(prog);
 		offload->dev_state = !ret;
 	}
kernel/bpf/precision.c +44 -0

50 lines not on this page · raw message

kernel/bpf/precision.h +1 -0
index 39284d1df97..f833b4642bc 100644
@@ -62,6 +62,7 @@ struct bpf_precision {
 	u64 start_cost, pass_cost;	/* env->cost before the pass, the cost of a pass */
 	/* the cost that a partition can add to it, and that this one can add */
 	u64 budget, budget_left;
+	u64 good_budget;		/* see bpf_restore_precision() */
 	u8 partitioned_by, too_costly;	/* bits of PARTITION_* */
 	bool failing_path_due;		/* see bpf_failing_path_is_due() */
 	bool budget_grew;		/* see partition_next() */
kernel/bpf/verifier.c +87 -10

185 lines not on this page · raw message

Signature · 1 line
2.55.0
#45 lore raw

Re: [PATCH bpf-next v2 36/49] bpf: Do not let a join raise what a program requires

TL;DR: bpf_restore_precision() may restore a stale prec->undo if find_calls_to_unproven() fails (-E2BIG, -ENOMEM, -EINTR), mixing old masks with current loop precision; an offloaded program's replay…
Quoted 1 line

bpf: Do not let a join raise what a program requires

TL;DR: bpf_restore_precision() may restore a stale prec->undo if find_calls_to_unproven() fails (-E2BIG, -ENOMEM, -EINTR), mixing old masks with current loop precision; an offloaded program's replay pass could then fail or differ.

Quoted 3 lines
kernel/bpf/precision.c +0 -0

[ ... ]

Quoted 18 lines
kernel/bpf/precision.c +18 -0
+int bpf_partition_for_pessimized(struct bpf_verifier_env *env)
+{
+	struct bpf_precision *prec = env->precision;
+	int ret;
+	u32 i;
+
+	if (!env->pessimized)
+		return 0;
+	prec->good_budget = prec->budget;
+	for (i = 0; i < prec->loop_cnt; i++)
+		prec->loops[i]->good = prec->loops[i]->precision;
+	for (i = 0; i < env->prog->len; i++)
+		if (env->insn_aux_data[i].pessimized)
+			note_unproven_after_pass(env, i);
+	ret = bpf_partition_more(env);
+	if (ret <= 0 && prec->data_deps)
+		bpf_restore_precision(env);
+	return ret;

kernel/bpf/precision.c int bpf_partition_more(struct bpf_verifier_env *env) · line 1538

Quoted 10 lines
kernel/bpf/precision.c +10 -0
+}
+
+/* Go back to the precision of the last pass without errors */
+void bpf_restore_precision(struct bpf_verifier_env *env)
+{
+	struct bpf_precision *prec = env->precision;
+	struct bpf_loop *loop;
+	u32 i;
+
+	memcpy(prec->data_deps, prec->undo, 5 * prec->words * sizeof(long));

Can this restore a stale copy of the masks?

prec->undo is set to the current data_deps only in partition_next(). In bpf_partition_more(), partition_next() runs only if find_calls_to_unproven() succeeds:

	return find_calls_to_unproven(env) ?: partition_next(env);

find_calls_to_unproven() calls bpf_add_cost_and_check(), which can return -E2BIG, -ENOMEM or -EINTR. On that path data_deps still holds the precision of the good pass, but prec->undo holds the data_deps from before the partition that led to this pass.

The memcpy() above then replaces data_deps, control_deps, disjoint_apart, type_apart and in_frames with that older copy, while loop->precision below gets loop->good, which is the current value. No pass ran with that mix, so the comment "Go back to the precision of the last pass without errors" does not hold here.

For an offloaded program, the replay pass would then run with this mixed precision instead of being the good pass once more. Could it fail, or give the driver requirements that differ from the pass just accepted?

Would it work to make undo match data_deps before calling bpf_partition_more(), or to restore only when partition_next() actually ran?

kernel/bpf/precision.c int bpf_partition_more(struct bpf_verifier_env *env) · line 1548

Quoted 10 lines
kernel/bpf/precision.c +10 -0
+	for (i = 0; i < 5 * prec->words; i++)
+		prec->kept[i] &= prec->data_deps[i];
+	prec->budget = prec->good_budget;
+	for (i = 0; i < prec->loop_cnt; i++) {
+		loop = prec->loops[i];
+		loop->precision = loop->good;
+		loop->partitioned = false;
+		loop->changed = true;
+	}
+}

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

#46 lore raw

PATCH v2 37/49 bpf: Verify in passes

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Put the parts together. do_check_all() runs passes until a pass has no error, or until there is no more precision:

pass 0: join all numbers
|

  +---------> run a pass
  |               |
  |            error ? --- no ---> pessimized ? --- no ---> ACCEPT
  |               | yes                 | yes
  |               v                     v
  |       good pass before ?      save the good pass,
  |          | no      | yes      partition, cut the budget
  |          |         v                |
  |          |   ACCEPT, use that pass  +---> run a pass
  |          v
  |      partition
  |          |
  |  failing path ? --- yes ---> log it; if no guess, cut the budget
  |          | no                       |
  |          +<-------------------------+
  |          v
  +- yes - is more kept apart ? --- no ---> REJECT

A good pass has no error. It is a complete proof, with any precision. If no state before the error was imprecise, the error is real and the verifier stops. The path-sensitive run needs the deps, so it comes after the partition. A failing path with a guess does not cut the budget. If a pass has a real error, the log has that error and not the guess.

A valid program that no precision can prove must not use up the limit. After the first error the limit is the larger of BPF_PARTITION_BUDGET and two times the cost so far.

A program of 1M insns needs 1.2 GB for its tables, so BPF_MAX_MEM is large. If the states of a small program explode, they must not use all of it. With 2 GB a program of 500 insns takes 30 seconds before it is rejected. So the passes can add 256 MB to the tables, and 32 KB for each insn. That is one state with a full stack.

The later passes and the path-sensitive runs have no log, and make no text for diagnostics. The one that gives the log runs once more. That work is not in the limit on cost. Log level 2 has all of them.

A later pass must not hide a bug of the verifier. bpf_note_bug() sets env->bug and turns the log on. The load ends with -EFAULT.

Programs load again: remove the refusal in bpf_check() and -Wno-unused-function. Rename round_is_dropped() to pass_needs_restart().

---
 include/linux/bpf_verifier.h |  14 +-
 kernel/bpf/Makefile          |   1 -
 kernel/bpf/diagnostics.c     |   4 +-
 kernel/bpf/failing_path.c    |   8 ++
 kernel/bpf/precision.c       |   4 +
 kernel/bpf/verifier.c        | 247 ++++++++++++++++++++++++++++++-----
 6 files changed, 243 insertions(+), 35 deletions(-)
include/linux/bpf_verifier.h +13 -1
index 8c5eecf7501..c1ddcf6d7c4 100644
@@ -12,6 +12,7 @@
 #include <linux/math64.h> /* for div_s64_rem() */
 #include <linux/freezer.h>
 #include <linux/sched/signal.h>
+#include <linux/sizes.h>
 
 /* No memory fails the load. It does not wake up the OOM killer. */
 #define BPF_GFP_MAYFAIL (__GFP_RETRY_MAYFAIL | __GFP_NOWARN)
@@ -1436,6 +1437,7 @@ struct bpf_verifier_env {
 	bool no_rcu_read_lock;
 	bool signature;
 	u8 bug:1;			/* ends the load, see bpf_note_bug() */
+	u8 log_level:7;			/* of the user */
 	u32 insn_aux_data_len;
 	struct bpf_insn_aux_data *insn_aux_data; /* array of per-insn state */
 	struct bpf_patch_list patch_list;
@@ -1605,6 +1607,13 @@ __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env,
 				  u32 insn_off,
 				  const char *prefix_fmt, ...);
 
+/* No later pass can hide a bug of the verifier. Its message goes into the log. */
+static inline void bpf_note_bug(struct bpf_verifier_env *env)
+{
+	env->bug = true;
+	env->log.level = env->log_level;
+}
+
 #define verifier_bug_if(cond, env, fmt, args...)						\
 	({											\
 		bool __cond = (cond);								\
@@ -1615,6 +1624,7 @@ __printf(3, 4) void verbose_linfo(struct bpf_verifier_env *env,
 #define verifier_bug(env, fmt, args...)								\
 	({											\
 		BPF_WARN_ONCE(1, "verifier bug: " fmt "\n", ##args);				\
+		bpf_note_bug(env);								\
 		bpf_log(&env->log, "verifier bug: " fmt "\n", ##args);				\
 	})
 
@@ -1768,6 +1778,9 @@ void bpf_precision_free(struct bpf_verifier_env *env);
 #define BPF_COST_STATE	512	/* make, order and free a state */
 #define BPF_MAX_COST	(1ULL << 33)
 #define BPF_MAX_MEM	(1ULL << 31)
+/* What the passes can add to the tables. A loop keeps a state at each join point. */
+#define BPF_PASS_MEM_BASE	SZ_256M
+#define BPF_PASS_MEM_PER_INSN	SZ_32K	/* a state with a full stack */
 /* The floors of the cost after the first error, and of the budget of a partition */
 #define BPF_PARTITION_BUDGET	(BPF_MAX_COST / 3)
 #define BPF_MIN_BUDGET	(BPF_MAX_COST >> 12)
@@ -1806,7 +1819,6 @@ void bpf_flow_next_is_no_bound(struct bpf_verifier_env *env, int insn_idx, int h
 bool bpf_flow_loops_lost_bound(struct bpf_verifier_env *env);
 void bpf_flow_new_pass(struct bpf_verifier_env *env);
 void bpf_flow_drop_guards(struct bpf_verifier_env *env);
-void bpf_flow_new_round(struct bpf_verifier_env *env);
 int bpf_flow_place_guards(struct bpf_verifier_env *env);
 /* verifier.c, for flow.c */
 int bpf_flow_loop_enter(struct bpf_verifier_env *env, struct bpf_loop **backedge_loop,
kernel/bpf/Makefile +0 -1
index 389e78b0bc4..03f0539490c 100644
@@ -5,7 +5,6 @@ ifneq ($(CONFIG_BPF_JIT_ALWAYS_ON),y)
 cflags-nogcse-$(CONFIG_X86)$(CONFIG_CC_IS_GCC) := -fno-gcse
 endif
 CFLAGS_core.o += -Wno-override-init $(cflags-nogcse-yy)
-ccflags-y += -Wno-unused-function
 
 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 diagnostics.o loops.o
 obj-$(CONFIG_BPF_SYSCALL) += bpf_iter.o map_iter.o task_iter.o prog_iter.o link_iter.o
kernel/bpf/diagnostics.c +3 -1
index 0e12078ffe1..8972b429bbc 100644
@@ -255,7 +255,7 @@ static char *diag_fmt_alloc(struct bpf_verifier_env *env, size_t size)
 	size_t capacity, available;
 	char *buf;
 
-	if (!diag || !size || size > INT_MAX)
+	if (!diag || !bpf_diag_enabled(env) || !size || size > INT_MAX)
 		return NULL;
 
 	if (!list_empty(&diag->fmt_chunks)) {
@@ -406,6 +406,8 @@ void bpf_diag_event_log_restore(struct bpf_verifier_env *env, u64 log_pos)
 	if (!diag)
 		return;
 
+	/* no text is in use between two blocks */
+	diag_fmt_restore(env, (struct diag_fmt_mark){});
 	log = &diag->log;
 	end_seq = log_end(log);
 	if (WARN_ON_ONCE(log_pos > end_seq))
kernel/bpf/failing_path.c +8 -0
index 0aebd7bfe8f..677ec423622 100644
@@ -252,7 +252,15 @@ bool bpf_failing_path_is_due(struct bpf_verifier_env *env)
 int bpf_failing_path_prepare(struct bpf_verifier_env *env, bool repeat)
 {
 	struct bpf_precision *prec = env->precision;
+	struct bpf_loop *loop;
+	u32 i;
 
+	for (i = 0; i < prec->loop_cnt; i++) {
+		loop = prec->loops[i];
+		if (repeat)
+			loop->infinite = loop->was_infinite;
+		loop->was_infinite = loop->infinite;
+	}
 	prec->failing_path_due = false;
 	if (prec->seen)
 		memset(prec->seen, 0, sizeof(*prec->seen) << prec->seen_bits);
kernel/bpf/precision.c +4 -0
index ae9559a6e30..bb71d31c45c 100644
@@ -1550,6 +1550,7 @@ void bpf_restore_precision(struct bpf_verifier_env *env)
 void bpf_precision_new_pass(struct bpf_verifier_env *env)
 {
 	struct bpf_precision *prec = env->precision;
+	u32 i;
 
 	bitmap_zero(prec->this_pass.unproven_insns, env->prog->len);
 	bitmap_zero(prec->this_pass.bad_read_insns, env->prog->len);
@@ -1560,6 +1561,9 @@ void bpf_precision_new_pass(struct bpf_verifier_env *env)
 	if (prec->apart_xregno)
 		memset(prec->apart_xregno, 0, env->prog->len * sizeof(u16));
 	if (prec->data_deps && !env->replay && (prec->budget_grew || env->for_log)) {
+		/* the last error came before the last partition */
+		for (i = 0; env->for_log && i < 5 * prec->words; i++)
+			prec->kept[i] &= prec->undo[i];
 		keep_precision(prec, false);
 		prec->partitioned_by = prec->pass_cost = 0;
 	}
kernel/bpf/verifier.c +215 -32

301 lines not on this page · raw message

Signature · 1 line
2.55.0
#47 lore raw

Re: [PATCH bpf-next v2 37/49] bpf: Verify in passes

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider: - [Medium] bpf: cost limit not bypassed during repeat run in log_failing_path() --

Thank you for your contribution! Sashiko AI review found 1 potential issue to consider:
- [Medium] bpf: cost limit not bypassed during repeat run in log_failing_path()
--

commit 57a53f1fbdfbf66fd6d495ccd155fb967701e9d9
Author: Alexei Starovoitov <[email protected]>

bpf: Verify in passes

This commit implements the multi-pass verification loop in do_check_all(), running iterative partitioning passes and path-sensitive checks with cost and memory budgets while re-running the final pass or failing path to populate the verifier log.

Quoted 4 lines
kernel/bpf/verifier.c +0 -0
index f34c010138497..92b0f4bbf8955 100644

[ ... ]

Quoted 23 lines
kernel/bpf/verifier.c +19 -0
@@ -23466,40 +23488,202 @@ static int find_failing_path(struct bpf_verifier_env *env, struct bpf_snapshot *
 	}
 }
 
+/* Level 2 has the log of all passes. Else the log has one pass, or the failing path. */
+struct pass_log {
+	u32 level, len_max;
+	u64 pos;
+};
+
+static void restart_log(struct bpf_verifier_env *env, struct pass_log *log)
+{
+	env->log.level = log->level;
+	/* the log is dropped when a function is found to be safe */
+	log->pos = min(log->pos, env->log.end_pos);
+	if (log->level & BPF_LOG_LEVEL2)
+		return;
+	bpf_vlog_reset(&env->log, log->pos);
+	env->log.len_max = log->len_max;
+}
+
+/* Repeat the last run. The verdict does not depend on the log, so it has no cost. */
+static int log_failing_path(struct bpf_verifier_env *env, struct bpf_snapshot *initial,

kernel/bpf/verifier.c static int find_failing_path(struct bpf_verifier_env *env, struct bpf_snapshot * · line 23519

Quoted 10 lines
kernel/bpf/verifier.c +10 -0
+			    struct pass_log *log)
+{
+	u32 insns = env->insn_processed, states = env->total_states;
+	u64 cost = env->cost;
+	int i, ret;
+
+	restart_log(env, log);
+	ret = run_path_sensitive(env, initial, true);
+	env->log.level = 0;
+	env->cost = cost;

[Severity: Medium]
Can the repeat run in log_failing_path() hit env->max_cost in bpf_check_limits()?

log_failing_path() saves and restores env->cost around run_path_sensitive(), but neither rewinds env->cost to its value before the unlogged run nor raises env->max_cost (unlike the env->for_log replay, which sets env->max_cost = 2 * env->cost). During the repeat run, check_funcs() charges the path's cost a second time on top of env->cost and checks it against env->max_cost:

kernel/bpf/flow.c:bpf_check_limits() {
	if (env->cost <= min(env->max_cost, env->pass_max_cost) && env->mem <= env->max_mem &&
	    !env->over_limit)
		return 0;
	verbose(env, "BPF program is too complex: cost %llu of %llu, memory %llu of %llu\n",
		env->cost, min(env->max_cost, env->pass_max_cost), env->mem, env->max_mem);
	env->over_limit = true;
	return -E2BIG;
}

When find_failing_path() succeeds near env->max_cost, the doubled run cost pushes env->cost past env->max_cost. That logs a complexity failure, sets env->over_limit = true so env->err stays 0, and makes log_failing_path() return 0 instead of err, losing the failing-path log.

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

Re: [PATCH bpf-next v2 37/49] bpf: Verify in passes

In reply to Alexei Starovoitov
kernel test robot noticed the following build errors:

Hi Alexei,

kernel test robot noticed the following build errors:

[auto build test ERROR on 82cc2b4383e3edfa1026c8612fb4e90a9329ba11]

url:    https://github.com/intel-lab-lkp/linux/commits/Alexei-Starovoitov/bpf-Look-for-bpf_clone_redirect-once-in-check_recursion/20261120-204909
base:   82cc2b4383e3edfa1026c8612fb4e90a9329ba11
patch link:    https://lore.kernel.org/r/20261120204959.614908-38-alexei.starovoitov%40gmail.com
patch subject: [PATCH bpf-next v2 37/49] bpf: Verify in passes
config: csky-randconfig-1000-20261121 (https://download.01.org/0day-ci/archive/20261122/[email protected]/config)
compiler: csky-linux-gcc (GCC) 11.5.0
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20261122/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All errors (new ones prefixed by >>):

csky-linux-ld: kernel/bpf/verifier.o: in function `do_check_block':

>> kernel/bpf/verifier.c:21686:(.text+0x27540): undefined reference to `bpf_prog_offload_verify_insn'
>> csky-linux-ld: kernel/bpf/verifier.c:21816:(.text+0x27640): undefined reference to `bpf_prog_offload_verify_insn'

vim +21686 kernel/bpf/verifier.c

faed5c27d37622 Alexei Starovoitov      2026-11-20  21602  
5395aa9bbeb569 Alexei Starovoitov      2026-11-07  21603  /* Process the current state until it gets to the start of a basic block. */
5395aa9bbeb569 Alexei Starovoitov      2026-11-07  21604  static int do_check_block(struct bpf_verifier_env *env, int prev_insn_idx)
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21605  {
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21606  	struct bpf_verifier_state *state = env->cur_state;
ce70cdf9582e07 Alexei Starovoitov      2026-11-20  21607  	struct bpf_verifier_stack_elem *elem;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21608  	struct bpf_insn *insns = env->prog->insnsi;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21609  	int insn_cnt = env->prog->len;
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21610  	bool do_print_state = true, from_unproven;
532cf1318e675e Alexei Starovoitov      2026-11-20  21611  	struct prog_requirements prog_requirements, new_requirements;
ce70cdf9582e07 Alexei Starovoitov      2026-11-20  21612  	bool again = prev_insn_idx == env->insn_idx;
532cf1318e675e Alexei Starovoitov      2026-11-20  21613  	unsigned long ranges;
532cf1318e675e Alexei Starovoitov      2026-11-20  21614  	bool stack_args;
aba707a5c97228 Alexei Starovoitov      2026-11-20  21615  	u32 held;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21616  
ce70cdf9582e07 Alexei Starovoitov      2026-11-20  21617  	mark_verifier_state_scratched(env);
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21618  	for (;;) {
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21619  		struct bpf_insn *insn;
dadb59104c6441 Luis Gerhorst           2025-07-05  21620  		struct bpf_insn_aux_data *insn_aux;
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21621  		struct bpf_insn_fixups fixups;
6762e3a0bce5fc Eduard Zingerman        2026-04-10  21622  		int err;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21623  
faed5c27d37622 Alexei Starovoitov      2026-11-20  21624  		err = bpf_check_limits(env);
faed5c27d37622 Alexei Starovoitov      2026-11-20  21625  		if (err)
faed5c27d37622 Alexei Starovoitov      2026-11-20  21626  			return err;
8fd58560b71e97 Alexei Starovoitov      2026-11-07  21627  
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21628  		env->prev_insn_idx = prev_insn_idx;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21629  		if (env->insn_idx >= insn_cnt) {
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21630  			verbose(env, "invalid insn idx %d insn_cnt %d\n",
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21631  				env->insn_idx, insn_cnt);
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21632  			return -EFAULT;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21633  		}
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21634  
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21635  		insn = &insns[env->insn_idx];
dadb59104c6441 Luis Gerhorst           2025-07-05  21636  		insn_aux = &env->insn_aux_data[env->insn_idx];
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21637  
14c950ac2be8ca Kumar Kartikeya Dwivedi 2026-08-13  21638  		account_processed_insn(env);
14c950ac2be8ca Kumar Kartikeya Dwivedi 2026-08-13  21639  
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21640  		state->last_insn_idx = env->prev_insn_idx;
13f843c0177eeb Eduard Zingerman        2025-06-11  21641  		state->insn_idx = env->insn_idx;
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21642  		/*
5395aa9bbeb569 Alexei Starovoitov      2026-11-07  21643  		 * Record the incoming edge. A zero-offset conditional has identical
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21644  		 * successors, so its outcome cannot be reconstructed from the edge.
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21645  		 */
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21646  		if (!state->speculative && prev_insn_idx >= 0 && prev_insn_idx < insn_cnt) {
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21647  			struct bpf_insn *prev_insn = &insns[prev_insn_idx];
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21648  			int fallthrough_idx = prev_insn_idx + 1;
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21649  			int branch_idx = prev_insn_idx + bpf_jmp_offset(prev_insn) + 1;
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21650  			u8 class = BPF_CLASS(prev_insn->code);
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21651  			u8 opcode = BPF_OP(prev_insn->code);
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21652  
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21653  			if ((class == BPF_JMP || class == BPF_JMP32) &&
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21654  			    opcode != BPF_JA && opcode != BPF_CALL && opcode != BPF_EXIT &&
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21655  			    opcode <= BPF_JCOND && branch_idx != fallthrough_idx) {
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21656  				if (env->insn_idx == branch_idx)
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21657  					bpf_diag_record_branch(env, prev_insn_idx, true);
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21658  				else if (env->insn_idx == fallthrough_idx)
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21659  					bpf_diag_record_branch(env, prev_insn_idx, false);
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21660  			}
daf8248701b621 Kumar Kartikeya Dwivedi 2026-08-15  21661  		}
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21662  
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21663  		if (env->log.level & BPF_LOG_LEVEL2 && do_print_state) {
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21664  			verbose(env, "\nfrom %d to %d%s:",
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21665  				env->prev_insn_idx, env->insn_idx,
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21666  				env->cur_state->speculative ?
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21667  				" (speculative execution)" : "");
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21668  			print_verifier_state(env, state, state->curframe, true);
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21669  			do_print_state = false;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21670  		}
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21671  
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21672  		if (env->log.level & BPF_LOG_LEVEL) {
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21673  			if (verifier_state_scratched(env))
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21674  				print_insn_state(env, state, state->curframe);
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21675  
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21676  			verbose_linfo(env, env->insn_idx, "; ");
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21677  			env->prev_log_pos = env->log.end_pos;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21678  			verbose(env, "%d: ", env->insn_idx);
19dbb134748110 Alexei Starovoitov      2026-04-02  21679  			bpf_verbose_insn(env, insn);
483a1bb0b6cf81 Eduard Zingerman        2026-08-07  21680  			verbose(env, "\n");
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21681  			env->prev_insn_print_pos = env->log.end_pos - env->prev_log_pos;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21682  			env->prev_log_pos = env->log.end_pos;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21683  		}
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21684  
532cf1318e675e Alexei Starovoitov      2026-11-20  21685  		if (env->replay) {
8b7df50fd40d7a Luis Gerhorst           2025-06-03 @21686  			err = bpf_prog_offload_verify_insn(env, env->insn_idx,
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21687  							   env->prev_insn_idx);
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21688  			if (err)
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21689  				return err;
532cf1318e675e Alexei Starovoitov      2026-11-20  21690  		} else if (bpf_prog_is_offloaded(env->prog->aux)) {
532cf1318e675e Alexei Starovoitov      2026-11-20  21691  			/* the driver cannot forget what an imprecise state shows */
532cf1318e675e Alexei Starovoitov      2026-11-20  21692  			note_pessimized_insn(env, env->insn_idx);
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21693  		}
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21694  
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21695  		sanitize_mark_insn_seen(env);
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21696  		insn_aux->suspect_loops |= state->suspect_loops;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21697  		prev_insn_idx = env->insn_idx;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21698  
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21699  		/* Sanity check: precomputed constants must match verifier state */
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21700  		if (!state->speculative && !env->err && !env->extra_values &&
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21701  		    insn_aux->const_reg_mask) {
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21702  			struct bpf_reg_state *regs = cur_regs(env);
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21703  			u16 mask = insn_aux->const_reg_mask;
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21704  
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21705  			for (int r = 0; r < ARRAY_SIZE(insn_aux->const_reg_vals); r++) {
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21706  				u32 cval = insn_aux->const_reg_vals[r];
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21707  
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21708  				if (!(mask & BIT(r)))
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21709  					continue;
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21710  				if (regs[r].type != SCALAR_VALUE)
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21711  					continue;
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21712  				if (!tnum_is_const(regs[r].var_off))
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21713  					continue;
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21714  				if (verifier_bug_if((u32)regs[r].var_off.value != cval,
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21715  						    env, "const R%d: %u != %llu",
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21716  						    r, cval, regs[r].var_off.value))
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21717  					return -EFAULT;
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21718  			}
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21719  		}
f1606dd0ac4923 Alexei Starovoitov      2026-04-02  21720  
d6f1c85f22534d Luis Gerhorst           2025-06-03  21721  		/* Reduce verification complexity by stopping speculative path
d6f1c85f22534d Luis Gerhorst           2025-06-03  21722  		 * verification when a nospec is encountered.
d6f1c85f22534d Luis Gerhorst           2025-06-03  21723  		 */
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21724  		if (state->speculative && insn_aux->non_speculative_first)
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21725  			need_nospec(env, env->insn_idx);
dadb59104c6441 Luis Gerhorst           2025-07-05  21726  		if (state->speculative && insn_aux->nospec)
d6f1c85f22534d Luis Gerhorst           2025-06-03  21727  			goto process_bpf_exit;
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21728  		insn_aux->speculative_first |= !insn_aux->seen;
d6f1c85f22534d Luis Gerhorst           2025-06-03  21729  
532cf1318e675e Alexei Starovoitov      2026-11-20  21730  		ranges = operands_with_range(env, insn);
532cf1318e675e Alexei Starovoitov      2026-11-20  21731  		stack_args = cur_func(env)->out_stack_arg_cnt;
532cf1318e675e Alexei Starovoitov      2026-11-20  21732  
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21733  		err = check_loop_guard(env) ?: check_recursion_guard(env);
eaea7390705214 Alexei Starovoitov      2026-11-07  21734  		if (err)
eaea7390705214 Alexei Starovoitov      2026-11-07  21735  			return err;
eaea7390705214 Alexei Starovoitov      2026-11-07  21736  
46bc0f24720aa7 Alexei Starovoitov      2026-11-20  21737  		bpf_equations_before_insn(env);
aba707a5c97228 Alexei Starovoitov      2026-11-20  21738  		held = held_cnt(state);
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21739  		from_unproven = reads_from_unproven(env);
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21740  		fixups = insn_aux->fixups;
532cf1318e675e Alexei Starovoitov      2026-11-20  21741  		prog_requirements = get_prog_requirements(env);
28d9a7acba4a20 Alexei Starovoitov      2026-11-20  21742  		env->no_report = state->speculative;
46bc0f24720aa7 Alexei Starovoitov      2026-11-20  21743  		err = do_check_insn(env, &do_print_state) ?: bpf_equations_after_insn(env);
28d9a7acba4a20 Alexei Starovoitov      2026-11-20  21744  		env->no_report = false;
532cf1318e675e Alexei Starovoitov      2026-11-20  21745  		new_requirements = get_prog_requirements(env);
532cf1318e675e Alexei Starovoitov      2026-11-20  21746  		/* a join adds values only to a range */
532cf1318e675e Alexei Starovoitov      2026-11-20  21747  		if ((ranges || stack_args || again) &&
532cf1318e675e Alexei Starovoitov      2026-11-20  21748  		    memcmp(&prog_requirements, &new_requirements, sizeof(new_requirements)))
532cf1318e675e Alexei Starovoitov      2026-11-20  21749  			note_pessimized_insn(env, prev_insn_idx);
5614fba52b4c0b Alexei Starovoitov      2026-11-20  21750  		/* a call or an exit gave the state to the flow, the error is from there */
5614fba52b4c0b Alexei Starovoitov      2026-11-20  21751  		if (err < 0 && !state->frame[0])
5614fba52b4c0b Alexei Starovoitov      2026-11-20  21752  			return err;
aba707a5c97228 Alexei Starovoitov      2026-11-20  21753  		insn_aux->releases |= held_cnt(state) < held && err != PROCESS_BPF_EXIT;
aba707a5c97228 Alexei Starovoitov      2026-11-20  21754  		insn_aux->acquires |= held_cnt(state) > held;
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21755  		if (nospec_ends_path(env, state, err)) {
d6f1c85f22534d Luis Gerhorst           2025-06-03  21756  			/* Prevent this speculative path from ever reaching the
d6f1c85f22534d Luis Gerhorst           2025-06-03  21757  			 * insn that would have been unsafe to execute.
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21758  			 * What it noted does not apply to the other paths.
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21759  			 * check_fastcall_stack_contract() clears the pattern only once.
d6f1c85f22534d Luis Gerhorst           2025-06-03  21760  			 */
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21761  			fixups.fastcall_spills_num = insn_aux->fastcall_spills_num;
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21762  			insn_aux->fixups = fixups;
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21763  			need_nospec(env, prev_insn_idx);
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21764  			free_pushed_states(env);
d6f1c85f22534d Luis Gerhorst           2025-06-03  21765  			goto process_bpf_exit;
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21766  		} else if (error_is_recoverable(err) && !env->path_sensitive) {
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21767  			env->insn_idx = prev_insn_idx;
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21768  			if (bpf_same_insns_unproven(env))
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21769  				return err;
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21770  			if (from_unproven)
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21771  				bpf_note_reads_from_unproven(env, prev_insn_idx);
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21772  			else
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21773  				note_error(env, err);
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21774  			err = skip_unproven_insn(env, insn);
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21775  			if (err < 0)
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21776  				return err;
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21777  			if (err)
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21778  				goto process_bpf_exit;
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21779  			mark_from_unproven(env, prev_insn_idx, true);
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21780  			env->insn_idx++;
d6f1c85f22534d Luis Gerhorst           2025-06-03  21781  		} else if (err < 0) {
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21782  			return err;
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21783  		} else if (err == PROCESS_BPF_EXIT) {
d6f1c85f22534d Luis Gerhorst           2025-06-03  21784  			goto process_bpf_exit;
2ec74a053611ed Alexei Starovoitov      2026-04-11  21785  		} else if (err == INSN_IDX_UPDATED) {
2ec74a053611ed Alexei Starovoitov      2026-04-11  21786  		} else if (err == 0) {
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21787  			if (!bpf_pseudo_call(insn) && !bpf_is_callx(insn))
dab17a2b0bfd16 Alexei Starovoitov      2026-11-20  21788  				mark_from_unproven(env, prev_insn_idx, from_unproven);
2ec74a053611ed Alexei Starovoitov      2026-04-11  21789  			env->insn_idx++;
d6f1c85f22534d Luis Gerhorst           2025-06-03  21790  		}
d6f1c85f22534d Luis Gerhorst           2025-06-03  21791  
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21792  		/* only a store that stays gets it, see bpf_convert_ctx_accesses() */
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21793  		if (state->speculative && insn_aux->nospec_result && !insn_aux->fastcall_pattern &&
0810f59cd31bd0 Alexei Starovoitov      2026-11-20  21794  		    bpf_is_mem_insn(insn) && BPF_MODE(insn->code) == BPF_MEM) {
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21795  process_bpf_exit:
14c950ac2be8ca Kumar Kartikeya Dwivedi 2026-08-13  21796  			account_current_path(env);
faed5c27d37622 Alexei Starovoitov      2026-11-20  21797  			bpf_free_verifier_state(env, state, false);
5395aa9bbeb569 Alexei Starovoitov      2026-11-07  21798  			memset(state, 0, sizeof(*state));
5395aa9bbeb569 Alexei Starovoitov      2026-11-07  21799  			return flow_drain(env);
5395aa9bbeb569 Alexei Starovoitov      2026-11-07  21800  		}
5395aa9bbeb569 Alexei Starovoitov      2026-11-07  21801  
ce70cdf9582e07 Alexei Starovoitov      2026-11-20  21802  		/* if the insn pushed a part, the current state is a part too */
ce70cdf9582e07 Alexei Starovoitov      2026-11-20  21803  		for (elem = env->head; elem; elem = elem->next)
ce70cdf9582e07 Alexei Starovoitov      2026-11-20  21804  			again |= elem->again;
5395aa9bbeb569 Alexei Starovoitov      2026-11-07  21805  		err = flow_drain(env);
c9e31900b54cad Eduard Zingerman        2025-06-11  21806  		if (err)
c9e31900b54cad Eduard Zingerman        2025-06-11  21807  			return err;
5395aa9bbeb569 Alexei Starovoitov      2026-11-07  21808  
ce70cdf9582e07 Alexei Starovoitov      2026-11-20  21809  		/* the parts of a state meet at the next insn */
ce70cdf9582e07 Alexei Starovoitov      2026-11-20  21810  		if (env->insn_idx < insn_cnt &&
ce70cdf9582e07 Alexei Starovoitov      2026-11-20  21811  		    (again || bpf_flow_is_bb_start(env, env->insn_idx))) {
5395aa9bbeb569 Alexei Starovoitov      2026-11-07  21812  			account_current_path(env);
ce70cdf9582e07 Alexei Starovoitov      2026-11-20  21813  			return bpf_flow_deliver(env, state, env->insn_idx, prev_insn_idx, false);
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21814  		}
8b7df50fd40d7a Luis Gerhorst           2025-06-03  21815  	}

17a5267067f3c3 Alexei Starovoitov 2014-09-26 @21816 }
17a5267067f3c3 Alexei Starovoitov 2014-09-26 21817

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
#49 lore raw

PATCH v2 38/49 bpf: Make a returned pointer to the stack unreadable

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

A void static function does not set r0. So r0 can hold a pointer to the stack at the exit:

static void f(void) { char buf[8]; r0 = buf; ...; }
f(); <- nothing reads r0

The exit failed with "cannot return stack pointer to the caller". Let the read fail, not the exit: the register is unreadable in the caller.

old: exit of f() -> fails
new: exit of f() -> r0 is unreadable -> a read fails

---
 Documentation/bpf/kfuncs.rst |  4 ++--
 kernel/bpf/diagnostics.c     |  3 +++
 kernel/bpf/diagnostics.h     |  1 +
 kernel/bpf/verifier.c        | 40 ++++++++++++++++++------------------
 4 files changed, 26 insertions(+), 22 deletions(-)
Documentation/bpf/kfuncs.rst +2 -2
index c7da603cab7..335dbb833bf 100644
@@ -704,8 +704,8 @@ from a pointer is a leak, so the verifier rejects it with::
 Initialize the whole return value, for example ``struct pair p = {};``, to
 avoid this. A static subprogram is exempt from the scalar-only rule: it is
 verified inline, so an unassigned R2 is simply passed back to the caller as
-uninitialized and only a caller that reads it fails. A stack pointer left in
-R2 is still rejected there, just as one in R0 is.
+uninitialized and only a caller that reads it fails. The same holds for a
+stack pointer left in R2 or in R0.
 
 .. _BPF_kfunc_lifecycle_expectations:
 
kernel/bpf/diagnostics.c +3 -0
index 8972b429bbc..e17689d638b 100644
@@ -2233,6 +2233,9 @@ static void diag_print_mod(struct bpf_verifier_env *env, const struct bpf_diag_h
 			 "call invalidated this outgoing stack argument" :
 			 "call invalidated this caller-saved register";
 		break;
+	case BPF_DIAG_MOD_RET_STACK_PTR:
+		reason = "the caller cannot read a returned pointer to the stack";
+		break;
 	case BPF_DIAG_MOD_WRITE:
 		if (target->kind == BPF_DIAG_MOD_TARGET_STACK_SLOT)
 			reason = "a later stack write overwrote this spilled value";
kernel/bpf/diagnostics.h +1 -0
index cb255218c41..c0303c4aab4 100644
@@ -26,6 +26,7 @@ enum bpf_diag_mod_reason {
 	BPF_DIAG_MOD_SLICE_BUF,
 	BPF_DIAG_MOD_NON_OWN_REF,
 	BPF_DIAG_MOD_CALLER_SAVED,
+	BPF_DIAG_MOD_RET_STACK_PTR,
 };
 
 enum bpf_diag_context_kind {
kernel/bpf/verifier.c +20 -20
index 92b0f4bbf89..94499fdaaf9 100644
@@ -11641,21 +11641,32 @@ static int call_func_on_its_own(struct bpf_verifier_env *env, int subprog, int i
 	return err ?: PROCESS_BPF_EXIT;
 }
 
+/*
+ * A void function can leave a pointer to the stack in r0. The caller cannot read it. That holds
+ * for the stack of a caller too: for stack liveness a call returns no pointer to the stack.
+ */
+static void hide_returned_stack_ptrs(struct bpf_verifier_env *env, int subprog,
+				     struct bpf_reg_state *regs)
+{
+	u32 i, nregs = bpf_ret_reg_pair(env, subprog) ? 2 : 1;
+
+	for (i = 0; i < nregs; i++) {
+		if (regs[ret_regs[i]].type != PTR_TO_STACK)
+			continue;
+		verbose(env, "the caller cannot read the stack pointer in R%d\n", ret_regs[i]);
+		bpf_diag_record_scrub(env, &regs[ret_regs[i]], BPF_DIAG_MOD_RET_STACK_PTR);
+		bpf_mark_reg_not_init(env, &regs[ret_regs[i]]);
+	}
+}
+
 /* The current state is at exit of a function that is verified on its own. */
 static int exit_func_on_its_own(struct bpf_verifier_env *env)
 {
 	struct bpf_verifier_state *state = env->cur_state;
 	struct bpf_func_state *callee = state->frame[0];
-	u32 i, nregs;
 	int err;
 
-	nregs = bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1;
-	for (i = 0; i < nregs; i++) {
-		if (callee->regs[ret_regs[i]].type != PTR_TO_STACK)
-			continue;
-		verbose(env, "cannot return stack pointer to the caller\n");
-		return -EINVAL;
-	}
+	hide_returned_stack_ptrs(env, callee->subprogno, callee->regs);
 	state->unwound |= bpf_is_unwind_exit(&env->prog->insnsi[env->insn_idx]);
 
 	/* Invalidate callee-local dynptrs and their slices before the frame goes away. */
@@ -12417,18 +12428,6 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 	callee = state->frame[state->curframe];
 	r0 = &callee->regs[BPF_REG_0];
 	nregs = bpf_ret_reg_pair(env, callee->subprogno) ? 2 : 1;
-	for (i = 0; i < nregs; i++) {
-		if (callee->regs[ret_regs[i]].type != PTR_TO_STACK)
-			continue;
-		/* technically it's ok to return caller's stack pointer
-		 * (or caller's caller's pointer) back to the caller,
-		 * since these pointers are valid. Only current stack
-		 * pointer will be invalid as soon as function exits,
-		 * but let's be conservative
-		 */
-		verbose(env, "cannot return stack pointer to the caller\n");
-		return -EINVAL;
-	}
 
 	caller = state->frame[state->curframe - 1];
 	if (bpf_is_unwind_exit(&env->prog->insnsi[*insn_idx]) || state->unwound) {
@@ -12487,6 +12486,7 @@ static int prepare_func_exit(struct bpf_verifier_env *env, int *insn_idx)
 			caller->regs[regno] = callee->regs[regno];
 			bpf_diag_mod_end(env);
 		}
+		hide_returned_stack_ptrs(env, callee->subprogno, caller->regs);
 	}
 
 	/* Invalidate callee-local dynptrs and their slices before the frame goes away. */
Signature · 1 line
2.55.0
#50 lore raw

PATCH v2 39/49 bpf: Keep two states apart if a live xreg has two types

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Pass 0 joins all states. A join of two types or two objects is unreadable. If the xreg is live, the program probably reads it. Then the pass has an error, and the price is two more runs:

  r6 = 0;               r6 = map value;
          \            /
           if (r6 == 0) goto out;

old: join -> r6 !read_ok -> path-sensitive run -> pass 1: apart
new: pass 0: apart

The same holds for a packet pointer that has checked bytes in one state and has none in the other state.

bpf_hash_live_types() adds the types and objects of the live xregs to the hash of a state. So such states do not meet.

- Numbers are joined as before.
- The arguments of the calls of an instance are joined as before, else the calls do not share it.
- N such xregs can give 1 << N states. So the rule has a budget in each
pass: 1/64 of the limits on cost and memory. The cost of a state that is alone does not count, see bpf_flow_next(). A pass that is over the budget joins from there on, and so do the next passes. Then an error selects the xregs.
- Offloaded programs are joined as before. The replay for the driver has to join where the good pass did.

insns processed

  program                            before    after
  profiler3 kprobe__vfs_link         7969      3865
  test_cls_redirect_subprogs         5726      3091
  xdp_synproxy_kern syncookie_xdp    8136      7630
  bpf_flow flow_dissector_0          1363      701
---
 include/linux/bpf_verifier.h |  2 ++
 kernel/bpf/flow.c            | 18 +++++++++++
 kernel/bpf/precision.c       | 60 ++++++++++++++++++++++++++++++++++++
 kernel/bpf/precision.h       |  3 ++
 4 files changed, 83 insertions(+)
include/linux/bpf_verifier.h +2 -0
index c1ddcf6d7c4..47939e49908 100644
@@ -1730,6 +1730,8 @@ bool bpf_must_keep_apart(struct bpf_verifier_env *env, const struct bpf_verifier
 			 const struct loop_stack_entry *entry);
 bool bpf_values_grew_in_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
 			     const struct bpf_verifier_state *new);
+u64 bpf_hash_live_types(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			u64 hash, u64 apart_cost);
 u64 bpf_hash_apart_xregs(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 			 u64 hash, bool consts);
 u64 bpf_hash_args(struct bpf_verifier_env *env, const struct bpf_verifier_state *st, u64 hash);
kernel/bpf/flow.c +18 -0
index 4dbf288f11a..d6f353a7bb2 100644
@@ -59,6 +59,7 @@ struct flow_state {
 	bool pending;
 	bool returned;			/* FLOW_FUNC_EXIT: the calls have a part of it */
 	bool late_exit_reaches;		/* a late exit state can get to it */
+	bool from_apart;		/* it comes from a state that was not alone */
 	/* it is kept until the states leave this loop, see flow_loop_is_left() */
 	u8 kept_frameno, kept_depth;
 	/* the order of pending states, see flow_set_pending() */
@@ -119,6 +120,7 @@ struct bpf_flow {
 	/* of the pass */
 	u64 *cost;			/* per function */
 	u64 budget, charged_cost;
+	u64 apart_cost;			/* of states that are not alone, see bpf_flow_next() */
 	u32 budget_func_cnt;
 
 	/* of the check */
@@ -129,6 +131,7 @@ struct bpf_flow {
 	struct flow_instance **instances;	/* bpf_verifier_state.instance_id is the index */
 	u32 instance_cnt, instance_cap;
 	struct flow_instance *last_instance;	/* of the last pending state */
+	bool last_is_apart;			/* it adds to @apart_cost */
 	u64 priority_gen;
 	struct list_head unused;		/* struct flow_kept */
 	u32 seq;
@@ -427,6 +430,7 @@ void bpf_flow_new_pass(struct bpf_verifier_env *env)
 	memset(flow->cost, 0, env->subprog_cnt * sizeof(*flow->cost));
 	flow->budget = bpf_precision_budget(env);
 	flow->budget_func_cnt = 0;
+	flow->apart_cost = 0;
 	flow->start_cnt++;
 	for (i = 0; i < env->prog->len; i++, aux++) {
 		if (aux->callback_loop)
@@ -632,6 +636,7 @@ static struct flow_state *flow_new_state(struct bpf_verifier_env *env, int prev_
 	INIT_LIST_HEAD(&s->node);
 	s->prev_insn_idx = prev_insn_idx;
 	s->seq = ++flow->seq;
+	s->from_apart = flow->last_is_apart;
 	s->log_pos = env->log.end_pos;
 	s->diag_pos = bpf_diag_event_log_save(env);
 	bpf_add_cost(env, 1, BPF_COST_STATE);
@@ -724,6 +729,7 @@ void bpf_flow_reset(struct bpf_verifier_env *env)
 	env->mem -= flow->instance_cnt * INSTANCE_BYTES;
 	flow->instance_cnt = 0;
 	flow->last_instance = NULL;
+	flow->last_is_apart = false;
 }
 
 void bpf_flow_free(struct bpf_verifier_env *env)
@@ -871,6 +877,9 @@ static struct flow_state *flow_find(struct bpf_verifier_env *env, struct flow_st
 
 	hash = bpf_hash_apart_xregs(env, &s->st, bpf_hash_join_key(env, &s->st) + s->kind,
 				    s->kind == FLOW_PEELED);
+	/* the arguments are joined, else calls do not share an instance */
+	if (s->kind != FLOW_FUNC_ENTRY && s->kind != FLOW_JOINED_CALLS)
+		hash = bpf_hash_live_types(env, &s->st, hash, env->flow->apart_cost);
 	if (s->kind == FLOW_FUNC_ENTRY && (!e || e->peeled))
 		hash = bpf_hash_args(env, &s->st, hash);
 	if (s->kind == FLOW_AT ? !aux->loop && !aux->callback_loop :
@@ -1729,6 +1738,8 @@ int bpf_flow_next(struct bpf_verifier_env *env, int *prev_insn_idx, u64 *log_pos
 again:
 	if (flow->last_instance && flow->last_instance->cost)
 		*flow->last_instance->cost += env->cost - flow->charged_cost;
+	if (flow->last_is_apart)
+		flow->apart_cost += env->cost - flow->charged_cost;
 	flow->charged_cost = env->cost;
 	if (flow->last_instance)
 		flow_end_instance(env, flow->last_instance);
@@ -1738,6 +1749,13 @@ int bpf_flow_next(struct bpf_verifier_env *env, int *prev_insn_idx, u64 *log_pos
 	s = rb_entry(n, struct flow_state, rb);
 	flow_clear_pending(flow, s);
 	flow->last_instance = flow_state_instance(flow, s);
+	/*
+	 * Is another state at this insn? In a loop the states go one by one, and only the join
+	 * points of a leftover keep them. So a yes holds up to a join point that is not peeled.
+	 */
+	if (test_bit(s->st.insn_idx, flow->join_points) && !flow_in_peeled_trip(&s->st))
+		s->from_apart = false;
+	flow->last_is_apart = s->from_apart || flow->nr_states[s->st.insn_idx] > 1;
 	instance = s->callee;
 	if (instance) {
 		if (instance->entry_state && !instance->priority) {
kernel/bpf/precision.c +60 -0

91 lines not on this page · raw message

kernel/bpf/precision.h +3 -0
index f833b4642bc..3af6f10eed7 100644
@@ -67,6 +67,9 @@ struct bpf_precision {
 	bool failing_path_due;		/* see bpf_failing_path_is_due() */
 	bool budget_grew;		/* see partition_next() */
 	bool new_nospec;
+	/* see bpf_hash_live_types() */
+	u64 live_types_cost, live_types_mem, start_mem;
+	bool live_types_over, join_live_types;	/* in this pass, in all next passes */
 
 	u16 *apart_xregno;	/* per insn, see bpf_range_of_data_dep() */
 
Signature · 1 line
2.55.0
#51 lore raw

Re: [PATCH bpf-next v2 39/49] bpf: Keep two states apart if a live xreg has two types

TL;DR: live_types_mem budget is computed before max_mem is clamped, so with CAP_BPF it may allow about 7-8 times the stated 1/64 memory before joining states again.
Quoted 1 line

bpf: Keep two states apart if a live xreg has two types

TL;DR: live_types_mem budget is computed before max_mem is clamped, so with CAP_BPF it may allow about 7-8 times the stated 1/64 memory before joining states again.

Quoted 3 lines
kernel/bpf/precision.c +0 -0

[ ... ]

kernel/bpf/precision.c int bpf_precision_init(struct bpf_verifier_env *env) · line 1685

Quoted 6 lines
kernel/bpf/precision.c +2 -0
@@ -1625,6 +1681,10 @@ int bpf_precision_init(struct bpf_verifier_env *env)
 	prec->this_pass.unproven_funcs = bits + 16 * words;
 	prec->last_pass.unproven_funcs = bits + 17 * words;
 	prec->pass_cost = env->cost;
+	prec->live_types_cost = env->max_cost / LIVE_TYPES_PART;
+	prec->live_types_mem = env->max_mem / LIVE_TYPES_PART;

The commit message says the budget is "1/64 of the limits on cost and memory". Is live_types_mem computed from the right value?

bpf_precision_init() runs before do_check_all() clamps env->max_mem:

	initial = save_snapshot(env, NULL);
	if (!initial || bpf_precision_init(env)) {
		...
	}
	env->max_mem = min(env->max_mem, env->mem + BPF_PASS_MEM_BASE +
			   (u64)BPF_PASS_MEM_PER_INSN * env->prog->len);

With CAP_BPF, env->max_mem is still BPF_MAX_MEM (2 GiB) at that point, so live_types_mem is 32 MiB for every program.

For a program of about 1000 insns the enforced limit is the clamped value, roughly 256 MiB plus 31 MiB plus the per-insn tables, and 1/64 of that is about 4.5 MiB. The check in bpf_hash_live_types():

	env->mem > prec->start_mem + prec->live_types_mem

then allows about 7-8 times the stated 1/64 before falling back to joining.

Without CAP_BPF the clamp does not bite (64 MiB), so the ratio there is 1/64, and the budget scales differently for privileged and unprivileged loads. The cost budget is not affected, since env->max_cost is not changed between bpf_check() and bpf_precision_init().

Should live_types_mem be computed from the clamped env->max_mem, for example after the clamp in do_check_all()?

kernel/bpf/precision.c int bpf_precision_init(struct bpf_verifier_env *env) · line 1687

Quoted 2 lines
kernel/bpf/precision.c +0 -0
 	/* the replay for the driver has to join where the good pass did */
 	prec->join_live_types = bpf_prog_is_offloaded(env->prog->aux);

[ ... ]

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

#52 lore raw

PATCH v2 40/49 bpf: Check the body of a counted loop once

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The leftover needs three walks over the body. Two walks only collect what the third walk needs:

  walk 1   i = 0          shows the step, 150
  walk 2   i = 0, 150     shows the threshold, k <= 3
  walk 3   i = 150 * k    is the proof

Often the code shows the step and the bound. The spine is the insns that each trip runs once. find_steps() follows the xregs along it:

header -> a -> b -> ... -> back edge on the spine: x += constant

             `-> c -'                     off the spine: x is inexact

bpf_guess_first_trips() makes the states that trips 1 and 2 possibly give, and joins them with the state that enters. So walk 3 is first.

It is a guess. The state only grows, and the state that comes back is compared with it as before. The guess is not used if
- a carried xreg is a sum, or the last value of an iv, and its start is known: only two walks show its equation,
- 'i != n' has a range, see add_distance_equation(),
- a partition needs an xreg that the loop changes,
- a state had no trip count for the loop.

A wrong guess can cost the trip count. Then the loop gets may_goto. It can also move a register that const_fold.c knows as a constant. So do_check_block() does not compare the two after env->extra_values is set.

insns processed

  program              bpf-next   without   with this patch
  pyperf600            37285      109729    37284
  pyperf180            22165      43304     22164
  pyperf600_nounroll   1289       1758      1288
---
 include/linux/bpf_verifier.h |   6 +
 kernel/bpf/equation_join.c   | 409 +++++++++++++++++++++++++++++++++++
 kernel/bpf/fixups.c          |   1 +
 kernel/bpf/flow.c            |   6 +
 kernel/bpf/precision.c       |  15 ++
 5 files changed, 437 insertions(+)
include/linux/bpf_verifier.h +6 -0
index 47939e49908..df4a46cfa04 100644
@@ -897,6 +897,8 @@ struct bpf_loop {
 	bool was_infinite;	/* at the start of the last path-sensitive run */
 	bool infinite;		/* see failing_path_trip() */
 	bool infinite_is_guess;	/* see fast_forward_trips() */
+	bool no_first_trips_guess;	/* a state had no trip count, @steps can be wrong */
+	struct bpf_loop_steps *steps;	/* see bpf_guess_first_trips() */
 	struct bpf_iv_threshold *iv_thresholds;	/* where an iv can stop, see equation_join.c */
 	u32 iv_threshold_cnt, iv_threshold_cap;
 	u32 leftover_epoch;	/* how many leftovers started */
@@ -1739,6 +1741,8 @@ void bpf_range_of_data_dep(struct bpf_verifier_env *env, const struct bpf_verifi
 			   u32 *first, u32 *last);
 bool bpf_call_needs_frames(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 			   u16 args);
+bool bpf_xregs_are_partitioned(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			       u32 fr, const unsigned long *xregs);
 bool bpf_xreg_in_data_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
 			   u32 fr, u32 xregno);
 bool bpf_xreg_in_deps(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
@@ -2548,6 +2552,8 @@ bool bpf_equations_join_forgets(struct bpf_verifier_env *env, const struct bpf_v
 u32 bpf_equations_hash(struct bpf_verifier_env *env, const struct bpf_verifier_state *st, u32 fr,
 		       const unsigned long *xregs, u32 bits);
 void bpf_collect_iv_thresholds(struct bpf_verifier_env *env);
+int bpf_guess_first_trips(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+			  struct bpf_loop *loop);
 bool bpf_steps_are_constant(struct bpf_verifier_env *env, const struct loop_stack_entry *entry,
 			    const unsigned long *iv_xregs, bool infinite);
 void bpf_fast_forward_xregs(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
kernel/bpf/equation_join.c +409 -0

412 lines not on this page · raw message

kernel/bpf/fixups.c +1 -0
index 3bec52051a9..eed9d13f6a6 100644
@@ -755,6 +755,7 @@ static void free_loop(struct bpf_loop *loop)
 		return;
 	kvfree(loop->thresholds);
 	kvfree(loop->iv_thresholds);
+	kvfree(loop->steps);
 	kvfree(loop);
 }
 
kernel/bpf/flow.c +6 -0
index d6f353a7bb2..33e50e1ad8c 100644
@@ -392,6 +392,7 @@ int bpf_flow_needs_guard(struct bpf_verifier_env *env, struct bpf_loop *loop)
 {
 	if (loop->rt_bounded)
 		return 0;
+	loop->no_first_trips_guess = true;
 	if (!loop->has_guards) {
 		verbose(env, "loop at insn %d never exits\n", loop->header);
 		return -EINVAL;
@@ -1266,6 +1267,11 @@ static int flow_prune_or_join(struct bpf_verifier_env *env, struct flow_state *s
 		joined = false;
 	if (log && joined)
 		verbose(env, "from %d to %d: %s\n", prev, insn_idx, widened ? "widened" : "joined");
+	err = enters && !widened ? bpf_guess_first_trips(env, &s->st, loop) : 0;
+	if (err < 0)
+		goto free;
+	if (err)
+		flow_find(env, s);
 	flow_link(env, s);
 	return 0;
 free:
kernel/bpf/precision.c +15 -0
index a33cc8664bc..9d55d3134e4 100644
@@ -84,6 +84,21 @@ bool bpf_call_needs_frames(struct bpf_verifier_env *env, const struct bpf_verifi
 	return false;
 }
 
+/* Did a partition ask for the value or the type of one of @xregs in frame @fr? */
+bool bpf_xregs_are_partitioned(struct bpf_verifier_env *env, const struct bpf_verifier_state *st,
+			       u32 fr, const unsigned long *xregs)
+{
+	unsigned long types[XREG_WORDS], control_deps[XREG_WORDS];
+	u32 bits;
+
+	if (!env->precision->data_deps)
+		return false;
+	bits = bpf_frame_mask(env, env->precision->type_apart, st, fr, types);
+	bpf_frame_mask(env, env->precision->control_deps, st, fr, control_deps);
+	return bitmap_intersects(xregs, types, bits) ||
+	       bitmap_intersects(xregs, control_deps, bits);
+}
+
 /* The value in a slot. NULL if the slot has bytes of several types. */
 static const struct bpf_reg_state *slot_value(struct bpf_verifier_env *env,
 					      const struct bpf_func_state *f, u32 spi,
Signature · 1 line
2.55.0
#53 lore raw

Re: [PATCH bpf-next v2 40/49] bpf: Check the body of a counted loop once

TL;DR: merge_origins() may keep an xreg exact after sibling-path or nested-loop writes, so the first-trips guess can be wrong. Not unsound per the review; it may cost the trip count and fall back to…
Quoted 1 line

bpf: Check the body of a counted loop once

TL;DR: merge_origins() may keep an xreg exact after sibling-path or nested-loop writes, so the first-trips guess can be wrong. Not unsound per the review; it may cost the trip count and fall back to may_goto.

Quoted 3 lines
kernel/bpf/equation_join.c +0 -0

[ ... ]

kernel/bpf/equation_join.c void bpf_collect_iv_thresholds(struct bpf_verifier_env *env) · line 1166

Quoted 12 lines
kernel/bpf/equation_join.c +12 -0
+static void merge_origins(struct scan *scan)
+{
+	struct origin *old, *new;
+	u32 i;
+
+	for_each_set_bit(i, scan->written, MAX_BPF_XREG) {
+		bpf_add_cost(scan->env, 1, BPF_COST_COPY);
+		old = &scan->before[i];
+		new = &scan->xregs[i];
+		if (old->xregno == new->xregno && old->off == new->off && old->exact &&
+		    new->exact && old->shifted == new->shifted)
+			continue;

Can this shortcut keep an xreg exact when it was changed on another path?

The comment in scan_loop() and the changelog say an off-spine write makes the xreg inexact, but this check only compares xregs[] with before[], which is the state from a single walk of a single path, and before[i].changed is never consulted.

Sibling paths: flow_compute_order() walks the jump target before the fallthrough, so with:

  0: r2 = r1               header, spine
  1: if r3 != 0 goto 4     spine
  2: r1 = r2               fallthrough, walked last
  3: goto 5
  4: r1 += 1               target, walked first
  5: r1 += 1               spine
  6: if r1 < 100 goto 0    spine, leaves the loop

at insn 4, r1 = origin(r1)+1 and before[r1] = origin(r1) with changed set. At insn 2, merge_origins() makes r1 inexact, and then r1 = r2 sets it back to an exact origin(r1). At insn 5, old and new are equal and exact, so the shortcut fires. The scan ends with r1 = origin(r1)+1 exact, and find_steps() keeps the jump at insn 6 with step 1, although the r3 != 0 path adds 2 per trip.

Nested loops: insns of an inner loop are off the spine, but the walk goes through the inner body once and ignores its back edge:

0: r2 = r1 outer header
1: r1 = r2 inner header
2: r2 += 1
3: if r2 < r3 goto 1
4: r4 += 1
5: if r4 < 100 goto 0

At insn 4, before[r1] and xregs[r1] are both an exact origin(r1), so r1 stays exact and is_invariant() is true. steps->changed_xregs and steps->nonlinear_xregs miss r1, although a second inner iteration sets r1 = r1_hdr + 1. So bpf_xregs_are_partitioned() can pass even when a partition needs r1, which the changelog says blocks the guess ("a partition needs an xreg that the loop changes").

The joined state only grows and the returning state is still compared as before, so this does not look unsound. The cost is a wrong first-trips guess, which per the changelog "can cost the trip count. Then the loop gets may_goto."

Would it work to also mark before[i] inexact on a mismatch, require !old->changed on the shortcut, and not keep an xreg exact if it was written in a nested loop (bpf_loop_at_index(env, n) != h)?

kernel/bpf/equation_join.c void bpf_collect_iv_thresholds(struct bpf_verifier_env *env) · line 1173

Quoted 7 lines
kernel/bpf/equation_join.c +7 -0
+		new->xregno = new->xregno < ORIGIN_CONST ? new->xregno : old->xregno;
+		new->changed |= old->changed;
+		new->exact = false;
+	}
+	if (scan->on_spine)
+		bitmap_zero(scan->written, MAX_BPF_XREG);
+}

[ ... ]

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

#54 lore raw

PATCH v2 41/49 bpf: Refine the copies of a number that AND or OR splits

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

maybe_fork_scalars() splits the state when AND or OR reads a number that is 0 or -1. The copies of the number are not split. The two states forget that the copies go with the result:

w8 = 0 or -1

  w2 = w8; w2 &= 255          state A: w2 = 255   state B: w2 = 0
  if w2 > 9 goto out          only B continues, w8 is still 0 or -1
  r2 = r8; r2 &= 255          split again, a use of r2 = 255 fails

A split is a jump that is not in the program. Refine the related numbers as after a jump: w8 is -1 in A and 0 in B.

Without bypass_spec_v1 a join does not relate two constants again. So the copies are not refined there.

A program with this code in a loop goes from 11 passes to 1.

---
 include/linux/bpf_verifier.h |  2 ++
 kernel/bpf/equation.c        | 18 ++++++++++++++++++
 kernel/bpf/verifier.c        |  2 ++
 3 files changed, 22 insertions(+)
include/linux/bpf_verifier.h +2 -0
index df4a46cfa04..bb20fde51f0 100644
@@ -2533,6 +2533,8 @@ void bpf_equations_refine_all(struct bpf_verifier_env *env, struct bpf_verifier_
 void bpf_equations_jump(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int idx,
 			bool taken);
 u16 bpf_args_with_equation(const struct bpf_verifier_state *st);
+void bpf_equations_fork(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+			const struct scalar *part);
 void bpf_equations_next_trip(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
 			     u32 depth);
 bool bpf_equations_subsume(struct bpf_verifier_env *env, const struct bpf_verifier_state *old,
kernel/bpf/equation.c +18 -0
index 387156696ee..86b2c08c698 100644
@@ -1040,6 +1040,24 @@ void bpf_equations_jump(struct bpf_verifier_env *env, struct bpf_verifier_state
 		refine_diff(env, st, &untruncated[0], &untruncated[1], op, true);
 }
 
+/*
+ * The insn is checked in parts. In @st the operand that it overwrites is in @part.
+ * Without bypass_spec_v1 a join does not relate the constants again, see join_expr().
+ */
+void bpf_equations_fork(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+			const struct scalar *part)
+{
+	struct bpf_equation_env *eq_env = env->eq_env;
+	struct scalar bounds = *part;
+
+	if (!eq_env || !env->bypass_spec_v1 || !eq_env->has_expr[0] ||
+	    !eq_env->operand_expr[0].coef)
+		return;
+	scalar_bounds_sync(&bounds);
+	refine_sym(env, &st->equations, eq_env->operand_expr[0], bounds, 1);
+	propagate_bounds(env, st, false);
+}
+
 /* The largest sum of two arguments of a call: numbers, or offsets of pointers. Modulo 2^64. */
 s64 bpf_equations_max_sum(struct bpf_verifier_env *env, int regno1, int regno2)
 {
kernel/bpf/verifier.c +2 -0
index 94499fdaaf9..146718823e3 100644
@@ -17637,6 +17637,8 @@ static int maybe_fork_scalars(struct bpf_verifier_env *env, struct bpf_insn *ins
 		__mark_reg_known(reg, 0);
 		__mark_reg_known(dst_reg, -1ull);
 	}
+	bpf_equations_fork(env, branch, scalar_of(reg));
+	bpf_equations_fork(env, env->cur_state, scalar_of(dst_reg));
 	/*
 	 * The insn is done with in the branch too, and what gets to the next insn is a state
 	 * like any other. At this insn the branch is a part of the state that is looked at:
Signature · 1 line
2.55.0
#55 lore raw

PATCH v2 42/49 bpf: Allow a range of offsets for a constant string

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

clang merges two calls that differ only in a string. The join of the two pointers has a range. "is not a constant address" costs one more pass.

The map is read-only. If a zero is at the largest offset or after it, it ends all strings that start before it:

.rodata a % d 0 b c d 0

            ^       ^     ^
            umin    umax  ends both

Allow the range. There are two exceptions:
- bpf_snprintf(): the verifier checks the format,
- no bypass_spec_v1: the cpu can speculate past the test of the offset.

---
 kernel/bpf/verifier.c | 22 +++++++++++++---------
 1 file changed, 13 insertions(+), 9 deletions(-)
kernel/bpf/verifier.c +13 -9
index 146718823e3..8d0767b3bd4 100644
@@ -9585,7 +9585,8 @@ static int check_arg_const_str(struct bpf_verifier_env *env,
 		return -EACCES;
 	}
 
-	if (!tnum_is_const(reg->var_off)) {
+	/* the cpu can speculate past the test of a variable offset */
+	if (!tnum_is_const(reg->var_off) && !env->bypass_spec_v1) {
 		verbose(env, "%s is not a constant address'\n", reg_arg_name(env, argno));
 		return -EACCES;
 	}
@@ -9595,13 +9596,12 @@ static int check_arg_const_str(struct bpf_verifier_env *env,
 		return -EACCES;
 	}
 
-	err = check_map_access(env, reg, argno, 0,
-			       map->value_size - reg->var_off.value, false,
-			       ACCESS_HELPER);
+	err = check_map_access(env, reg, argno, 0, 1, false, ACCESS_HELPER);
 	if (err)
 		return err;
 
-	map_off = reg->var_off.value;
+	/* the zero of the last string ends all strings that start before it */
+	map_off = reg_umax(reg);
 	err = map->ops->map_direct_value_addr(map, &map_addr, map_off);
 	if (err) {
 		verbose(env, "direct value access on string failed\n");
@@ -9614,7 +9614,8 @@ static int check_arg_const_str(struct bpf_verifier_env *env,
 		return -EINVAL;
 	}
 	/* the bytes of a pointer to a function are not known until the program is jitted */
-	if (bpf_map_range_func_ptrs(env, map, map_off, strlen(str_ptr + map_off) + 1, &cnt)) {
+	map_off += strlen(str_ptr + map_off) + 1;
+	if (bpf_map_range_func_ptrs(env, map, reg_umin(reg), map_off - reg_umin(reg), &cnt)) {
 		verbose(env, "string overlaps with a pointer to a function\n");
 		return -EACCES;
 	}
@@ -12776,9 +12777,12 @@ static int check_bpf_snprintf_call(struct bpf_verifier_env *env,
 		return -EINVAL;
 	num_args = data_len_reg->var_off.value / 8;
 
-	/* fmt being ARG_PTR_TO_CONST_STR guarantees that var_off is const
-	 * and map_direct_value_addr is set.
-	 */
+	if (!tnum_is_const(fmt_reg->var_off)) {
+		verbose(env, "R3 is not a constant address\n");
+		return -EACCES;
+	}
+
+	/* fmt being ARG_PTR_TO_CONST_STR guarantees that map_direct_value_addr is set */
 	fmt_map_off = fmt_reg->var_off.value;
 	err = fmt_map->ops->map_direct_value_addr(fmt_map, &fmt_addr,
 						  fmt_map_off);
Signature · 1 line
2.55.0
#56 lore raw

PATCH v2 43/49 bpf: Keep spilled pointers at a range of stack offsets

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

An access to the stack with a range of offsets forgets the pointers that are spilled in the range. The access is proven, and a later use of the pointer is unproven. Two cases need no such loss.

1. A call writes at one of several offsets:

     *(u64 *)(r10 - 16) = ptr
     r1 = fp-24 or fp-8           the join is fp-24..fp-8, step 16
     r2 = 8
     call bpf_probe_read_kernel   it does not touch fp-16

Skip the bytes between two offsets. The size has to be a constant, see size_at_max_offset().

2. A load reads one element of an array of pointers:

     char *p[2] = { a, b };
     bpf_for(i, 0, 2)
             sum += p[i][63];

i is 0..1 in each trip. The range comes from a load and a test, not from a join. So it does not help to keep states apart. fork_stack_load() does the load once for each slot:

     r1 = *(u64 *)(r2 + 0)

     r2 = fp-16 or fp-8  --+--> r2 = fp-16, r1 = a
                           +--> r2 = fp-8,  r1 = b

The equations refine the related numbers: i is 0 in the first state and 1 in the second one.

A program can also use such a word as a number. 'sum += word[i]' fails if the word is a pointer. So a load forks only if its result flows into an insn that needed a pointer and got a number. ADD_DEPS finds these loads with one more backward slice. The slice follows both operands of an add. So if a program adds such a word to such a pointer, both loads fork, and the add can fail.

The cpu can speculate with the address of another state, so the fork needs bypass_spec_v1.

insns processed

  program                                bpf-next   without   with
  wprof wprof_task_switch                32379      123446    79727
  tetragon generic_lsm_process_event     114211     64030     31347
  tracee trace_ret_vfs_write             5418       9413      3495
  bpf_flow flow_dissector_0              715        2235      701
---
 include/linux/bpf_verifier.h |  5 +++
 kernel/bpf/equation.c        | 10 +++++
 kernel/bpf/precision.c       | 60 +++++++++++++++++++++++++
 kernel/bpf/precision.h       |  4 ++
 kernel/bpf/verifier.c        | 87 ++++++++++++++++++++++++++++++++++--
 5 files changed, 163 insertions(+), 3 deletions(-)
include/linux/bpf_verifier.h +5 -0
index bb20fde51f0..ce7675dd4dc 100644
@@ -1038,6 +1038,7 @@ struct bpf_insn_aux_data {
 	 * are not in @use_regs. The bits above r10 are not valid.
 	 */
 	u16 use_regs, def_regs;
+	u16 needs_ptr_regs;	/* see bpf_note_needs_ptr() */
 	/*
 	 * Bitmask of R0-R9 that hold known values at this instruction.
 	 * const_reg_mask: scalar constants that fit in 32 bits.
@@ -1762,6 +1763,8 @@ void bpf_precision_new_pass(struct bpf_verifier_env *env);
 u64 bpf_pass_max_cost(struct bpf_verifier_env *env);
 u64 bpf_precision_budget(struct bpf_verifier_env *env);
 u64 bpf_precision_first_budget(struct bpf_verifier_env *env);
+void bpf_note_needs_ptr(struct bpf_verifier_env *env, const struct bpf_reg_state *reg);
+bool bpf_insn_makes_ptr(struct bpf_verifier_env *env);
 bool bpf_failing_path_is_due(struct bpf_verifier_env *env);
 int bpf_failing_path_prepare(struct bpf_verifier_env *env, bool repeat);
 bool bpf_failing_path_may_end_at(struct bpf_verifier_env *env, u32 idx);
@@ -2530,6 +2533,8 @@ void bpf_equations_spill(struct bpf_verifier_env *env, struct bpf_func_state *fr
 void bpf_equations_fill(struct bpf_verifier_env *env, struct bpf_func_state *frame, int spi,
 			int size);
 void bpf_equations_refine_all(struct bpf_verifier_env *env, struct bpf_verifier_state *st);
+void bpf_equations_refine_by_reg(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+				 u32 regno);
 void bpf_equations_jump(struct bpf_verifier_env *env, struct bpf_verifier_state *st, int idx,
 			bool taken);
 u16 bpf_args_with_equation(const struct bpf_verifier_state *st);
kernel/bpf/equation.c +10 -0
index 86b2c08c698..c84ebcba948 100644
@@ -875,6 +875,16 @@ static void refine_from_reg(struct bpf_verifier_env *env, struct bpf_verifier_st
 	eq_env->jump_expr.coef = 0;
 }
 
+/* @regno has fewer values now */
+void bpf_equations_refine_by_reg(struct bpf_verifier_env *env, struct bpf_verifier_state *st,
+				 u32 regno)
+{
+	if (!env->eq_env)
+		return;
+	refine_from_reg(env, st, regno);
+	propagate_bounds(env, st, false);
+}
+
 /* Apply all equations */
 void bpf_equations_refine_all(struct bpf_verifier_env *env, struct bpf_verifier_state *st)
 {
kernel/bpf/precision.c +60 -0

108 lines not on this page · raw message

kernel/bpf/precision.h +4 -0
index 3af6f10eed7..295c744cfd7 100644
@@ -24,6 +24,7 @@ struct precision_per_pass {
 	bool disjoint_joined;			/* disjoint values in data_deps were joined */
 	bool over_budget, calls_joined;
 	bool arg_lost_equation;			/* see bpf_call_needs_frames() */
+	bool can_fork;				/* see fork_stack_load() */
 };
 
 /* callx calls one of the functions whose address is taken. They count as one function. */
@@ -54,6 +55,8 @@ struct bpf_precision {
 	unsigned long *last_unproven_insns;	/* in the last pass */
 	unsigned long *bad_read_insns_done;
 	unsigned long *earlier_unproven_insns;	/* in an earlier pass */
+	unsigned long *needs_ptr_insns;		/* got a number in place of a pointer */
+	unsigned long *makes_ptr_insns;		/* the result flows into needs_ptr_insns */
 	unsigned long *control_seeds, *controlled_insns, *controlled_insns_done, *def_insns;
 	u32 first_unproven_insn;	/* of the last pass */
 	u32 last_unproven_left;		/* last_unproven_insns whose check did not fail again */
@@ -67,6 +70,7 @@ struct bpf_precision {
 	bool failing_path_due;		/* see bpf_failing_path_is_due() */
 	bool budget_grew;		/* see partition_next() */
 	bool new_nospec;
+	bool ptr_deps_only;		/* see add_makes_ptr_insns() */
 	/* see bpf_hash_live_types() */
 	u64 live_types_cost, live_types_mem, start_mem;
 	bool live_types_over, join_live_types;	/* in this pass, in all next passes */
kernel/bpf/verifier.c +84 -3

148 lines not on this page · raw message

Signature · 1 line
2.55.0
#57 lore raw

PATCH v2 44/49 selftests/bpf: Adjust tests to the new log text

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

verifier_scev.c tests trip counts and ranges in loops. Rename it to verifier_trip_count.c. All programs stay. The verdicts do not change.

  old text                          new text
  id=2                              id={{[0-9]+}}, ids are renumbered
  from 3 to 7: within               from 3 to 7: pruned
  header_count is 5                 loop at 3 has trip count 5
  can't compute iterations count    loop at 3 has no trip count
  widening r7 to 0..99              the state at the header, see RANGE()
  r6=(linear r6 2), can't widen r7  no such text
  exit from 5 to 7                  first exit to 7
  processed 48 insns                another number, or a pattern
  math between ... is not allowed   the access through the far pointer
                                    fails, not the add
  R1 has pointer with unsupported   gone with REASON_*, unprivileged
  alu operation                     loads get the error of root
  first error in the order          the error on the failing path
  cannot return stack pointer       R0 !read_ok in the caller

Some ranges are smaller, so an error has another offset or text. Some results keep a step.

Some loops get may_goto, or lose it:
- NO_COUNT now: 'w6 += -n' wraps in each trip (post32_gt, _ge, _ne, _sgt, _sge, backedges_end_then_wrap), the first step can wrap (range_first_wraps_s32), or the counter starts with any value (uninit_slot_counter, range_lt_dir_any_first, no_widen_small_spill_counter).
- COUNT() now: irreducible loops, 17 back edges, 301 exits in a nested loop, back edges that test different registers.

A jump on r9 gives a trip count now. LIMIT_ITERATIONS hides r9 behind an atomic add, so the count comes from the tested jump. Three pre_lt tests move to the new largest count.

A few tests change an insn to keep the error that they are about. Two tests of a double release keep NULL away from the second release. shift_with_64_bit_input needs an access through the far pointer, else it loads. variable_subtraction loads a second number. Five tests in verifier_spill_fill.c make STACK_MISC with other stores: a spill keeps its low bytes now. dynptr_slice_var_len2 uses 29 sizes: the call is safe for each of 15, and then a later store is the error. aggregate_ret_static_ptr_fail reads through r2, else it loads. var_off_insn_off_test1 and _test2 keep NULL away from the access. more_back_edge was safe, it tests a new number in each trip now.

guard_at_head_dead_slot was safe and loads now: the slot is live at the header. A larger shift makes it fail with another error.

---
 .../selftests/bpf/prog_tests/log_fixup.c      |    6 +-
 .../selftests/bpf/prog_tests/spin_lock.c      |   12 +-
 .../selftests/bpf/prog_tests/verifier.c       |    4 +-
 .../selftests/bpf/progs/aggregate_ret_func.c  |   10 +-
 .../bpf/progs/compute_live_registers.c        |   10 +-
 .../testing/selftests/bpf/progs/dynptr_fail.c |    6 +-
 tools/testing/selftests/bpf/progs/iters.c     |    4 +-
 .../selftests/bpf/progs/iters_state_safety.c  |    6 +-
 .../selftests/bpf/progs/iters_testmod_seq.c   |    2 +-
 .../selftests/bpf/progs/map_kptr_fail.c       |    2 +-
 .../testing/selftests/bpf/progs/rbtree_fail.c |    2 +-
 .../bpf/progs/refcounted_kptr_fail.c          |    4 +-
 .../struct_ops_refcounted_fail__ref_leak.c    |    2 +-
 tools/testing/selftests/bpf/progs/timer.c     |    5 +-
 .../selftests/bpf/progs/timer_failure.c       |    6 +-
 .../selftests/bpf/progs/verifier_align.c      |   12 +-
 .../selftests/bpf/progs/verifier_arena.c      |    2 +-
 .../bpf/progs/verifier_array_access.c         |    2 +-
 .../selftests/bpf/progs/verifier_bounds.c     |   36 +-
 .../bpf/progs/verifier_bounds_deduction.c     |   14 +-
 .../bpf/progs/verifier_bounds_step.c          |   33 +-
 .../selftests/bpf/progs/verifier_budget.c     |   16 +-
 .../bpf/progs/verifier_direct_packet_access.c |    6 +-
 .../verifier_direct_stack_access_wraparound.c |   10 +-
 .../bpf/progs/verifier_jumps_ahead.c          |    2 +-
 .../bpf/progs/verifier_linked_scalars.c       |    2 +-
 .../selftests/bpf/progs/verifier_live_stack.c |   10 +-
 .../bpf/progs/verifier_liveness_exp.c         |    4 +-
 .../selftests/bpf/progs/verifier_loop_as_is.c |   23 +-
 .../bpf/progs/verifier_loop_hierarchy.c       |   13 +-
 .../selftests/bpf/progs/verifier_loop_latch.c |   81 +-
 .../selftests/bpf/progs/verifier_loop_need.c  |   23 +-
 .../selftests/bpf/progs/verifier_loop_walk.c  |    2 +-
 .../bpf/progs/verifier_meta_access.c          |    2 +-
 .../selftests/bpf/progs/verifier_precision.c  |    2 +-
 .../bpf/progs/verifier_ref_tracking.c         |    7 +-
 .../selftests/bpf/progs/verifier_scalar_ids.c |   12 +-
 .../selftests/bpf/progs/verifier_sock.c       |    4 +-
 .../selftests/bpf/progs/verifier_spill_fill.c |   36 +-
 .../selftests/bpf/progs/verifier_spin_lock.c  |    2 +-
 .../selftests/bpf/progs/verifier_stack_ptr.c  |   14 +-
 .../bpf/progs/verifier_subprog_callers.c      |    2 +-
 .../bpf/progs/verifier_subprog_precision.c    |    8 +-
 ...{verifier_scev.c => verifier_trip_count.c} | 1216 ++++++-----------
 .../selftests/bpf/progs/verifier_unpriv.c     |    3 +-
 tools/testing/selftests/bpf/verifier/calls.c  |    2 +-
 .../testing/selftests/bpf/verifier/map_kptr.c |    2 +-
 47 files changed, 678 insertions(+), 1006 deletions(-)
 rename tools/testing/selftests/bpf/progs/{verifier_scev.c => verifier_trip_count.c} (77%)
tools/testing/selftests/bpf/prog_tests/log_fixup.c +3 -3
index 89a7f594708..57c6751a0e4 100644
@@ -41,7 +41,7 @@ static void bad_core_relo(size_t log_buf_size, enum trunc_type trunc_type)
 				  "struct task_struct___bad.fake_field (0:1 @ offset 4)\n",
 				  "log_buf_part2");
 		ASSERT_HAS_SUBSTR(log_buf,
-				  "max_states_per_insn 1 total_states 1 peak_states 1 mark_read 0\n",
+				  "max_states_per_insn 1 total_states 2 peak_states 1 mark_read 0\n",
 				  "log_buf_end");
 		break;
 	case TRUNC_PARTIAL:
@@ -50,7 +50,7 @@ static void bad_core_relo(size_t log_buf_size, enum trunc_type trunc_type)
 				  "struct task_struct___bad.fake_field (0:1 @ offset 4)\n",
 				  "log_buf_part2");
 		/* we shouldn't get full end of BPF verifier log */
-		ASSERT_NULL(strstr(log_buf, "max_states_per_insn 1 total_states 1 peak_states 1 mark_read 0\n"),
+		ASSERT_NULL(strstr(log_buf, "max_states_per_insn 1 total_states 2 peak_states 1 mark_read 0\n"),
 			    "log_buf_end");
 		break;
 	case TRUNC_FULL:
@@ -58,7 +58,7 @@ static void bad_core_relo(size_t log_buf_size, enum trunc_type trunc_type)
 		ASSERT_NULL(strstr(log_buf, "struct task_struct___bad.fake_field (0:1 @ offset 4)\n"),
 			    "log_buf_part2");
 		/* we shouldn't get full end of BPF verifier log */
-		ASSERT_NULL(strstr(log_buf, "max_states_per_insn 1 total_states 1 peak_states 1 mark_read 0\n"),
+		ASSERT_NULL(strstr(log_buf, "max_states_per_insn 1 total_states 2 peak_states 1 mark_read 0\n"),
 			    "log_buf_end");
 		break;
 	}
tools/testing/selftests/bpf/prog_tests/spin_lock.c +6 -6
index e368370262c..99051ce543b 100644
@@ -13,8 +13,8 @@ static struct {
 	const char *err_msg;
 } spin_lock_fail_tests[] = {
 	{ "lock_id_kptr_preserve",
-	  "[0-9]\\+: (bf) r1 = r0                       ; R0=ptr_foo(id=2)"
-	  " R1=ptr_foo(id=2) refs=2\n"
+	  "[0-9]\\+: (bf) r1 = r0                       ; R0=ptr_foo(id=\\([0-9]\\+\\))"
+	  " R1=ptr_foo(id=\\1) refs=\\1\n"
 	  "[0-9]\\+: (85) call bpf_this_cpu_ptr#154\n"
 	  "R1 type=ptr_ expected=percpu_ptr_" },
 	{ "lock_id_global_zero",
@@ -22,14 +22,14 @@ static struct {
 	  "R1 type=map_value expected=percpu_ptr_" },
 	{ "lock_id_mapval_preserve",
 	  "[0-9]\\+: (bf) r1 = r0                       ;"
-	  " R0=map_value(id=1,map=array_map,ks=4,vs=8)"
-	  " R1=map_value(id=1,map=array_map,ks=4,vs=8)\n"
+	  " R0=map_value(id=\\([0-9]\\+\\),map=array_map,ks=4,vs=8)"
+	  " R1=map_value(id=\\1,map=array_map,ks=4,vs=8)\n"
 	  "[0-9]\\+: (85) call bpf_this_cpu_ptr#154\n"
 	  "R1 type=map_value expected=percpu_ptr_" },
 	{ "lock_id_innermapval_preserve",
 	  "[0-9]\\+: (bf) r1 = r0                      ;"
-	  " R0=map_value(id=2,ks=4,vs=8)"
-	  " R1=map_value(id=2,ks=4,vs=8)\n"
+	  " R0=map_value(id=\\([0-9]\\+\\),ks=4,vs=8)"
+	  " R1=map_value(id=\\1,ks=4,vs=8)\n"
 	  "[0-9]\\+: (85) call bpf_this_cpu_ptr#154\n"
 	  "R1 type=map_value expected=percpu_ptr_" },
 	{ "lock_id_mismatch_kptr_kptr", "bpf_spin_unlock of different lock" },
tools/testing/selftests/bpf/prog_tests/verifier.c +2 -2
index 57ff2578a99..67151c55b03 100644
@@ -127,7 +127,6 @@
 #include "verifier_ringbuf.skel.h"
 #include "verifier_runtime_jit.skel.h"
 #include "verifier_scalar_ids.skel.h"
-#include "verifier_scev.skel.h"
 #include "verifier_sdiv.skel.h"
 #include "verifier_search_pruning.skel.h"
 #include "verifier_sock.skel.h"
@@ -146,6 +145,7 @@
 #include "verifier_subreg.skel.h"
 #include "verifier_tailcall.skel.h"
 #include "verifier_tailcall_jit.skel.h"
+#include "verifier_trip_count.skel.h"
 #include "verifier_typedef.skel.h"
 #include "verifier_uninit.skel.h"
 #include "verifier_unpriv.skel.h"
@@ -350,7 +350,6 @@ void test_verifier_regalloc(void)             { RUN(verifier_regalloc); }
 void test_verifier_ringbuf(void)              { RUN(verifier_ringbuf); }
 void test_verifier_runtime_jit(void)          { RUN(verifier_runtime_jit); }
 void test_verifier_scalar_ids(void)           { RUN(verifier_scalar_ids); }
-void test_verifier_scev(void)                 { RUN(verifier_scev); }
 void test_verifier_sdiv(void)                 { RUN(verifier_sdiv); }
 void test_verifier_search_pruning(void)       { RUN(verifier_search_pruning); }
 void test_verifier_sock(void)                 { RUN(verifier_sock); }
@@ -369,6 +368,7 @@ void test_verifier_subprog_topo(void)        { RUN(verifier_subprog_topo); }
 void test_verifier_subreg(void)               { RUN(verifier_subreg); }
 void test_verifier_tailcall(void)             { RUN(verifier_tailcall); }
 void test_verifier_tailcall_jit(void)         { RUN(verifier_tailcall_jit); }
+void test_verifier_trip_count(void)           { RUN(verifier_trip_count); }
 void test_verifier_typedef(void)              { RUN(verifier_typedef); }
 void test_verifier_uninit(void)               { RUN(verifier_uninit); }
 void test_verifier_unpriv(void)               { RUN(verifier_unpriv); }
tools/testing/selftests/bpf/progs/aggregate_ret_func.c +5 -5
index 2671323255c..bb2f19f2b1a 100644
@@ -70,18 +70,18 @@ static __naked __noinline u128 static_agg_bad_ptr(void)
 }
 
 /*
- * R2 is a return register once the subprogram returns a pair, so a stack
- * pointer left in it is rejected at the callee's exit exactly as one in R0
- * is: the callee frame is gone by the time the caller could use it.
+ * R2 is a return register once the subprogram returns a pair, so the caller
+ * cannot read a stack pointer left in it, exactly as one in R0: the callee
+ * frame is gone by the time the caller could use it.
  */
 SEC("tc")
 __load_if_JITed()
-__failure __msg("cannot return stack pointer to the caller")
+__failure __msg("R2 !read_ok")
 __naked int aggregate_ret_static_ptr_fail(void)
 {
 	asm volatile (
 	"call %[static_agg_bad_ptr];"
-	"r0 = 0;"
+	"r0 = *(u8 *)(r2 - 1);"
 	"exit;"
 	:
 	: __imm(static_agg_bad_ptr)
tools/testing/selftests/bpf/progs/compute_live_registers.c +5 -5
index f5c505dfd46..f1a0c2187c6 100644
@@ -356,13 +356,13 @@ __naked void ldimm64(void)
 		:: __clobber_all);
 }
 
-/* No rules specific for LD_ABS/LD_IND, default behaviour kicks in */
+/* LD_ABS/LD_IND read r6 and clobber r0-r5 */
 SEC("socket")
 __log_level(2)
-__msg("2: 0123456789 (30) r0 = *(u8 *)skb[42]")
-__msg("3: 012.456789 (0f) r7 += r0")
-__msg("4: 012.456789 (b7) r3 = 42")
-__msg("5: 0123456789 (50) r0 = *(u8 *)skb[r3 + 0]")
+__msg("2: ......67.. (30) r0 = *(u8 *)skb[42]")
+__msg("3: 0.....67.. (0f) r7 += r0")
+__msg("4: ......67.. (b7) r3 = 42")
+__msg("5: ...3..67.. (50) r0 = *(u8 *)skb[r3 + 0]")
 __msg("6: 0......7.. (0f) r7 += r0")
 __naked void ldabs(void)
 {
tools/testing/selftests/bpf/progs/dynptr_fail.c +3 -3
index 2425e05a12a..232886dcfc5 100644
@@ -91,7 +91,7 @@ int ringbuf_missing_release1(void *ctx)
 }
 
 SEC("?raw_tp")
-__failure __msg("Unreleased reference id=3")
+__failure __msg("Unreleased reference id=")
 int ringbuf_missing_release2(void *ctx)
 {
 	struct bpf_dynptr ptr1, ptr2;
@@ -782,7 +782,7 @@ int dynptr_pruning_overwrite(struct __sk_buff *ctx)
 }
 
 SEC("?tc")
-__success __msg("to 12: within") __log_level(2)
+__success __msg("to 12: pruned") __log_level(2)
 int dynptr_pruning_stacksafe(struct __sk_buff *ctx)
 {
 	asm volatile (
@@ -1879,7 +1879,7 @@ __failure __msg("must be a known constant")
 __msg("requires this memory size to be a verifier-known constant")
 int dynptr_slice_var_len2(struct __sk_buff *skb)
 {
-	char buffer[sizeof(struct ethhdr)] = {};
+	char buffer[2 * sizeof(struct ethhdr)] = {};
 	struct bpf_dynptr ptr;
 	struct ethhdr *hdr;
 
tools/testing/selftests/bpf/progs/iters.c +2 -2
index b9677d30e69..6621559713a 100644
@@ -47,7 +47,7 @@ int iter_err_unsafe_c_loop(const void *ctx)
 }
 
 SEC("?raw_tp")
-__failure __msg("math between map_value pointer and register with unbounded min value is not allowed")
+__failure __msg("{{R1 unbounded memory access|makes map_value pointer be out of bounds}}")
 int iter_err_unsafe_asm_loop(const void *ctx)
 {
 	struct bpf_iter_num it;
@@ -1989,7 +1989,7 @@ static int loop1_wrapper(void)
  */
 SEC("raw_tp")
 /* -32 or -31 */
-__failure __msg("misaligned stack access off (0xffffffffffffffe0; 0x1)+0 size 8")
+__failure __msg("misaligned stack access off -31+0 size 8")
 __naked void absent_mark_in_the_middle_state4(void)
 {
 	/*
tools/testing/selftests/bpf/progs/iters_state_safety.c +3 -3
index fa9604f0a17..52487631a52 100644
@@ -30,7 +30,7 @@ int force_clang_to_emit_btf_for_externs(void *ctx)
 
 SEC("?raw_tp")
 __success __log_level(2)
-__msg("fp-8=iter_num(id=1,state=active)")
+__msg("fp-8=iter_num(id={{[0-9]+}},state=active)")
 int create_and_destroy(void *ctx)
 {
 	struct bpf_iter_num iter;
@@ -208,7 +208,7 @@ SEC("?raw_tp")
 __failure
 /* ensure there was a call to subprog, which might happen without __noinline */
 __msg("0: (85) call pc+2")
-__msg("Unreleased reference id=2 alloc_insn=7")
+__msg("Unreleased reference id={{[0-9]+}} alloc_insn=7")
 int leak_iter_from_subprog_fail(void *ctx)
 {
 	subprog_with_iter();
@@ -218,7 +218,7 @@ int leak_iter_from_subprog_fail(void *ctx)
 
 SEC("?raw_tp")
 __success __log_level(2)
-__msg("fp-8=iter_num(id=1,state=active)")
+__msg("fp-8=iter_num(id={{[0-9]+}},state=active)")
 int valid_stack_reuse(void *ctx)
 {
 	struct bpf_iter_num iter;
tools/testing/selftests/bpf/progs/iters_testmod_seq.c +1 -1
index 88ce4b7a9c3..1822aabdf0e 100644
@@ -59,7 +59,7 @@ static volatile int zero = 0;
 SEC("raw_tp/sys_enter")
 __success __log_level(2)
 __msg("fp-16=iter_testmod_seq(id=1,state=active)")
-__msg("fp-16=iter_testmod_seq(id=1,state=drained)")
+__msg("fp-16=iter_testmod_seq(id={{[0-9]+}},state=drained)")
 __msg("call bpf_iter_testmod_seq_destroy")
 int testmod_seq_truncated(const void *ctx)
 {
tools/testing/selftests/bpf/progs/map_kptr_fail.c +1 -1
index ac4003bfb8b..f3dfe08b365 100644
@@ -345,7 +345,7 @@ int reject_indirect_global_func_access(struct __sk_buff *ctx)
 }
 
 SEC("?tc")
-__failure __msg("Unreleased reference id=4 alloc_insn=")
+__failure __msg("Unreleased reference id={{[0-9]+}} alloc_insn=")
 int kptr_xchg_ref_state(struct __sk_buff *ctx)
 {
 	struct prog_test_ref_kfunc *p;
tools/testing/selftests/bpf/progs/rbtree_fail.c +1 -1
index 08709f23ec0..a22d912d489 100644
@@ -107,7 +107,7 @@ long rbtree_api_remove_unadded_node(void *ctx)
 }
 
 SEC("?tc")
-__failure __msg("Unreleased reference id=3 alloc_insn={{[0-9]+}}")
+__failure __msg("Unreleased reference id={{[0-9]+}} alloc_insn={{[0-9]+}}")
 long rbtree_api_remove_no_drop(void *ctx)
 {
 	struct bpf_rb_node *res;
tools/testing/selftests/bpf/progs/refcounted_kptr_fail.c +2 -2
index e80f78fae22..e2ff5db90e0 100644
@@ -76,7 +76,7 @@ static bool less(struct bpf_rb_node *a, const struct bpf_rb_node *b)
 }
 
 SEC("?tc")
-__failure __msg("Unreleased reference id=4 alloc_insn={{[0-9]+}}")
+__failure __msg("Unreleased reference id={{[0-9]+}} alloc_insn={{[0-9]+}}")
 long rbtree_refcounted_node_ref_escapes(void *ctx)
 {
 	struct node_acquire *n, *m;
@@ -239,7 +239,7 @@ long graph_kptr_after_spin_unlock(void *ctx)
 }
 
 SEC("?tc")
-__failure __msg("Unreleased reference id=3 alloc_insn={{[0-9]+}}")
+__failure __msg("Unreleased reference id={{[0-9]+}} alloc_insn={{[0-9]+}}")
 long rbtree_refcounted_node_ref_escapes_owning_input(void *ctx)
 {
 	struct node_acquire *n, *m;
tools/testing/selftests/bpf/progs/struct_ops_refcounted_fail__ref_leak.c +1 -1
index e945b1a0429..aae5e0dd984 100644
@@ -9,7 +9,7 @@ char _license[] SEC("license") = "GPL";
  * kptr through context without releasing the reference
  */
 SEC("struct_ops/test_refcounted")
-__failure __msg("Unreleased reference id=1 alloc_insn=0")
+__failure __msg("Unreleased reference id={{[0-9]+}} alloc_insn=0")
 int BPF_PROG(refcounted_fail__ref_leak, int dummy,
 	     struct task_struct *task)
 {
tools/testing/selftests/bpf/progs/timer.c +1 -4
index aa966dbed02..83a96aaf157 100644
@@ -159,10 +159,7 @@ static __noinline int sum_to(__u64 n)
 
 static int loop_cb(void *map, int *key, struct elem *val);
 
-/*
- * Re-arms from a frame below the callback's, where the caller frame carries
- * no async_entry_cnt of its own.
- */
+/* Re-arms from a function that the callback calls. */
 static __noinline void rearm(struct elem *val)
 {
 	if (loop_rearm > 0) {
tools/testing/selftests/bpf/progs/timer_failure.c +1 -5
index 84ea861575f..d5fd85ccc1b 100644
@@ -60,11 +60,7 @@ long BPF_PROG2(test_bad_ret, int, a)
 	return 0;
 }
 
-/*
- * A real loop inside an async callback must still be rejected: both entries
- * into the callback have the same async_entry_cnt, so telling entries apart
- * does not apply here.
- */
+/* A loop with no exit is rejected in an async callback too. */
 static int timer_cb_infinite_loop(void *map, int *key, struct elem *val)
 {
 	for (;;) {}
tools/testing/selftests/bpf/progs/verifier_align.c +6 -6
index aecc5279dba..9dbaec98a0d 100644
@@ -247,7 +247,7 @@ __msg("7: {{.*}} R6={{[^)]*}}var_off=(0x0; 0x3fc)")
 /* Offset is added to packet pointer R5, resulting in
  * known fixed offset, and variable offset from R6.
  */
-__msg("11: {{.*}} R5=pkt(id=1,{{[^)]*}},var_off=(0x2; 0x7fc)")
+__msg("11: {{.*}} R5=pkt(id={{[0-9]+}},{{[^)]*}},var_off=(0x2; 0x7fc)")
 /* At the time the word size load is performed from R5,
  * it's total offset is NET_IP_ALIGN + reg->off (0) +
  * reg->aux_off (14) which is 16.  Then the variable
@@ -266,7 +266,7 @@ __msg("18: {{.*}} R4={{[^)]*}}var_off=(0x0; 0x3fc){{.*}} R5={{[^)]*}}var_off=(0x
 /* Constant offset is added to R5, resulting in
  * reg->off of 14.
  */
-__msg("19: {{.*}} R5=pkt(id=2,{{[^)]*}}var_off=(0x2; 0x7fc)")
+__msg("19: {{.*}} R5=pkt(id={{[0-9]+}},{{[^)]*}}var_off=(0x2; 0x7fc)")
 /* At the time the word size load is performed from R5,
  * its total fixed offset is NET_IP_ALIGN + reg->off
  * (14) which is 16.  Then the variable offset is 4-byte
@@ -284,7 +284,7 @@ __msg("26: {{.*}} R5=pkt(r=8,imm=14)")
  */
 __msg("28: {{.*}} R4={{[^)]*}}var_off=(0x2; 0x7fc){{.*}} R5={{[^)]*}}var_off=(0x2; 0x7fc)")
 /* Constant is added to R5 again, setting reg->off to 18. */
-__msg("29: {{.*}} R5=pkt(id=3,{{[^)]*}}var_off=(0x2; 0xffc)")
+__msg("29: {{.*}} R5=pkt(id={{[0-9]+}},{{[^)]*}}var_off=(0x2; 0xffc)")
 /* And once more we add a variable; resulting {{[^)]*}}var_off
  * is still (4n), fixed offset is not changed.
  * Also, we create a new reg->id.
@@ -432,8 +432,8 @@ __msg("9: {{.*}} R5={{[^)]*}}var_off=(0x2; 0x7ffffffffffffffc)")
 /* packet pointer + nonnegative (4n+2) */
 __msg("11: {{.*}} R4={{[^)]*}}var_off=(0x2; 0x7ffffffffffffffc){{.*}} R6={{[^)]*}}var_off=(0x2; 0x7ffffffffffffffc)")
 __msg("12: (07) r4 += 4")
-/* packet smax bound overflow */
-__msg("pkt pointer offset -9223372036854775808 is not allowed")
+/* the offset can overflow, so the bounds check gives r6 no range */
+__msg("R6 min value is outside of the allowed memory range")
 __naked void dubious_pointer_arithmetic(void)
 {
 	asm volatile ("					\
@@ -494,7 +494,7 @@ __naked void variable_subtraction(void)
 	asm volatile ("					\
 	/* Create an unknown offset, (4n+2)-aligned */	\
 	" LOAD_UNKNOWN("r6") "				\
-	r7 = r6;					\
+	r7 = *(u8*)(r2 + 1);				\
 	r6 <<= 2;					\
 	r6 += 14;					\
 	/* Create another unknown, (4n)-aligned, and subtract\
tools/testing/selftests/bpf/progs/verifier_arena.c +1 -1
index 4741cd7d20c..99856ee1079 100644
@@ -618,7 +618,7 @@ __naked void name(void)								\
 	:: __imm_addr(arena) : __clobber_all);					\
 }
 
-#define NOT_UNROLLED100	__msg("loop header at 5, widening r7 to 0..99 step 1")
+#define NOT_UNROLLED100	__msg("to 5: {{.*}}R7=scalar(smin=smin32=0,smax=umax=smax32=umax32=99,")
 /* A loop that moves the pointer is not unrolled */
 ARENA_TEST(arena_pointer_moves, "r6 += 8;", __success NOT_UNROLLED100)
 /* The loop makes a number of it: the state that returns to the loop header tells */
tools/testing/selftests/bpf/progs/verifier_array_access.c +1 -1
index 29bed1e496a..d81c886a8bb 100644
@@ -738,7 +738,7 @@ unsigned int a_pcpu_array_with_a_key_in_range_no_nullness(void)
 	return val->index;
 }
 
-/* Scalar evolution gives r6 the range [0, 1] for all iterations */
+/* The trip count gives r6 the range [0, 1] for all iterations */
 SEC("socket")
 __description("valid map access into an array using the counter of a loop without nullness")
 __success __retval(0)
tools/testing/selftests/bpf/progs/verifier_bounds.c +18 -18
index 9dc23611332..8382ea850e2 100644
@@ -48,7 +48,7 @@ SEC("socket")
 __description("subtraction bounds (map value) variant 2")
 __failure
 __msg("R0 min value is negative, either use unsigned index or do a if (index >=0) check.")
-__msg_unpriv("R1 has unknown scalar with mixed signed bounds")
+__failure_unpriv
 __naked void bounds_map_value_variant_2(void)
 {
 	asm volatile ("					\
@@ -140,7 +140,7 @@ l0_%=:	/* exit */					\
 
 SEC("socket")
 __description("bounds check based on sign-extended MOV. test1")
-__failure __msg("map_value pointer and 4294967295")
+__failure __msg("R0 min value is outside of the allowed memory range")
 __failure_unpriv
 __naked void on_sign_extended_mov_test1(void)
 {
@@ -202,7 +202,7 @@ l0_%=:	/* exit */					\
 
 SEC("tc")
 __description("bounds check based on reg_off + var_off + insn_off. test1")
-__failure __msg("map_value pointer offset 1073741822 is not allowed")
+__failure __msg("R0 min value is outside of the allowed memory range")
 __naked void var_off_insn_off_test1(void)
 {
 	asm volatile ("					\
@@ -218,8 +218,8 @@ __naked void var_off_insn_off_test1(void)
 	r6 += %[__imm_0];				\
 	r0 += r6;					\
 	r0 += %[__imm_0];				\
-l0_%=:	r0 = *(u8*)(r0 + 3);				\
-	r0 = 0;						\
+	r0 = *(u8*)(r0 + 3);				\
+l0_%=:	r0 = 0;						\
 	exit;						\
 "	:
 	: __imm(bpf_map_lookup_elem),
@@ -231,7 +231,7 @@ l0_%=:	r0 = *(u8*)(r0 + 3);				\
 
 SEC("tc")
 __description("bounds check based on reg_off + var_off + insn_off. test2")
-__failure __msg("value 1073741823")
+__failure __msg("R0 min value is outside of the allowed memory range")
 __naked void var_off_insn_off_test2(void)
 {
 	asm volatile ("					\
@@ -247,8 +247,8 @@ __naked void var_off_insn_off_test2(void)
 	r6 += %[__imm_0];				\
 	r0 += r6;					\
 	r0 += %[__imm_1];				\
-l0_%=:	r0 = *(u8*)(r0 + 3);				\
-	r0 = 0;						\
+	r0 = *(u8*)(r0 + 3);				\
+l0_%=:	r0 = 0;						\
 	exit;						\
 "	:
 	: __imm(bpf_map_lookup_elem),
@@ -484,7 +484,7 @@ l0_%=:	/* exit */					\
 
 SEC("socket")
 __description("bounds check after 32-bit right shift with 64-bit input")
-__failure __msg("math between map_value pointer and 4294967294 is not allowed")
+__failure __msg("R0 min value is outside of the allowed memory range")
 __failure_unpriv
 __naked void shift_with_64_bit_input(void)
 {
@@ -503,10 +503,10 @@ __naked void shift_with_64_bit_input(void)
 	w1 >>= 31;					\
 	/* r1 = 0xffff'fffe (NOT 0!) */			\
 	w1 -= 2;					\
-	/* error on computing OOB pointer */		\
+	/* computes OOB pointer */			\
 	r0 += r1;					\
-	/* exit */					\
-	r0 = 0;						\
+	/* OOB access */				\
+	r0 = *(u8*)(r0 + 0);				\
 l0_%=:	exit;						\
 "	:
 	: __imm(bpf_map_lookup_elem),
@@ -516,7 +516,7 @@ l0_%=:	exit;						\
 
 SEC("socket")
 __description("bounds check map access with off+size signed 32bit overflow. test1")
-__failure __msg("map_value pointer and 2147483646")
+__failure __msg("R0 min value is outside of the allowed memory range")
 __failure_unpriv
 __naked void size_signed_32bit_overflow_test1(void)
 {
@@ -541,7 +541,7 @@ l1_%=:	exit;						\
 
 SEC("socket")
 __description("bounds check map access with off+size signed 32bit overflow. test2")
-__failure __msg("pointer offset 1073741822")
+__failure __msg("R0 min value is outside of the allowed memory range")
 __msg_unpriv("R0 pointer arithmetic of map value goes out of range")
 __naked void size_signed_32bit_overflow_test2(void)
 {
@@ -568,7 +568,7 @@ l1_%=:	exit;						\
 
 SEC("socket")
 __description("bounds check map access with off+size signed 32bit overflow. test3")
-__failure __msg("pointer offset -1073741822")
+__failure __msg("R0 min value is negative")
 __msg_unpriv("R0 pointer arithmetic of map value goes out of range")
 __naked void size_signed_32bit_overflow_test3(void)
 {
@@ -594,7 +594,7 @@ l1_%=:	exit;						\
 
 SEC("socket")
 __description("bounds check map access with off+size signed 32bit overflow. test4")
-__failure __msg("map_value pointer and 1000000000000")
+__failure __msg("R0 min value is outside of the allowed memory range")
 __failure_unpriv
 __naked void size_signed_32bit_overflow_test4(void)
 {
@@ -1572,7 +1572,7 @@ l0_%=:	r0 = 0;				\
 SEC("socket")
 __description("bounds deduction cross sign boundary, negative overlap")
 __success __log_level(2)
-__msg("7: (1f) r0 -= r6 {{.*}} R0=scalar(smin=smin32=-527,smax=smax32=-146,umin=0xfffffffffffffdf1,umax=0xffffffffffffff6e,umin32=0xfffffdf1,umax32=0xffffff6e,var_off=(0xfffffffffffffc00; 0x3ff))")
+__msg("7: (1f) r0 -= r6 {{.*}} R0=scalar(smin=smin32=-400,smax=smax32=-273,umin=0xfffffffffffffe70,umax=0xfffffffffffffeef,umin32=0xfffffe70,umax32=0xfffffeef,var_off=(0xfffffffffffffe00; 0xff))")
 __retval(0)
 __naked void bounds_deduct_negative_overlap(void)
 {
@@ -2286,7 +2286,7 @@ l0_%=:	r0 = 0;						\
 }
 
 /*
- * The insn that forks is the head of a loop that scalar evolution counted. The state with
+ * The insn that forks is the head of a loop with a trip count. The state with
  * [-1, 0] is kept there, and the state with 0 that is split off is within it.
  */
 SEC("socket")
tools/testing/selftests/bpf/progs/verifier_bounds_deduction.c +7 -7
index a474c9978a3..14e10760606 100644
@@ -8,7 +8,7 @@
 SEC("socket")
 __description("check deducing bounds from const, 1")
 __failure __msg("R0 tried to subtract pointer from scalar")
-__msg_unpriv("R1 has pointer with unsupported alu operation")
+__failure_unpriv
 __naked void deducing_bounds_from_const_1(void)
 {
 	asm volatile ("					\
@@ -40,7 +40,7 @@ l1_%=:	r1 -= r0;					\
 SEC("socket")
 __description("check deducing bounds from const, 3")
 __failure __msg("R0 tried to subtract pointer from scalar")
-__msg_unpriv("R1 has pointer with unsupported alu operation")
+__failure_unpriv
 __naked void deducing_bounds_from_const_3(void)
 {
 	asm volatile ("					\
@@ -73,7 +73,7 @@ l1_%=:	r6 -= r0;					\
 SEC("socket")
 __description("check deducing bounds from const, 5")
 __failure __msg("R0 tried to subtract pointer from scalar")
-__msg_unpriv("R1 has pointer with unsupported alu operation")
+__failure_unpriv
 __naked void deducing_bounds_from_const_5(void)
 {
 	asm volatile ("					\
@@ -87,7 +87,7 @@ l0_%=:	exit;						\
 SEC("socket")
 __description("check deducing bounds from const, 6")
 __failure __msg("R0 tried to subtract pointer from scalar")
-__msg_unpriv("R1 has pointer with unsupported alu operation")
+__failure_unpriv
 __naked void deducing_bounds_from_const_6(void)
 {
 	asm volatile ("					\
@@ -102,7 +102,7 @@ l0_%=:	r0 -= r1;					\
 SEC("socket")
 __description("check deducing bounds from const, 7")
 __failure __msg("dereference of modified ctx ptr")
-__msg_unpriv("dereference of modified ctx ptr")
+__failure_unpriv
 __flag(BPF_F_ANY_ALIGNMENT)
 __naked void deducing_bounds_from_const_7(void)
 {
@@ -121,7 +121,7 @@ l0_%=:	r1 -= r0;					\
 SEC("socket")
 __description("check deducing bounds from const, 8")
 __failure __msg("negative offset ctx ptr R1 off=-1 disallowed")
-__msg_unpriv("R1 has pointer with unsupported alu operation")
+__failure_unpriv
 __flag(BPF_F_ANY_ALIGNMENT)
 __naked void deducing_bounds_from_const_8(void)
 {
@@ -140,7 +140,7 @@ l0_%=:	r0 = *(u32*)(r1 + %[__sk_buff_mark]);		\
 SEC("socket")
 __description("check deducing bounds from const, 9")
 __failure __msg("R0 tried to subtract pointer from scalar")
-__msg_unpriv("R1 has pointer with unsupported alu operation")
+__failure_unpriv
 __naked void deducing_bounds_from_const_9(void)
 {
 	asm volatile ("					\
tools/testing/selftests/bpf/progs/verifier_bounds_step.c +18 -15
index 2b8ff0f44c3..28bdc63f48d 100644
@@ -38,7 +38,7 @@ __naked void step_arith64_no_overflow(void)
 /*
  * Safe ALU32 multiplication and addition preserve the stride and scale its base:
  * step=0+3 -> step=1+3 -> step=2+6. MOV32 preserves the result.
- * LSH32 currently resets the stride, but must preserve the correct upper bound.
+ * LSH32 resets the stride, the equation of the result tells it again.
  */
 SEC("socket")
 __success __log_level(2)
@@ -46,7 +46,7 @@ __msg("w0 *= 3 {{.*}}step=0+3)")
 __msg("w0 += 1 {{.*}}step=1+3)")
 __msg("w0 *= 2 {{.*}}step=2+6)")
 __msg("w1 = w0 {{.*}}R0=scalar({{.*}}step=2+6) R1=scalar({{.*}}step=2+6)")
-__msg("w0 <<= 1 {{.*}}smax=umax=smax32=umax32=3064,") __no_step
+__msg("w0 <<= 1 {{.*}}smax=umax=smax32=umax32=3064,{{.*}}step=4+12)")
 __naked void step_arith32_no_overflow(void)
 {
 	asm volatile ("					\
@@ -93,13 +93,14 @@ __naked void step_neg_value_range(void)
  * incorrectly narrows the result to 1.
  * Shifting the same input left by 1 gives {0xfffffff8, 0xfffffffe};
  * inferring step=0+6 incorrectly narrows the result to 0xfffffffc.
+ * The equation of a result tells the right base.
  */
 SEC("socket")
 __success __log_level(2)
 __msg("w0 *= 7 {{.*}}umax=0xffffffff,") __no_step
 __msg("r2 = r0 {{.*}}R0=scalar({{.*}}step=0+3) R2=scalar({{.*}}step=0+3)")
-__msg("w0 += 4 {{.*}}smax=umax=smax32=umax32=3,") __no_step
-__msg("w2 <<= 1 {{.*}}smax=umax=umax32=0xfffffffe,") __no_step
+__msg("w0 += 4 {{.*}}smax=umax=smax32=umax32=3,{{.*}}step=0+3)")
+__msg("w2 <<= 1 {{.*}}smax=umax=umax32=0xfffffffe,{{.*}}step=2+6)")
 __naked void step_arith32_overflow(void)
 {
 	asm volatile ("					\
@@ -132,16 +133,18 @@ __naked void step_arith32_overflow(void)
  *
  * Shifting {0x4000000000000008, 0x400000000000000b} left by 1 gives
  * {S64_MIN + 16, S64_MIN + 22}. Keeping step=0+6 excludes both.
+ *
+ * The equation of a result tells the right base.
  */
 SEC("socket")
 __success __log_level(2)
-__msg("r0 *= 3 {{.*}}smax=0x8000000000000004,") __no_step
+__msg("r0 *= 3 {{.*}}smax=0x8000000000000004,{{.*}}step=2+3)")
 __msg("r0 += r1 {{.*}}step=0+3)")
-__msg("r0 += 5 {{.*}}smax=0x8000000000000003,") __no_step
+__msg("r0 += 5 {{.*}}smax=0x8000000000000003,{{.*}}step=1+3)")
 __msg("r0 += r1 {{.*}}step=2+3)")
-__msg("r0 += -5 {{.*}}umax=0x7fffffffffffffff,") __no_step
+__msg("r0 += -5 {{.*}}umax=0x7fffffffffffffff,{{.*}}step=1+3)")
 __msg("r0 += r1 {{.*}}step=0+3)")
-__msg("r0 <<= 1 {{.*}}smax=0x8000000000000016,") __no_step
+__msg("r0 <<= 1 {{.*}}smax=0x8000000000000016,{{.*}}step=2+6)")
 __naked void step_arith64_overflow(void)
 {
 	asm volatile ("					\
@@ -231,11 +234,11 @@ __naked void step_mov32_negative(void)
 SEC("socket")
 __success __log_level(2)
 __msg("r0 += 128 {{.*}}step=2+3)")
-__msg("r0 = (s8)r0 {{.*}}smax=smax32=-125,") __no_step
+__msg("r0 = (s8)r0 {{.*}}smax=smax32=-125,{{.*}}step=1+3)")
 __msg("r0 += 32768 {{.*}}step=2+3)")
-__msg("r0 = (s16)r0 {{.*}}smax=smax32=-32765,") __no_step
+__msg("r0 = (s16)r0 {{.*}}smax=smax32=-32765,{{.*}}step=1+3)")
 __msg("r0 += r1 {{.*}}step=2+3)")
-__msg("r0 = (s32)r0 {{.*}}smax=0xffffffff80000003,") __no_step
+__msg("r0 = (s32)r0 {{.*}}smax=0xffffffff80000003,{{.*}}step=1+3)")
 __naked void step_movsx(void)
 {
 	asm volatile ("					\
@@ -329,18 +332,18 @@ l_out_%=:						\
  * r1 = (s16)r0  -> [0, 168]    step=0+24
  * r0 += -24     -> [-24, 144]  step=0+24
  * r2 = (s16)r0  -> [-24, 144]  step=0+24
- * r3 = (s8)r0   -> [-128, 127] no step
+ * r3 = (s8)r0   -> [-128, 120] no step
  * w4 = (s16)w1  -> [0, 168]    step=0+24
- * w5 = (s8)w1   -> [-128, 127] no step
+ * w5 = (s8)w1   -> [-128, 120] no step
  * Bounds and step stay in sync, the step is dropped when the value does not fit.
  */
 SEC("socket")
 __success __log_level(2)
 __msg("r1 = (s16)r0 {{.*}}R1=scalar(smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)")
 __msg("r2 = (s16)r0 {{.*}}R2=scalar(smin=smin32=-24,smax=smax32=144,{{.*}}step=0+24)")
-__msg("r3 = (s8)r0 {{.*}}R3=scalar(smin=smin32=-128,smax=smax32=127)")
+__msg("r3 = (s8)r0 {{.*}}R3=scalar(smin=smin32=-128,smax=smax32=120,var_off=(0x0; 0xfffffffffffffff8))")
 __msg("w4 = (s16)w1 {{.*}}R4=scalar(smin=smin32=0,smax=umax=smax32=umax32=168,{{.*}}step=0+24)")
-__msg("w5 = (s8)w1 {{.*}}R5=scalar({{.*}}smin32=-128,smax32=127,var_off=(0x0; 0xffffffff))")
+__msg("w5 = (s8)w1 {{.*}}R5=scalar({{.*}}smin32=-128,smax32=120,var_off=(0x0; 0xfffffff8))")
 __naked void step_movsx_bounds_on_line(void)
 {
 	asm volatile ("					\
tools/testing/selftests/bpf/progs/verifier_budget.c +8 -8
index 61c22ac58c1..890b316166c 100644
@@ -1112,7 +1112,7 @@ __naked void guard_at_head_unset_reg_caller(void)
 	);
 }
 
-/* fp-8 is 0 on every edge of the program that gets behind the loop. It's dead at the head. */
+/* fp-8 is 0 on every edge of the program that leaves the loop. It's 1 at the header. */
 __naked __noinline __used
 static unsigned long spins_and_makes_slot(void)
 {
@@ -1127,7 +1127,7 @@ static unsigned long spins_and_makes_slot(void)
 		"*(u64 *)(r10 - 8) = r7;"
 		"if r1 != 2 goto 1b;"
 		"r0 = *(u64 *)(r10 - 8);"
-		"r0 <<= 3;"
+		"r0 <<= 12;"
 		"r8 += r0;"
 		"r0 = *(u64 *)(r8 + 0);"
 		"exit;"
@@ -1138,8 +1138,8 @@ static unsigned long spins_and_makes_slot(void)
 }
 
 SEC("socket")
-__description("budget: may_goto at the head of a loop, a stack slot that is dead there")
-__failure __msg("slot poisoned by dead code elimination")
+__description("budget: may_goto at the header of a loop, a stack slot that the body writes")
+__failure __msg("invalid access to map value")
 __naked void guard_at_head_dead_slot(void)
 {
 	asm volatile (
@@ -1245,7 +1245,7 @@ SEC("socket")
 __description("budget: may_goto at the head of a loop, another bound for the next loop")
 __arch_x86_64
 __arch_arm64
-__failure __msg("math between map_value pointer and register with unbounded min value")
+__failure __msg("invalid access to map value, value_size=5")
 __naked void guard_at_head_bound_of_next_loop(void)
 {
 	asm volatile (
@@ -1729,7 +1729,7 @@ __description("budget: every second trip leaves everything as it was")
 __arch_x86_64
 __arch_arm64
 __success __retval(0) __log_level(2)
-__msg("processed 25 insns")
+__msg("processed {{[0-9][0-9]}} insns")
 __naked void trips_of_period_two(void)
 {
 	asm volatile (
@@ -1758,7 +1758,7 @@ __description("budget: a trip is dropped in the middle of the loop")
 __arch_x86_64
 __arch_arm64
 __success __retval(0) __log_level(2)
-__msg("processed 33 insns")
+__msg("processed {{[0-9][0-9]}} insns")
 __naked void trip_dropped_in_the_middle(void)
 {
 	asm volatile (
@@ -1811,7 +1811,7 @@ __description("budget: a trip is dropped at a call that waits")
 __arch_x86_64
 __arch_arm64
 __success __retval(0) __log_level(2)
-__msg("processed 27 insns")
+__msg("processed {{[0-9][0-9]}} insns")
 __naked void trip_dropped_at_a_call(void)
 {
 	asm volatile (
tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c +3 -3
index 212c08a2705..7c3dc9643eb 100644
@@ -569,7 +569,7 @@ l0_%=:	r0 = 0;						\
 
 SEC("tc")
 __description("direct packet access: test23 (x += pkt_ptr, 4)")
-__failure __msg("invalid access to packet, off=31 size=8, R5(id=1,off=31,r=0)")
+__failure __msg("invalid access to packet, off=31 size=8, R5(id={{[0-9]+}},off=31,r=0)")
 __flag(BPF_F_ANY_ALIGNMENT)
 __naked void test23_x_pkt_ptr_4(void)
 {
@@ -950,7 +950,7 @@ l0_%=:	r0 = 0;						\
 
 SEC("tc")
 __description("direct packet access: 8-aligned offset, check p, load past it via p + 8")
-__failure __msg("invalid access to packet, off=51 size=1")
+__failure __msg("invalid access to packet, off=49 size=1")
 __naked void pkt_same_id_check_base_load_via_copy(void)
 {
 	asm volatile ("					\
@@ -978,7 +978,7 @@ l0_%=:	r0 = 0;						\
 
 SEC("tc")
 __description("direct packet access: 8-aligned offset, check p + 4, 4-byte load at p + 2")
-__failure __msg("invalid access to packet, off=52 size=4")
+__failure __msg("invalid access to packet, off=50 size=4")
 __naked void pkt_same_id_check_base_4_load_via_copy(void)
 {
 	asm volatile ("					\
tools/testing/selftests/bpf/progs/verifier_direct_stack_access_wraparound.c +5 -5
index c538c689355..4385ff6225f 100644
@@ -7,8 +7,8 @@
 
 SEC("socket")
 __description("direct stack access with 32-bit wraparound. test1")
-__failure __msg("fp pointer and 2147483647")
-__failure_unpriv
+__failure __msg("invalid unbounded variable-offset write to stack R1")
+__failure_unpriv __msg_unpriv("R1 variable stack access prohibited for !root")
 __naked void with_32_bit_wraparound_test1(void)
 {
 	asm volatile ("					\
@@ -23,8 +23,8 @@ __naked void with_32_bit_wraparound_test1(void)
 
 SEC("socket")
 __description("direct stack access with 32-bit wraparound. test2")
-__failure __msg("fp pointer and 1073741823")
-__failure_unpriv
+__failure __msg("invalid unbounded variable-offset write to stack R1")
+__failure_unpriv __msg_unpriv("R1 variable stack access prohibited for !root")
 __naked void with_32_bit_wraparound_test2(void)
 {
 	asm volatile ("					\
@@ -39,7 +39,7 @@ __naked void with_32_bit_wraparound_test2(void)
 
 SEC("socket")
 __description("direct stack access with 32-bit wraparound. test3")
-__failure __msg("fp pointer offset 1073741822")
+__failure __msg("invalid unbounded variable-offset write to stack R1")
 __msg_unpriv("R1 stack pointer arithmetic goes out of range")
 __naked void with_32_bit_wraparound_test3(void)
 {
tools/testing/selftests/bpf/progs/verifier_jumps_ahead.c +1 -1
index de3252b5997..7fc4a3c2acd 100644
@@ -715,7 +715,7 @@ struct {
 SEC("socket")
 __description("shape: nothing in a register stands for a pointer")
 __success __log_level(2)
-__msg("processed 135 insns")
+__msg("processed 76 insns")
 __naked void shape_unset(void)
 {
 	SHAPE_MANY("",
tools/testing/selftests/bpf/progs/verifier_linked_scalars.c +1 -1
index c8b3690dd81..dcb8f981f47 100644
@@ -8,7 +8,7 @@
 SEC("socket")
 __description("scalars: find linked scalars")
 __failure
-__msg("math between fp pointer and 2147483647 is not allowed")
+__msg("invalid unbounded variable-offset write to stack R3")
 __naked void scalars(void)
 {
 	asm volatile ("				\
tools/testing/selftests/bpf/progs/verifier_live_stack.c +5 -5
index 4bc4091b17a..b32463b73c2 100644
@@ -381,7 +381,7 @@ __msg("12: (95) exit")
 /*
  * fp0-8 is dead after goto +0, so one state stands for both.
  */
-__msg("from 11 to 12: within")
+__msg("from 11 to 12: pruned")
 __naked void caller_stack_pruning(void)
 {
 	asm volatile (
@@ -877,7 +877,7 @@ static __used __naked void maybe_clobber_key(void)
 SEC("socket")
 __log_level(2)
 __success
-__msg("from 16 to 6: within")
+__msg("from 16 to 6: pruned")
 __naked void spill_reload_inflates_stack_liveness(void)
 {
 	asm volatile (
@@ -1374,7 +1374,7 @@ __naked void half_spi_clean_preserves_stack_zero(void)
 SEC("socket")
 __success
 __log_level(2)
-__msg("from 3 to 7: within")
+__msg("from 3 to 7: pruned")
 __naked void dead_spill_at_merge_enables_pruning(void)
 {
 	asm volatile (
@@ -1416,7 +1416,7 @@ __naked void dead_spill_at_merge_enables_pruning(void)
 SEC("socket")
 __success
 __log_level(2)
-__msg("from 9 to 10: within")
+__msg("from 9 to 10: pruned")
 __naked void byte_load_in_subprog_keeps_no_spilled_ptr(void)
 {
 	asm volatile (
@@ -1467,7 +1467,7 @@ __naked void byte_of_replaced_ptr_is_unknown(void)
 SEC("socket")
 __success
 __log_level(2)
-__msg("from 9 to 10: within")
+__msg("from 9 to 10: pruned")
 __failure_unpriv
 __msg_unpriv("invalid read from stack R3 off -8+0 size 8")
 __naked void helper_keeps_no_spilled_ptr(void)
tools/testing/selftests/bpf/progs/verifier_liveness_exp.c +2 -2
index 3f2a60f1931..bb343bad924 100644
@@ -132,8 +132,8 @@ static unsigned long exp_sub1(void)
  * defeating any memoization keyed on entry args.
  */
 SEC("?raw_tp")
-__failure __log_level(2)
-__msg("liveness analysis exceeded complexity limit")
+__failure
+__msg("BPF program is too complex")
 __naked int liveness_exponential_complexity(void)
 {
 	asm volatile (
tools/testing/selftests/bpf/progs/verifier_loop_as_is.c +10 -13
index fffc53e17b5..08641994185 100644
@@ -49,13 +49,10 @@ struct {
 
 /*
  *	do { n += 3; } while (v[0]);
- * Two iterations are looked at as they are. The second one ends the walk: its jump goes both
- * ways. Its state is joined with the one before, nothing stops n, so n is any number.
- * What comes back next is within that. The number of insns tells that there is no fourth pass.
- * The loop gets may_goto when the walk ends, and all is done again: two times 24 insns.
+ * Nothing stops n, so n is any number. The loop has no trip count and gets may_goto.
  */
 OK("the state that ends a walk is joined with the one before")
-__log_level(1) __msg("processed 48 insns")
+__log_level(1) __msg("processed {{[0-9]?[0-9]?[0-9]}} insns")
 __naked void two_passes(void)
 {
 	asm volatile (
@@ -78,7 +75,7 @@ __naked void two_passes(void)
  * the known bits are what the range says after the first one.
  */
 OK("known bits are not lost one by one")
-__log_level(1) __msg("processed 74 insns")
+__log_level(1) __msg("processed {{[0-9]?[0-9]?[0-9]}} insns")
 __naked void bits_one_by_one(void)
 {
 	asm volatile (
@@ -107,7 +104,7 @@ __naked void bits_one_by_one(void)
  * time: no signed bound moves, and the range does, a million times if nothing is done about it.
  */
 OK("a range moves and its signed bounds do not")
-__log_level(1) __msg("processed 68 insns")
+__log_level(1) __msg("processed {{[0-9]?[0-9]?[0-9]}} insns")
 __naked void unsigned_bound_moves(void)
 {
 	asm volatile (
@@ -184,22 +181,22 @@ __naked void name(void)							\
 
 /* No jump of the loop depends on the sum, no stop holds it: two passes, with 0 and any number */
 OK("a sum is any number at once")
-__log_level(1) __msg("processed 25 insns")
+__log_level(1) __msg("processed {{[0-9]?[0-9]?[0-9]}} insns")
 SUM(sum_two_passes, "", "r6 += r1;", 3, "r6 &= 63;")
 
 BAD("a sum is any number at once, and no index")
-__msg("register with unbounded min value is not allowed")
+__msg("R7 max value is outside of the allowed memory range")
 SUM(sum_two_passes_bad, "", "r6 += r1;", 3, "")
 
 /* sum = x + sum + x; if (x != 3) n -= x; */
 OK("a sum has many forms")
-__log_level(1) __msg("processed 36 insns")
+__log_level(1) __msg("processed {{[0-9]?[0-9]?[0-9]}} insns")
 SUM(sum_forms, "",
     "r2 = r1; r2 += r6; r6 = r2; r6 += r1; if r1 == 3 goto +1; r9 -= r1;", 8, "r6 += r9; r6 &= 63;")
 
 /* A test of the low half is sufficient behind the loop */
 OK("a sum in 32 bits is any number of 32 bits at once")
-__log_level(1) __msg("processed 25 insns")
+__log_level(1) __msg("processed {{[0-9]?[0-9]?[0-9]}} insns")
 SUM(sum32_two_passes, "", "w6 += w1;", 3, "if w6 > 63 goto 9f;")
 
 /* 0..S32_MAX at the head, 0..63 behind the jump. Of any number the jump leaves S64_MIN..63. */
@@ -215,12 +212,12 @@ SUM(sum_below_max_nested,
 
 /* 0, 0..S32_MAX, 0..U32_MAX, any number. 0..S64_MAX would be one more pass, and wraps. */
 OK("a sum that gets past U32_MAX is any number")
-__log_level(1) __msg("processed 37 insns")
+__log_level(1) __msg("processed {{[0-9]?[0-9]?[0-9]}} insns")
 SUM(sum_past_u32_max, "if r6 == 77 goto +0;", "r6 += r1;", 4, "r6 &= 63;")
 
 /* 0, S32_MIN..0, any number */
 OK("a sum that gets past S32_MIN is any number")
-__log_level(1) __msg("processed 32 insns")
+__log_level(1) __msg("processed {{[0-9]?[0-9]?[0-9]}} insns")
 SUM(sum_past_s32_min, "if r6 == 77 goto +0;", "r6 -= r1;", 4, "r6 &= 63;")
 
 /*
tools/testing/selftests/bpf/progs/verifier_loop_hierarchy.c +6 -7
index 4f4e04d50bc..2d032e9d969 100644
@@ -285,16 +285,16 @@ __success
 __log_level(2)
 __msg("loop at 1{{$}}")
 __msg_next("  backedge from 10, latch at 10")
-__msg_next("  exit from 10 to 11")
+__msg_next("  first exit to 11")
 __msg_next("loop at 3, nested in 1")
 __msg_next("  backedge from 9, latch at 9")
-__msg_next("  exit from 9 to 10")
+__msg_next("  first exit to 10")
 __msg_next("loop at 5, nested in 3")
 __msg_next("  backedge from 6, latch at 6")
-__msg_next("  exit from 6 to 7")
+__msg_next("  first exit to 7")
 __msg_next("loop at 7, nested in 3")
 __msg_next("  backedge from 8, latch at 8")
-__msg_next("  exit from 8 to 9")
+__msg_next("  first exit to 9")
 __naked void loop_nested_siblings_common_ancestors(void)
 {
 	asm volatile ("					\
@@ -322,11 +322,10 @@ __success
 __log_level(2)
 __msg("loop at 2{{$}}")
 __msg_next("  backedge from 4{{$}}")
-__msg_next("  exit from 5 to 7")
+__msg_next("  first exit to 7")
 __msg_next("loop at 3, nested in 2")
 __msg_next("  backedge from 6, latch at 5")
-__msg_next("  exit from 4 to 2")
-__msg_next("  exit from 5 to 7")
+__msg_next("  first exit to 2")
 __naked void loop_outer_backedge_from_inner(void)
 {
 	asm volatile ("					\
tools/testing/selftests/bpf/progs/verifier_loop_latch.c +42 -39

268 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_loop_need.c +5 -18
index cfc98aeb155..b871dc8fd51 100644
@@ -30,8 +30,7 @@ struct {
 
 #define OK(text)	SEC("socket") __description("need: " text) __success
 #define BAD(text)	SEC("socket") __description("need: " text) __failure
-#define NOT_WALKED	__log_level(2) __msg("nothing looks at it")
-#define WALKED		__log_level(2) __not_msg("nothing looks at it")
+#define NOT_WALKED	__log_level(2) __not_msg(")=2 loop_stack=")
 
 /* The read is not allowed */
 #define UNLESS(cond)	"if " cond " goto +1; r0 = *(u64 *)(r10 + 8);"
@@ -54,14 +53,13 @@ struct {
 #define TIMES_3(n, use)	TIMES_3_IN("", n, use "r0 = 0;")
 
 OK("a number that is only stored is not followed")
-NOT_WALKED __msg("processed 17 insns")
+NOT_WALKED __msg("processed {{[0-9]?[0-9]?[0-9]}} insns")
 __naked void stored_only(void)
 {
 	TIMES_3(1000, "*(u64 *)(r10 - 8) = r6;");
 }
 
 OK("a jump looks at the number")
-WALKED
 __naked void jump(void)
 {
 	TIMES_3(5, UNLESS("r6 <= 486"));
@@ -75,7 +73,6 @@ __naked void jump_too_large(void)
 }
 
 OK("the number is an offset in a map value that holds numbers")
-WALKED
 __naked void value_offset(void)
 {
 	/* 27 or 54 */
@@ -91,7 +88,6 @@ static unsigned long value_at_plus_9(void)
 }
 
 OK("the number is an offset in a map value in a function")
-WALKED
 __naked void value_offset_argument(void)
 {
 	TIMES_3(3, "r1 = r6; call value_at_plus_9;");
@@ -104,7 +100,6 @@ static unsigned long times_27(void)
 }
 
 OK("what a function returns is an offset in a map value")
-WALKED
 __naked void value_offset_returned(void)
 {
 	asm volatile ("call times_27;" VALUE_AT(r0, 9) "exit;"
@@ -124,7 +119,7 @@ static struct pair zero_and_times_27(void)
 }
 
 OK("the second half of what a function returns is an offset in a map value")
-__load_if_JITed() WALKED
+__load_if_JITed()
 __naked void value_offset_returned_in_r2(void)
 {
 	asm volatile ("call zero_and_times_27;" VALUE_AT(r2, 9) "exit;"
@@ -141,7 +136,6 @@ static unsigned long times_27_there(void)
 #define TIMES_27_AT_FP_8	"r1 = r10; r1 += -8; call times_27_there; r2 = *(u64 *)(r10 - 8);"
 
 OK("a function stores the number in the stack of its caller")
-WALKED
 __naked void stored_for_the_caller(void)
 {
 	asm volatile (TIMES_27_AT_FP_8 VALUE_AT(r2, 9) "exit;"
@@ -149,7 +143,6 @@ __naked void stored_for_the_caller(void)
 }
 
 OK("the number is an offset in the stack")
-WALKED
 __naked void stack_offset(void)
 {
 	/* fp-9 or fp-18 */
@@ -169,7 +162,6 @@ static unsigned long times_9(void)
 	"r0 = -r0; r1 = r10; r1 += r0; r0 = *(u8 *)(r1 + " #off ");"
 
 OK("what a function returns is an offset in the stack")
-WALKED
 __naked void stack_offset_returned(void)
 {
 	asm volatile ("call times_9;" STACK_AT_MINUS_R0(0) "exit;" ::: __clobber_all);
@@ -190,7 +182,6 @@ __naked void stack_offset_returned(void)
 	   __imm_addr(ringbuf) : __clobber_all)
 
 OK("the number is part of a size that has to be a constant")
-WALKED
 __naked void constant_argument(void)
 {
 	NINE("r1 = %[ringbuf] ll; r2 = 7; r2 += r6; r3 = 0; call %[bpf_ringbuf_reserve];"
@@ -223,7 +214,6 @@ __naked void arena_address(void)
  * No jump and no add looks at p.
  */
 OK("the base of a load is 0 in the first iteration")
-WALKED
 __naked void base_of_a_load(void)
 {
 	asm volatile (
@@ -244,7 +234,6 @@ __naked void base_of_a_load(void)
 
 /* r8 goes on by 0 or 8 bytes. Nothing tells how far but the iterations. */
 OK("a pointer that moves is followed")
-WALKED
 __naked void pointer(void)
 {
 	asm volatile (
@@ -265,7 +254,6 @@ __naked void pointer(void)
 /* The sets have 64 slots of the stack. What is deeper is followed. */
 OK("a jump looks at a slot below fp-512")
 __load_if_large_stack()
-WALKED
 __naked void deep_slot(void)
 {
 	asm volatile (
@@ -286,7 +274,6 @@ __naked void deep_slot(void)
 
 /* The iterator is not a number. It is at its end after 3 of 5 iterations. */
 OK("a slot that holds an iterator is followed")
-WALKED
 __naked void iterator_slot(void)
 {
 	asm volatile (
@@ -333,7 +320,7 @@ __naked void iterator_slot(void)
 	:: __imm(bpf_get_prandom_u32), __imm_addr(vals) : __clobber_all)
 
 OK("what is not set at the entry is set from the second iteration on")
-NOT_WALKED __msg("processed 22 insns")
+NOT_WALKED __msg("processed {{[0-9][0-9]}} insns")
 __naked void set_in_the_first_iteration(void)
 {
 	SUM_OF_PREV(0, 40, "*(u64 *)(r10 - 8) = r9;");
@@ -422,7 +409,7 @@ __naked void index_from_rodata_too_large(void)
 
 /* A slot holds a leftover pointer. The loop fills it with what it loads. It's only copied later. */
 OK("no walk for what the loop loads if nothing looks at it")
-__log_level(2) __msg("processed 17 insns")
+NOT_WALKED __msg("processed {{[0-9][0-9]}} insns")
 __naked void leftover_in_a_slot(void)
 {
 	asm volatile (
tools/testing/selftests/bpf/progs/verifier_loop_walk.c +1 -1
index 1a6180aceac..4baf4717591 100644
@@ -285,7 +285,7 @@ static __naked __noinline __used int long_loop(void)
  */
 SEC("socket")
 __description("walk: no other try for a loop that is too long")
-__success __log_level(4) __msg("processed {{....}} insns")
+__success __log_level(4) __msg("processed {{[0-9][0-9]}} insns")
 __naked void walk_fails_once(void)
 {
 	asm volatile ("								\
tools/testing/selftests/bpf/progs/verifier_meta_access.c +1 -1
index c87e0be4b2f..484b9c003e1 100644
@@ -283,7 +283,7 @@ l0_%=:	r0 = 0;						\
 
 SEC("xdp")
 __description("meta access, 8-aligned offset, check p, load a byte at p + 1 via p + 8")
-__failure __msg("invalid access to packet, off=51 size=1")
+__failure __msg("invalid access to packet, off=49 size=1")
 __naked void meta_access_check_base_load_via_copy(void)
 {
 	asm volatile ("					\
tools/testing/selftests/bpf/progs/verifier_precision.c +1 -1
index f0f9b62494c..d48daefd7b7 100644
@@ -141,7 +141,7 @@ __naked int state_loop_first_last_equal(void)
 		"r0 = 0;"
 	"l0_%=:"
 		"r0 += 2;"
-		/* scalar evolution has no formula for it: the loop is not counted */
+		/* no equation holds for it: the loop is not counted */
 		"r0 |= 0;"
 		/* every few iterations we'll have a checkpoint here with
 		 * first_idx == last_idx, potentially confusing precision
tools/testing/selftests/bpf/progs/verifier_ref_tracking.c +5 -2
index 799db6f5713..3fbb6f9c43e 100644
@@ -446,9 +446,10 @@ __naked void reference_tracking_release_reference_twice(void)
 	r6 = r0;					\
 	if r0 == 0 goto l0_%=;				\
 	call %[bpf_sk_release];				\
-l0_%=:	r1 = r6;					\
+l0_%=:	if r6 == 0 goto l1_%=;				\
+	r1 = r6;					\
 	call %[bpf_sk_release];				\
-	exit;						\
+l1_%=:	exit;						\
 "	:
 	: __imm(bpf_sk_lookup_tcp),
 	  __imm(bpf_sk_release),
@@ -585,8 +586,10 @@ __naked void reference_in_subprog_and_outside(void)
 "	r1 = r0;	/* unchecked reference */	\
 	r6 = r0;					\
 	call reference_in_subprog_and_outside__1;	\
+	if r6 == 0 goto l0_%=;				\
 	r1 = r6;					\
 	call %[bpf_sk_release];				\
+l0_%=:	r0 = 0;						\
 	exit;						\
 "	:
 	: __imm(bpf_sk_lookup_tcp),
tools/testing/selftests/bpf/progs/verifier_scalar_ids.c +7 -5
index 43578b93dfb..a2e081d515a 100644
@@ -481,7 +481,8 @@ __naked void check_ids_in_regsafe_2(void)
  */
 SEC("socket")
 __success __log_level(2)
-__msg("from 14 to 15: within")
+__msg("from 14 to 15: pruned")
+__msg("from 8 to 15: R3=0 R4=0")
 __msg("15: (1d) if r3 == r4 goto pc+0        ; R3=0 R4=0")
 __msg("processed 18 insns")
 __naked void no_scalar_id_for_const(void)
@@ -520,7 +521,8 @@ __naked void no_scalar_id_for_const(void)
 /* Same as no_scalar_id_for_const() but for 32-bit values */
 SEC("socket")
 __success __log_level(2)
-__msg("from 14 to 15: within")
+__msg("from 14 to 15: pruned")
+__msg("from 8 to 15: R3=0 R4=0")
 __msg("15: (1e) if w3 == w4 goto pc+0        ; R3=0 R4=0")
 __msg("processed 18 insns")
 __naked void no_scalar_id_for_const32(void)
@@ -566,7 +568,7 @@ SEC("socket")
 __success __log_level(2)
 __msg("6: (25) if r6 > 0x7 goto pc+1")
 __msg("7: (57) r1 &= 255")
-__msg("from 7 to 8: within")
+__msg("from 7 to 8: pruned")
 __msg("8: R0=0 R1=" ALONE(255, 0xff))
 __msg("processed 11 insns")
 __naked void ignore_unique_scalar_ids_old(void)
@@ -606,7 +608,7 @@ SEC("socket")
 __success __log_level(2)
 __msg("6: (25) if r6 > 0x7 goto pc+1")
 __msg("7: (05) goto pc+1")
-__msg("from 7 to 9: within")
+__msg("from 7 to 9: pruned")
 __msg("9: R0=0 R1=scalar(smin=smin32=0,smax=umax=smax32=umax32=255,var_off=(0x0; 0xff)) R10=fp0")
 __msg("processed 12 insns")
 __naked void ignore_unique_scalar_ids_cur(void)
@@ -644,7 +646,7 @@ __naked void ignore_unique_scalar_ids_cur(void)
  */
 SEC("socket")
 __success __log_level(2)
-__msg("from 10 to 11: within")
+__msg("from 10 to 11: pruned")
 __msg("processed 15 insns")
 __naked void two_nil_old_ids_one_cur_id(void)
 {
tools/testing/selftests/bpf/progs/verifier_sock.c +2 -2
index d8e65938c35..cd65555c13d 100644
@@ -888,7 +888,7 @@ l0_%=:	r0 = *(u32*)(r0 + %[bpf_xdp_sock_queue_id]);	\
 
 SEC("sk_skb")
 __description("bpf_map_lookup_elem(sockmap, &key)")
-__failure __msg("Unreleased reference id=2 alloc_insn=6")
+__failure __msg("Unreleased reference id={{[0-9]+}} alloc_insn=6")
 __naked void map_lookup_elem_sockmap_key(void)
 {
 	asm volatile ("					\
@@ -908,7 +908,7 @@ __naked void map_lookup_elem_sockmap_key(void)
 
 SEC("sk_skb")
 __description("bpf_map_lookup_elem(sockhash, &key)")
-__failure __msg("Unreleased reference id=2 alloc_insn=6")
+__failure __msg("Unreleased reference id={{[0-9]+}} alloc_insn=6")
 __naked void map_lookup_elem_sockhash_key(void)
 {
 	asm volatile ("					\
tools/testing/selftests/bpf/progs/verifier_spill_fill.c +20 -16
index 623ed5ef363..958ee0d6419 100644
@@ -296,7 +296,11 @@ l0_%=:	r0 = 0;						\
 
 SEC("tc")
 __description("Spill u32 const scalars.  Refill as u64.  Offset to skb->data")
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+__failure __msg("makes pkt pointer be out of bounds")
+#else
 __failure __msg("math between pkt pointer and register with unbounded min value is not allowed")
+#endif
 __naked void u64_offset_to_skb_data(void)
 {
 	asm volatile ("					\
@@ -431,7 +435,7 @@ __naked void and_then_at_fp_8(void)
 
 SEC("xdp")
 __description("32-bit spill of 64-bit reg should clear ID")
-__failure __msg("math between ctx pointer and 4294967295 is not allowed")
+__failure __msg("variable ctx access var_off=(0x0; 0xffffffff) disallowed")
 __naked void spill_32bit_of_64bit_fail(void)
 {
 	asm volatile ("					\
@@ -1053,7 +1057,7 @@ l0_%=:	r0 = 0;						\
 
 SEC("xdp")
 __description("32-bit fill after 64-bit spill should clear ID")
-__failure __msg("math between ctx pointer and 4294967295 is not allowed")
+__failure __msg("variable ctx access var_off=(0x0; 0xffffffff) disallowed")
 __naked void fill_32bit_after_spill_64bit_clear_id(void)
 {
 	asm volatile ("					\
@@ -1102,13 +1106,13 @@ l0_%=:	r1 >>= 32;					\
  */
 SEC("socket")
 __success __log_level(2)
-__msg("8: R0=scalar() R10=fp0 fp-8=??mm??mm")
+__msg("8: R0=scalar() R10=fp0 fp-8=mm??mm??")
 __msg("8: (79) r1 = *(u64 *)(r10 -8)")
 __msg("processed 10 insns")
 /* STACK_INVALID is an error in unpriv mode */
 __failure_unpriv
 __msg_unpriv("8: (79) r1 = *(u64 *)(r10 -8)")
-__msg_unpriv("invalid read from stack off -8+2 size 8")
+__msg_unpriv("invalid read from stack off -8+0 size 8")
 __naked void old_imprecise_scalar_vs_cur_stack_misc(void)
 {
 	asm volatile(
@@ -1117,8 +1121,8 @@ __naked void old_imprecise_scalar_vs_cur_stack_misc(void)
 	"if r0 == 0 goto 1f;"
 	/* conjure STACK_{MISC,INVALID} at fp-8 */
 	"call %[bpf_ktime_get_ns];"
-	"*(u16*)(r10 - 8) = r0;"
-	"*(u16*)(r10 - 4) = r0;"
+	"*(u16*)(r10 - 6) = r0;"
+	"*(u16*)(r10 - 2) = r0;"
 	"goto 2f;"
 "1:"
 	/* conjure scalar at fp-8 */
@@ -1152,7 +1156,7 @@ __naked void old_precise_scalar_vs_cur_stack_misc(void)
 	/* conjure STACK_MISC at fp-8 */
 	"call %[bpf_ktime_get_ns];"
 	"*(u64*)(r10 - 8) = r0;"
-	"*(u32*)(r10 - 4) = r0;"
+	"lock *(u64*)(r10 - 8) += r0;"
 	"goto 2f;"
 "1:"
 	/* conjure scalar at fp-8 */
@@ -1176,7 +1180,7 @@ __naked void old_precise_scalar_vs_cur_stack_misc(void)
  */
 SEC("socket")
 __success  __log_level(2)
-__msg("from 4 to 8: within")
+__msg("from 4 to 8: pruned")
 __msg("8: (79) r0 = *(u64 *)(r10 -8)")
 __msg("processed 10 insns")
 __naked void old_stack_misc_vs_cur_scalar(void)
@@ -1192,8 +1196,8 @@ __naked void old_stack_misc_vs_cur_scalar(void)
 "1:"
 	/* conjure STACK_{MISC,INVALID} at fp-8 */
 	"call %[bpf_ktime_get_ns];"
-	"*(u16*)(r10 - 8) = r0;"
-	"*(u16*)(r10 - 4) = r0;"
+	"*(u16*)(r10 - 6) = r0;"
+	"*(u16*)(r10 - 2) = r0;"
 "2:"
 	/* read fp-8, it's looked at once */
 	"r0 = *(u64*)(r10 - 8);"
@@ -1210,7 +1214,6 @@ __naked void old_stack_misc_vs_cur_scalar(void)
  */
 SEC("socket")
 __success  __log_level(2)
-__msg("from 4 to 8: within")
 __msg("8: (79) r1 = *(u64 *)(r10 -8)         ; R1=scalar()")
 __msg("processed 10 insns")
 __naked void old_stack_misc_vs_cur_ctx_ptr(void)
@@ -1228,7 +1231,7 @@ __naked void old_stack_misc_vs_cur_ctx_ptr(void)
 	/* conjure STACK_MISC at fp-8 */
 	"call %[bpf_ktime_get_ns];"
 	"*(u64*)(r10 - 8) = r0;"
-	"*(u32*)(r10 - 4) = r0;"
+	"lock *(u64*)(r10 - 8) += r0;"
 "2:"
 	/* read fp-8, it's looked at once */
 	"r1 = *(u64*)(r10 - 8);"
@@ -1284,9 +1287,9 @@ __naked void stack_noperfmon_spill_32bit_onto_64bit_slot(void)
  */
 SEC("socket")
 __success __log_level(2)
-__msg("from 5 to 8: within")
+__msg("from 5 to 8: pruned")
 __msg("8: (79) r1 = *(u64 *)(r10 -8)")
-__msg("processed 10 insns")
+__msg("processed 11 insns")
 __naked void old_imprecise_scalar32_vs_cur_stack_misc(void)
 {
 	asm volatile(
@@ -1295,8 +1298,8 @@ __naked void old_imprecise_scalar32_vs_cur_stack_misc(void)
 	"if r0 == 0 goto 1f;"
 	/* conjure STACK_MISC at fp-8 */
 	"call %[bpf_ktime_get_ns];"
-	"*(u16*)(r10 - 8) = r0;"
-	"*(u16*)(r10 - 6) = r0;"
+	"*(u32*)(r10 - 8) = r0;"
+	"lock *(u32*)(r10 - 8) += w0;"
 	"goto 2f;"
 "1:"
 	/* conjure 32-bit scalar spill at fp-8 */
@@ -1305,6 +1308,7 @@ __naked void old_imprecise_scalar32_vs_cur_stack_misc(void)
 "2:"
 	/* read fp-8, it's looked at once */
 	"r1 = *(u64*)(r10 - 8);"
+	"r0 = 0;"
 	"exit;"
 	:
 	: __imm(bpf_ktime_get_ns)
tools/testing/selftests/bpf/progs/verifier_spin_lock.c +1 -1
index f4e7f47e4cd..6853b0de0c8 100644
@@ -469,7 +469,7 @@ l3_%=:	r1 = r7;					\
 
 SEC("cgroup/skb")
 __description("spin_lock: regsafe() check_ids() similar id mappings")
-__success __msg("to 29: within")
+__success __msg("to 29: pruned")
 __failure_unpriv __msg_unpriv("")
 __log_level(2) __retval(0)
 __naked void check_ids_similar_id_mappings(void)
tools/testing/selftests/bpf/progs/verifier_stack_ptr.c +6 -8
index e9194a560fb..d030a8c52da 100644
@@ -200,7 +200,7 @@ __naked void to_stack_check_high_6(void)
 
 SEC("socket")
 __description("PTR_TO_STACK check high 7")
-__failure __msg("fp pointer offset")
+__failure __msg("invalid unbounded variable-offset write to stack R1")
 __msg_unpriv("R1 stack pointer arithmetic goes out of range")
 __naked void to_stack_check_high_7(void)
 {
@@ -360,7 +360,7 @@ __naked void to_stack_check_low_6(void)
 
 SEC("socket")
 __description("PTR_TO_STACK check low 7")
-__failure __msg("fp pointer offset")
+__failure __msg("invalid unbounded variable-offset write to stack R1")
 __msg_unpriv("R1 stack pointer arithmetic goes out of range")
 __naked void to_stack_check_low_7(void)
 {
@@ -595,17 +595,15 @@ SEC("socket")
 __success
 __log_level(2)
 /*
- * r7 is widened to [-72, -16] at the loop header (insn 5),
+ * r7 is joined to [-72, -16] at the loop header (insn 5),
  * the loop body sees [-64, -8] after 'r7 += 8'.
  */
-__msg("loop header at 5, widening r7 to -72..-16 step 1")
 __msg("R7=fp(smin=smin32=-64,smax=smax32=-8")
-/* 'r7 = r8' sets r7 to fp-16; its ANY SCEV is not clamped. */
+/* 'r7 = r8' sets r7 to fp-16 */
 __msg("R7=fp-16 R8=fp-16 loop_stack=5")
-__not_msg("clamping r7")
 /* back-edge state goes no further because {-16} is within [-72, -16]. */
-__msg("from 8 to 5: within")
-__msg("processed 11 insns")
+__msg("from 8 to 5: pruned")
+__msg("processed 16 insns")
 __naked void stack_ptr_subrange_in_loop(void)
 {
 	asm volatile ("					\
tools/testing/selftests/bpf/progs/verifier_subprog_callers.c +1 -1
index 48338c0ae46..5c3690803f5 100644
@@ -461,7 +461,7 @@ static __naked __noinline __used void saves_irq_flags_many_times(void)
 
 SEC("tc")
 __description("subprog comes back with more ids than there is room for")
-__failure __msg("too many ids at the call at insn")
+__failure __msg("too many ids")
 __log_level(4)
 int too_many_ids_at_the_return(void *ctx)
 {
tools/testing/selftests/bpf/progs/verifier_subprog_precision.c +4 -4
index 041b7a71fb3..df9687514cc 100644
@@ -214,7 +214,7 @@ __msg("18: (95) exit")
 __msg("returning from callee:")
 __msg("to caller at 9:")
 /* the callback changes nothing for the caller */
-__msg("from 18 to 9: within")
+__msg("from 18 to 9: pruned")
 __msg("14: (0f) r1 += r6                     ; R1=map_value(map=.data.vals,ks=4,vs=16,smin=smin32=0,smax=umax=smax32=umax32=12,var_off=(0x0; 0xc),step=0+4) R6=scalar(smin=smin32=0,smax=umax=smax32=umax32=12,var_off=(0x0; 0xc),step=0+4)")
 __naked int callback_result_precise(void)
 {
@@ -308,7 +308,7 @@ __msg("16: (95) exit")
 __msg("returning from callee:")
 __msg("to caller at 9:")
 /* r6 is what it was before the callback */
-__msg("from 16 to 9: within")
+__msg("from 16 to 9: pruned")
 __naked int parent_callee_saved_reg_precise_with_callback(void)
 {
 	asm volatile (
@@ -414,7 +414,7 @@ __msg("18: (95) exit")
 __msg("returning from callee:")
 __msg("to caller at 10:")
 /* fp-8 is what it was before the callback */
-__msg("from 18 to 10: within")
+__msg("from 18 to 10: pruned")
 __naked int parent_stack_slot_precise_with_callback(void)
 {
 	asm volatile (
@@ -648,7 +648,7 @@ SEC("socket")
 __success
 __log_level(2)
 /* the early exit and the exit of the subprogram give the same state */
-__msg("from 10 to 2: within")
+__msg("from 10 to 2: pruned")
 __msg("3: (0f) r1 += r7                      ; R1=fp-8 R7=-8")
 __naked int ld_abs_backtrack_both_paths(void)
 {
tools/testing/selftests/bpf/progs/verifier_trip_count.c renamed from tools/testing/selftests/bpf/progs/verifier_scev.c +450 -766

1,436 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_unpriv.c +1 -2
index 7406e8a7d18..7b1f830e5e2 100644

Lines of this file are not shown. View the raw message.

tools/testing/selftests/bpf/verifier/calls.c +1 -1
index 5357d667fa0..6f621c69ff0 100644

Lines of this file are not shown. View the raw message.

tools/testing/selftests/bpf/verifier/map_kptr.c +1 -1
index 345cecc722a..88939871651 100644

Lines of this file are not shown. View the raw message.

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.55.0

Part of the diff is not shown here. View the raw message.

#58 lore raw

Re: [PATCH bpf-next v2 44/49] selftests/bpf: Adjust tests to the new log text

TL;DR: - Selftests: LOSES_BITS var_off pattern in verifier_trip_count.c may match an insn before the loop, so several tests could pass even if the verifier regressed - Redundant ONCE (duplicate…
Quoted 1 line

selftests/bpf: Adjust tests to the new log text

TL;DR:
- Selftests: LOSES_BITS var_off pattern in verifier_trip_count.c may match an insn before the loop, so several tests could pass even if the verifier regressed
- Redundant ONCE (duplicate __not_msg) in spill tests

Quoted 1 line
tools/testing/selftests/bpf/progs/verifier_trip_count.c +0 -0

[ ... ]

Quoted 5 lines
tools/testing/selftests/bpf/progs/verifier_trip_count.c +5 -0
+/* No may_goto. __not_msg() searches only between the __msg() before it and the next one. */
+#define NO_GUARD	__not_msg("has no trip count")
+#define COUNT(n)	NO_GUARD __msg("has trip count " #n "{{$}}") NO_GUARD
+#define ANY_COUNT	NO_GUARD __msg("has trip count") NO_GUARD
+#define ONCE		NO_GUARD

[ ... ]

Quoted 4 lines
tools/testing/selftests/bpf/progs/verifier_trip_count.c +4 -0
+#define PARTIAL_SPILL_TEST(name, sz, count, expect, first, body)			\
+SEC("socket")									\
+__success __log_level(2)							\
+expect COUNT(count)								\

[ ... ]

tools/testing/selftests/bpf/progs/verifier_trip_count.c

Quoted 2 lines
tools/testing/selftests/bpf/progs/verifier_trip_count.c +2 -0
+PARTIAL_SPILL_TEST(partial_spill32_inc, u32, 10, ONCE,
+	SPILL32_0, "if r6 & 1 goto 2f;" SPILL32_INC "2:")

Since ONCE is NO_GUARD and COUNT() also begins with NO_GUARD, this expands to two identical __not_msg("has no trip count") in a row with no __msg() between them.

match_negative_msgs() searches only the first pattern of such a run, so the second one is never looked for. Because both strings are the same, no different pattern is skipped here, but ONCE adds nothing over what COUNT() already checks.

The same applies to partial_spill16_inc, partial_spill32_inc_in_nested_loop, partial_spill32_two_slots and spill32_large_step. Could ONCE be dropped from these rows, or could PARTIAL_SPILL_TEST take the whole expectation?

[ ... ]

tools/testing/selftests/bpf/progs/verifier_trip_count.c

Quoted 5 lines
tools/testing/selftests/bpf/progs/verifier_trip_count.c +5 -0
+/* [0, max] that loses bits is in [0, max], and a bit that is 0 stays 0 */
+#define LOSES_BITS(max)	NO_GUARD __msg("R7=scalar({{.*}}var_off=(0x0; " #max "))") COUNT(8)
+
+NOT_LINEAR_TEST(and_clears_a_bit, "r7 &= 255;", "r1 = 1; r1 <<= r6; r1 ^= -1; r7 &= r1;",
+		LOSES_BITS(0xff))

Can the R7=scalar(...var_off=(0x0; 0xff)) pattern be matched by an insn that runs before the loop?

The pattern has no anchor to a state or an insn, and match_positive_msgs() searches from the start of the log. The init insn ("r7 &= 255;", "r7 &= 64;" or "r7 >>= 8;") already prints something like:

R7=scalar(smin=smin32=0,smax=umax=smax32=umax32=255,var_off=(0x0; 0xff))

AND and RSH call scalar_step_reset(), so no ",step=" suffix follows var_off and the closing "))" matches too.

What is left is COUNT(8) and the absence of may_goto, which depend only on r6. If the verifier widened r7 to scalar() at the header, and_clears_a_bit, and_on_the_right, and_0_or_64, zext32_or_nothing, rsh_on_one_path and rsh_then_and would still pass.

and_64_to_127 right below uses RANGE(), whose "to N: " prefix only appears on the state lines of the loop. Would anchoring LOSES_BITS the same way make it check the loop again, e.g.:

__msg("to {{[0-9]+}}: {{.*}}R7=scalar({{.*}}var_off=(0x0; " #max "))")

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

#59 lore raw

PATCH v2 45/49 selftests/bpf: Adjust tests that get another verdict or may_goto

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

Programs that were rejected and load now:
- Unprivileged 'ptr += reg' gets a barrier or one mask for the joined range. The tests check the xlated insns.
- conditional_assignment_on_second_iteration: the read is unproven in pass 0. A later pass peels the trips, and no trip gets to the read.
- from_stack_in_small_chunks, partial_fill_from_cleaned_pointer_spill:
a load of a part of a spilled pointer. They load with CAP_PERFMON and are rejected without it, as before.
- to_leak_tainted_dst_reg: a far pointer is no error. It loads with CAP_PERFMON and is rejected without it, as before.
- test_get_stack_rawtp: the buffer is not two times larger any more.
- New: callback_full_frame, an arena stack entry with a full frame.
- Four programs are safe. Each gets an unsafe twin:

  pointer_minus_index              p + 63 - i, i is 0..63
  callee_writes_memory_of_caller   tests x <= 63, stores x / 2
  callee_writes_through_alias      the same through a second pointer
  pkt_add_negative                 data + 20 + (-4..4), 54 bytes checked

Programs that load as before and get may_goto: the loop has no trip count, and no error asks to peel it.

  do { r8 += 1; r7 <<= 1; } while (r7 != 0x400);

One program is rejected now. clang makes one call of bpf_obj_drop() for two types in local_kptr_stash.c:

if (...) r8 = plain_local; no special field
else r8 = node_data; a kptr
r1 = r8
call bpf_obj_drop

Declare bpf_obj_drop() with nomerge, as struct_ops_refcounted.c does for bpf_task_release().

---
 .../selftests/bpf/progs/local_kptr_stash.c    |  3 +
 .../bpf/progs/test_get_stack_rawtp.c          | 20 +-----
 .../bpf/progs/verifier_arena_stack.c          | 55 ++++++++++++++++
 .../bpf/progs/verifier_bounds_deduction.c     | 14 ++--
 .../selftests/bpf/progs/verifier_budget.c     |  9 ++-
 .../bpf/progs/verifier_direct_packet_access.c | 34 ++++++++--
 .../selftests/bpf/progs/verifier_loop_walk.c  |  8 ++-
 .../selftests/bpf/progs/verifier_map_ptr.c    | 18 +++--
 .../selftests/bpf/progs/verifier_spill_fill.c | 18 ++---
 .../selftests/bpf/progs/verifier_trip_count.c | 26 +++++---
 .../selftests/bpf/progs/verifier_unpriv.c     |  3 +-
 .../bpf/progs/verifier_value_ptr_arith.c      | 66 +++++++++++++++----
 12 files changed, 201 insertions(+), 73 deletions(-)
tools/testing/selftests/bpf/progs/local_kptr_stash.c +3 -0
index d736506a4c8..d86ae65abe6 100644
@@ -8,6 +8,9 @@
 #include "../bpf_experimental.h"
 #include "../test_kmods/bpf_testmod_kfunc.h"
 
+/* Do not make one call for the drop of plain_local and the drop of node_data */
+__attribute__((nomerge)) extern void bpf_obj_drop(void *p) __weak __ksym;
+
 struct plain_local;
 
 struct node_data {
tools/testing/selftests/bpf/progs/test_get_stack_rawtp.c +1 -19
index b6a6eb279e5..41714c2182f 100644
@@ -29,29 +29,11 @@ struct {
 	__type(value, struct stack_trace_t);
 } stackdata_map SEC(".maps");
 
-/* Allocate per-cpu space twice the needed. For the code below
- *   usize = bpf_get_stack(ctx, raw_data, max_len, BPF_F_USER_STACK);
- *   if (usize < 0)
- *     return 0;
- *   ksize = bpf_get_stack(ctx, raw_data + usize, max_len - usize, 0);
- *
- * If we have value_size = MAX_STACK_RAWTP * sizeof(__u64),
- * verifier will complain that access "raw_data + usize"
- * with size "max_len - usize" may be out of bound.
- * The maximum "raw_data + usize" is "raw_data + max_len"
- * and the maximum "max_len - usize" is "max_len", verifier
- * concludes that the maximum buffer access range is
- * "raw_data[0...max_len * 2 - 1]" and hence reject the program.
- *
- * Doubling the to-be-used max buffer size can fix this verifier
- * issue and avoid complicated C programming massaging.
- * This is an acceptable workaround since there is one entry here.
- */
 struct {
 	__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
 	__uint(max_entries, 1);
 	__type(key, __u32);
-	__type(value, __u64[2 * MAX_STACK_RAWTP]);
+	__type(value, __u64[MAX_STACK_RAWTP]);
 } rawdata_map SEC(".maps");
 
 SEC("raw_tracepoint/sys_enter")
tools/testing/selftests/bpf/progs/verifier_arena_stack.c +55 -0

61 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_bounds_deduction.c +10 -4
index 14e10760606..63baf2fc61f 100644
@@ -21,8 +21,11 @@ l0_%=:	r0 -= r1;					\
 
 SEC("socket")
 __description("check deducing bounds from const, 2")
-__success __failure_unpriv
-__msg_unpriv("R1 has pointer with unsupported alu operation")
+__success __success_unpriv
+#ifdef SPEC_V1
+__xlated_unpriv("nospec")
+__xlated_unpriv("r1 -= r0")
+#endif
 __retval(1)
 __naked void deducing_bounds_from_const_2(void)
 {
@@ -53,8 +56,11 @@ l0_%=:	r0 -= r1;					\
 
 SEC("socket")
 __description("check deducing bounds from const, 4")
-__success __failure_unpriv
-__msg_unpriv("R6 has pointer with unsupported alu operation")
+__success __success_unpriv
+#ifdef SPEC_V1
+__xlated_unpriv("nospec")
+__xlated_unpriv("r6 -= r0")
+#endif
 __retval(0)
 __naked void deducing_bounds_from_const_4(void)
 {
tools/testing/selftests/bpf/progs/verifier_budget.c +6 -3
index 890b316166c..1bef19db503 100644
@@ -1874,14 +1874,17 @@ __naked void may_goto_stays_in_the_loop(void)
 	);
 }
 
-/* No state is within another one: the walk gets to the end of the loop, no may_goto */
+/* The loop has no trip count and no error asks for peeling: may_goto is added */
 SEC("socket")
 __description("budget: ten trips that differ")
 __success __retval(10) __log_level(2)
-__msg("processed 34 insns")
+__msg("processed {{[0-9][0-9]}} insns")
 __xlated("r8 += 1")
 __xlated("r7 <<= 1")
-__xlated("if r7 != 0x400 goto pc-3")
+__xlated("...")
+__xlated("if r13 == 0x0 goto")
+__xlated("...")
+__xlated("if r7 != 0x400 goto pc-{{[0-9]+}}")
 __naked void ten_trips_that_differ(void)
 {
 	asm volatile (
tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c +27 -7
index 7c3dc9643eb..7c29ffed743 100644
@@ -1060,16 +1060,36 @@ __naked void pkt_add_unknown_keeps_range(void)
 		     "r0 = *(u64*)(r2 + 8);");
 }
 
+#define PKT_ADD_NEGATIVE(off)						\
+	PKT_54_BYTES("if r4 > 8 goto l0_%=;"				\
+		     "r4 += -4;"					\
+		     "r2 += " #off ";"					\
+		     "r2 += r4;"					\
+		     "r0 = *(u8*)(r2 + 0);")
+
+/* The offset is 20 + (-4..4) = 16..24. 54 bytes are checked from the start of the packet. */
 SEC("tc")
 __description("direct packet access: checked pointer plus unknown that may be negative")
-__failure __msg("invalid access to packet, off=16 size=1, R2(id={{[0-9]+}},off=16,r=0)")
-__naked void pkt_add_negative_clears_range(void)
+__success __retval(0)
+__naked void pkt_add_negative(void)
 {
-	PKT_54_BYTES("if r4 > 8 goto l0_%=;"
-		     "r4 += -4;"
-		     "r2 += 20;"
-		     "r2 += r4;"
-		     "r0 = *(u8*)(r2 + 0);");
+	PKT_ADD_NEGATIVE(20);
+}
+
+SEC("tc")
+__description("direct packet access: the same before the packet")
+__failure __msg("R2 min value is negative")
+__naked void pkt_add_negative_below(void)
+{
+	PKT_ADD_NEGATIVE(3);
+}
+
+SEC("tc")
+__description("direct packet access: the same after what is checked")
+__failure __msg("invalid access to packet")
+__naked void pkt_add_negative_above(void)
+{
+	PKT_ADD_NEGATIVE(50);
 }
 
 /* The byte is in the packet, but a range that umax gets to is not kept */
tools/testing/selftests/bpf/progs/verifier_loop_walk.c +5 -3
index 4baf4717591..cd834d776d8 100644
@@ -65,17 +65,19 @@ WALKS(walks_32, 11)
 
 /*
  *	for (i = 7; i >= 0; i--) { if (i >= n) continue; a[i] = 0; }
- * A compiler tests 'i >= n' in front of the loop too and jumps into the middle of it. Such a loop
- * has no count. It's walked to its end whichever way its jumps go: no may_goto is added.
+ * A compiler tests 'i >= n' before the loop too and jumps into the middle of it. Such a loop
+ * has no trip count, so may_goto is added.
  */
 SEC("socket")
 __description("walk: a loop with two entries")
 __success __retval(0)
 __arch_x86_64
 __arch_arm64
+__xlated("if r13 == 0x0 goto")
+__xlated("...")
 __xlated("w3 += -1")
 __xlated("if w3 s< 0x0 goto pc+2")
-__xlated("if w3 < w2 goto pc-6")
+__xlated("if w3 < w2 goto pc-{{[0-9]+}}")
 __xlated("goto pc-4")
 __xlated("exit")
 __naked void two_entries(void)
tools/testing/selftests/bpf/progs/verifier_map_ptr.c +14 -4
index e0a65835c86..43fd9e26c76 100644
@@ -142,8 +142,13 @@ __naked void ptr_read_ops_field_accepted(void)
 
 SEC("socket")
 __description("bpf_map_ptr: r = 0, map_ptr = map_ptr + r")
-__success __failure_unpriv
-__msg_unpriv("R1 has pointer with unsupported alu operation")
+__success __success_unpriv
+#ifdef SPEC_V1
+__xlated_unpriv("r2 += -8")
+__xlated_unpriv("...")
+__xlated_unpriv("nospec")
+__xlated_unpriv("r1 += r0")
+#endif
 __retval(0)
 __naked void map_ptr_map_ptr_r(void)
 {
@@ -166,8 +171,13 @@ __naked void map_ptr_map_ptr_r(void)
 
 SEC("socket")
 __description("bpf_map_ptr: r = 0, r = r + map_ptr")
-__success __failure_unpriv
-__msg_unpriv("R0 has pointer with unsupported alu operation")
+__success __success_unpriv
+#ifdef SPEC_V1
+__xlated_unpriv("r2 += -8")
+__xlated_unpriv("...")
+__xlated_unpriv("nospec")
+__xlated_unpriv("r1 += r0")
+#endif
 __retval(0)
 __naked void _0_r_r_map_ptr(void)
 {
tools/testing/selftests/bpf/progs/verifier_spill_fill.c +9 -9
index 958ee0d6419..a7b11630eb6 100644
@@ -1208,14 +1208,14 @@ __naked void old_stack_misc_vs_cur_scalar(void)
 }
 
 /*
- * stacksafe(): the state with STACK_MISC is there, the state with a stack spill
- * of a non-scalar arrives. A program that may read uninitialized stack may
- * take a pointer for a number: the second state is within the first one.
+ * One state has STACK_MISC, the other one has a stack spill of a non-scalar.
+ * The slot is live, so the states stay apart.
  */
 SEC("socket")
 __success  __log_level(2)
 __msg("8: (79) r1 = *(u64 *)(r10 -8)         ; R1=scalar()")
-__msg("processed 10 insns")
+__msg("8: (79) r1 = *(u64 *)(r10 -8)         ; R1=ctx()")
+__msg("processed 12 insns")
 __naked void old_stack_misc_vs_cur_ctx_ptr(void)
 {
 	asm volatile(
@@ -1233,7 +1233,7 @@ __naked void old_stack_misc_vs_cur_ctx_ptr(void)
 	"*(u64*)(r10 - 8) = r0;"
 	"lock *(u64*)(r10 - 8) += r0;"
 "2:"
-	/* read fp-8, it's looked at once */
+	/* read fp-8 */
 	"r1 = *(u64*)(r10 - 8);"
 	"exit;"
 	:
@@ -1399,11 +1399,11 @@ __naked void var_off_write_over_scalar_spill(void)
 
 SEC("socket")
 __description("partial fill from cleaned pointer spill")
-__failure
+__success __caps_unpriv(CAP_BPF) __failure_unpriv
 __log_level(2)
-__msg("1: (05) goto pc+0")
-__msg("2: (61) r0 = *(u32 *)(r10 -4)")
-__msg("invalid size of register fill")
+__msg_unpriv("1: (05) goto pc+0")
+__msg_unpriv("2: (61) r0 = *(u32 *)(r10 -4)")
+__msg_unpriv("invalid size of register fill")
 __flag(BPF_F_TEST_STATE_FREQ)
 __naked void partial_fill_from_cleaned_pointer_spill(void)
 {
tools/testing/selftests/bpf/progs/verifier_trip_count.c +16 -10
index c8e3ddbc530..69288309ef0 100644
@@ -2751,13 +2751,13 @@ __naked void uninit_slot_counter(void)
  *
  * R7 is always 10 at the real exit. Widening loses the correlation between
  * R6 and R7, leaving R7 in [5, 10] both at the loop header and after the loop.
- * The verifier therefore rejects the possible invalid stack read.
+ * Pass 0 does not prove the read. A later pass peels the trips and does not get to it.
  */
 SEC("xdp")
-__failure
+__success __retval(0)
 __log_level(2)
-__msg("2: {{.*}}R7=scalar(smin=umin=smin32=umin32=5,smax=umax=smax32=umax32=10,var_off=(0x0; 0xf))")
-__msg("7: R7=scalar(smin=umin=smin32=umin32=5,smax=umax=smax32=umax32=10,var_off=(0x0; 0xf))")
+__msg("2: {{.*}}R7=scalar(smin=umin=smin32=umin32=5,smax=umax=smax32=umax32=10,var_off=(0x0; 0xf)")
+__msg("7: R7=scalar(smin=umin=smin32=umin32=5,smax=umax=smax32=umax32=10,var_off=(0x0; 0xf)")
 __msg("invalid read from stack R10 off=0 size=8")
 __naked void conditional_assignment_on_second_iteration(void)
 {
@@ -3387,9 +3387,11 @@ LINKED(dividend_tested, VALID,
 LINKED(operand_is_overwritten, MAP_OOB,
 	"r9 = r7; r9 *= 8; call %[bpf_get_prandom_u32]; r7 = r0; r7 &= 255;"
 	"if r7 > 7 goto out_%=; r1 = r6; r1 += r9;")
-/* a pointer is evaluated below an add only */
-LINKED(pointer_minus_index, __failure,
+/* r7 is 0..63, so 63 - r7 is 0..63 */
+LINKED(pointer_minus_index, VALID,
 	"r1 = r6; r1 += 63; r1 -= r7; if r7 > 63 goto out_%=;" USE_R6)
+LINKED(pointer_minus_index_oob, __failure __msg("R1 min value is"),
+	"r1 = r6; r1 += 63; r1 -= r7; if r7 > 64 goto out_%=;" USE_R6)
 /* r3 is an address as a scalar. r6 + r7 * 2 has the offset [0, 14]: that is not the range of r3 */
 LINKED(offset_of_pointer_is_not_scalar, UNBOUND,
 	"r2 = r7; r2 *= 2; r5 = r6; r5 += r2; r3 = r5; r3 = le64 r3; if r7 > 7 goto out_%=;"
@@ -3418,14 +3420,17 @@ static __naked __noinline __used void name(void)				\
 	"if r3 <= 63 goto +2; r3 = 0; *(u64 *)(r1 + 0) = r3; r0 = 0; exit;"	\
 	::: __clobber_all);							\
 }
-#define CALL(callee)								\
-	"*(u64 *)(r10 - 16) = r8; r1 = r10; r1 += -16; r4 = r1; r2 = r8; r2 >>= 1;"	\
+#define CALL_R2(set_r2, callee)							\
+	"*(u64 *)(r10 - 16) = r8; r1 = r10; r1 += -16; r4 = r1;" set_r2		\
 	"call " #callee "; r2 = *(u64 *)(r10 - 16); r1 = r6; r1 += r2;"
+#define CALL(callee)	CALL_R2("r2 = r8; r2 >>= 1;", callee)
 
 CLAMP(clamp, "")
 LINKED(callee_tests_memory_of_caller, VALID, CALL(clamp))
 CLAMP(store_and_clamp, "*(u64 *)(r1 + 0) = r2;")
-LINKED(callee_writes_memory_of_caller, __failure, CALL(store_and_clamp))
+/* It tests r8 and stores r8 / 2. If r8 is 0..63 then r8 / 2 is 0..31. Else it stores 0. */
+LINKED(callee_writes_memory_of_caller, VALID, CALL(store_and_clamp))
+LINKED(callee_writes_memory_of_caller_oob, MAP_OOB, CALL_R2("r2 = r7;", store_and_clamp))
 /* a store defines the memory */
 CLAMP(store_and_test, "r3 = r2; *(u64 *)(r1 + 0) = r3;")
 LINKED(callee_tests_what_it_stored, VALID, CALL(store_and_test))
@@ -3434,7 +3439,8 @@ CLAMP(store_next_and_clamp, "*(u64 *)(r1 + 8) = r2;")
 LINKED(callee_writes_next_field, VALID, CALL(store_next_and_clamp))
 /* another address base can be another name of the memory */
 CLAMP(store_alias_and_clamp, "*(u64 *)(r4 + 0) = r2;")
-LINKED(callee_writes_through_alias, __failure, CALL(store_alias_and_clamp))
+LINKED(callee_writes_through_alias, VALID, CALL(store_alias_and_clamp))
+LINKED(callee_writes_through_alias_oob, MAP_OOB, CALL_R2("r2 = r7;", store_alias_and_clamp))
 static __naked __noinline __used void clamp_through_r0(void)
 {
 	asm volatile (
tools/testing/selftests/bpf/progs/verifier_unpriv.c +1 -2
index 7b1f830e5e2..2d5a0263853 100644
@@ -286,8 +286,7 @@ __naked void mangle_pointer_on_stack_2(void)
 
 SEC("socket")
 __description("unpriv: read pointer from stack in small chunks")
-__failure __msg("invalid size")
-__failure_unpriv
+__success __failure_unpriv __msg_unpriv("invalid size")
 __naked void from_stack_in_small_chunks(void)
 {
 	asm volatile ("					\
tools/testing/selftests/bpf/progs/verifier_value_ptr_arith.c +54 -12

102 lines not on this page · raw message

Signature · 1 line
2.55.0
#60 lore raw

PATCH v2 46/49 selftests/bpf: Test barriers and far pointers

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

verifier_barrier.c: check the place of the barrier for each kind of
edge: inlined bpf_loop(), exit of a callback, may_goto, recursion, a call that never returns, far jumps.
Check what a speculative state must not decide for other states. Check that a far pointer gives no compare, no access and no constant offset. Check the log of a dropped path, of a leak and of a speculative state.

far_map_value.c: a load through a far pointer to a read-only map value is not folded to a constant.

verifier_btf_array_access.c, verifier_load_acquire.c: a far load from a flexible array gets a fault handler, a far load-acquire is rejected.

---
 .../selftests/bpf/prog_tests/far_map_value.c  |  38 +
 .../selftests/bpf/prog_tests/verifier.c       |   2 +
 .../selftests/bpf/progs/verifier_barrier.c    | 849 ++++++++++++++++++
 .../bpf/progs/verifier_btf_array_access.c     |  53 ++
 .../bpf/progs/verifier_load_acquire.c         |  19 +
 5 files changed, 961 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/prog_tests/far_map_value.c
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_barrier.c
tools/testing/selftests/bpf/prog_tests/far_map_value.c new file +38 -0
new file mode 100644
index 00000000000..f2fb2aaaa26
@@ -0,0 +1,38 @@
+// SPDX-License-Identifier: GPL-2.0
+
+#include <test_progs.h>
+
+#define FAR_OFF		(1 << 29)	/* BPF_MAX_VAR_OFF */
+
+/* See far_rodata in verifier_barrier.c. Here ld_imm64 makes the far pointer. */
+void serial_test_far_map_value(void)
+{
+	LIBBPF_OPTS(bpf_map_create_opts, opts, .map_flags = BPF_F_RDONLY_PROG);
+	struct bpf_insn insns[] = {
+		BPF_LD_MAP_VALUE(BPF_REG_1, 0, FAR_OFF),
+		BPF_ALU64_IMM(BPF_ADD, BPF_REG_1, -16),
+		BPF_LDX_MEM(BPF_B, BPF_REG_2, BPF_REG_1, 0),
+		BPF_MOV64_IMM(BPF_REG_3, 2),
+		BPF_ALU64_IMM(BPF_MUL, BPF_REG_3, 2),
+		BPF_MOV64_IMM(BPF_REG_0, 0),
+		BPF_JMP_REG(BPF_JNE, BPF_REG_2, BPF_REG_3, 1),
+		BPF_MOV64_REG(BPF_REG_0, BPF_REG_2),
+		BPF_EXIT_INSN(),
+	};
+	int map_fd, prog_fd;
+
+	map_fd = bpf_map_create(BPF_MAP_TYPE_ARRAY, NULL, 4, FAR_OFF + 8, 1, &opts);
+	if (map_fd == -ENOMEM) {
+		test__skip();
+		return;
+	}
+	if (!ASSERT_GE(map_fd, 0, "map_create"))
+		return;
+	ASSERT_OK(bpf_map_freeze(map_fd), "map_freeze");
+	insns[0].imm = map_fd;
+	prog_fd = bpf_prog_load(BPF_PROG_TYPE_SOCKET_FILTER, NULL, "GPL", insns,
+				ARRAY_SIZE(insns), NULL);
+	if (ASSERT_GE(prog_fd, 0, "prog_load"))
+		close(prog_fd);
+	close(map_fd);
+}
tools/testing/selftests/bpf/prog_tests/verifier.c +2 -0
index 67151c55b03..ab15e69a622 100644
@@ -21,6 +21,7 @@
 #include "verifier_arena_globals2.skel.h"
 #include "verifier_array_access.skel.h"
 #include "verifier_async_cb_context.skel.h"
+#include "verifier_barrier.skel.h"
 #include "verifier_basic_stack.skel.h"
 #include "verifier_bitfield_write.skel.h"
 #include "verifier_bounds.skel.h"
@@ -231,6 +232,7 @@ void test_verifier_arena_stack(void)          { RUN_TESTS(verifier_arena_stack);
 void test_verifier_arena_large(void)          { RUN(verifier_arena_large); }
 void test_verifier_arena_globals1(void)       { RUN(verifier_arena_globals1); }
 void test_verifier_arena_globals2(void)       { RUN(verifier_arena_globals2); }
+void test_verifier_barrier(void)              { RUN(verifier_barrier); }
 void test_verifier_basic_stack(void)          { RUN(verifier_basic_stack); }
 void test_verifier_bitfield_write(void)       { RUN(verifier_bitfield_write); }
 void test_verifier_bounds(void)               { RUN(verifier_bounds); }
tools/testing/selftests/bpf/progs/verifier_barrier.c new file +849 -0

849 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_btf_array_access.c +53 -0

59 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_load_acquire.c +19 -0
index bcc34e798c6..46ddd3f5b1b 100644
@@ -249,6 +249,25 @@ int load_acquire_from_rdonly_untrusted_mem(void *ctx)
 	return 0;
 }
 
+/* struct mm_struct ends with a flexible array of bytes */
+SEC("tp_btf/exit_mmap")
+__description("load-acquire at a far offset of a trusted pointer")
+__failure __msg("BPF_ATOMIC loads from R1 {{.*}} is not allowed")
+__naked void load_acquire_far_offset(void)
+{
+	asm volatile (
+	"r1 = *(u64 *)(r1 + 0);"
+	"r2 = 0x10000000000 ll;"
+	"r1 += r2;"
+	".8byte %[load_acquire_insn];" // w0 = load_acquire((u8 *)(r1 + 0));
+	"r0 = 0;"
+	"exit;"
+	:
+	: __imm_insn(load_acquire_insn,
+		     BPF_ATOMIC_OP(BPF_B, BPF_LOAD_ACQ, BPF_REG_0, BPF_REG_1, 0))
+	: __clobber_all);
+}
+
 SEC("socket")
 __description("load-acquire with invalid register R15")
 __failure __failure_unpriv __msg("R15 is invalid")
Signature · 1 line
2.55.0
#61 lore raw

PATCH v2 47/49 selftests/bpf: Test passes, instances, precision and the failing path

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

verifier_passes.c has one group for each mechanism, for example deps, live types, unreadable, peel, trip count, ids, instances, held, fixups, pessimized, strings, failing_path, budget, log. verifier_partition.c tests the order of the partitions, the undo, the suspect loops, calls in frames, the load of a part of a spilled pointer and arrays of pointers on the stack. Many valid programs have an unsafe twin that has to be rejected.

liveness_many_calls has 12000 calls. verifier_callx_rodata.c tests an error in one function of a set.

---
 .../selftests/bpf/prog_tests/verifier.c       |    4 +
 .../bpf/progs/verifier_callx_rodata.c         |  130 +
 .../bpf/progs/verifier_liveness_exp.c         |   48 +
 .../selftests/bpf/progs/verifier_partition.c  | 1555 +++++++
 .../selftests/bpf/progs/verifier_passes.c     | 3758 +++++++++++++++++
 .../bpf/progs/verifier_subprog_insn_stats.c   |   14 +
 .../selftests/bpf/progs/verifier_var_off.c    |   46 +
 7 files changed, 5555 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_partition.c
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_passes.c
tools/testing/selftests/bpf/prog_tests/verifier.c +4 -0
index ab15e69a622..da112954a74 100644
@@ -112,6 +112,7 @@
 #include "verifier_netfilter_retcode.skel.h"
 #include "verifier_bpf_fastcall.skel.h"
 #include "verifier_or_jmp32_k.skel.h"
+#include "verifier_passes.skel.h"
 #include "verifier_no_limits.skel.h"
 #include "verifier_patch_list.skel.h"
 #include "verifier_percpu_addr.skel.h"
@@ -120,6 +121,7 @@
 #include "verifier_private_stack.skel.h"
 #include "verifier_ptr_off.skel.h"
 #include "verifier_ptr_to_buf.skel.h"
+#include "verifier_partition.skel.h"
 #include "verifier_raw_stack.skel.h"
 #include "verifier_raw_tp_writable.skel.h"
 #include "verifier_reg_equal.skel.h"
@@ -324,6 +326,7 @@ void test_verifier_netfilter_retcode(void)    { RUN(verifier_netfilter_retcode);
 void test_verifier_bpf_fastcall(void)         { RUN(verifier_bpf_fastcall); }
 void test_verifier_no_limits(void)            { RUN_JITED(verifier_no_limits); }
 void test_verifier_or_jmp32_k(void)           { RUN(verifier_or_jmp32_k); }
+void test_verifier_passes(void)               { RUN(verifier_passes); }
 /*
  * Run serially with bpf_jit_harden at 0: blinding changes the xlated insns that
  * the tests compare, and other tests set the sysctl.
@@ -344,6 +347,7 @@ void test_verifier_prevent_map_lookup(void)   { RUN(verifier_prevent_map_lookup)
 void test_verifier_private_stack(void)        { RUN(verifier_private_stack); }
 void test_verifier_ptr_off(void)              { RUN(verifier_ptr_off); }
 void test_verifier_ptr_to_buf(void)           { RUN(verifier_ptr_to_buf); }
+void test_verifier_partition(void)            { RUN(verifier_partition); }
 void test_verifier_raw_stack(void)            { RUN(verifier_raw_stack); }
 void test_verifier_raw_tp_writable(void)      { RUN(verifier_raw_tp_writable); }
 void test_verifier_reg_equal(void)            { RUN(verifier_reg_equal); }
tools/testing/selftests/bpf/progs/verifier_callx_rodata.c +130 -0

148 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_liveness_exp.c +48 -0

51 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_partition.c new file +1555 -0

1,555 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_passes.c new file +3758 -0

1,218 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_subprog_insn_stats.c +14 -0
index e7636b86cc2..e08f0501a25 100644

Lines of this file are not shown. View the raw message.

tools/testing/selftests/bpf/progs/verifier_var_off.c +46 -0

46 lines not on this page · raw message

The rest of this diff is not shown. View the raw message.

Signature · 1 line
2.55.0

Part of the diff is not shown here. View the raw message.

#62 lore raw

PATCH v2 48/49 selftests/bpf: Test equations

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

verifier_equations.c has one group for each kind of insn: truncation, AND, op, shift, division, spill. It also tests joins, rings such as '(i + 1) & 63', irreducible loops, the join rule, steps, an int that goes through 0, sign extensions, the distance of two pointers, packet pointers, far pointers, new ids, speculation past a stored condition, a number that grows in two loops, right and wrong steps from the code of a loop, the offset and the size of a memory argument, a test against the rest of a buffer, and a test of the carry.
INDEX_TEST() makes two programs: the array is large enough for the index, and the array is too small.

The other files get tests for the trip index, thresholds, atomic insns, packet pointers that share an id or have two lengths, hidden registers, division, and an AND that splits the state.

---
 .../selftests/bpf/prog_tests/verifier.c       |    2 +
 .../selftests/bpf/progs/verifier_and.c        |  150 ++
 .../bpf/progs/verifier_arena_stack.c          |   50 +
 .../bpf/progs/verifier_bounds_step.c          |   53 +
 .../bpf/progs/verifier_bpf_fastcall.c         |   33 +
 .../bpf/progs/verifier_direct_packet_access.c |  145 ++
 .../bpf/progs/verifier_div_mod_bounds.c       |   28 +
 .../selftests/bpf/progs/verifier_equations.c  | 1583 +++++++++++++++++
 .../bpf/progs/verifier_linked_scalars.c       |  144 ++
 .../selftests/bpf/progs/verifier_movsx.c      |   20 +
 .../selftests/bpf/progs/verifier_spill_fill.c |   26 +
 .../selftests/bpf/progs/verifier_trip_count.c |  501 ++++++
 12 files changed, 2735 insertions(+)
 create mode 100644 tools/testing/selftests/bpf/progs/verifier_equations.c
tools/testing/selftests/bpf/prog_tests/verifier.c +2 -0
index da112954a74..22e948cf66e 100644
@@ -60,6 +60,7 @@
 #include "verifier_div_const.skel.h"
 #include "verifier_div_mod_bounds.skel.h"
 #include "verifier_div_overflow.skel.h"
+#include "verifier_equations.skel.h"
 #include "verifier_flow_keys.skel.h"
 #include "verifier_global_subprogs.skel.h"
 #include "verifier_global_ptr_args.skel.h"
@@ -274,6 +275,7 @@ void test_verifier_div0(void)                 { RUN(verifier_div0); }
 void test_verifier_div_const(void)            { RUN(verifier_div_const); }
 void test_verifier_div_mod_bounds(void)       { RUN(verifier_div_mod_bounds); }
 void test_verifier_div_overflow(void)         { RUN(verifier_div_overflow); }
+void test_verifier_equations(void)            { RUN(verifier_equations); }
 void test_verifier_flow_keys(void)            { RUN(verifier_flow_keys); }
 void test_verifier_global_subprogs(void)      { RUN(verifier_global_subprogs); }
 void test_verifier_global_ptr_args(void)      { RUN(verifier_global_ptr_args); }
tools/testing/selftests/bpf/progs/verifier_and.c +150 -0

154 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_arena_stack.c +50 -0

56 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_bounds_step.c +53 -0

57 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_bpf_fastcall.c +33 -0
index 314652a0006..2120f4e71fb 100644
@@ -671,6 +671,39 @@ __naked void helper_zero_size_buffer(void)
 	: __clobber_all);
 }
 
+/* The size is 0 only at the largest offset. The other offsets touch the stack. */
+SEC("raw_tp")
+__arch_x86_64
+__log_level(4)
+__msg("subprog 0 (helper_zero_size_at_max_offset) main {{.*}} stack 128")
+__success
+__naked void helper_zero_size_at_max_offset(void)
+{
+	asm volatile (
+	"call %[bpf_ktime_get_ns];"
+	"r6 = r0;"
+	"if r6 > 128 goto 1f;"
+	"r1 = 1;"
+	"*(u64 *)(r10 - 8) = r1;"
+	"call %[bpf_get_smp_processor_id];"
+	"r1 = *(u64 *)(r10 - 8);"
+	"r1 = r10;"
+	"r1 += -128;"
+	"r1 += r6;"
+	"r2 = 128;"
+	"r2 -= r6;"
+	"r3 = 0;"
+	"call %[bpf_probe_read_kernel];"
+"1:"
+	"r0 = 0;"
+	"exit;"
+	:
+	: __imm(bpf_get_smp_processor_id),
+	  __imm(bpf_ktime_get_ns),
+	  __imm(bpf_probe_read_kernel)
+	: __clobber_all);
+}
+
 SEC("raw_tp")
 __arch_x86_64
 /* main, not patched */
tools/testing/selftests/bpf/progs/verifier_direct_packet_access.c +145 -0

155 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_div_mod_bounds.c +28 -0
index e814a054d69..4040e71c2d3 100644
@@ -1149,3 +1149,31 @@ l0_%=:	r0 = *(u64 *)(r1 + 0);				\
 	: __imm_const(llong_min, LLONG_MIN)
 	: __clobber_all);
 }
+
+/* r6 is computed from r7, then r7 is tested: 0..200. The division is reached if r6 > @max. */
+#define OP_THEN_TEST(op, max)				\
+	asm volatile ("					\
+	call %[bpf_ktime_get_ns];			\
+	r7 = r0;					\
+	r6 = r0;					\
+	" op ";						\
+	if r7 > 200 goto l0_%=;				\
+	if r6 <= " #max " goto l0_%=;			\
+	r0 /= 0;					\
+l0_%=:	r0 = 0;						\
+	exit;						\
+"	:						\
+	: __imm(bpf_ktime_get_ns)			\
+	: __clobber_all)
+
+#define TEST_OP(name, op, max, below)			\
+SEC("socket") __success					\
+__naked void name(void) { OP_THEN_TEST(op, max); }	\
+SEC("socket") __failure __msg("div by zero")		\
+__naked void name##_bad(void) { OP_THEN_TEST(op, below); }
+
+TEST_OP(rsh32_of_wide, "w6 >>= 2", 50, 49)
+TEST_OP(div32_of_wide, "w6 /= 5", 40, 39)
+TEST_OP(mod32_of_wide, "w6 %%= 1000", 200, 199)
+TEST_OP(rsh_by_0, "r6 >>= 0", 200, 199)
+TEST_OP(div_by_1, "r6 /= 1", 200, 199)
tools/testing/selftests/bpf/progs/verifier_equations.c new file +1583 -0

1,583 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_linked_scalars.c +144 -0

154 lines not on this page · raw message

tools/testing/selftests/bpf/progs/verifier_movsx.c +20 -0
index 44730109db5..0197c2c21b8 100644
@@ -526,6 +526,26 @@ label_%=: 	                                        \
 	: __clobber_all);
 }
 
+/* The source is even, so the result is even */
+#define KEEPS_LOW_BIT(name, insns)				\
+SEC("socket")							\
+__success __retval(0)						\
+__naked void name(void)						\
+{								\
+	asm volatile (						\
+	"call %[bpf_get_prandom_u32];"				\
+	insns							\
+	"r0 &= 1;"						\
+	"if r0 == 0 goto 1f;"					\
+	"r0 /= 0;"						\
+	"1: exit;"						\
+	:: __imm(bpf_get_prandom_u32) : __clobber_all);		\
+}
+
+KEEPS_LOW_BIT(mov64sx_s8_one_sign_keeps_low_bit, "r0 &= 0x7e; r0 |= 0x100; r0 = (s8)r0;")
+KEEPS_LOW_BIT(mov32sx_s8_one_sign_keeps_low_bit, "w0 &= 0x7e; w0 |= 0x100; w0 = (s8)w0;")
+KEEPS_LOW_BIT(mov32sx_s8_keeps_low_bit, "w0 &= -2; w0 = (s8)w0;")
+
 #else
 
 SEC("socket")
tools/testing/selftests/bpf/progs/verifier_spill_fill.c +26 -0
index a7b11630eb6..56a316d787a 100644
@@ -1486,6 +1486,32 @@ FIRST_HALF(spill_of_64_bits_vs_spill_of_32_bits,
 	   "r6 = r0; r6 <<= 32; if r0 > 5 goto 1f; *(u32 *)(r10 - 8) = r6; goto 2f;"
 	   "1: r6 = 0x7ffffff000000000 ll; *(u64 *)(r10 - 8) = r6; 2:")
 
+#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+/* The low 16 bits of the fill are from the spill */
+#define FILL_32_SPILL_16(mask)							\
+	asm volatile (								\
+	"call %[bpf_ktime_get_ns];"						\
+	"*(u64 *)(r10 - 8) = r0; r1 = 5; *(u16 *)(r10 - 8) = r1;"		\
+	"r1 = *(u32 *)(r10 - 8); r1 &= " #mask ";"				\
+	"if r1 == 5 goto 1f; r0 /= 0;"						\
+	"1: r0 = 0; exit;"							\
+	:: __imm(bpf_ktime_get_ns) : __clobber_all)
+
+SEC("raw_tp")
+__success
+__naked void fill_32_bits_spill_16_bits(void)
+{
+	FILL_32_SPILL_16(0xffff);
+}
+
+SEC("raw_tp")
+__failure __msg("div by zero")
+__naked void fill_32_bits_spill_16_bits_bad(void)
+{
+	FILL_32_SPILL_16(0x1ffff);
+}
+#endif
+
 /* check valid spill/fill, ptr to tp buffer */
 SEC("raw_tracepoint.w")
 __success
tools/testing/selftests/bpf/progs/verifier_trip_count.c +501 -0

511 lines not on this page · raw message

Signature · 1 line
2.55.0
#63 lore raw

Re: [PATCH bpf-next v2 48/49] selftests/bpf: Test equations

TL;DR: Test issue: in verifier_equations.c, the __msg() on past_64k_keeps_range_bad is written inline, so it likely always matches the logged source line and may not check the intended packet-range…
Quoted 1 line

selftests/bpf: Test equations

TL;DR: Test issue: in verifier_equations.c, the __msg() on past_64k_keeps_range_bad is written inline, so it likely always matches the logged source line and may not check the intended packet-range error; use BAD_PKT.

Quoted 5 lines
tools/testing/selftests/bpf/progs/verifier_equations.c new file +0 -0
new file mode 100644
index 000000000000..e88d6ff0ca8e

[ ... ]

tools/testing/selftests/bpf/progs/verifier_equations.c line 1034

Quoted 4 lines
tools/testing/selftests/bpf/progs/verifier_equations.c new file +4 -0
+AWAY_AND_BACK(near_pointer_keeps_range, __success, 1000, 7)
+AWAY_AND_BACK(near_pointer_keeps_range_bad, BAD_PKT, 1000, 8)
+AWAY_AND_BACK(past_64k_keeps_range, __success, 70000, 7)
+AWAY_AND_BACK(past_64k_keeps_range_bad, __failure __msg("invalid access to packet"), 70000, 8)

Is the __msg() check for past_64k_keeps_range_bad able to fail? The header comment of this file says:

The log has the first source line of a macro call. If __msg() is in that line, the log always matches it.

and BAD_PKT exists so that the expected text is not written on that line.

Here "invalid access to packet" is written inline on the AWAY_AND_BACK() line. The rejected load is retried with log_level 1, and verbose_linfo() prints that source line into the log:

; AWAY_AND_BACK(past_64k_keeps_range_bad, __failure __msg("invalid access to packet"), 70000, 8)

so the strstr() in validate_msgs() always finds the pattern. The subtest then passes for any rejection of the program, for example a failure that only shows up with the far 70000 offset, not just the packet range error at off 8.

Would using BAD_PKT here, as near_pointer_keeps_range_bad does, make the message check real?

AWAY_AND_BACK(past_64k_keeps_range_bad, BAD_PKT, 70000, 8)

Quoted 1 line

+AWAY_AND_BACK(before_64k_keeps_range, __success, -70000, 7)

[ ... ]

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

#64 lore raw

PATCH v2 49/49 bpf, docs: Rewrite verifier.rst

In reply to Alexei Starovoitov

From: Alexei Starovoitov <[email protected]>

The document describes a walk over paths with pruning. The verifier does not work that way. The types, the log text and the errors are old too.

Write it from scratch, in reading order, with examples:

  overview     the main idea, proof and guess
  state        numbers, pointers, ids, the stack, what is held
  one insn     the checks, packets
  pass         liveness, prune, join, join_key, the order
  precision    data and control deps, the join rule, on one example
  equations    insn, jump, call, join, prune
  loops        widening, trip index, may_goto, peel, suspects
  functions    instances, callbacks, recursion
  errors       partition, fork, budget, failing path, all passes
  the rest     fixups, speculation, limits, what is trusted, the log

Update the limits and one reference in bpf_design_QA.rst.

---
 Documentation/bpf/bpf_design_QA.rst |    6 +-
 Documentation/bpf/verifier.rst      | 2008 ++++++++++++++++++++-------
 2 files changed, 1497 insertions(+), 517 deletions(-)
Documentation/bpf/bpf_design_QA.rst +3 -3
index f86b272920a..4956c2741cb 100644
@@ -94,8 +94,8 @@ It's the maximum number of instructions that the unprivileged bpf
 program can have. The verifier has various internal limits.
 The largest program can consist of 1 million instructions.
 There is a limit to the number of nested bpf-to-bpf
-calls, a limit to the number of the verifier states per instruction,
-a limit to the number of maps used by the program.
+calls, a limit to the work of the verifier and a limit to its memory.
+See 'Limits' in Documentation/bpf/verifier.rst.
 All these limits can be hit with a sufficiently complex program.
 There are also non-numerical limits that can cause the program
 to be rejected. The verifier used to recognize only pointer + constant
@@ -121,7 +121,7 @@ C code cannot express them and has to use builtin intrinsics?
 
 A: This is artifact of compatibility with classic BPF. Modern
 networking code in BPF performs better without them.
-See 'direct packet access'.
+See 'Packets' in Documentation/bpf/verifier.rst.
 
 Q: BPF instructions mapping not one-to-one to native CPU
 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Documentation/bpf/verifier.rst +1494 -514

2,054 lines not on this page · raw message

Signature · 1 line
2.55.0
#65 lore raw

Re: [PATCH bpf-next v2 49/49] bpf, docs: Rewrite verifier.rst

TL;DR: Docs nit in verifier.rst: the "what stops it" column for loops omits iterators, which the review says also end a loop without a trip count or may_goto, so it may mislead readers.
Quoted 1 line

bpf, docs: Rewrite verifier.rst

TL;DR: Docs nit in verifier.rst: the "what stops it" column for loops omits iterators, which the review says also end a loop without a trip count or may_goto, so it may mislead readers.

Quoted 3 lines
Documentation/bpf/verifier.rst +0 -0

[ ... ]

Documentation/bpf/verifier.rst line 911

Quoted 13 lines
Documentation/bpf/verifier.rst +13 -0
+Calls that go around
+--------------------
+
+The calls of a callback and recursive calls go around like the body of a loop.
+They use the same code: join, widen, peel.
+
+==================  ============================  ==============================
+kind                header                        what stops it
+==================  ============================  ==============================
+loop                the target of the back edge   trip count or ``may_goto``
+callback            the call of the helper        the helper
+recursion           the start of the function     a check at run time
+==================  ============================  ==============================

Is the "what stops it" entry for loop complete? An iterator loop also stops without a trip count or may_goto. In kernel/bpf/flow.c, flow_is_bound() treats the iterator's next insn like may_goto:

    if (bpf_is_may_goto_insn(insn)) { ... }
    if (!bpf_insn_is_iter_next(env, insn))
            return false;

and flow_loop_is_bounded() uses that to accept a bpf_for()/bpf_iter_* loop with no trip count and no added may_goto.

This same document lists the iterator as its own case in the table in "The loop must end" ("each trip takes from an iterator / an iterator has an end"), and says "An iterator is assumed to stop its loop." in "A pass assumes what stops a loop".

A reader comparing loops with callbacks and recursion here would conclude that an iterator loop needs a trip count or gets may_goto. Would something like "trip count, iterator or ``may_goto``" fit in the 30 character column?

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