← Writing

The Verifier Said No

57 min readSystemsEbpfLinuxKernelCVerifier
Contents

A loop that clears the lowest set bit of a 32-bit number until none are left cannot go round more than 32 times, and any C programmer can see it. The Linux 5.15 verifier went round it 166,665 times, spent its entire budget of a million instructions, and refused to load the program. I added a second condition, that a counter stay below 64, a bound the loop can never even reach, and the same kernel accepted the program after checking 707 instructions.

That is the verifier in one example: it is not trying to understand your program, only to prove a handful of things about it, and it proves them by walking it, path by path, with a model of every register. This post opens that model up, from the kernel’s own source, and then breaks it in every way I could find, so that the next time it says no, the message means something.

This is Part 4 of a series on eBPF, written for C programmers who know what a process, a system call and a socket are, and nothing about kernel internals. Everything here ran on Ubuntu 22.04’s release kernel, 5.15.0-25-generic, with the 22.04 userland (clang 14, libbpf 0.5), except the bpf_loop measurements, which need 5.17 or later and ran on the mainline 5.18 build. Every log is pasted from those runs. The note at the end says exactly where and how.

What the verifier promises

Part 1 ended with the verifier refusing a program that dereferenced a pointer which might be NULL, and stated its one rule: every memory access must be provably safe on every path. That rule is the one people meet first, but the verifier proves a little more than that before a program may run. On the kernel I’m using, it establishes that:

  • the program terminates: there is no path that runs forever;
  • every memory access is in bounds and to memory of the right kind: the program’s own stack, a map value, a packet between its start and end, the fields of its context it may read;
  • nothing is read before it is written: no register or stack byte is used uninitialised;
  • every helper call is allowed for this program type and licence, and its arguments have the types the helper expects;
  • every kernel object the program acquires is released, such as a socket reference;
  • for unprivileged programs only, no kernel address escapes to user space.

What it does not promise is that the program is correct. A program that counts the wrong thing loads fine. The verifier cares about the kernel, not about you.

It also does not, and cannot, decide these questions exactly. Whether an arbitrary program terminates is the halting problem. So the verifier answers a narrower question: can I prove, with the rules I have, that this program is safe? When the answer is “I can’t tell”, it says no. Every rejection in this post is that kind of no. Most of them are about programs that are perfectly safe, written in a way the verifier cannot see through. Learning to write BPF is largely learning which ways those are.

The code is one file, kernel/bpf/verifier.c, 13,901 lines in 5.15. Its entry point, bpf_check(), runs when user space calls bpf(BPF_PROG_LOAD, ...). Condensed to the calls that matter here, it does this:

/* kernel/bpf/verifier.c (5.15), bpf_check(), condensed; the comments are mine */
ret = add_subprog_and_kfunc(env);   /* find the functions inside the program */
ret = check_subprogs(env);          /* no jumps between them */
ret = resolve_pseudo_ldimm64(env);  /* map fds become map pointers */
ret = check_cfg(env);               /* pass 1: the shape of the program */
ret = do_check_subprogs(env);
ret = ret ?: do_check_main(env);    /* pass 2: walk every path */
...
ret = convert_ctx_accesses(env);    /* rewrite context field accesses */
ret = do_misc_fixups(env);          /* inline helpers, like Part 1's map lookup */
...
print_verification_stats(env);      /* "processed N insns ..." */

Two passes do the proving: check_cfg, which looks at the program as a graph, and do_check, which runs it symbolically. Everything after them rewrites a program that has already been accepted. Before we take the passes one at a time, a tool for watching them.

Asking for the log

The verifier writes a log only if the loader asks for one, and how much depends on a level the loader passes in bpf_attr.log_level, a bit field:

  • 1 prints the instructions on the path that failed, with register states where paths split;
  • 2 prints the full register state after every instruction on every path;
  • 4 prints statistics only: time, stack depth and the instruction count.

libbpf, the loader from Part 1, asks for a level-1 log by itself when a load fails, which is the log Part 1 printed. To see the log of programs that pass, and to choose the level, I used this small loader for every listing in this post. Ubuntu 22.04’s libbpf 0.5 takes the level through bpf_object__load_xattr, and prints the log of a successful load at its debug level, so the print callback lets debug messages through only if they are that log:

// vload.c — load every program in a BPF object file and print the verifier's log
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <bpf/libbpf.h>

static int print(enum libbpf_print_level level, const char *fmt, va_list ap)
{
	/* libbpf's own chatter is debug-level; keep only the verifier log
	 * (printed at debug level on success) and warnings (failures) */
	if (level == LIBBPF_DEBUG && !strstr(fmt, "verifier log"))
		return 0;
	return vfprintf(stdout, fmt, ap);
}

int main(int argc, char **argv)
{
	struct bpf_object_load_attr attr = {};
	struct bpf_object *obj;
	int err;

	if (argc < 2) {
		fprintf(stderr, "usage: %s prog.bpf.o [log_level]\n", argv[0]);
		return 2;
	}
	libbpf_set_print(print);
	obj = bpf_object__open_file(argv[1], NULL);
	if (libbpf_get_error(obj))
		return 1;
	attr.obj = obj;
	attr.log_level = argc > 2 ? atoi(argv[2]) : 1;
	err = bpf_object__load_xattr(&attr);
	printf("%s: %s\n", argv[1], err ? "REJECTED" : "loaded");
	bpf_object__close(obj);
	return err ? 1 : 0;
}

The BPF programs in this post use the kernel’s UAPI headers rather than a generated vmlinux.h, so the BPF compile needs the multiarch include directory, where asm/types.h lives on Ubuntu:

cc -O2 -Wall vload.c -lbpf -lelf -lz -o vload
clang -g -O2 -target bpf -I/usr/include/x86_64-linux-gnu -c hist.bpf.c -o hist.bpf.o
sudo ./vload hist.bpf.o 2

(libbpf 0.8, released in May, has since added a cleaner way to pass a log buffer per object, but 22.04 ships 0.5 and the old interface still works.)

Pass 1: the program as a graph

Before it runs anything, the verifier looks at the program’s shape. check_cfg treats the instructions as the nodes of a graph, with an edge from each instruction to the next and from every jump to its target, and walks it depth first from instruction 0. Each node is first discovered, pushed on a stack, and then explored once all its successors are done. An edge that leads back to a node that is discovered but not yet explored, one still on the stack, is a back-edge: a loop.

Here is the decision, in push_insn:

/* kernel/bpf/verifier.c (5.15), push_insn() */
	} else if ((insn_state[w] & 0xF0) == DISCOVERED) {
		if (loop_ok && env->bpf_capable)
			return DONE_EXPLORING;
		verbose_linfo(env, t, "%d: ", t);
		verbose_linfo(env, w, "%d: ", w);
		verbose(env, "back-edge from insn %d to %d\n", t, w);
		return -EINVAL;

Until kernel 5.3, there was no such exception: every back-edge was rejected here, so a BPF program was a directed acyclic graph and terminated trivially. Since 5.3 a privileged loader may have loops (root at first; since 5.8, CAP_BPF is enough, which is what bpf_capable checks), and termination is left to the second pass to prove. An unprivileged loader still gets the old rule. On 22.04 unprivileged BPF is switched off by default, as Part 1 showed, but root can switch it back on with sysctl kernel.unprivileged_bpf_disabled=0, and then an ordinary user loading this socket filter

// unpriv.bpf.c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

SEC("socket")
int sum_len(struct __sk_buff *skb)
{
	__u32 v = skb->len, sum = 0;

#pragma clang loop unroll(disable)
	for (int i = 0; i < 4; i++) {
		sum += v & 0xff;
		v >>= 8;
	}
	return sum;
}

char LICENSE[] SEC("license") = "GPL";

is stopped before a single instruction has been simulated:

$ setpriv --reuid=nobody --regid=nogroup --clear-groups ./vload unpriv.bpf.o
back-edge from insn 15 to 5
processed 0 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

“processed 0 insns” says it all: pass 2 never started. Root loads the same object without complaint. The #pragma is there because clang would otherwise unroll a four-iteration loop into straight-line code and there would be no back-edge to find.

The second thing check_cfg enforces is that every instruction is reachable. After the walk, any instruction that was never explored is an error:

/* kernel/bpf/verifier.c (5.15), check_cfg() */
	for (i = 0; i < insn_cnt; i++) {
		if (insn_state[i] != EXPLORED) {
			verbose(env, "unreachable insn %d\n", i);

Compilers don’t emit dead code, so it takes a little inline assembly to see this one:

// dead.bpf.c
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

SEC("xdp")
int dead(struct xdp_md *ctx)
{
	asm volatile("goto +1\n\tr0 = 0" ::: "r0");
	return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";
$ sudo ./vload dead.bpf.o
unreachable insn 1
processed 0 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

The goto +1 jumps over instruction 1, and nothing else reaches it. The same walk also catches jumps outside the program. Its last job is quieter: every jump target, and the instruction after every call, is marked as a prune point. Those marks matter in pass 2.

Pass 2: running the program without running it

The second pass, do_check, is where the verifier earns its reputation. It executes the program from instruction 0, but on abstract values: instead of a number, each register holds a description of what it could be. At every conditional jump whose outcome it can’t predict, it follows one side and pushes the other on a stack of states to come back to. When a path reaches exit, it pops the next state and carries on from there. When the stack is empty, every path has been checked.

The description of a register starts with its type. The verifier’s names for them print in the log through this table:

/* kernel/bpf/verifier.c (5.15) */
static const char * const reg_type_str[] = {
	[NOT_INIT]		= "?",
	[SCALAR_VALUE]		= "inv",
	[PTR_TO_CTX]		= "ctx",
	[CONST_PTR_TO_MAP]	= "map_ptr",
	[PTR_TO_MAP_VALUE]	= "map_value",
	[PTR_TO_MAP_VALUE_OR_NULL] = "map_value_or_null",
	[PTR_TO_STACK]		= "fp",
	[PTR_TO_PACKET]		= "pkt",
	[PTR_TO_PACKET_META]	= "pkt_meta",
	[PTR_TO_PACKET_END]	= "pkt_end",
	...
	[PTR_TO_MEM]		= "mem",
	[PTR_TO_MEM_OR_NULL]	= "mem_or_null",

A scalar (SCALAR_VALUE, printed inv on this kernel) is a number: something you can do arithmetic on and compare, but not dereference. A pointer type says what the pointer points into, and the type decides what may be done with it. PTR_TO_CTX is the program’s context argument, the struct xdp_md * or struct __sk_buff *; only certain fields may be read, at fixed offsets. PTR_TO_STACK is r10, the frame pointer, or something derived from it. PTR_TO_MAP_VALUE points into a map value, whose size the verifier knows from the map. PTR_TO_PACKET and PTR_TO_PACKET_END are the start and end of a network packet, and a packet pointer carries a range, the number of bytes after it already proven to be inside the packet.

The _OR_NULL types are the ones Part 1 tripped over. A helper that may fail, like bpf_map_lookup_elem, returns PTR_TO_MAP_VALUE_OR_NULL, which cannot be dereferenced and cannot have arithmetic done on it. The only useful thing to do with it is compare it against zero, and that comparison is where the verifier’s model splits in two. In mark_ptr_or_null_reg, on the side of the branch where the pointer is NULL it becomes the scalar 0, and on the other side it becomes a real pointer:

/* kernel/bpf/verifier.c (5.15), mark_ptr_or_null_reg(), condensed */
		if (is_null) {
			reg->type = SCALAR_VALUE;
			...
			return;
		}
		mark_ptr_not_null_reg(reg);   /* PTR_TO_MAP_VALUE_OR_NULL -> PTR_TO_MAP_VALUE */

Every register that holds a copy of the same pointer shares an id and is converted with it, so checking a copy counts too.

The stack is modelled in the same spirit, byte by byte. Each of the 512 bytes is invalid (never written), holds part of a spilled register (a full 8-byte register saved with its type), holds miscellaneous data, or is known to be zero. A log prints the slots as eight characters per 8-byte word, ? for invalid, m for misc, 0 for zero, r for a spilled register.

The idea is easiest to see on a real program, so here is one, taken apart instruction by instruction.

A worked example: a histogram of packet sizes

This XDP program counts packets by size, in 64 buckets of 32 bytes each. Bucket b counts packets of 32b to 32b + 31 bytes, and everything from 2,016 bytes up goes into the last one.

// hist.bpf.c — a histogram of packet sizes, 64 buckets of 32 bytes each
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct hist {
	__u64 bucket[64];
};

struct {
	__uint(type, BPF_MAP_TYPE_ARRAY);
	__uint(max_entries, 1);
	__type(key, __u32);
	__type(value, struct hist);
} sizes SEC(".maps");

SEC("xdp")
int size_hist(struct xdp_md *ctx)
{
	void *data = (void *)(long)ctx->data;
	void *data_end = (void *)(long)ctx->data_end;
	__u32 key = 0;
	struct hist *h;
	__u64 b;

	h = bpf_map_lookup_elem(&sizes, &key);
	if (!h)
		return XDP_PASS;
	b = (__u64)(data_end - data) / 32;
	if (b > 63)
		b = 63;
	__sync_fetch_and_add(&h->bucket[b], 1);
	return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";

The cast in the division is not decoration. Subtracting two pointers gives a signed result, and clang 14 refuses to compile a signed division for BPF (Unsupport signed division for DAG ... Please convert to unsigned div/mod), because the instruction set has no signed divide. With the cast, clang turns the division into a shift. Here is what it produced, as llvm-objdump -d prints it, in the notation Part 2 took apart:

Disassembly of section xdp:
0000000000000000 <size_hist>:
       0:	r6 = *(u32 *)(r1 + 4)
       1:	r7 = *(u32 *)(r1 + 0)
       2:	r1 = 0
       3:	*(u32 *)(r10 - 4) = r1
       4:	r2 = r10
       5:	r2 += -4
       6:	r1 = 0 ll
       8:	call 1
       9:	if r0 == 0 goto +9 <LBB0_4>
      10:	r6 -= r7
      11:	r6 >>= 5
      12:	r1 = 63
      13:	if r1 > r6 goto +1 <LBB0_3>
      14:	r6 = 63
0000000000000078 <LBB0_3>:
      15:	r6 <<= 3
      16:	r0 += r6
      17:	r1 = 1
      18:	lock *(u64 *)(r0 + 0) += r1
0000000000000098 <LBB0_4>:
      19:	r0 = 2
      20:	exit

The kernel accepted it. With log_level 2 the verifier printed the state after every instruction on every path, 105 lines of it. The figure steps through every instruction it processed, and the rest of this section reads the parts that matter. Register states read as R6_w=inv(...): register 6, written on this path (_w), a scalar, with the bounds in brackets. A P after the type, as in invP, marks a scalar the verifier has decided it must track precisely; we’ll see why later.

The verifier walking the histogram program

Every path, in the order the verifier took them, with the register states from its level-2 log. The strip is R6, the bucket number, one cell per bit.

path 1 · start

0: (61) r6 = *(u32 *)(r1 +4)
R1=ctx(id=0,off=0,imm=0) R6_w=pkt_end(id=0,off=0,imm=0)

At entry only R1, the context, and R10, the frame pointer, are initialised. Loading ctx->data_end gives a register of type pkt_end: the verifier knows what that offset of an xdp_md means.

path 1

1: (61) r7 = *(u32 *)(r1 +0)
R7_w=pkt(id=0,off=0,r=0,imm=0)

ctx->data is a packet pointer with a proven range r=0: no byte of the packet may be read through it yet.

path 1

2: (b7) r1 = 0
3: (63) *(u32 *)(r10 -4) = r1
R1_w=invP0 fp-8=0000????

The key goes on the stack. The 8-byte word at fp-8 is now four bytes known to be zero and four never written (?).

path 1

4: (bf) r2 = r10
5: (07) r2 += -4
6: (18) r1 = map
R1_w=map_ptr(id=0,off=0,ks=4,vs=512,imm=0) R2_w=fp-4

R2 is a stack pointer to the key, R1 the map: 4-byte keys, 512-byte values. The helper's prototype asks for exactly these two types.

path 1

8: (85) call bpf_map_lookup_elem#1
R0_w=map_value_or_null(id=1,off=0,ks=4,vs=512,imm=0) fp-8=mmmm????

The result may be NULL. It can't be dereferenced or offset until it has been compared with zero. id=1 lets copies of it be tracked together.

path 1 · branch · 1 path pending

9: (15) if r0 == 0x0 goto pc+9
 R0_w=map_value(id=0,off=0,ks=4,vs=512,imm=0)

The state splits. The verifier follows the fall-through, where R0 is now a real map_value pointer, and pushes the jump side, where R0 is the scalar 0, to come back to.

path 1

10: (1f) r6 -= r7
R6_w=inv(id=0)

End minus start: a scalar the verifier knows nothing about. Every bit is unknown and there are no bounds.

path 1

11: (77) r6 >>= 5
R6_w=inv(id=0,umax_value=576460752303423487,var_off=(0x0; 0x7ffffffffffffff))

The division by 32. The top five bits are now known zero, and the unsigned maximum is 259 − 1. Two records of one fact.

path 1

12: (b7) r1 = 63
R1=inv63

A constant: a tnum with no unknown bits.

path 1 · branch · 2 paths pending

13: (2d) if r1 > r6 goto pc+1
 R6=inv(id=0,umin_value=63,umax_value=576460752303423487,var_off=(0x0; 0x7ffffffffffffff))

The clamp. On the fall-through 63 is not greater than R6, so R6 is at least 63: the minimum rises, the bits don't change. The jump side, R6 ≤ 62, is pushed.

path 1

14: (b7) r6 = 63
R6_w=inv63

The clamp's assignment: R6 is the constant 63.

path 1

15: (67) r6 <<= 3
R6_w=inv504

Bucket to byte offset: 63 × 8 = 504.

path 1

16: (0f) r0 += r6
regs=40 stack=0 before 15: (67) r6 <<= 3
regs=40 stack=0 before 14: (b7) r6 = 63
R0_w=map_value(id=0,off=504,ks=4,vs=512,imm=0) R6_w=invP504

A scalar added to a pointer decides where the pointer points, so the verifier walks back and marks R6 and what it came from precise (the P). R0 now points 504 bytes into the value.

path 1 · memory access

17: (b7) r1 = 1
18: (db) lock *(u64 *)(r0 +0) += r1
 R0_w=map_value(id=0,off=504,ks=4,vs=512,imm=0) R1_w=inv1

The atomic add is checked: offset 504, size 8, value size 512. 504 + 8 ≤ 512: allowed.

path 1 · exit · pop

19: (b7) r0 = 2
20: (95) exit
R0_w=inv2

XDP_PASS. Path 1 is safe, after 20 instructions. The verifier pops the most recent pending state: instruction 15, from the clamp.

path 2 · from 13 to 15

15: R0=map_value(id=0,off=0,ks=4,vs=512,imm=0) R1=inv63 R6=inv(id=0,umax_value=62,var_off=(0x0; 0x3f))

The jump side of the clamp: R6 < 63, so umax is 62. From that bound the verifier derived a tighter tnum: a number no larger than 62 has nothing set above bit 5, so only six bits remain unknown.

path 2

15: (67) r6 <<= 3
R6_w=inv(id=0,umax_value=496,var_off=(0x0; 0x1f8))

The shift moves the unknown bits up three places and multiplies the bound by 8. The three low bits are known zero: the offset is a multiple of 8.

path 2

16: (0f) r0 += r6
R0_w=map_value(id=0,off=0,ks=4,vs=512,umax_value=496,var_off=(0x0; 0x1f8),s32_max_value=504,u32_max_value=504)
R6_w=invP(id=0,umax_value=496,var_off=(0x0; 0x1f8))

Now R0 has a variable offset: somewhere in 0…496, in steps of 8. This state can't be pruned against path 1's, where R6 was exactly 504.

path 2 · memory access

17: (b7) r1 = 1
18: (db) lock *(u64 *)(r0 +0) += r1

The check uses the largest possible offset: 496 + 8 = 504 ≤ 512. Allowed for every value R6 could hold.

path 2 · exit · pop

19: (b7) r0 = 2
20: (95) exit

Path 2 is safe, after 6 more instructions. One state left: the lookup's NULL side, at instruction 19.

path 3 · from 9 to 19 · done

19: R0_w=inv0 R6_w=pkt_end(id=0,off=0,imm=0) R7_w=pkt(id=0,off=0,r=0,imm=0)
19: (b7) r0 = 2
20: (95) exit
processed 28 insns (limit 1000000) max_states_per_insn 0 total_states 2 peak_states 2 mark_read 1

On the side where the lookup failed, R0 is the scalar 0, and the path is two instructions long. Nothing is pending: the program is accepted, after 28 instructions processed for a 20-instruction program.

Path 1 (teal) takes every fall-through first; path 2 (green) is the clamp's jump side, popped first because it was pushed last; path 3 (copper) is the failed lookup. In the strip, a filled cell is a bit known to be 1, a dark cell a bit known to be 0, and a pale cell a bit the verifier doesn't know.

Instructions 0 and 1 load ctx->data_end and ctx->data. They are ordinary 32-bit loads from the context, but the verifier knows what those two offsets of an xdp_md mean, and the registers come out typed:

1: R1=ctx(id=0,off=0,imm=0) R6_w=pkt_end(id=0,off=0,imm=0) R10=fp0
2: R1=ctx(id=0,off=0,imm=0) R6_w=pkt_end(id=0,off=0,imm=0) R7_w=pkt(id=0,off=0,r=0,imm=0) R10=fp0

r=0 on the packet pointer is its proven range: zero bytes. Nothing in the packet may be read yet. (After the program is accepted, convert_ctx_accesses rewrites these two loads into loads from the kernel’s real struct xdp_buff, which has a different layout.)

Instructions 2 to 8 put the key on the stack and call the lookup. The stack word at fp-8 becomes 0000????: four bytes known to be zero, the key, and four never written. The call returns

9: R0_w=map_value_or_null(id=1,off=0,ks=4,vs=512,imm=0) R6_w=pkt_end(id=0,off=0,imm=0) ...

a pointer that may be NULL, into a map with 4-byte keys and 512-byte values (ks=4,vs=512), with id 1 so that copies can be tracked.

Instruction 9 is if r0 == 0x0 goto pc+9. The verifier follows the fall-through, where r0 is not NULL, and pushes the other side, where it is, for later. On the fall-through R0 is now map_value(id=0,off=0,ks=4,vs=512,imm=0): a pointer to the start of a 512-byte value.

Instruction 10, r6 -= r7, subtracts the packet start from the packet end. The difference of two pointers is a number the verifier knows nothing about, so R6 becomes inv(id=0), a scalar with no bounds at all. (This is allowed for privileged programs only. An unprivileged program would be refused here, because the difference of two kernel addresses can leak information about them.)

Instruction 11, r6 >>= 5, is the division by 32, and the first instruction that teaches the verifier something:

12: ... R6_w=inv(id=0,umax_value=576460752303423487,var_off=(0x0; 0x7ffffffffffffff)) ...

A 64-bit number shifted right by five has its top five bits clear. The verifier records this twice, in two different forms: as an unsigned maximum, umax_value, which is 2⁵⁹ − 1, and as var_off=(0x0; 0x7ffffffffffffff), a tnum, which says which individual bits are known. Both are explained properly in the next section. For now, read the tnum as “the top five bits are 0, the other 59 could be anything”.

Instruction 13 is the clamp, if (b > 63) b = 63, which clang compiled as if r1 > r6 goto pc+1 with r1 = 63: “if 63 is greater than b, skip the assignment”. The verifier can’t predict it, so the state splits again. On the fall-through, 63 is not greater than b, so b is at least 63:

 R6=inv(id=0,umin_value=63,umax_value=576460752303423487,var_off=(0x0; 0x7ffffffffffffff))

and instruction 14 overwrites it with the constant 63 anyway. On the jump side, b is less than 63, which is the state the verifier pushes for later.

Instructions 15 to 18, on the fall-through path first: r6 <<= 3 turns the bucket number into a byte offset, 63 × 8 = 504; r0 += r6 moves the map value pointer to that bucket; and the atomic add at r0 + 0 is checked against the map value’s size. The pointer now says off=504, the access is 8 bytes, 504 + 8 ≤ 512, so it is allowed. Then r0 = 2 (XDP_PASS) and exit. One path done.

At r0 += r6 the log also prints a few lines that look like noise:

last_idx 16 first_idx 13
regs=40 stack=0 before 15: (67) r6 <<= 3
regs=40 stack=0 before 14: (b7) r6 = 63

That is the verifier walking backwards from instruction 16, marking r6 (bit 6 of regs=40) and everything it was computed from as precise. A scalar that is added to a pointer decides where the pointer points, so its exact value matters. Hold on to that idea for the section on pruning.

The second path starts from the state pushed at instruction 13, at instruction 15, with b anywhere from 0 to 62:

15: R0=map_value(id=0,off=0,ks=4,vs=512,imm=0) R1=inv63 R6=inv(id=0,umax_value=62,var_off=(0x0; 0x3f)) ...

The comparison left the unsigned maximum at 62, and the verifier then derived a better tnum from it: a number no larger than 62 has nothing set above bit 5, so var_off shrank from 59 unknown bits to 6, (0x0; 0x3f). The shift multiplies both forms by 8:

16: ... R6_w=inv(id=0,umax_value=496,var_off=(0x0; 0x1f8)) ...

and adding it to the map value pointer gives a pointer with a variable offset:

17: R0_w=map_value(id=0,off=0,ks=4,vs=512,umax_value=496,var_off=(0x0; 0x1f8),s32_max_value=504,u32_max_value=504) ...

For the access at instruction 18, the verifier takes the largest offset the pointer can have, 496, adds the access size, 8, and checks the result against the value size: 504 ≤ 512. Allowed. (The 32-bit bounds say 504 where the 64-bit one says 496. They were derived from the tnum, whose largest member is 0x1f8 = 504, rather than from the comparison. Both are true, and the verifier uses whichever is tighter.)

The third path is the one pushed at instruction 9, where the lookup returned NULL. R0 is inv0 there, the scalar zero, and the path is two instructions long: r0 = 2, exit. The summary line:

processed 28 insns (limit 1000000) max_states_per_insn 0 total_states 2 peak_states 2 mark_read 1

28 instructions processed for a 20-instruction program: 20 on the first path, 6 on the second, 2 on the third. The verifier never needed to know the packet’s size. It needed to know only that whatever the size, the bucket index stays between 0 and 63.

Now delete the two lines of the clamp and load it again:

10: (1f) r6 -= r7
; __sync_fetch_and_add(&h->bucket[b], 1);
11: (77) r6 >>= 2
12: (18) r1 = 0x3ffffffffffffff8
; b = (__u64)(data_end - data) / 32;
14: (5f) r6 &= r1
; __sync_fetch_and_add(&h->bucket[b], 1);
15: (0f) r0 += r6
...
16: (b7) r1 = 1
; __sync_fetch_and_add(&h->bucket[b], 1);
17: (db) lock *(u64 *)(r0 +0) += r1
 R0_w=map_value(id=0,off=0,ks=4,vs=512,umax_value=4611686018427387896,var_off=(0x0; 0x3ffffffffffffff8),s32_max_value=2147483640,u32_max_value=-8) R1_w=inv1 R6_w=invP(id=0,umax_value=4611686018427387896,var_off=(0x0; 0x3ffffffffffffff8),s32_max_value=2147483640,u32_max_value=-8) R7_w=pkt(id=0,off=0,r=0,imm=0) R10=fp0 fp-8=mmmm????
R0 unbounded memory access, make sure to bounds check any such access
processed 16 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

Without the clamp, clang folded the division by 32 and the multiplication by 8 into one shift and a mask, but the verifier’s conclusion is the same: nothing stops b from being anything up to 2⁵⁹ − 1, and the byte offset, up to umax_value=4611686018427387896, is far outside a 512-byte value. The verifier refuses even to compute a maximum offset that large (anything at or above 2²⁹ counts as unbounded) and asks for a bounds check. (The ... marks where I cut the precision-backtracking lines out of the middle of the log.) The program is wrong only for packets bigger than 2 KiB, which an XDP program on a standard 1,500-byte MTU never sees. The verifier doesn’t know about MTUs.

Tristate numbers, from first principles

A verifier that tracked every possible value of every register exactly would run forever. One that tracked only “known constant” or “unknown” would reject every program that computes an index. The verifier sits in between, with two approximations for each scalar, and it is worth seeing how each works, because almost every bounds-check rejection is about one of them.

The first is a set of ranges: an unsigned minimum and maximum (umin_value, umax_value) and a signed pair (smin_value, smax_value), for the full 64 bits and, since 5.7, again for the low 32 bits. Ranges are good at comparisons. if (b > 63) narrows one bound and leaves the other alone, and a range doesn’t care how the number is represented.

The second is a tnum, a tracked or tristate number, introduced in 4.14. It records, bit by bit, what is known: each bit is 0, 1, or unknown, written x. In the kernel it is two 64-bit words:

/* include/linux/tnum.h (5.15) */
struct tnum {
	u64 value;
	u64 mask;
};

A bit set in mask is unknown. A bit clear in mask is known, and its value is the matching bit of value. The log prints the pair as var_off=(value; mask). Some examples, writing only the low eight bits:

tnumbitsthe set it stands for
(0x0; 0x0)00000000{0}, the constant 0
(0x0; 0xff)xxxxxxxxany byte, 0…255: what a 1-byte load produces
(0x0; 0x3c)00xxxx00multiples of 4 from 0 to 60: a byte AND 0x3c
(0x1; 0xfe)xxxxxxx1the odd bytes: a byte OR 1
(0x10; 0xf)0001xxxx16…31

Tnums are good at exactly what ranges are bad at. A range can’t say “even” or “a multiple of 8”, and alignment checks need that. A tnum says it directly, as known-zero low bits. And bitwise operations are as precise on tnums as they can be. AND is the simplest:

/* kernel/bpf/tnum.c (5.15) */
struct tnum tnum_and(struct tnum a, struct tnum b)
{
	u64 alpha, beta, v;

	alpha = a.value | a.mask;
	beta = b.value | b.mask;
	v = a.value & b.value;
	return TNUM(v, alpha & beta & ~v);
}

alpha and beta are “bits that might be 1” in each operand, and v is “bits that are certainly 1 in both”. A result bit is certainly 1 if it is in v, might be 1 if it might be in both, and is otherwise certainly 0. Feed it (0x0; 0xff) and the constant (0x3c; 0x0): alpha = 0xff, beta = 0x3c, v = 0, so the result is (0x0; 0x3c), the table’s third row.

Addition is the clever one, because carries make bits depend on each other:

/* kernel/bpf/tnum.c (5.15) */
struct tnum tnum_add(struct tnum a, struct tnum b)
{
	u64 sm, sv, sigma, chi, mu;

	sm = a.mask + b.mask;
	sv = a.value + b.value;
	sigma = sm + sv;
	chi = sigma ^ sv;
	mu = chi | a.mask | b.mask;
	return TNUM(sv & ~mu, mu);
}

sv is the sum with every unknown bit taken as 0, the smallest possible sum. sigma is the sum with every unknown bit taken as 1, the largest. Any bit where those two differ, chi, might have been touched by a carry, so it is unknown, along with any bit that was unknown going in. Take {0, 1, 2, 3} = (0x0; 0x3) plus the constant 4:

  • sm = 3, sv = 4, sigma = 7, chi = 7 ^ 4 = 3, mu = 3 | 3 | 0 = 3;
  • result (4 & ~3; 3) = (0x4; 0x3) = 000001xx = {4, 5, 6, 7}. Exact.

Now {4, 5, 6, 7} = (0x4; 0x3) plus 1, whose true answer is {5, 6, 7, 8}:

  • sm = 3, sv = 5, sigma = 8, chi = 8 ^ 5 = 0b1101 = 13, mu = 13 | 3 = 15;
  • result (5 & ~15; 15) = (0x0; 0xf) = 0000xxxx = {0, …, 15}.

Sound, but loose: the carry out of the low two bits could reach bit 3, so bits 0 to 3 all become unknown, and the tnum now admits 0. This is exactly why the verifier keeps ranges as well. The range of the same addition is computed separately, [4 + 1, 7 + 1] = [5, 8], exact.

The two forms then inform each other after every operation. __update_reg_bounds tightens the ranges from the tnum (the smallest and largest numbers the bit pattern allows), and __reg_bound_offset goes the other way, intersecting the tnum with one built from the range:

/* kernel/bpf/verifier.c (5.15) */
static void __reg_bound_offset(struct bpf_reg_state *reg)
{
	struct tnum var64_off = tnum_intersect(reg->var_off,
					       tnum_range(reg->umin_value,
							  reg->umax_value));

tnum_range(min, max) keeps the bits on which min and max agree, above the highest bit where they differ, and marks everything from that bit down as unknown. That is precisely the step in the worked example where b ≤ 62 turned the tnum (0x0; 0x7ffffffffffffff) into (0x0; 0x3f): tnum_range(0, 62) is (0x0; 0x3f), and intersecting the two keeps the six low bits unknown and everything else zero. I checked each of these values by compiling the functions from tnum.c in user space and running them on the examples.

What a comparison teaches

The narrowing at a branch is done by reg_set_min_max, which takes the register’s state on each side of the jump and the constant it was compared with. For an unsigned greater-than it is two lines of arithmetic:

/* kernel/bpf/verifier.c (5.15), reg_set_min_max() */
	case BPF_JGE:
	case BPF_JGT:
	{
		...
			u64 false_umax = opcode == BPF_JGT ? val    : val - 1;
			u64 true_umin = opcode == BPF_JGT ? val + 1 : val;

			false_reg->umax_value = min(false_reg->umax_value, false_umax);
			true_reg->umin_value = max(true_reg->umin_value, true_umin);

If x > val was false, x is at most val; if true, at least val + 1. The signed comparisons (JSGT and friends) narrow the signed bounds the same way, and the 32-bit jumps the 32-bit bounds. Equality is the strongest: on the side where x == val holds, the register becomes the constant. When it is the constant that sits on the left, as in the histogram’s if r1 > r6, a mirror-image function, reg_set_min_max_inv, does the same job for the register on the right. After the narrowing, the bounds and the tnum are reconciled again, which is how the histogram’s tnum shrank.

One consequence is easy to miss: a comparison narrows only the bounds it talks about. An unsigned comparison says nothing directly about the signed bounds, and the other way round. A signed int index compared with < 64 is still allowed to be −2 billion, and as the gallery will show, the verifier will say so. Another consequence is that the verifier learns nothing about a register that is compared against another unknown register, beyond what it already knew. The bounds check has to be against a constant, or against something the verifier already has bounds for.

When a comparison’s outcome can be predicted from the bounds, is_branch_taken says so, and the verifier follows only the side that can happen. That is what makes bounded loops possible, as we’ll see: i < 100 with i known to be 7 is not a branch at all.

Not walking every path: pruning

A program with n independent if statements has 2ⁿ paths. If the verifier really walked every one of them, a program with 30 checks of different header fields would take a billion steps. It doesn’t, because of state pruning. At each prune point, the instructions check_cfg marked, is_state_visited compares the current state with the states that earlier paths had at the same instruction and that were then proven safe all the way to exit. If the current state is no more permissive than one of those, every path from here is a path the verifier already checked, with values that are a subset of the ones it checked them with. It stops, and prints safe.

The comparison is states_equal, and the heart of it is regsafe, register by register:

/* kernel/bpf/verifier.c (5.15), regsafe() */
	if (!(rold->live & REG_LIVE_READ))
		/* explored state didn't use this */
		return true;
	...
	switch (rold->type) {
	case SCALAR_VALUE:
		if (env->explore_alu_limits)
			return false;
		if (rcur->type == SCALAR_VALUE) {
			if (!rold->precise && !rcur->precise)
				return true;
			/* new val must satisfy old val knowledge */
			return range_within(rold, rcur) &&
			       tnum_in(rold->var_off, rcur->var_off);

Two ideas make pruning work, and both are visible here.

Liveness. A register that the rest of the old path never read can hold anything now: it cannot matter. The verifier records, as it goes, which registers and stack slots each state’s continuation actually read (REG_LIVE_READ), and ignores the rest.

Precision. A scalar that was only stored, compared or returned can’t make anything unsafe, whatever its value. Its value matters only if it fed into something the verifier had to check: a pointer offset, a helper’s size argument, a branch whose outcome was predicted from it. Those are the scalars the verifier marks precise, by walking back from the use, as we saw at the histogram’s r0 += r6. Two imprecise scalars are “equal” whatever they hold. A precise one in the old state accepts the new one only if the new range and tnum fit inside the old.

To see how much this matters, I wrote a program with K branches in a row, each adding a different power of two to x if a random bit is set, so that every one of the 2ᴷ paths ends with a different x. Then I compiled it twice: once where x is merely stored, and once where it is used as an index into a map value.

// paths.bpf.c — K independent branches; does the verifier walk 2^K paths?
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

#ifndef K
#define K 4
#endif

struct row { __u64 slot[64]; };

struct {
	__uint(type, BPF_MAP_TYPE_ARRAY);
	__uint(max_entries, 1);
	__type(key, __u32);
	__type(value, struct row);
} rows SEC(".maps");

__u64 result;

SEC("xdp")
int paths(struct xdp_md *ctx)
{
#ifdef ONSTACK
	volatile
#endif
	__u64 x = 0;
	__u32 key = 0;
	struct row *r;

#pragma unroll
	for (int k = 0; k < K; k++)
		if (bpf_get_prandom_u32() & 1) {
			x += 1ULL << k;
			asm volatile("" ::: "memory");
		}
#ifdef INDEX
	r = bpf_map_lookup_elem(&rows, &key);
	if (r)
		result = r->slot[x & 63];
#else
	result = x;
#endif
	return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";

(The empty asm statement stops clang from turning each if into branch-free arithmetic, which it otherwise does, and which would leave the verifier no branches to explore.) The figure shows what happened, for K from 1 to 32.

K branches in a row: how many instructions did the verifier process?

Same program, three ways of keeping x. Pick a variant and a number of branches; the chart's y axis is logarithmic.

Variant

instructions processed

states stored for pruning

Table of every measured point
Kstoredindexon the stack

Teal circles: x is only stored, an imprecise scalar, so paths that differ only in x are pruned where they join. Copper squares: x indexes a map value, so it is precise and every one of the 2K values is a separate state. Green diamonds: x lives on the stack and starts at 0, which 5.15 marks precise; it explodes although it is only stored. A cross is a rejection: "BPF program is too large".

When x is only stored, the verifier’s work grows by about eight and a half instructions per branch: at every join, the path arriving second has a different x, but an imprecise one, so it is pruned on the spot. 276 instructions for 32 branches. When x is used as an index, it is precise, every one of the 2ᴷ values of x is a different state, and the count roughly doubles with every branch: 69,631 instructions at K = 12, 557,056 at 15, and at 16 the program is rejected. Same code, same branches. The only difference is whether the value that differs between paths is ever used for something the verifier must check.

The limits

Pruning makes most programs cheap to verify, and some programs expensive anyway. A privileged loader runs into two budgets, each with its own rejection, and the log reports how much of them a program used.

One million instructions processed. do_check counts every instruction it simulates, on every path, and stops at BPF_COMPLEXITY_LIMIT_INSNS:

/* kernel/bpf/verifier.c (5.15), do_check() */
		if (++env->insn_processed > BPF_COMPLEXITY_LIMIT_INSNS) {
			verbose(env,
				"BPF program is too large. Processed %d insn\n",
				env->insn_processed);
			return -E2BIG;
		}

It is 1,000,000 since 5.2, when it went up from 131,072. The commit that raised it explains why: users had taken to recompiling their programs with smaller and smaller loop counts until one loaded, and splitting programs into chains of tail calls to get more budget. The same commit raised the maximum size of a privileged program from 4,096 instructions to the same million. So “too large” in the message really means “too expensive to verify”; a 14-instruction loop can hit it, as we’ll see.

8,192 pending branches. Every unexplored side of a branch is a full copy of the verifier state, pushed on a stack. If more than BPF_COMPLEXITY_LIMIT_JMP_SEQ (8,192 since 5.3) are waiting at once, push_stack gives up with “The sequence of 8193 jumps is too complex.”

The last line of every log reports how close a program came. Here is the histogram’s again:

processed 28 insns (limit 1000000) max_states_per_insn 0 total_states 2 peak_states 2 mark_read 1

processed is the budget used. total_states is how many states were stored at prune points for future comparison, and peak_states how many were alive at once, which is the verifier’s memory use. max_states_per_insn is the longest list of stored states any one instruction accumulated: a program where it is large is one where pruning keeps failing. mark_read is the longest walk the liveness tracking had to make back through parent states.

For unprivileged programs there is a fourth budget, BPF_COMPLEXITY_LIMIT_STATES: beyond 64 stored states at one instruction, the verifier stops storing more, which makes it give up sooner.

Loops: unroll, bound, or hand them to a helper

Since a BPF program had to be a DAG until 5.3, the only loop before then was one the compiler removed: #pragma unroll in front of a loop with a constant count, so that clang pasted the body in n times. It works, and it costs n copies of the body in program size, against the 4,096-instruction limit of the time.

Bounded loops (5.3). Since 5.3 a privileged program may contain a real loop, and the verifier treats it the simplest way possible: it walks it. A loop counter is a scalar like any other. On each trip round the loop, the counter is a different constant, is_branch_taken predicts the loop condition, and the walk goes round again, until the condition is predicted false and the walk leaves the loop. There is no induction and no loop analysis. The cost is exactly what it looks like: the body’s instructions, once per iteration, against the million. This program runs N rounds of a pseudo-random number generator:

// loop.bpf.c — N rounds of a 64-bit LCG, as a bounded loop
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

#ifndef N
#define N 100
#endif

__u64 result, hits;

SEC("xdp")
int bounded(struct xdp_md *ctx)
{
	__u64 x = bpf_get_prandom_u32(), sum = 0;

#pragma clang loop unroll(disable)
	for (__u32 i = 0; i < N; i++) {
		x = x * 6364136223846793005ULL + 1442695040888963407ULL;
		sum += x >> 33;
#ifdef BRANCHY
		if (x & (1ULL << 40))
			__sync_fetch_and_add(&hits, 1);
#endif
	}
	result = sum;
	return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";

Its loop body compiles to 12 instructions, and the verifier processed 12N + 10 instructions for every N I tried from 5 to 83,332. (For N of 1 and 2, clang emits different code, and the counts are 12 and 31.) The largest N that loads is 83,332, at 999,994 instructions; one more iteration and it is “too large”. The pragma matters here too: without it clang partially unrolls the loop, which changes the constant but not the shape.

So a loop can be bounded and still be refused because the bound is too big for the budget. And the cost per iteration is not just the body: it is everything the body makes the verifier do. Compile the same loop with -DBRANCHY, which adds one if and an atomic increment to the body, and each iteration now leaves a pushed state behind, the side of the if not taken. Most are pruned when popped, but not all, because the verifier deliberately stores few states inside loops. The measured cost rose to about 62 instructions per iteration, and the limit that ends it is a different one:

24: (0f) r0 += r3
; if (x & (1ULL << 40))
25: (bf) r7 = r0
26: (5f) r7 &= r4
; if (x & (1ULL << 40))
27: (15) if r7 == 0x0 goto pc-14
The sequence of 8193 jumps is too complex.
processed 139279 insns (limit 1000000) max_states_per_insn 4 total_states 1368 peak_states 1368 mark_read 2

At N = 8,192 the program loads, after 508,079 instructions; at 8,193 it hits the jump-sequence limit, long before the million. Each iteration leaves one state pending, and none is popped until the first path has left the loop, so a loop with an unpredictable branch in its body stops at 8,192 iterations, however cheap the body is.

Instructions the verifier processed, by loop count

One loop, three ways. Both axes are logarithmic; the dashed line is the one-million-instruction budget.

Hover or tap a point.

Run time per iteration, 5.18

BPF_PROG_TEST_RUN, every round shown. Same generator, bounded loop against bpf_loop.

Hover or tap a point.

Table of every measured point
seriesNprocessedresult

The chart needs JavaScript; the table above has every value.

The bounded loop costs 12 instructions per iteration, and stops loading past N = 83,332. The branch inside the second loop costs more per iteration and runs into the 8,192 pending-branch limit at N = 8,193. bpf_loop's count never enters the verification.

Loops it cannot bound. Back to the opening example, a loop that counts set bits by clearing the lowest one until none are left:

// popcount.bpf.c — count the set bits of a random 32-bit number
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

SEC("xdp")
int popcount(struct xdp_md *ctx)
{
	__u64 x = bpf_get_prandom_u32();
	int n = 0;

	while (x) {
		x &= x - 1;
		n++;
	}
	return n;
}

char LICENSE[] SEC("license") = "GPL";
; n++;
10: (07) r0 += 1
11: (bf) r1 = r2
; while (x) {
12: (55) if r2 != 0x0 goto pc-5

from 12 to 8: R0_w=inv166665 R1_w=inv(id=166667,umax_value=4294967295,var_off=(0x0; 0xffffffff)) R2_w=inv(id=166667,umax_value=4294967295,var_off=(0x0; 0xffffffff)) R10=fp0
; x &= x - 1;
8: (07) r2 += -1
; x &= x - 1;
9: (5f) r2 &= r1
BPF program is too large. Processed 1000001 insn
processed 1000001 insns (limit 1000000) max_states_per_insn 4 total_states 9806 peak_states 9806 mark_read 2

The loop always ends within 32 iterations, but the proof involves an argument about bits that the verifier doesn’t make. To it, x &= x - 1 of some 32-bit x is just some 32-bit x again: the log prints the same umax_value=4294967295,var_off=(0x0; 0xffffffff) on every trip. n goes up by one every time, so no iteration’s state equals an earlier one, and nothing is ever pruned. It walked until the budget ran out, with n at 166,665 in the last state it printed. The fix is to give the loop a counter the verifier can follow:

	for (int i = 0; i < 64 && x; i++) {
		x &= x - 1;
		n++;
	}

Now there are two exits each time round. x becoming zero still can’t be predicted, so every iteration pushes the exit path, but i < 64 can, so the walk is over after 64 trips at most: 707 instructions processed. At run time the bound costs a counter and a comparison, and never triggers, because x runs out first.

Loops that might never end. The opposite case is a loop whose state really does repeat:

// spin.bpf.c — retry until a random number is zero
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

SEC("xdp")
int spin(struct xdp_md *ctx)
{
	while (bpf_get_prandom_u32() != 0)
		;
	return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";
from 3 to 0: R0_w=inv(id=0,umax_value=4294967295,var_off=(0x0; 0xffffffff)) R10=fp0
; while (bpf_get_prandom_u32() != 0)
0: (85) call bpf_get_prandom_u32#7
1: (67) r0 <<= 32
2: (77) r0 >>= 32
; while (bpf_get_prandom_u32() != 0)
3: (55) if r0 != 0x0 goto pc-4

from 3 to 0: R0_w=inv(id=0,umax_value=4294967295,var_off=(0x0; 0xffffffff)) R10=fp0
; while (bpf_get_prandom_u32() != 0)
0: (85) call bpf_get_prandom_u32#7
infinite loop detected at insn 1
processed 14 insns (limit 1000000) max_states_per_insn 0 total_states 1 peak_states 1 mark_read 1

When the walk comes back to the top of the loop, nothing in the state has changed: the random number is unknown every time. The bounded-loop commit added a check for exactly this in is_state_visited: if the walk arrives at an instruction in a state equal to one that is still being explored, on the same path, it is going round in a circle. The loop ends with probability one, but not on every path, and “on every path” is the verifier’s only standard.

bpf_loop (5.17). Kernel 5.17, released in March, added a different answer: a helper that runs a callback a given number of times.

long bpf_loop(u32 nr_loops, void *callback_fn, void *callback_ctx, u64 flags);

The helper is ordinary kernel C, so the loop is the kernel’s, not the program’s. The verifier checks the callback once, as a function whose first argument is an unknown iteration number and whose second is the context pointer, and checks that it returns 0 (continue) or 1 (stop). The number of iterations no longer appears in the verification at all. The kernel caps it at 2²³, 8,388,608, at run time. Here is the same generator, written for bpf_loop. libbpf 0.5’s headers predate the helper, so it is declared by hand, with its number from the kernel’s UAPI header:

// loopcb.bpf.c — the same N rounds, as a bpf_loop callback
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

#ifndef N
#define N 100
#endif

/* bpf_loop is helper 181, new in 5.17; libbpf 0.5's headers predate it */
static long (*bpf_loop)(__u32 nr_loops, void *callback_fn, void *callback_ctx,
			__u64 flags) = (void *)181;

struct state {
	__u64 x, sum;
};

__u64 result;

static int step(__u32 i, void *ctx)
{
	struct state *s = ctx;

	s->x = s->x * 6364136223846793005ULL + 1442695040888963407ULL;
	s->sum += s->x >> 33;
	return 0;
}

SEC("xdp")
int with_bpf_loop(struct xdp_md *ctx)
{
	struct state s = { bpf_get_prandom_u32(), 0 };

	bpf_loop(N, step, &s, 0);
	result = s.sum;
	return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";

On 5.18, the verifier processed 29 instructions for this program whether N was 1 or 8,388,608. The bounded loop on the same kernel cost the same 12N + 10 as on 5.15. Its level-2 log shows the callback being checked: the caller runs up to the call, then the verifier walks step once, as frame1, with R1=Pscalar() for the unknown iteration number and R2=fp-16, a pointer into the caller’s stack where s lives, and returns to the caller at the next instruction. That is the whole loop, as far as the verifier is concerned.

What bpf_loop might cost instead is run time: every iteration is an indirect call from the helper into the callback, and the callback reaches its state through a pointer rather than registers. To measure it, I ran both programs with BPF_PROG_TEST_RUN, the bpf() command (4.12) that runs a program on a packet you supply, many times over, and reports the average time per run:

// bench.c — load an object and run its first program R times with BPF_PROG_TEST_RUN
#include <stdio.h>
#include <stdlib.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>

int main(int argc, char **argv)
{
	struct bpf_object *obj;
	struct bpf_program *prog;
	char pkt[64] = {};
	__u32 retval, ns;
	int repeat = argc > 2 ? atoi(argv[2]) : 1000;

	if (argc < 2)
		return 2;
	obj = bpf_object__open_file(argv[1], NULL);
	if (libbpf_get_error(obj) || bpf_object__load(obj))
		return 1;
	prog = bpf_program__next(NULL, obj);
	if (bpf_prog_test_run(bpf_program__fd(prog), repeat, pkt, sizeof(pkt),
			      NULL, NULL, &retval, &ns))
		return 1;
	printf("%s: %u ns per run\n", argv[1], ns);
	bpf_object__close(obj);
	return 0;
}

I ran seven rounds, each running both programs at each of four loop counts, interleaved, with no other test virtual machine running. The figure above shows every round. With this body the difference is small. At N = 10,000 the bounded loop took 8,281 to 8,377 ns per run (median 8,294, 0.83 ns per iteration), and bpf_loop 8,316 to 9,266 (median 8,504, 0.85 ns per iteration): about 2.5% more at the median, with a wider spread. At N = 1,000 the two ranges overlap, 815–845 against 828–935 ns. The clearest difference is the fixed cost: at N = 10 the bounded loop took 7 ns in every round and bpf_loop 11 or 12, so calling the helper and setting up the callback costs about 4 ns. Per iteration, the indirect call hides behind the generator itself, a chain of dependent 64-bit multiplications that the processor can’t hurry, so it gets the call’s bookkeeping done in the time it is waiting anyway. A body with less of a dependency chain would show more of the call. This is one body, on one virtual machine.

So the choice is a trade. A bounded loop is the fastest code there is and costs verification in proportion to its count, which caps it at tens of thousands of iterations of a tiny body, or 8,192 of one with a branch. bpf_loop verifies in constant time, allows millions, and here cost a few nanoseconds per call and a few per cent per iteration. For a short loop, over packet headers say, the bounded loop is simpler and as fast. For a loop over anything big, bpf_loop is the only one that loads.

What follows are nine more programs the verifier refused, each a mistake that is easy to make and each with the log it produced and the fix. The logs are the last lines of level-1 output; libbpf’s own framing lines are trimmed.

1. A signed index

// signed.bpf.c — bump a counter chosen by the first four bytes of the packet
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct row { __u64 slot[64]; };

struct {
	__uint(type, BPF_MAP_TYPE_ARRAY);
	__uint(max_entries, 1);
	__type(key, __u32);
	__type(value, struct row);
} rows SEC(".maps");

SEC("xdp")
int bump(struct xdp_md *ctx)
{
	void *data = (void *)(long)ctx->data;
	void *data_end = (void *)(long)ctx->data_end;
	__u32 key = 0;
	struct row *r;

	if (data + 4 > data_end)
		return XDP_PASS;
	int i = *(int *)data;
	r = bpf_map_lookup_elem(&rows, &key);
	if (!r)
		return XDP_PASS;
	if (i < 64)
		r->slot[i]++;
	return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";
14: (67) r6 <<= 32
15: (c7) r6 s>>= 32
; if (!r)
16: (65) if r6 s> 0x3f goto pc+5
 R0=map_value(id=0,off=0,ks=4,vs=512,imm=0) R6_w=inv(id=0,smin_value=-2147483648,smax_value=63) R10=fp0 fp-8=mmmm????
; r->slot[i]++;
17: (67) r6 <<= 3
18: (0f) r0 += r6
...
math between map_value pointer and register with unbounded min value is not allowed
processed 18 insns (limit 1000000) max_states_per_insn 0 total_states 1 peak_states 1 mark_read 1

i < 64 is a signed comparison (s> in the log), so it caps i from above and leaves it free to be any negative int: smin_value=-2147483648,smax_value=63. Shifting that left by three to make a byte offset loses the lower bound altogether, and the verifier won’t add a register with no lower bound to a map value pointer at all. Fix: declare i as __u32. The same comparison is then unsigned and bounds it to 0…63, and the program loads.

2. Struct padding on the stack

// padding.bpf.c — remember when each process called execve()
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct key {
	__u32 pid;
	__u64 start;
};

struct {
	__uint(type, BPF_MAP_TYPE_HASH);
	__uint(max_entries, 1024);
	__type(key, struct key);
	__type(value, __u64);
} seen SEC(".maps");

SEC("tracepoint/syscalls/sys_enter_execve")
int on_exec(void *ctx)
{
	struct key k;
	__u64 one = 1;

	k.pid = bpf_get_current_pid_tgid() >> 32;
	k.start = bpf_ktime_get_ns();
	bpf_map_update_elem(&seen, &k, &one, BPF_ANY);
	return 0;
}

char LICENSE[] SEC("license") = "GPL";
8: (07) r2 += -16
9: (bf) r3 = r10
10: (07) r3 += -24
; bpf_map_update_elem(&seen, &k, &one, BPF_ANY);
13: (b7) r4 = 0
14: (85) call bpf_map_update_elem#2
invalid indirect read from stack R2 off -16+4 size 16
processed 14 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

Both fields are set, and the read is still uninitialised. struct key is 16 bytes: pid at offset 0, then 4 bytes of padding so that start is 8-aligned. The helper reads all 16 bytes of the key, and bytes 4 to 7, off -16+4, were never written. In ordinary C that is harmless garbage. Here it is kernel stack contents flowing into a map, where user space can read them, so it is refused. Fix: struct key k = {}; or __builtin_memset(&k, 0, sizeof(k)) before filling it in. Both loaded.

3. A ring buffer reservation without a NULL check

// ringbuf.bpf.c — send each execve() caller's pid to user space
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct {
	__uint(type, BPF_MAP_TYPE_RINGBUF);
	__uint(max_entries, 4096);
} events SEC(".maps");

SEC("tracepoint/syscalls/sys_enter_execve")
int on_exec(void *ctx)
{
	__u64 *e = bpf_ringbuf_reserve(&events, sizeof(*e), 0);

	*e = bpf_get_current_pid_tgid();
	bpf_ringbuf_submit(e, 0);
	return 0;
}

char LICENSE[] SEC("license") = "GPL";
4: (85) call bpf_ringbuf_reserve#131
5: (bf) r6 = r0
; *e = bpf_get_current_pid_tgid();
6: (85) call bpf_get_current_pid_tgid#14
; *e = bpf_get_current_pid_tgid();
7: (7b) *(u64 *)(r6 +0) = r0
R6 invalid mem access 'mem_or_null'
processed 7 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

Part 1’s NULL check, in a different costume. bpf_ringbuf_reserve (5.8) fails when the buffer is full, and returns PTR_TO_MEM_OR_NULL. Fix: if (!e) return 0; before the store, which loaded.

4. Reading a header that wasn’t checked

// proto.bpf.c — drop UDP
#include <linux/bpf.h>
#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_endian.h>

SEC("xdp")
int drop_udp(struct xdp_md *ctx)
{
	void *data = (void *)(long)ctx->data;
	void *data_end = (void *)(long)ctx->data_end;
	struct ethhdr *eth = data;
	struct iphdr *ip = data + sizeof(*eth);

	if ((void *)(eth + 1) > data_end)
		return XDP_PASS;
	if (eth->h_proto != bpf_htons(ETH_P_IP))
		return XDP_PASS;
	if (ip->protocol == IPPROTO_UDP)
		return XDP_DROP;
	return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";
6: (71) r2 = *(u8 *)(r1 +12)
7: (71) r3 = *(u8 *)(r1 +13)
8: (67) r3 <<= 8
9: (4f) r3 |= r2
; if (eth->h_proto != bpf_htons(ETH_P_IP))
10: (55) if r3 != 0x8 goto pc+4
 R0_w=inv2 R1_w=pkt(id=0,off=0,r=14,imm=0) R2_w=inv(id=0,umax_value=255,var_off=(0x0; 0xff)) R3_w=inv8 R10=fp0
; if (ip->protocol == IPPROTO_UDP)
11: (71) r1 = *(u8 *)(r1 +23)
invalid access to packet, off=23 size=1, R1(id=0,off=23,r=14)
R1 offset is outside of the packet
processed 12 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

This one is in every XDP tutorial’s list of mistakes, and the log is unusually direct. The comparison of eth + 1 with data_end gave the packet pointer a proven range of 14 bytes, r=14, which is exactly the Ethernet header. ip->protocol is byte 23 (14 + 9), outside it. Fix: check the IP header too, if ((void *)(ip + 1) > data_end) return XDP_PASS;, which proves 34 bytes and loaded.

5. A misaligned atomic

// packed.bpf.c — a packed counter struct
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct stats {
	__u32 flags;
	__u64 packets;
} __attribute__((packed));

struct {
	__uint(type, BPF_MAP_TYPE_ARRAY);
	__uint(max_entries, 1);
	__type(key, __u32);
	__type(value, struct stats);
} st SEC(".maps");

SEC("xdp")
int count(struct xdp_md *ctx)
{
	__u32 key = 0;
	struct stats *s = bpf_map_lookup_elem(&st, &key);

	if (s)
		__sync_fetch_and_add(&s->packets, 1);
	return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";
; if (s)
7: (15) if r0 == 0x0 goto pc+2
 R0_w=map_value(id=0,off=0,ks=4,vs=12,imm=0) R10=fp0 fp-8=mmmm????
8: (b7) r1 = 1
; __sync_fetch_and_add(&s->packets, 1);
9: (db) lock *(u64 *)(r0 +4) += r1
misaligned value access off (0x0; 0x0)+0+4 size 8
processed 9 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

On x86-64 the verifier lets ordinary loads and stores be misaligned, because the CPU handles them. Two kinds of access are always checked strictly anyway: stack accesses, because the spill tracking depends on them, and atomics, which check_atomic passes to check_mem_access with strict alignment forced on. packets sits at offset 4, and an 8-byte atomic there is refused. (0x0; 0x0) in the message is the tnum of the pointer’s variable offset: none. clang warned about this at compile time (taking address of packed member 'packets' ... may result in an unaligned pointer value). Fix: drop packed, or put the 64-bit field first.

6. A socket reference never released

// sklookup.bpf.c — mark packets when something listens on port 80
#include <linux/bpf.h>
#include <linux/pkt_cls.h>
#include <bpf/bpf_helpers.h>

SEC("classifier")
int has_listener(struct __sk_buff *skb)
{
	struct bpf_sock_tuple t = {};
	struct bpf_sock *sk;

	t.ipv4.dport = __builtin_bswap16(80);
	sk = bpf_sk_lookup_tcp(skb, &t, sizeof(t.ipv4), BPF_F_CURRENT_NETNS, 0);
	if (!sk)
		return TC_ACT_OK;
	skb->mark = 1;
	return TC_ACT_OK;
}

char LICENSE[] SEC("license") = "GPL";
16: (15) if r0 == 0x0 goto pc+2
 R0_w=sock(id=0,ref_obj_id=2,off=0,imm=0) R6_w=ctx(id=0,off=0,imm=0) R10=fp0 fp-8=????0000 fp-16_w=00000000 fp-24_w=00000000 fp-32_w=0000mmmm fp-40_w=mmmmmmmm refs=2
17: (b7) r1 = 1
; skb->mark = 1;
18: (63) *(u32 *)(r6 +8) = r1
; }
19: (b7) r0 = 0
20: (95) exit
Unreleased reference id=2 alloc_insn=15
processed 21 insns (limit 1000000) max_states_per_insn 0 total_states 1 peak_states 1 mark_read 0

bpf_sk_lookup_tcp (4.20) returns a socket with its reference count raised, and the verifier tracks that reference, here id 2, acquired at instruction 15, like a resource in a language with linear types. Reaching exit with it still held would leak a socket every time the program ran. The NULL path is fine, which is why the error appears only at the end of the non-NULL path. Fix: bpf_sk_release(sk); before the return, which loaded.

7. A helper the program type doesn’t get

// xdpcomm.bpf.c — record which process a packet arrived during
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct {
	__uint(type, BPF_MAP_TYPE_ARRAY);
	__uint(max_entries, 1);
	__type(key, __u32);
	__type(value, char[16]);
} who SEC(".maps");

SEC("xdp")
int whose_packet(struct xdp_md *ctx)
{
	__u32 key = 0;
	char *comm = bpf_map_lookup_elem(&who, &key);

	if (comm)
		bpf_get_current_comm(comm, 16);
	return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";
7: (15) if r0 == 0x0 goto pc+3
 R0_w=map_value(id=0,off=0,ks=4,vs=16,imm=0) R10=fp0 fp-8=mmmm????
; bpf_get_current_comm(comm, 16);
8: (bf) r1 = r0
9: (b7) r2 = 16
10: (85) call bpf_get_current_comm#16
unknown func bpf_get_current_comm#16
processed 10 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

“unknown func” is misleading: the helper exists, helper 16, and clang compiled the call happily, because to clang a helper is just a number. Each program type has its own function that maps helper numbers to what that type may call, and XDP’s doesn’t include this one. An XDP program runs in the driver’s receive path, in whatever task happened to be interrupted, so “the current task” is meaningless there. Fix: none, in XDP. The question has to be asked from a hook that runs in process context, such as a tracepoint or kprobe.

8. A GPL-only helper in a non-GPL program

// nongpl.bpf.c — read a word of the kprobe's context
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

SEC("kprobe/do_sys_openat2")
int peek(void *ctx)
{
	__u64 v = 0;

	bpf_probe_read_kernel(&v, sizeof(v), ctx);
	return v == 0;
}

char LICENSE[] SEC("license") = "Proprietary";
; bpf_probe_read_kernel(&v, sizeof(v), ctx);
5: (b7) r2 = 8
6: (85) call bpf_probe_read_kernel#113
cannot call GPL-restricted function from non-GPL compatible program
processed 7 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

This is the licence string from Part 1 doing its job. Each helper’s prototype has a gpl_only flag, and on this kernel most of the tracing helpers set it: bpf_probe_read_kernel and _user, bpf_trace_printk, bpf_get_current_task, even bpf_perf_event_output for tracepoint programs. The kernel checks the string with the same license_is_gpl_compatible it uses for modules. Fix: a GPL-compatible licence, such as "GPL" or "Dual BSD/GPL", or a helper without the flag.

9. A kernel address handed back to an unprivileged user

// leak.bpf.c — return the context pointer
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>

SEC("socket")
int leak(struct __sk_buff *skb)
{
	return (long)skb;
}

char LICENSE[] SEC("license") = "GPL";
$ setpriv --reuid=nobody --regid=nogroup --clear-groups ./vload leak.bpf.o
0: (bf) r0 = r1
1: (95) exit
R0 leaks addr as return value
processed 2 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

A socket filter’s return value decides how much of the packet the socket receives, and anyone who can attach a filter can observe that. If the return value could be a kernel address, an unprivileged user could learn where the kernel keeps its data, which is a large step towards exploiting any other bug. So env->allow_ptr_leaks is set only for loaders with CAP_PERFMON (or root), and without it a pointer may not be returned, stored into a map, or passed where it could be read back. Root loads this program without complaint. Fix: don’t return pointers; it is never what you meant.

Reading a rejection

After a few dozen of these, a routine settles in.

  • Read the last line before the statistics first. It names the register and what was wrong with it. Then read the state printed just above it, where the register’s type and bounds are.
  • Find the instruction in the C. With -g, the log interleaves source lines (; if (!h)), courtesy of the BTF line information the loader uploads. They are approximate: clang moves code around, and a source line can stand above instructions from several lines.
  • Ask what the verifier knew, not what you know. Every fix in this post adds information the verifier could not infer: a bounds check, a NULL check, a narrower type, an explicit loop counter, an initialised byte.
  • When a fix doesn’t take, look for the compiler. clang may have kept the variable in a different register from the one that was checked, merged two checks, or turned a branch into arithmetic. The objdump and the level-2 log together show what the verifier actually saw.
  • Watch the instruction count, not just the result. A program that loads at 900,000 processed instructions is one compiler upgrade away from not loading.

What’s around in July 2022

The kernel I ran these on is 5.15, Ubuntu 22.04’s. The newest release is 5.18, from May, and 5.19 is at its sixth release candidate. The verifier on all of them is the same design as in this post. One thing a reader on a newer kernel will notice is that the log reads differently. On 5.18 the histogram’s instruction 11 prints as

11: (77) r6 >>= 5                     ; R6_w=scalar(umax=576460752303423487,var_off=(0x0; 0x7ffffffffffffff))

with each state on its instruction’s own line after a ;, scalar where 5.15 says inv, umax for umax_value, and the precision mark in front (Pscalar). The facts are the same. On the user-space side, libbpf 0.8 (May) and bpftrace 0.15 (May) are the current releases, and libbpf 1.0 is still being prepared. Every one of these tools ends in the same BPF_PROG_LOAD, so every one of them meets the same verifier.

What we covered

  • The verifier proves that a program terminates, accesses only memory it may, reads nothing uninitialised, calls only the helpers its type and licence allow, and releases what it acquires. When it can’t prove something, it refuses: “I don’t know” means no.
  • Pass 1, check_cfg, walks the program as a graph: unreachable instructions and jumps out of range are rejected, and back-edges too, unless the loader has CAP_BPF (since 5.3).
  • Pass 2, do_check, executes the program on abstract values. Each register has a type (scalar, or a pointer to context, stack, map value, packet, …); _OR_NULL pointers become real pointers on one side of a NULL check and the scalar 0 on the other.
  • Scalars carry signed and unsigned bounds for 64 and 32 bits, and a tnum, which tracks each bit as 0, 1 or unknown. Comparisons narrow bounds, and the two forms tighten each other.
  • State pruning stops a path when its state is within one already proven safe. Liveness and precision decide which differences matter: K branches cost eight and a half instructions each when the differing value was only stored, and doubled the work with every branch when it was used as an index.
  • The budgets: 1,000,000 processed instructions (5.2), 8,192 pending branches (5.3).
  • Bounded loops (5.3) are verified by walking every iteration: 12 instructions per iteration of a 12-instruction body, at most 83,332 iterations. bpf_loop (5.17) verifies the body once, 29 instructions for any count up to 8,388,608, and costs more per iteration at run time.
  • Nine rejections, nine fixes: a signed index, struct padding, a missing NULL check, an unchecked header, a misaligned atomic, a leaked socket, a helper the type doesn’t get, a GPL-only helper, and a leaked pointer.

The next part leaves the verifier and turns to the data structures programs keep their state in: maps, in all their kinds, and the ring buffer that is taking over from the perf buffer for getting events out.

A note on the evidence

What I ran, and where. Every log in this post is pasted from a real run. The machine was a KVM virtual machine with 4 virtual CPUs and 4 GiB of memory, booting Ubuntu 22.04’s release kernel, 5.15.0-25-generic #25-Ubuntu SMP Wed Mar 30 15:54:22 UTC 2022, on a minimal 22.04 userland built from the release archive only: clang 14.0.0-1ubuntu1 and libbpf-dev 0.5.0-1. The bpf_loop section ran on the Ubuntu mainline build of 5.18, 5.18.0-051800-generic #202205222030, with the same 22.04 userland. Every C file in this post, and the build commands, were extracted from this page, compiled, and loaded as shown; each fix described in the gallery was applied to the extracted file and loaded too.

What I trimmed. The gallery logs are the last lines of each level-1 log. libbpf’s framing lines (libbpf: load bpf program failed, -- BEGIN DUMP LOG ---, and the closing ones) are cut, and so are the instruction lines that load a map address, which print a kernel address that changes with every boot, and the line arg#0 reference type('UNKNOWN ') size cannot be determined: -22 that opens the logs of the tracepoint and kprobe programs, a BTF diagnostic about their void *ctx argument that doesn’t affect the result. Where a log is cut in the middle, the cut is marked .... The level-2 log of the worked example is quoted register by register, and the figure shows, for each instruction, the registers that changed, as that log printed them. The objdump is as printed, without the raw-bytes column.

The measurements. Instruction counts are the verifier’s own processed figure, from loads with log_level 4, which are deterministic: the same object gave the same count on every load. The verification times in data/ebpf_part04.json are from the same loads and vary from load to load; I quote none of them in the text. The run-time comparison used BPF_PROG_TEST_RUN on a 64-byte zeroed packet, seven interleaved rounds of both programs at N = 10, 100, 1,000 and 10,000, each measurement 2,000,000/N runs, with no other test virtual machine running, and the figure shows every round.

What I cited rather than ran. The kernel versions in which features landed (tnums in 4.14, BPF_PROG_TEST_RUN in 4.12, bpf_sk_lookup_tcp in 4.20, the 1M limit in 5.2, bounded loops and the jump-sequence limit in 5.3, 32-bit bounds in 5.7, bpf_loop in 5.17) were checked by asking which release tag first contains the commit that introduced each, and the limits before 5.2 and 5.3 by reading verifier.c at the older tags. The quotations are from 5.15’s verifier.c and tnum.c, condensed where marked. The tnum examples were checked by running the functions from tnum.c in user space.

What I’d still change. The run-time numbers come from one virtual machine and one loop body, a chain of dependent multiplications that hides most of the indirect call’s cost. A body with more independent work would show more of it, and I’d want a few such bodies before putting a number on bpf_loop’s overhead in general. And the verifier counts here are for clang 14’s code. Another compiler version can emit a different body, and the counts with it.

More