← Writing

eBPF Learns to Allocate

Contents

On Linux 6.10, a sleep command ran for a tenth of a second, exited and was reaped by its parent, and the kernel duly reported that no process with its ID existed any more. A BPF map still held the kernel’s record of it, the task structure, with a reference count of exactly one: the map’s own. A red-black tree, built by a BPF program out of objects it had allocated itself, named the five most CPU-hungry of ten processes, in order. The loop from Part 4 that had spent the verifier’s entire budget of a million instructions loaded after 42, with one line added. And a user-space program walked a million-node linked list that a BPF program had built, following ordinary pointers, in about 2.2 milliseconds; through map lookups, the same walk took about 370.

Two years ago, Part 5 of this series was called “Maps are the only memory you get”, and it was right. This part is about how that stopped being true: kernel pointers kept in maps, objects a program allocates and frees, lists and trees built from them, loops the verifier no longer has to walk, and memory shared with user space, each added one release at a time without giving up any of the verifier’s guarantees.

This is Part 13 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 Linux 6.10, released on 14 July, under Ubuntu 24.04’s userland (clang 18), with libbpf 1.4.5 and bpftool 7.4.0 built from their release tags. The output is pasted from those runs, not reconstructed. The note at the end says exactly where and how.

Where Part 5 left off

On Linux 5.19, where Part 5 ran, the title was the plain truth. A BPF program had eleven registers and a 512-byte stack, both gone when it returned. Everything it kept, it kept in a map: a kernel object of a fixed type, with keys and values of sizes fixed when the map was created. A hash map with room for a million entries cost 77 MiB the moment it existed, because hash maps allocate every element in advance unless told not to, so that a program running inside the memory allocator itself can never be the one that needs it.

That model is safe for reasons that are easy to state. The verifier knows the size of every value, so it can check every access against it. There are no pointers between values, so nothing can dangle. Nothing is allocated while the program runs, so nothing can leak. But look at what it rules out:

  • Holding on to a kernel object. A program that sees a struct task_struct go past can copy fields out of it. It cannot keep the task itself, because a pointer stored in a map would outlive the task, and nothing would stop it being read after the task was freed.
  • Allocating on demand. Every object is a map value, so the most objects a program can ever have is decided when the map is created, and their memory is spent from then on whether it is used or not.
  • Linking objects. A linked list in a hash map is a value holding the key of the next value. Following one link is a map lookup: a helper call in the program, a system call from user space.
  • Looping over anything big. Part 4 measured that the verifier walks a bounded loop once per iteration, which runs into its budget of a million instructions at tens of thousands of trips, and that bpf_loop escapes the budget only by moving the loop body into a callback.

Each of those has been lifted since, one release at a time, and none of them by switching the verifier off. This part goes through them in order, each with a program I loaded and ran on 6.10: kernel pointers in maps (5.19), objects a program allocates itself (6.2), lists and trees built from them (6.2 and 6.3), loops the verifier no longer has to walk (6.4 and 6.9), and finally an arena, a region of memory shared between a BPF program and user space in which a pointer means the same thing on both sides (6.9). Along the way come exceptions (6.7), a way to defer work that sleeps (6.10), and the BPF token, which hands a slice of all this to a process that is not root (6.9).

From fixed-size values to shared pages

The releases that changed what a BPF program can keep. Pick one; the grid shows what a program could do by then.

Linux 3.19 · 2015-02-08

Hash and array maps

State that outlives one run, and the only state there is: fixed-size values under fixed-size keys, the sizes chosen when the map is created. A program reaches a value only by looking it up.

val = bpf_map_lookup_elem(&counts, &key);

Linux 5.1 · 2019-05-05

bpf_spin_lock

A lock inside a map value, so a value with several fields can be updated as a unit. The verifier makes sure it is released on every path and that nothing is called while it is held.

struct val { struct bpf_spin_lock lock; __u64 a, b; };

Linux 5.3 · 2019-09-15

Bounded loops

Real backward jumps, which the verifier proves finite by walking every iteration. The cost of the proof grows with the count.

for (i = 0; i < N; i++) ...

Linux 5.5 · 2020-01-26

mmap-able arrays

User space can map an array's memory and read it without a system call. Still one fixed array, sized at creation, its elements linked only by index.

__uint(map_flags, BPF_F_MMAPABLE);

Linux 5.17 · 2022-03-20

bpf_loop

The kernel runs a callback up to 223 times; the verifier checks the callback once.

bpf_loop(N, step, &state, 0);

Linux 5.19 · 2022-07-31

kptrs in map values

A map value can hold a typed pointer to a kernel object. A referenced kptr keeps the object alive; bpf_kptr_xchg moves ownership in and out atomically.

struct task_struct __kptr *task;
old = bpf_kptr_xchg(&v->task, ref);

Linux 6.1 · 2022-12-11

The BPF memory allocator

Not something a program calls: per-CPU caches of free objects, refilled from irq_work, so that allocation is safe in any context a program can run in, NMI included. What the next release builds on.

kernel/bpf/memalloc.c

Linux 6.2 · 2023-02-19

bpf_obj_new, linked lists, task kptrs

A program allocates objects of its own types, and links them into a list whose head sits in a map value next to the lock that guards it. Tasks gain acquire and release kfuncs.

e = bpf_obj_new(typeof(*e));
bpf_list_push_back(&head, &e->node);

Linux 6.3 · 2023-04-23

Red-black trees

Ordered collections: add with a less() callback, take the leftmost node, remove it. Same ownership rules as the list.

bpf_rbtree_add(&root, &e->node, less);

Linux 6.4 · 2023-06-25

Open-coded iterators, shared ownership

A loop driven by an iterator object, which the verifier checks until its state stops changing rather than once per iteration. Local objects get a reference count, so one can sit in a list and a tree at once. __kptr now means referenced.

bpf_for(i, 0, n) ...

Linux 6.7 · 2024-01-07

Exceptions

bpf_throw ends the program from any depth, and an exception callback chooses the return value: assertions that also teach the verifier a bound.

bpf_assert(x < 100);

Linux 6.9 · 2024-05-12

Arena, may_goto, BPF token

Up to 4 GiB of pages shared with user space, where a pointer means the same thing on both sides. A loop instruction with a hidden budget. And a way to hand a slice of BPF to a container.

__uint(type, BPF_MAP_TYPE_ARENA);
cond_break;

Linux 6.10 · 2024-07-14

bpf_wq

A work item in a map value: a program that may not sleep hands a callback to a kernel worker that may.

bpf_wq_start(&job->wq, 0);

What a program could do by then

keep fixed-size values between runs3.19 update a multi-field value under a lock5.1 loop, if the verifier can count the iterations5.3 share an array's memory with user space5.5 loop millions of times, through a callback5.17 hold a kernel object alive in a map5.19 allocate and free objects of its own types6.2 link them into a list6.2 keep them sorted in a tree6.3 loop in place, verified in constant work6.4 abort from any depth6.7 loop where the verifier cannot see the end6.9 build pointer structures user space reads directly6.9 be loaded from inside a user namespace6.9 defer work that sleeps6.10

Versions are the first release whose tag contains the feature's commit. The 6.1 allocator is internal; nothing in a program names it, but every allocation in this post goes through it.

The toolchain, July 2024

Ubuntu 24.04 came out in April with Linux 6.8, clang 18, libbpf 1.3, bpftrace 0.20.2 and BCC 0.29.1. Most of this part needs more than that.

The kernel is the obvious gap: the arena, may_goto and the token are 6.9, and bpf_wq is 6.10. I ran everything on Ubuntu’s mainline build of 6.10, 6.10.0-061000-generic, under the 24.04 userland.

libbpf 1.3 is the next gap. libbpf 1.4, released on 1 April, is the first version that knows the arena map type and the special section its globals live in, and the first that can create and use a BPF token, so I built libbpf 1.4.5, released on 11 July, from its tag, and installed it under /usr/local. Ubuntu ships bpftool only inside each kernel’s linux-tools package, and there is none for a mainline 6.10, so I built bpftool 7.4.0 from its tag too.

The compiler is the subtle one. Two of the features in this part come with new instructions: an address-space cast for the arena, and may_goto for loops. A compiler that knows about them announces it with a predefined macro. clang 18 knows neither:

$ clang -target bpf -dM -E - </dev/null | grep -c FEATURE
0

The kernel’s own BPF selftests have the same problem on older compilers, and the headers they use carry a fallback: when the macros are missing, the instructions are written out by hand, as raw bytes in inline assembly. Those two headers, bpf_experimental.h and bpf_arena_common.h from tools/testing/selftests/bpf in the 6.10 tree, are also where the convenience macros for everything else in this part live (bpf_obj_new, __contains, cond_break, bpf_assert), so every program below includes one or both. They are test headers, not a stable API: everything in this part that is not in libbpf’s own headers comes from them.

Here is the whole build. It needs clang, libelf-dev, zlib1g-dev, and libbpf 1.4 and bpftool 7.4 installed as above:

# build.sh — everything in this post, from one directory
T=https://raw.githubusercontent.com/torvalds/linux/v6.10/tools/testing/selftests/bpf
curl -sO $T/bpf_experimental.h
curl -sO $T/bpf_arena_common.h
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h

BPF="clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -I. -I/usr/local/include"
CC="cc -g -O2 -Wall -I. -I/usr/local/include"
LIBS="-L/usr/local/lib64 -l:libbpf.a -lelf -lz"

for p in stash topn arenalist defer; do			# programs with a skeleton
	$BPF -c $p.bpf.c -o $p.bpf.o
	bpftool gen skeleton $p.bpf.o > $p.skel.h
	$CC $p.c $LIBS -o $p
done
$BPF -c popcount.bpf.c -o popcount.bpf.o
$BPF -c throw.bpf.c -o throw.bpf.o
$BPF -DN=100 -c loops.bpf.c -o loops.bpf.o		# and -DN=<count> for the sweep
$CC bench.c $LIBS -o bench
$CC token.c $LIBS -o token

kfuncs. Almost everything new in this part is called through a kfunc rather than a helper. Helpers have fixed numbers in the UAPI and live forever; a kfunc is an ordinary kernel function that the kernel exports to BPF by listing it, with flags saying how the verifier must treat it, and it can change between releases. A program declares one as an extern with the __ksym attribute, and libbpf finds its BTF ID in the running kernel’s BTF at load time. The prototypes in this part come either from bpf_experimental.h or, where there are only two, are written out in the program.

Pointers the verifier can follow: kptrs

The first step, in 5.19, was letting a map value hold a pointer at all. A kptr is a field in a map value, declared with the __kptr tag, that holds a pointer to a kernel object of one BTF type. The verifier knows the field’s type from the program’s BTF, so when the program loads it, the result is not a number but a typed pointer, and the program can read the object’s fields through it the way it can read the fields of a tracepoint’s arguments.

The hard part is lifetime, and that is what the two kinds of kptr are about.

An untrusted kptr (on 6.10, __kptr_untrusted) stores a pointer and nothing else. The object may be freed while the pointer sits in the map. Reads through it are compiled as probe reads, which cannot crash the kernel but may return garbage or zeros, and the pointer cannot be passed to anything that acts on the object.

A referenced kptr (__kptr) owns a reference to the object. The only way to put one into a map value is bpf_kptr_xchg, which swaps the field with a pointer the program holds a reference to, atomically, and hands back whatever was there before. The reference moves into the map; the old one, if any, moves out to the program, which now has to release it. When the map element is deleted, or the map itself is freed, the kernel calls the type’s registered destructor, so a reference in a map can never leak either.

That needs the type to have acquire and release functions and a destructor. 5.19 added the mechanism, but in 5.19 and 6.1 the only type with a destructor registered was a test object in net/bpf/test_run.c; tasks and cgroups got theirs, with bpf_task_acquire and bpf_task_release, in 6.2. And in 6.4 the names were swapped round: what 5.19 called __kptr_ref became plain __kptr, and the old unreferenced __kptr became __kptr_untrusted, so code from 2022 means the opposite of what it says.

Here is a program that keeps a referenced pointer to every task that executes sleep, keyed by its PID, and a second program, run on demand from user space, that takes the pointer back out:

// stash.bpf.c — keep a counted reference to a task in a map value
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>

struct task_struct *bpf_task_acquire(struct task_struct *p) __ksym;
void bpf_task_release(struct task_struct *p) __ksym;

struct stash {
	struct task_struct __kptr *task;	/* a referenced kptr */
};

struct {
	__uint(type, BPF_MAP_TYPE_HASH);
	__uint(max_entries, 64);
	__type(key, int);
	__type(value, struct stash);
} stashed SEC(".maps");

struct seen {
	char comm[16];
	int pid, exit_code;
	unsigned int state, exit_state, refs;
};
struct seen seen;	/* filled in by inspect(), read by user space */

SEC("tp_btf/sched_process_exec")
int BPF_PROG(remember, struct task_struct *p)
{
	struct stash empty = {}, *s;
	struct task_struct *ref, *old;
	int pid = p->pid;

	if (p->comm[0] != 's' || p->comm[1] != 'l' || p->comm[2] != 'e')
		return 0;			/* only "sleep" */
	bpf_map_update_elem(&stashed, &pid, &empty, BPF_NOEXIST);
	s = bpf_map_lookup_elem(&stashed, &pid);
	if (!s)
		return 0;
	ref = bpf_task_acquire(p);		/* reference count + 1 */
	if (!ref)
		return 0;
	old = bpf_kptr_xchg(&s->task, ref);	/* the map owns it now */
	if (old)
		bpf_task_release(old);
	return 0;
}

SEC("syscall")
int inspect(int *ctx)
{
	int pid = *ctx;				/* a map key must be on the stack */
	struct stash *s = bpf_map_lookup_elem(&stashed, &pid);
	struct task_struct *t;

	if (!s)
		return -1;
	t = bpf_kptr_xchg(&s->task, NULL);	/* now we own it */
	if (!t)
		return -2;
	__builtin_memcpy(seen.comm, t->comm, sizeof(seen.comm));
	seen.pid = t->pid;
	seen.exit_code = t->exit_code;
	seen.state = t->__state;
	seen.exit_state = t->exit_state;
	seen.refs = t->usage.refs.counter;
	bpf_task_release(t);			/* and give it back */
	return 0;
}

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

remember is a tp_btf program, a tracepoint whose arguments arrive with their BTF types, so p is a trusted pointer to the task that just called execve(). It acquires a reference to it, and bpf_kptr_xchg puts that reference into the map. inspect is a SEC("syscall") program, a type that is never attached to anything and only runs when user space asks it to through BPF_PROG_TEST_RUN, with whatever context user space passes in; here, a PID. It swaps the pointer out of the map, so the program now owns the reference, reads six fields from the task, and releases it.

User space starts a sleep, waits for it to exit and reaps it, so that as far as the rest of the system is concerned the process is gone, and then runs inspect:

// stash.c — run "sleep", reap it, then ask the map about it
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>

struct seen {				/* the layout of the BPF side's global */
	char comm[16];
	int pid, exit_code;
	unsigned int state, exit_state, refs;
};
#include "stash.skel.h"

int main(void)
{
	LIBBPF_OPTS(bpf_test_run_opts, opts);
	struct stash_bpf *skel = stash_bpf__open_and_load();
	int pid, status, err;

	if (!skel || stash_bpf__attach(skel))
		return 1;
	pid = fork();
	if (pid == 0) {
		execl("/bin/sleep", "sleep", "0.1", (char *)NULL);
		_exit(127);
	}
	waitpid(pid, &status, 0);		/* reaped: the pid is gone */
	printf("sleep was pid %d, exited %d; kill(%d, 0) now says: %s\n",
	       pid, WEXITSTATUS(status), pid,
	       kill(pid, 0) ? "no such process" : "alive");

	opts.ctx_in = &pid;
	opts.ctx_size_in = sizeof(pid);
	err = bpf_prog_test_run_opts(bpf_program__fd(skel->progs.inspect), &opts);
	if (err || opts.retval) {
		fprintf(stderr, "inspect: err %d retval %d\n", err, opts.retval);
		return 1;
	}
	printf("the map still held: comm=%s pid=%d exit_code=%d __state=0x%x "
	       "exit_state=0x%x usage=%u\n", skel->bss->seen.comm,
	       skel->bss->seen.pid, skel->bss->seen.exit_code,
	       skel->bss->seen.state, skel->bss->seen.exit_state,
	       skel->bss->seen.refs);
	stash_bpf__destroy(skel);
	return 0;
}
$ sudo ./stash
sleep was pid 317, exited 0; kill(317, 0) now says: no such process
the map still held: comm=sleep pid=317 exit_code=0 __state=0x80 exit_state=0x10 usage=1

kill(pid, 0) says the process does not exist. The map disagrees: it still holds the task_struct, and the fields are those of a dead task. __state is 0x80, TASK_DEAD; exit_state is 0x10, EXIT_DEAD, the state of a task whose parent has collected its exit status. And usage, the task’s reference count, is 1. Every other holder has let go, the PID has been freed, and the only thing keeping this structure in memory is the map’s reference, which inspect then released. A copy-the-fields program could have told us the same about a live task; only a referenced kptr can still answer after the process is gone.

The verifier’s side of this is reference tracking, the same machinery Part 4 showed rejecting a socket lookup that was never released. Each acquire gives the result a reference ID, and the program must release or hand off every ID before it exits, on every path. Delete the bpf_task_release(t) line from inspect and:

$ sudo ./bench stash_norelease.bpf.o inspect
40: (bf) r0 = r1                      ; R0_w=0 R1_w=0 refs=3
41: (95) exit
Unreleased reference id=3 alloc_insn=12
processed 38 insns (limit 1000000) max_states_per_insn 0 total_states 1 peak_states 1 mark_read 1
inspect: not loaded

Instruction 12 is the bpf_kptr_xchg call: the swap out of the map counts as an acquire, because from that point the program, not the map, owns the reference.

Objects of your own: bpf_obj_new

A kptr points at something the kernel made. The next step, in 6.2, was letting a program make things. bpf_obj_new(type) allocates an object of a struct type defined in the program itself, and bpf_obj_drop() frees one. These are called local kptrs: pointers to objects whose type comes from the program’s BTF rather than the kernel’s.

Two things made that safe. The first is the allocator. A BPF program can run in contexts where the ordinary kernel allocator must not be called, inside an NMI handler or with the allocator’s own locks held, which is exactly why Part 5’s hash maps preallocate. 6.1 added a BPF-specific allocator, kernel/bpf/memalloc.c, that keeps per-CPU caches of free objects and refills them from a deferred irq_work, so that taking an object from the cache never has to call into the page allocator from the program’s context. bpf_obj_new takes from those caches.

The second is that the object comes back as an owning reference, tracked exactly like the task reference above: it may be NULL, and once it isn’t, every path must free it or give it to something that will. The verifier also knows the object’s layout. A struct can contain special fields, struct bpf_rb_node, struct bpf_list_node, a bpf_spin_lock or a reference count, and the program may not read or write those directly; everything else is ordinary memory the program owns. One consequence is worth knowing: bpf_obj_new initialises only the special fields (the 6.10 source clears the tree node and sets a reference count to 1). The rest of the object is whatever was in the cache, so write a field before you read it.

An object nobody points to is not much use, and the obvious place to put one, a __kptr field in a map value, works: bpf_kptr_xchg accepts local kptrs as well as kernel ones. The more interesting place is a data structure.

Lists and trees, and who owns what

6.2 added linked lists and 6.3 red-black trees, built from objects that bpf_obj_new returned. The kernel already has both, in include/linux/list.h and lib/rbtree.c, and the BPF versions are thin wrappers around them. What is new is the set of rules that lets the verifier prove a program cannot corrupt them, and those rules are the most interesting part of this post.

A list or tree has a root, struct bpf_list_head or struct bpf_rb_root, and its elements contain a node, struct bpf_list_node or struct bpf_rb_node. The rules:

  1. The root lives in a map value, next to the lock that guards it. A bpf_spin_lock in the same value protects the root, and every operation on the root must be done with that lock held. Because the lock and the root are in one value, the verifier can check this without knowing anything at run time: “the lock at offset 0 of this map value is held” is a fact about the program’s state, like a register’s type.
  2. The root declares what it contains. A BTF declaration tag, written with the __contains macro, names the element type and which field of it is the node, so the verifier knows that a node it gets back from the tree is part of a struct entry and where the rest of it is.
  3. Adding transfers ownership. bpf_rbtree_add or bpf_list_push_back consumes the owning reference. The program’s pointer to the object survives as a non-owning reference, which it may still use, but only until the lock is released, because after that another CPU can remove the object and free it.
  4. Removing transfers it back. bpf_rbtree_remove or bpf_list_pop_front returns an owning reference again, which must be freed or added somewhere.
  5. Nothing else is called with the lock held. The list and tree kfuncs and the unlock are the only calls allowed inside, so the lock is held for a bounded, short time, and a program can never sleep, or free memory, with it held.

For a tree there is one more thing: bpf_rbtree_add takes a less() callback, a BPF function the kernel calls during the insert to compare two nodes. The tree in 6.10 offers add, remove, and bpf_rbtree_first, which returns the leftmost node; there is no way to walk it, or look up a key, other than taking the smallest node out.

The worked example: the five hungriest tasks

That is enough for a classic use of a tree: keep the top N of something, here the five tasks that used the most CPU time before they exited. A min-ordered tree does it cheaply. Insert every task as it exits; if the tree now has six entries, the leftmost one is the smallest of them, so remove it and free it. What is left is always the five largest seen so far.

// topn.bpf.c — the five tasks that used the most CPU before they exited
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include "bpf_experimental.h"

#define TOPN 5

struct entry {
	struct bpf_rb_node node;	/* what links it into the tree */
	__u64 runtime_ns;
	int pid;
	char comm[16];
};

/* The lock and the root it protects must live in the same map value:
 * here, one global section, which libbpf turns into one array map. */
#define private(name) SEC(".data." #name) __hidden __attribute__((aligned(8)))
private(top) struct bpf_spin_lock lock;
private(top) struct bpf_rb_root root __contains(entry, node);
private(top) __u32 count;

struct row {
	__u64 runtime_ns;
	int pid;
	char comm[16];
} out[TOPN];				/* filled in by report() */
__u64 exits;

static bool less(struct bpf_rb_node *a, const struct bpf_rb_node *b)
{
	struct entry *x = container_of(a, struct entry, node);
	struct entry *y = container_of(b, struct entry, node);

	return x->runtime_ns < y->runtime_ns;
}

SEC("tp_btf/sched_process_exit")
int BPF_PROG(on_exit, struct task_struct *p)
{
	struct bpf_rb_node *n;
	struct entry *e;

	__sync_fetch_and_add(&exits, 1);
	e = bpf_obj_new(typeof(*e));		/* owning reference, or NULL */
	if (!e)
		return 0;
	e->runtime_ns = p->se.sum_exec_runtime;
	e->pid = p->pid;
	__builtin_memcpy(e->comm, p->comm, sizeof(e->comm));

	bpf_spin_lock(&lock);
	bpf_rbtree_add(&root, &e->node, less);	/* the tree owns e now */
	if (++count <= TOPN) {
		bpf_spin_unlock(&lock);
		return 0;
	}
	n = bpf_rbtree_first(&root);		/* the smallest: evict it */
	if (n)
		n = bpf_rbtree_remove(&root, n);	/* owning reference again */
	if (n)
		count--;
	bpf_spin_unlock(&lock);
	if (n)
		bpf_obj_drop(container_of(n, struct entry, node));
	return 0;
}

SEC("syscall")
int report(void *ctx)
{
	struct bpf_rb_node *n;
	struct entry *e;
	int i;

	bpf_for(i, 0, TOPN) {			/* pops in ascending order */
		bpf_spin_lock(&lock);
		n = bpf_rbtree_first(&root);
		if (n)
			n = bpf_rbtree_remove(&root, n);
		if (n)
			count--;
		bpf_spin_unlock(&lock);
		if (!n)
			break;
		e = container_of(n, struct entry, node);
		out[TOPN - 1 - i].runtime_ns = e->runtime_ns;
		out[TOPN - 1 - i].pid = e->pid;
		__builtin_memcpy(out[TOPN - 1 - i].comm, e->comm, sizeof(e->comm));
		bpf_obj_drop(e);
	}
	return 0;
}

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

Taking it from the top:

  • struct entry is the object the program allocates. Its first member is the tree node, 32 bytes the program must not touch, and the rest is its own: the CPU time, the PID and the name.
  • private(top) puts the lock, the root and a counter into one section, .data.top. libbpf turns every global data section into a single-element array map, so these three variables become one map value: the lock at offset 0, the root at offset 8, the counter at 24. That is rule 1, met by the layout. The macro is the selftests’ idiom; a struct in an ordinary array or hash map would do the same, and then each map element would be a separate tree with its own lock.
  • __contains(entry, node) on the root is rule 2.
  • less() orders by CPU time, smallest first, so bpf_rbtree_first is the cheapest entry.
  • on_exit runs on the sched_process_exit tracepoint, for every task that exits. It allocates an entry and fills it in from the exiting task: se.sum_exec_runtime is the scheduler’s running total of the CPU time the task has used, in nanoseconds. Then, under the lock, it adds the entry, bumps the count, and if there are more than five, removes the smallest. The free happens after the unlock (rule 5).
  • report is another syscall program. It takes the entries out smallest first, writes them into the global array out from the end backwards, so that out[0] is the largest, and frees them. It uses bpf_for, which comes later in this post; for now, it is a for loop from 0 to 5 that the verifier can check without walking it five times.

The user-space half starts ten child processes that each burn a different amount of CPU, from 10 ms to 100 ms, one after the other and in a scrambled order, then runs report. It also turns on bpf_stats, the kernel’s per-program run-time accounting, to see what all this costs per exit; an optional argument adds that many children that exit at once, to give the average more runs:

// topn.c — start ten CPU burners, then ask the tree which five burned most
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <sys/prctl.h>
#include <sys/wait.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>

struct row {				/* the layout of the BPF side's global */
	__u64 runtime_ns;
	int pid;
	char comm[16];
};
#include "topn.skel.h"

static void burn(int ms)	/* spin until this thread has used ms of CPU */
{
	struct timespec t;
	char name[16];

	snprintf(name, sizeof(name), "burn%d", ms);
	prctl(PR_SET_NAME, name);
	do
		clock_gettime(CLOCK_THREAD_CPUTIME_ID, &t);
	while (t.tv_sec * 1000 + t.tv_nsec / 1000000 < ms);
}

int main(int argc, char **argv)
{
	static const int ms[] = { 30, 90, 10, 60, 100, 20, 80, 50, 40, 70 };
	int i, extra = argc > 1 ? atoi(argv[1]) : 0, stats_fd;
	LIBBPF_OPTS(bpf_test_run_opts, opts);
	struct bpf_prog_info info = {};
	__u32 len = sizeof(info);
	struct topn_bpf *skel;

	skel = topn_bpf__open_and_load();
	if (!skel || topn_bpf__attach(skel))
		return 1;
	stats_fd = bpf_enable_stats(BPF_STATS_RUN_TIME);	/* time every run */
	for (i = 0; i < 10 + extra; i++) {
		if (fork() == 0) {
			if (i < 10)
				burn(ms[i]);
			_exit(0);		/* the extras exit at once */
		}
		wait(NULL);
	}
	bpf_prog_get_info_by_fd(bpf_program__fd(skel->progs.on_exit), &info, &len);
	bpf_prog_test_run_opts(bpf_program__fd(skel->progs.report), &opts);
	printf("%llu exits seen, on_exit took %llu ns per run\n",
	       (unsigned long long)skel->bss->exits,
	       (unsigned long long)(info.run_cnt ? info.run_time_ns / info.run_cnt : 0));
	for (i = 0; i < 5; i++)
		printf("%-8s pid %-5d %6.1f ms\n", skel->bss->out[i].comm,
		       skel->bss->out[i].pid, skel->bss->out[i].runtime_ns / 1e6);
	close(stats_fd);
	topn_bpf__destroy(skel);
	return 0;
}
$ sudo ./topn 2000
2010 exits seen, on_exit took 1170 ns per run
burn100  pid 329    100.0 ms
burn90   pid 326     90.0 ms
burn80   pid 331     80.0 ms
burn70   pid 334     70.0 ms
burn60   pid 328     60.0 ms

The five largest of the ten, in order, each within a tenth of a millisecond of what it was asked to burn. 2,010 tasks exited while the program was attached: the ten burners and the 2,000 that exited at once, all of which went through the tree and all but five of which were evicted and freed. The allocate, lock, insert, evict, unlock and free took about a microsecond per exit, measured by bpf_stats in a virtual machine, which includes the cost of reading the clock twice. Over five more runs the average per exit had a median of 1,162 ns, and ranged from 1,044 to 3,162.

What the verifier saw

The interesting thing is not that it works, but that the verifier agreed it was safe without being told anything at run time. Its level-2 log of on_exit shows what it believed about the entry at every instruction, and the figure steps through it.

Who owns the entry, instruction by instruction

The verifier's walk of on_exit, from its level-2 log. The badges say what it believes about the new entry and the lock at that point.

entry: none yetlock: free
; int BPF_PROG(on_exit, struct task_struct *p)
0: (79) r6 = *(u64 *)(r1 +0)
R6_w=trusted_ptr_task_struct()

The tracepoint's argument is a trusted pointer to the exiting task: the verifier knows its type from BTF and lets the program read its fields directly, but the program holds no reference to it and owes nothing.

entry: owned, may be NULLlock: free
; e = bpf_obj_new(typeof(*e));
5: (18) r1 = 0x6
7: (b7) r2 = 0
8: (85) call bpf_obj_new_impl#96902
R0_w=ptr_or_null_entry(id=2,ref_obj_id=2) refs=2

0x6 is struct entry's type ID in the program's own BTF, which the macro passes so the kernel knows the size and where the special fields are. The result is a pointer to an entry, or NULL, and it carries reference 2: the list refs=2 is what the program owes.

entry: owned (ref 2)lock: free
; if (!e)
9: (15) if r0 == 0x0 goto pc+38
R0_w=ptr_entry(ref_obj_id=2) refs=2

Past the NULL check it is an owning reference. From here every path must either free the entry or give it to something that will.

entry: owned (ref 2)lock: free
; e->runtime_ns = p->se.sum_exec_runtime;
10: (79) r1 = *(u64 *)(r6 +216)
11: (7b) *(u64 *)(r0 +32) = r1
; e->pid = p->pid;
12: (61) r1 = *(u32 *)(r6 +2496)
13: (63) *(u32 *)(r0 +40) = r1
  … 14–24: comm, four bytes at a time

Reads from the task, writes into the entry. The entry's first 32 bytes are its bpf_rb_node, which the program may not touch; the fields after it are ordinary memory it owns.

entry: owned (ref 2)lock: held
; bpf_spin_lock(&lock);
25: (18) r1 = .data.top
27: (bf) r6 = r0
28: (85) call bpf_spin_lock#93
R1_w=map_value(map=.data.top,ks=4,vs=28) R6_w=ptr_entry(ref_obj_id=2) refs=2

The lock is at offset 0 of the 28-byte value of .data.top, the map libbpf made from the private(top) section. The tree's root is in the same value, at offset 8, which is how the verifier knows this lock guards that tree.

If instead the add came before the lock: bpf_spin_lock at off=0 must be held for bpf_rb_root.

entry: non-owninglock: held
; bpf_rbtree_add(&root, &e->node, less);
29: (18) r1 = .data.top+8
31: (bf) r2 = r6
32: (18) r3 = less
34: (b7) r4 = 0
35: (b7) r5 = 0
36: (85) call bpf_rbtree_add_impl#96912
R0_w=scalar() R6=ptr_entry(non_own_ref)

refs=2 is gone: the reference was consumed, and the tree owns the entry. R6 still points at it, as a non-owning reference: usable, even writable, but only while the lock is held, because only the lock stops another CPU from removing and freeing it.

entry: non-owninglock: released
; if (++count <= TOPN) {
44: (25) if r2 > 0x5 goto pc+5
45: (18) r1 = .data.top
47: (85) call bpf_spin_unlock#94
48: (b7) r0 = 0
49: (95) exit

Five or fewer entries: unlock and return. At the unlock every non-owning reference is invalidated; R6 becomes a scalar. At the exit nothing is owed, so this path is safe.

If instead the program wrote e->pid = 0 after the unlock: R6 invalid mem access 'scalar'.

smallest: non-owning, may be NULLlock: held
; n = bpf_rbtree_first(&root);
from 44 to 50: R2_w=scalar(smin=umin=umin32=6,smax=umax=0xffffffff,var_off=(0x0; 0xffffffff)) R6=ptr_entry(non_own_ref)
50: (18) r1 = .data.top+8
52: (85) call bpf_rbtree_first#96914
R0_w=ptr_or_null_entry(id=3,non_own_ref)

The other branch: six or more. The leftmost node comes back as a non-owning reference: the program may look, and may ask for it to be removed, but does not own it.

evicted: owned (ref 5), may be NULLlock: held
; n = bpf_rbtree_remove(&root, n);
53: (15) if r0 == 0x0 goto pc-9
54: (18) r1 = .data.top+8
56: (bf) r2 = r0
57: (85) call bpf_rbtree_remove#96916
R0=ptr_or_null_entry(id=5,ref_obj_id=5) refs=5

Removal turns it back into an owning reference, number 5. It may still be NULL: bpf_rbtree_remove refuses a node that is not in the tree.

evicted: owned (ref 5)lock: released
; bpf_spin_unlock(&lock);
59: (15) if r6 == 0x0 goto pc-15
  … 60–64: count--
65: (18) r1 = .data.top
67: (85) call bpf_spin_unlock#94
refs=5

The unlock invalidates non-owning references, not owning ones: the evicted entry is still the program's after it, and still owed.

If instead the program freed it before the unlock: function calls are not allowed while holding a lock. Only the list and tree kfuncs and the unlock may be called inside.

evicted: releasedlock: free
; bpf_obj_drop(container_of(n, struct entry, node));
68: (bf) r1 = r6
69: (b7) r2 = 0
70: (85) call bpf_obj_drop_impl#96900
71: (05) goto pc-24
48: (b7) r0 = 0
49: (95) exit

The drop releases reference 5 and refs is empty again: the second path is safe too.

If instead the drop were left out: Unreleased reference id=5 alloc_insn=53, at the exit.

a, b: non-owninglock: held by the caller
from 36 to 72: frame1: R1=ptr_entry(non_own_ref) R2=ptr_entry(non_own_ref) R10=fp0 refs=2 cb
; return x->runtime_ns < y->runtime_ns;
72: (79) r1 = *(u64 *)(r1 +32)
73: (79) r2 = *(u64 *)(r2 +32)
74: (b7) r0 = 1
75: (2d) if r2 > r1 goto pc+1
76: (b7) r0 = 0
77: (95) exit
processed 76 insns (limit 1000000) max_states_per_insn 0 total_states 7 peak_states 7 mark_read 1

Last, the callback, checked as a separate frame (cb) called from instruction 36, with both arguments non-owning entries it may read. Each return value is followed back to the caller. Then the last pending state, the allocation's NULL side from instruction 9, which is two instructions to the exit. Nothing is left: 76 instructions processed, and the program loads.

Green: the program owns the object and must free it or hand it on. Teal: it may use the object, only while the lock is held. Copper: the tree's lock. The "if instead" lines are what the verifier said to versions of the program with that one change.

Three lines in that log carry the whole design. After bpf_obj_new, R0 is ptr_or_null_entry(id=2,ref_obj_id=2) and the state ends in refs=2: the program owes reference 2. After bpf_rbtree_add, refs is gone and R6 has become ptr_entry(non_own_ref): the tree owns the entry, and the program has a pointer it may use only while the lock is held. After bpf_rbtree_remove, R0 is ptr_or_null_entry(id=5,ref_obj_id=5) with refs=5: the evicted entry is the program’s again, and has to be freed before the exit.

Each rule can be broken in one line, and each is refused with its own message. I made four versions of topn.bpf.c with one change each:

change to on_exitthe verifier said
call bpf_rbtree_add before bpf_spin_lockbpf_spin_lock at off=0 must be held for bpf_rb_root
write e->pid = 0 after the first bpf_spin_unlockR6 invalid mem access 'scalar'
call bpf_obj_drop before the second bpf_spin_unlockfunction calls are not allowed while holding a lock
leave out bpf_obj_dropUnreleased reference id=5 alloc_insn=53

The second is the subtle one. Writing to e after the add but before the unlock is allowed; I tried that too, and it loads, because a non-owning reference may be written while the lock is held. After the unlock, the verifier has turned R6 into a plain scalar, and dereferencing a number is refused with the same kind of message Part 1 got for a map value that might have been NULL.

Since 6.4 an object can also carry a struct bpf_refcount, and bpf_refcount_acquire then gives a second owning reference to it, so one object can be in a tree and a list at once: an LRU, say, ordered by time in a list and by key in a tree. And since 6.7 bpf_percpu_obj_new allocates a per-CPU object. Neither is needed here.

Loops, a third time

Part 4 ended on loops: a bounded loop costs the verifier its whole body once per iteration, and bpf_loop avoids that by moving the body into a callback. 6.4 and 6.9 added two more answers, and they are what make loops over the structures above practical.

Open-coded iterators (6.4). An iterator is a small struct on the program’s stack, driven by three kfuncs: _new initialises it, _next returns a pointer to the next element or NULL, and _destroy cleans up. The first kind iterates over numbers, bpf_iter_num_new(&it, start, end), and libbpf’s bpf_helpers.h wraps it in a macro, so a loop over i from 0 to n is written bpf_for(i, 0, n). (The macros moved from the selftests into libbpf’s headers in libbpf 1.2.) The verifier knows what _next promises, that it will eventually return NULL, so it does not need to see the loop end. Instead, each time the walk comes back to the _next call, it compares the state with the one it had the last time round, and once nothing has changed that matters, it stops. And bpf_for also tells the verifier that i is between the bounds, so it can index an array.

may_goto (6.9). A new jump instruction, which the cond_break macro emits, that means “jump, if you have to”. At load time the verifier rewrites it into a counter in a hidden stack slot, set to 8,388,608 (2²³, the same cap as bpf_loop’s) at the start of every run and decremented by every may_goto; when it reaches zero the jump is taken. To the verifier, the instruction is a branch it treats like an iterator’s _next: one side leaves the loop, so the loop can always end, and when the walk returns to it, it checks for a repeat state the same way.

The difference between those two and a bounded loop is what “nothing has changed that matters” means. At an iterator’s _next or a may_goto, the verifier widens any scalar that differs from its last visit and that it has not marked precise, the mark that Part 4 showed it putting on scalars whose exact value decided something, such as a pointer offset or a branch. A counter it has never needed exactly becomes “some number”, and the next time round the state is the same, so the walk ends.

Here is Part 4’s random-number loop, four ways:

// loops.bpf.c — Part 4's N rounds of a 64-bit LCG, written four ways
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include "bpf_experimental.h"		/* for cond_break */

#ifndef N
#define N 100
#endif
#define STEP(x, sum) do {						\
	x = x * 6364136223846793005ULL + 1442695040888963407ULL;	\
	sum += x >> 33;							\
} while (0)

__u64 result;				/* keeps the loop from being optimised away */
__u64 limit = N;			/* writable, so the verifier can't know it */

SEC("xdp")
int bounded(struct xdp_md *ctx)		/* 5.3: the verifier walks it */
{
	__u64 x = bpf_get_prandom_u32(), sum = 0, i;

#pragma clang loop unroll(disable)
	for (i = 0; i < N; i++)
		STEP(x, sum);
	result = sum;
	return i;				/* rounds actually run */
}

struct lcg {
	__u64 x, sum;
};

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

	STEP(s->x, s->sum);
	return 0;
}

SEC("xdp")
int with_bpf_loop(struct xdp_md *ctx)	/* 5.17: a helper runs a callback */
{
	struct lcg s = { bpf_get_prandom_u32(), 0 };
	long n = bpf_loop(N, step, &s, 0);

	result = s.sum;
	return n;
}

SEC("xdp")
int with_bpf_for(struct xdp_md *ctx)	/* 6.4: an open-coded iterator */
{
	__u64 x = bpf_get_prandom_u32(), sum = 0, n = 0;
	int i;

	bpf_for(i, 0, N) {
		STEP(x, sum);
		n++;
	}
	result = sum;
	return n;
}

SEC("xdp")
int with_cond_break(struct xdp_md *ctx)	/* 6.9: may_goto */
{
	__u64 x = bpf_get_prandom_u32(), sum = 0, i;

	for (i = 0; i < N; i++) {
		STEP(x, sum);
		cond_break;
	}
	result = sum;
	return i;				/* rounds actually run */
}

SEC("xdp")
int with_cond_break_unknown(struct xdp_md *ctx)	/* 6.9, bound unknown */
{
	__u64 x = bpf_get_prandom_u32(), sum = 0, i;

	for (i = 0; i < limit; i++) {
		STEP(x, sum);
		cond_break;
	}
	result = sum;
	return i;
}

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

And the harness that loads one program out of an object, reports verified_insns, which is the verifier’s “processed” count kept in the program’s info, and runs it with BPF_PROG_TEST_RUN:

I compiled it with -DN= set to every count from 1 to 10,000,000 and loaded each program in turn:

Instructions the verifier processed, with “refused” where it gave up (and the count it had reached):

Nbounded loopbpf_loopbpf_forcond_break, N knowncond_break, N unknown
112331202659
10914612412659
100811461241,51159
1,0008,0114612415,01159
10,00080,01146124150,01159
50,000400,01146124750,01159
66,665533,33146124999,98659
66,666533,33946124refused (1,000,001)59
100,000800,01146124refused (1,000,001)59
124,998999,99546124refused (1,000,001)59
124,999refused (1,000,001)46124refused (1,000,001)59
1,000,000refused (1,000,001)46124refused (1,000,001)59
8,388,608refused (1,000,001)46124refused (1,000,001)59
10,000,000refused (1,000,001)46124refused (1,000,001)59

bpf_loop and bpf_for cost a constant, as expected: the verifier checks the callback or the iterator loop until it converges and never sees the count. The bounded loop costs 8 instructions per iteration with this compiler, 8N + 11 exactly, and is refused past N = 124,998.

The surprise is cond_break with a constant bound, which is worse than the bounded loop: 15N + 11, refused past N = 66,665. Each may_goto is a branch, and the verifier takes the side that leaves the loop first and queues the side that continues, so every iteration adds an extra path to check. And the walk never converges, because i is precise: the loop condition i < N compares it with a constant, the verifier decides that branch from i’s exact value, and in doing so marks i precise. Two states with different precise values of i are different states. cond_break saves nothing in a loop the verifier could already count.

What it is for is a loop the verifier cannot count. with_cond_break_unknown reads its bound from limit, a global the program can write, so the verifier has to assume it could be anything. Now i < limit can’t be decided, i is never marked precise, and at the may_goto it is widened to “some number” after one iteration: 59 instructions, whatever the bound. And the hidden counter is real. With limit set to 10,000,000, the loop stopped after 8,388,608 rounds and the program carried on as if the loop had ended normally. A may_goto loop never fails at load time for being too long; it is cut short at run time instead, silently, and the program has to be written so that stopping early is acceptable.

Now the loop from Part 4’s opening, which counted set bits by clearing the lowest one until none were left, and which exhausted the 5.15 verifier’s budget at 166,665 trips because nothing in it ever repeated:

// popcount.bpf.c — Part 4's loop the verifier could not bound, three ways
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include "bpf_experimental.h"

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

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

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

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

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

	bpf_for(i, 0, 64) {
		if (!x)
			break;
		x &= x - 1;
		n++;
	}
	return n;
}

char LICENSE[] SEC("license") = "GPL";
$ for p in plain with_cond_break with_bpf_for; do sudo ./bench popcount.bpf.o $p; done
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
plain: not loaded
with_cond_break: verified 42 insns, 1555 ns per run, returned 17
with_bpf_for: verified 103 insns, 8773 ns per run, returned 11

(The times in those lines are single runs and mean little; the timings come further down.) The plain version still fails on 6.10, the same way. One added line, cond_break, and it loads after 42 instructions: n is never needed exactly, so it is widened, and the second time the walk reaches the may_goto it is in a state it has seen. bpf_for with a bound of 64 and an explicit break works too, in 103.

What does each cost at run time? The four ways of running the generator loop, timed with BPF_PROG_TEST_RUN, five rounds in rotated order with no other test virtual machine running:

Median nanoseconds per iteration (run time divided by N), with the range over five rounds:

ns per iterationN = 10N = 100N = 1,000N = 10,000N = 100,000
bounded loop0.80 (0.70–0.80)0.79 (0.79–1.08)0.82 (0.79–0.84)0.82 (0.78–0.89)0.81 (0.79–0.93)
bpf_loop1.20 (1.10–1.20)0.85 (0.83–0.88)0.81 (0.81–0.83)0.82 (0.80–0.84)0.82 (0.81–0.94)
cond_break, N unknown1.10 (0.90–1.10)0.80 (0.78–0.82)0.82 (0.81–0.89)0.84 (0.83–0.85)0.84 (0.82–0.86)
bpf_for1.40 (1.30–1.70)0.88 (0.87–0.92)0.84 (0.82–0.91)0.82 (0.79–0.95)0.86 (0.82–1.06)

At a hundred thousand rounds they are within about 6% of each other, the bounded loop fastest and bpf_for slowest, which pays a kfunc call to bpf_iter_num_next every iteration. As in Part 4, the generator’s chain of dependent multiplications dominates and hides most of the difference; a smaller body would show more of it. On the popcount, whose body is two instructions, cond_break took 21 ns per run and bpf_for 25, medians of five rounds of a million runs each.

So the choice in 2024 goes like this. A loop with a small constant count can stay a plain loop. A loop over a range the program knows is a bpf_for, and a loop over kernel objects is one of the other iterators: 6.10 has open-coded iterators over tasks, cgroups, a cgroup’s tasks and a process’s memory mappings. A loop whose end the verifier can’t see, a list walk or a search, gets a cond_break and a plan for being cut short. bpf_loop is still there, and costs the least to verify, but needs its body in a callback.

Exceptions, briefly

6.7 added bpf_throw(cookie), a kfunc that ends the program at once, from any depth of function calls, unwinding the BPF stack frames. If the program has an exception callback, a global function named with the __exception_cb tag, the callback runs with the cookie and its return value becomes the program’s; without one, the program returns the cookie. The point is the bpf_assert macros in bpf_experimental.h, which throw when a condition fails: past an assertion, the verifier knows the condition is true, so an assertion can teach it a bound in the middle of a function as well as guard against a bug.

// throw.bpf.c — an assertion that ends the program, and what it returns
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include "bpf_experimental.h"

struct args {
	__u64 x;
};

int on_throw(__u64 cookie)		/* must be global; gets the cookie */
{
	return 1000 + cookie;
}

SEC("syscall")
__exception_cb(on_throw)
int checked(struct args *a)
{
	__u64 x = a->x;

	bpf_assert_with(x < 100, 7);		/* if not, bpf_throw(7) */
	return x * 2;
}

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

On this kernel it doesn’t load:

$ sudo ./bench throw.bpf.o checked
3: (b7) r1 = 7                        ; R1_w=7
4: (85) call bpf_throw#96947
JIT does not support calling kfunc bpf_throw#96947
processed 5 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0
checked: not loaded

The x86-64 JIT unwinds an exception by walking the kernel’s stack from inside bpf_throw back to the BPF frames, and for that it needs the ORC unwinder: bpf_jit_supports_exceptions() returns IS_ENABLED(CONFIG_UNWINDER_ORC). Ubuntu’s mainline 6.10 build is configured with CONFIG_UNWINDER_FRAME_POINTER=y and no ORC, so on it every program that can throw is refused, at the throw, with that message. A program meant to run on more than one kernel can’t assume exceptions exist.

What I could not run, I read. In the 6.10 verifier a throw is checked like an exit: references still held when it happens are reported as unreleased, a throw with a lock held is refused like any other call, and exceptions don’t free anything on the way out; the comment on bpf_throw in bpf_experimental.h says the same. Holding a bpf_obj_new object across an assertion is therefore a load error, not a leak.

Memory both sides can follow: the arena

Everything so far keeps the BPF program’s objects inside the kernel. User space sees a list or a tree only by asking a program to take things out of it, the way report did. The arena, in 6.9, is the other way round: memory that a BPF program and a user-space process both map, in which a pointer stored by one is a pointer the other can follow.

The arena is a map, BPF_MAP_TYPE_ARENA, whose max_entries is a number of pages, up to 4 GiB of address space. Creating it reserves 4 GiB of the kernel’s virtual address space, plus a guard region, and allocates no memory at all. A user-space process mmap()s it, which fixes where it lives in that process. Pages come into existence one at a time: a sleepable BPF program allocates them with bpf_arena_alloc_pages, or user space touches an address, and the page fault handler allocates one there (unless the map was created with BPF_F_SEGV_ON_FAULT). Either way, the page is zeroed and charged to the memory cgroup of the process that created the map.

The trick that makes one pointer work on both sides is in the address arithmetic, and the comment at the top of kernel/bpf/arena.c gives an example:

user_vm_start 7f7d26200000     // picked by mmap()
kern_vm_start ffffc90001e69000 // picked by get_vm_area()

User space uses ordinary 64-bit addresses. The BPF program uses only the low 32 bits of one, and the JIT adds the kernel’s base: an arena access compiles to mov eax, eax followed by a load or store at [rax + r12 + off], with r12 holding the kernel-side start. Since the arena never crosses a 4 GiB boundary, the low 32 bits identify the same page on both sides. Converting a pointer from one form to the other is the address-space cast: user to kernel keeps the low half, kernel to user puts the user mapping’s top half back.

What keeps this safe is that the verifier doesn’t try to prove anything about arena pointers at all. Any 32-bit offset is inside the 4 GiB reservation, and the guard region catches the 16-bit offset an instruction can add, so no arena access can touch memory outside it. A load or store to a page that hasn’t been allocated faults, and the JIT has registered every arena access in the exception table: a faulting load sets its destination register to zero, a faulting store is skipped. A bug in a program’s arena data structure is a bug in that data structure, not in the kernel.

The cost of clang 18 is that every cast is by hand. With a compiler that supports address spaces, pointers declared __arena are cast automatically; with this one, __arena expands to nothing and the program calls cast_kern() before dereferencing a pointer and cast_user() before storing one where user space will read it. Each is the 8 bytes of the cast instruction, emitted by bpf_arena_common.h as raw bytes.

Here is a linked list built three ways: in an arena, in a hash map with keys as links, and in an mmap-able array (5.5) with indices as links, which is the fairest “before” for reading, since user space can map that too:

// arenalist.bpf.c — one linked list, built three ways: in an arena,
// in a hash map, and in an mmap-able array
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include "bpf_experimental.h"
#include "bpf_arena_common.h"

#define MAX_NODES 1000000

struct args {
	int n;
};

/* 1. The arena: up to 8,192 pages (32 MiB) of address space, none of it
 *    backed by memory until a program asks for a page. */
struct {
	__uint(type, BPF_MAP_TYPE_ARENA);
	__uint(map_flags, BPF_F_MMAPABLE);
	__uint(max_entries, 8192);
} arena SEC(".maps");

struct lnode {
	struct lnode __arena *next;	/* an address user space can follow */
	__u64 key, val;
};
struct lnode __arena *head;		/* in .bss, in user-space form */

SEC("syscall")
int build_arena(struct args *a)
{
	int pages = (a->n * sizeof(struct lnode) + __PAGE_SIZE - 1) / __PAGE_SIZE;
	struct lnode __arena *base, *n;
	int i;

	base = bpf_arena_alloc_pages(&arena, NULL, pages, NUMA_NO_NODE, 0);
	if (!base)
		return -1;
	bpf_for(i, 0, a->n) {
		n = base + i;
		cast_kern(n);			/* to the kernel's view of the arena */
		n->key = i;
		n->val = i * 3;
		n->next = head;
		cast_user(n);			/* and back, before storing it */
		head = n;
	}
	return 0;
}

/* 2. Before arenas: nodes in a hash map, "pointers" are keys. */
struct hnode {
	__u64 next, key, val;
};

struct {
	__uint(type, BPF_MAP_TYPE_HASH);
	__uint(max_entries, MAX_NODES);
	__type(key, __u64);
	__type(value, struct hnode);
} hlist SEC(".maps");

__u64 hhead;

SEC("syscall")
int build_hash(struct args *a)
{
	struct hnode v;
	int i;

	bpf_for(i, 0, a->n) {
		__u64 id = i + 1;		/* 0 means "end of list" */

		v.next = hhead;
		v.key = i;
		v.val = i * 3;
		if (bpf_map_update_elem(&hlist, &id, &v, BPF_ANY))
			return -1;
		hhead = id;
	}
	return 0;
}

/* 3. An array user space can mmap (5.5): fixed size, linked by index. */
struct {
	__uint(type, BPF_MAP_TYPE_ARRAY);
	__uint(map_flags, BPF_F_MMAPABLE);
	__uint(max_entries, MAX_NODES + 1);
	__type(key, __u32);
	__type(value, struct hnode);
} alist SEC(".maps");

__u64 ahead;

SEC("syscall")
int build_array(struct args *a)
{
	struct hnode *v;
	int i;

	bpf_for(i, 0, a->n) {
		__u32 id = i + 1;

		v = bpf_map_lookup_elem(&alist, &id);
		if (!v)
			return -1;
		v->next = ahead;
		v->key = i;
		v->val = i * 3;
		ahead = id;
	}
	return 0;
}

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

build_arena asks for all the pages it needs in one call, 5,860 of them for a million 24-byte nodes, then writes the nodes and links each to the previous head. Every node’s next is stored in user-space form, and head, in .bss, is the user-space address of the last node written. On the kernel side, the verifier saw the casts as what they are:

46: (0f) r3 += r2                           ; R3_w=scalar()
47: (bf) r3 = addr_space_cast(r3, 0, 1)     ; R3_w=arena
48: (bf) r2 = r1
49: (27) r2 *= 3
50: (67) r2 <<= 32
51: (77) r2 >>= 32
52: (7b) *(u64 *)(r3 +16) = r2              ; R3_w=arena
53: (7b) *(u64 *)(r3 +8) = r1               ; R3_w=arena
54: (79) r1 = *(u64 *)(r9 +0)
55: (7b) *(u64 *)(r3 +0) = r1               ; R3_w=arena
56: (bf) r3 = addr_space_cast(r3, 1, 0)     ; R3_w=scalar()

User space builds all three lists, then walks each, five rounds in rotated order:

The arena walk is one line: for (p = skel->bss->head; p; p = p->next). No system call, no copy: p is an ordinary pointer, into memory the kernel mapped into this process when libbpf loaded the object. One run:

$ sudo ./arenalist 1000000 5
built 1000000 nodes: arena 6.2 ms, hash 207.7 ms, array 2.8 ms
round 0  arena, pointers            8.24 ms  sum ok
round 0  hash, lookup per node    386.47 ms  sum ok
round 0  hash, batch then walk    230.83 ms  sum ok
round 0  array, mmap-ed             3.28 ms  sum ok
round 1  hash, lookup per node    384.46 ms  sum ok
round 1  hash, batch then walk    221.42 ms  sum ok
round 1  array, mmap-ed             3.26 ms  sum ok
round 1  arena, pointers            1.90 ms  sum ok
round 2  hash, batch then walk    211.21 ms  sum ok
round 2  array, mmap-ed             3.29 ms  sum ok
round 2  arena, pointers            4.58 ms  sum ok
round 2  hash, lookup per node    382.14 ms  sum ok
round 3  array, mmap-ed             2.71 ms  sum ok
round 3  arena, pointers            2.22 ms  sum ok
round 3  hash, lookup per node    372.28 ms  sum ok
round 3  hash, batch then walk    186.22 ms  sum ok
round 4  arena, pointers            2.11 ms  sum ok
round 4  hash, lookup per node    356.94 ms  sum ok
round 4  hash, batch then walk    180.32 ms  sum ok
round 4  array, mmap-ed             2.14 ms  sum ok

Two things measured on 6.10

What a loop costs the verifier, four ways; and what reading a BPF-built list costs user space, four ways.

Instructions the verifier processed, by loop count

The same generator loop. Both axes logarithmic; the dashed line is the one-million budget; a cross is a refusal.

Hover or tap a point.

Table of every measured point
loopNprocessedresult

Walking a 1,000,000-node list that a BPF program built

Milliseconds for user space to visit every node, logarithmic axis. Every round of three processes; hollow marks are each process's first walk.

Hover or tap a point.

Table of every round
structuremedian msrange msfirst walks ms

The charts need JavaScript; the tables carry every value.

Bounded loop: 8 instructions per iteration, refused past N = 124,998. With cond_break and a bound the verifier can read, 15 per iteration, refused past N = 66,665. bpf_for, bpf_loop and cond_break with a bound it cannot read cost the same at every N. The arena and the mmap-ed array are read with plain loads; the hash map needs the kernel for every node, or a copy of the whole map.

Over the twelve later rounds of three processes, the arena walk took a median of 2.23 ms for the million nodes, about two nanoseconds a node, and the mmap-ed array 2.46. Through the hash map, one bpf_map_lookup_elem per node took 371 ms, about 0.37 µs a node, all of it system calls; copying the whole map out with batch lookups and then walking the copy took 197 ms.

Two things in those numbers are worth a second look. The first arena walk in each process took about 7 ms, three or four times the later ones: the BPF program had allocated the pages in the kernel, but they appear in the user-space mapping only when user space first touches each one, and that walk paid 5,860 page faults. The mmap-ed array has no such first-walk cost, because its mmap maps the whole array at once. The second is that the array reads as fast as the arena. Reading was never the arena’s advantage: an mmap-able array has let user space read a map without system calls since 5.5. What the array cannot do is grow, or hold a pointer: its size is fixed at creation and its links are indices that both sides have to agree on. The arena allocates pages when a program asks, up to 4 GiB, and its links are pointers.

The build times, measured around BPF_PROG_TEST_RUN from user space, show the same thing from the program’s side: 5.9–9.2 ms for the arena (including allocating the pages), 2.7–3.0 ms for the array, and 178–208 ms for the hash map, whose every insert takes a lock and links an element into a bucket.

One more restriction, and it explains why build_arena is a syscall program: allocating and freeing arena pages can sleep, so on 6.10 only sleepable programs may call them.

Deferring what sleeps: bpf_wq

That restriction is where 6.10’s own addition comes in. A bpf_wq is a work item that lives in a map value, like the bpf_timer of 5.15: a program initialises it, gives it a callback, and starts it, and the kernel runs the callback later from a workqueue, in process context, where it is allowed to sleep. The verifier checks the callback as sleepable even when the program that scheduled it is not.

So a program that may not sleep, here an XDP program, can still get an arena page:

// defer.bpf.c — a program that may not sleep gets an arena page anyway
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include "bpf_experimental.h"
#include "bpf_arena_common.h"

struct {
	__uint(type, BPF_MAP_TYPE_ARENA);
	__uint(map_flags, BPF_F_MMAPABLE);
	__uint(max_entries, 16);
} arena SEC(".maps");

struct job {
	struct bpf_wq wq;
};

struct {
	__uint(type, BPF_MAP_TYPE_ARRAY);
	__uint(max_entries, 1);
	__type(key, int);
	__type(value, struct job);
} jobs SEC(".maps");

__u64 __arena *page;			/* in user-space form */
int done;

static int grow(void *map, int *key, struct bpf_wq *wq)	/* may sleep */
{
	__u64 __arena *p = bpf_arena_alloc_pages(&arena, NULL, 1, NUMA_NO_NODE, 0);

	if (!p)
		return 0;
	cast_kern(p);
	*p = 0xbeef;
	cast_user(p);
	page = p;
	done = 1;
	return 0;
}

SEC("xdp")
int ask(struct xdp_md *ctx)			/* may not sleep */
{
	struct job *j;
	int key = 0;

#ifdef DIRECT
	page = bpf_arena_alloc_pages(&arena, NULL, 1, NUMA_NO_NODE, 0);
#endif
	j = bpf_map_lookup_elem(&jobs, &key);
	if (!j)
		return XDP_PASS;
	if (bpf_wq_init(&j->wq, &jobs, 0) ||
	    bpf_wq_set_callback(&j->wq, grow, 0) ||
	    bpf_wq_start(&j->wq, 0))
		return XDP_ABORTED;
	return XDP_PASS;
}

char LICENSE[] SEC("license") = "GPL";
// defer.c — run ask() once, then wait for the work it queued
#include <stdio.h>
#include <time.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "defer.skel.h"

int main(void)
{
	struct defer_bpf *skel = defer_bpf__open_and_load();
	char pkt[64] = {};
	LIBBPF_OPTS(bpf_test_run_opts, opts, .data_in = pkt, .data_size_in = sizeof(pkt));
	struct timespec ms = { 0, 1000000 };
	int waited = 0;

	if (!skel)
		return 1;
	bpf_prog_test_run_opts(bpf_program__fd(skel->progs.ask), &opts);
	printf("ask() returned %d; page = %p\n", opts.retval, (void *)skel->bss->page);
	while (!skel->bss->done && waited < 1000) {
		nanosleep(&ms, NULL);
		waited++;
	}
	printf("after ~%d ms: page = %p, *page = 0x%llx\n", waited,
	       (void *)skel->bss->page,
	       skel->bss->page ? (unsigned long long)*skel->bss->page : 0ULL);
	defer_bpf__destroy(skel);
	return 0;
}
$ sudo ./defer
ask() returned 2; page = 0x71aca26fe000
after ~0 ms: page = 0x71aca26fe000, *page = 0xbeef

ask returned XDP_PASS without waiting for anything; the callback ran on a kernel worker, allocated a page, wrote to it and published its address in page, and user space read the value through that pointer. In this run the worker had finished before user space first looked, which is why the first line already shows the page; in an earlier run it took about a millisecond. Compile the same file with -DDIRECT, which calls bpf_arena_alloc_pages from ask itself:

$ sudo ./bench defer_direct.bpf.o ask
program must be sleepable to call sleepable kfunc bpf_arena_alloc_pages
processed 8 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0
ask: not loaded

Handing it to a container: the BPF token

Everything above ran as root. Part 1 showed why: Ubuntu sets kernel.unprivileged_bpf_disabled to 2, and the 6.10 build I’m using has the same default, so loading a program needs CAP_BPF, plus CAP_PERFMON or CAP_NET_ADMIN for most program types, in the initial user namespace. Being root inside a container’s user namespace doesn’t count.

The BPF token, merged in 6.9 after a first version was taken out again before 6.8 was released, is a way to delegate some of that to a user namespace without giving it the capabilities on the host. A privileged process creates a BPF filesystem instance owned by the container’s user namespace, with mount options listing what may be delegated: which bpf() commands, which map types, which program types, which attach types. Inside the namespace, a process opens that mount and creates a token from it with BPF_TOKEN_CREATE; passing the token’s file descriptor with a command then makes the kernel check capabilities against the namespace that owns the mount, and only for what the mount allows. Setting the options takes CAP_SYS_ADMIN on the host, so a container cannot grant itself more.

The choreography takes two processes, because the namespace must create the filesystem and the host must configure it: the child, inside a new user namespace, opens a BPF filesystem with fsopen and sends the descriptor to the parent over a socket; the parent sets the delegation options and creates the mount; the child gets the mount back, puts it on /sys/fs/bpf in its own mount namespace, and makes a token.

// token.c — delegate a little BPF to an unprivileged user namespace
#define _GNU_SOURCE
#include <errno.h>
#include <fcntl.h>
#include <sched.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/mount.h>
#include <sys/prctl.h>
#include <sys/socket.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <linux/mount.h>
#include <bpf/bpf.h>

#ifndef BPF_F_TOKEN_FD
#define BPF_F_TOKEN_FD (1U << 16)	/* 6.9 UAPI; noble's 6.8 headers lack it */
#endif

static void sendfd(int sock, int fd)		/* pass a descriptor over a socket */
{
	char c = 0, buf[CMSG_SPACE(sizeof(int))] = {};
	struct iovec io = { &c, 1 };
	struct msghdr m = { .msg_iov = &io, .msg_iovlen = 1,
			    .msg_control = buf, .msg_controllen = sizeof(buf) };
	struct cmsghdr *cm = CMSG_FIRSTHDR(&m);

	cm->cmsg_level = SOL_SOCKET;
	cm->cmsg_type = SCM_RIGHTS;
	cm->cmsg_len = CMSG_LEN(sizeof(int));
	memcpy(CMSG_DATA(cm), &fd, sizeof(int));
	sendmsg(sock, &m, 0);
}

static int recvfd(int sock)
{
	char c, buf[CMSG_SPACE(sizeof(int))];
	struct iovec io = { &c, 1 };
	struct msghdr m = { .msg_iov = &io, .msg_iovlen = 1,
			    .msg_control = buf, .msg_controllen = sizeof(buf) };
	int fd = -1;

	if (recvmsg(sock, &m, 0) == 1)
		memcpy(&fd, CMSG_DATA(CMSG_FIRSTHDR(&m)), sizeof(int));
	return fd;
}

static void put(const char *path, const char *s)
{
	int fd = open(path, O_WRONLY);

	if (write(fd, s, strlen(s)) < 0)
		perror(path);
	close(fd);
}

static void try_map(const char *what, enum bpf_map_type type, int token)
{
	LIBBPF_OPTS(bpf_map_create_opts, o);
	int fd;

	if (token >= 0) {
		o.map_flags = BPF_F_TOKEN_FD;
		o.token_fd = token;
	}
	fd = bpf_map_create(type, NULL, 4, 8, 1, &o);
	printf("  %-44s %s\n", what, fd >= 0 ? "ok" : strerror(errno));
	close(fd);
}

static void try_prog(const char *what, enum bpf_prog_type type, int token)
{
	struct bpf_insn ret0[] = {
		{ .code = BPF_ALU64 | BPF_MOV | BPF_K, .dst_reg = 0, .imm = 0 },
		{ .code = BPF_JMP | BPF_EXIT },
	};
	LIBBPF_OPTS(bpf_prog_load_opts, o);
	int fd;

	if (token >= 0) {
		o.prog_flags = BPF_F_TOKEN_FD;
		o.token_fd = token;
	}
	fd = bpf_prog_load(type, NULL, "GPL", ret0, 2, &o);
	printf("  %-44s %s\n", what, fd >= 0 ? "ok" : strerror(errno));
	close(fd);
}

static int child(int sock)
{
	char line[512];
	FILE *f;
	int fs, mnt, token;

	if (setgid(1000) || setuid(1000))	/* an ordinary user from here on */
		return 1;
	prctl(PR_SET_DUMPABLE, 1);		/* so it may write its own uid_map */
	printf("uid %d, no namespace, no token:\n", getuid());
	try_map("create an array map", BPF_MAP_TYPE_ARRAY, -1);

	unshare(CLONE_NEWUSER);			/* root, but only in here */
	put("/proc/self/setgroups", "deny");
	put("/proc/self/uid_map", "0 1000 1");
	put("/proc/self/gid_map", "0 1000 1");
	unshare(CLONE_NEWNS);
	mount(NULL, "/", NULL, MS_REC | MS_PRIVATE, NULL);
	printf("uid %d in a new user namespace, no token:\n", getuid());
	try_map("create an array map", BPF_MAP_TYPE_ARRAY, -1);

	fs = syscall(SYS_fsopen, "bpf", 0);	/* a BPF FS owned by this namespace */
	sendfd(sock, fs);			/* the parent sets the options */
	mnt = recvfd(sock);
	syscall(SYS_move_mount, mnt, "", AT_FDCWD, "/sys/fs/bpf",
		MOVE_MOUNT_F_EMPTY_PATH);
	f = fopen("/proc/self/mounts", "r");
	while (fgets(line, sizeof(line), f))
		if (strstr(line, "/sys/fs/bpf"))
			printf("mounted: %s", line);
	fclose(f);

	token = bpf_token_create(open("/sys/fs/bpf", O_RDONLY), NULL);
	printf("bpf_token_create: %s\n", token >= 0 ? "ok" : strerror(errno));
	printf("uid %d in the namespace, with the token:\n", getuid());
	try_map("create an array map", BPF_MAP_TYPE_ARRAY, token);
	try_map("create a hash map (not delegated)", BPF_MAP_TYPE_HASH, token);
	try_prog("load a socket filter", BPF_PROG_TYPE_SOCKET_FILTER, token);
	try_prog("load a kprobe program (not delegated)", BPF_PROG_TYPE_KPROBE, token);
	fflush(stdout);
	execl("./bench", "bench", "popcount.bpf.o", "with_bpf_for", (char *)NULL);
	return 1;
}

int main(void)
{
	int sv[2], fs, mnt, status;
	pid_t pid;

	socketpair(AF_UNIX, SOCK_STREAM, 0, sv);
	pid = fork();
	if (pid == 0)
		return child(sv[1]);

	fs = recvfd(sv[0]);			/* the parent is real root */
	syscall(SYS_fsconfig, fs, FSCONFIG_SET_STRING, "delegate_cmds",
		"map_create:prog_load:btf_load", 0);
	syscall(SYS_fsconfig, fs, FSCONFIG_SET_STRING, "delegate_maps", "array", 0);
	syscall(SYS_fsconfig, fs, FSCONFIG_SET_STRING, "delegate_progs",
		"socket_filter:xdp", 0);
	syscall(SYS_fsconfig, fs, FSCONFIG_SET_STRING, "delegate_attachs", "any", 0);
	syscall(SYS_fsconfig, fs, FSCONFIG_CMD_CREATE, NULL, NULL, 0);
	mnt = syscall(SYS_fsmount, fs, 0, 0);
	sendfd(sv[0], mnt);
	waitpid(pid, &status, 0);
	return WEXITSTATUS(status);
}
$ sudo ./token
uid 1000, no namespace, no token:
  create an array map                          Operation not permitted
uid 0 in a new user namespace, no token:
  create an array map                          Operation not permitted
mounted: none /sys/fs/bpf bpf rw,relatime,uid=1000,gid=1000,delegate_cmds=map_create:prog_load:btf_load,delegate_maps=array,delegate_progs=socket_filter:xdp,delegate_attachs=any 0 0
bpf_token_create: ok
uid 0 in the namespace, with the token:
  create an array map                          ok
  create a hash map (not delegated)            Operation not permitted
  load a socket filter                         ok
  load a kprobe program (not delegated)        Operation not permitted
libbpf: Failed to bump RLIMIT_MEMLOCK (err = -1), you might need to do it explicitly!
with_bpf_for: verified 103 insns, 568 ns per run, returned 18

Read it from the top. As uid 1000 nothing is allowed, and as root of a fresh user namespace, still nothing. With the token, exactly what the mount line lists is allowed and nothing else: an array map but not a hash map, a socket filter but not a kprobe program. The mount needs delegate_attachs too, because the kernel checks a program’s expected attach type against it even for a socket filter, whose attach type is 0.

The last two lines are the part that matters in practice. The child ends by exec-ing the bench harness from earlier, unchanged, to load popcount.bpf.o’s XDP program. libbpf 1.4 looks for a token-enabled BPF filesystem at /sys/fs/bpf (or wherever LIBBPF_BPF_TOKEN_PATH says) and, if it finds one, uses a token for everything it does, so an ordinary libbpf tool works inside the namespace without a line changed. The one warning is libbpf’s own. Before it loads anything it checks whether the kernel charges BPF memory to memory cgroups (true since 5.11), with a probe that doesn’t use the token; in the namespace the probe is refused, so libbpf falls back to raising RLIMIT_MEMLOCK, which the namespace may not do either. The load goes ahead regardless.

What’s around in July 2024

The kernel. 6.10 came out a week ago, on 14 July, and the 6.11 merge window is open as I write. The memory features above are new enough that the best worked examples of them are still the kernel’s own selftests, which include a hash table and a list built in an arena (bpf_arena_htab.h and bpf_arena_list.h, next to the two headers this post borrowed), and progs/rbtree_fail.c, which breaks the tree’s rules on purpose, one small program per mistake.

The toolchain. libbpf 1.4 (1 April) brought arena and token support; the 1.4.5 used here came out on 11 July. bpftool 7.4.0 (8 April) generated the skeletons. Ubuntu 24.04 (25 April) is the first LTS with libbpf 1.x, but its 1.3 and its 6.8 kernel are both a release short of this part, and its clang 18 needs the hand-encoded instructions above. The compiler side matters more than it looks: with clang 18, every crossing between the two forms of an arena pointer is a cast written by hand, which the compiler has no way to check.

Elsewhere. eBPF for Windows reached v0.16.0 in April, and Part 12 looked at where it stands; nothing in this part has a counterpart there yet.

What we covered

  • Part 5’s model, fixed-size map values and nothing else, is safe because nothing points anywhere. Each step since has added a kind of pointer, and a rule the verifier enforces about it.
  • kptrs (5.19) put typed kernel pointers in map values. A referenced one, moved in and out with bpf_kptr_xchg, kept a reaped sleep’s task_struct alive with a reference count of 1. Forgetting the release is a load error. Tasks only became storable in 6.2, and 6.4 swapped the names __kptr and __kptr_ref.
  • bpf_obj_new (6.2) allocates objects of a program’s own types from the BPF allocator of 6.1, as owning references. Only the special fields are initialised.
  • Lists (6.2) and rbtrees (6.3) have roots in map values next to their lock. Adding gives the object to the structure and leaves a non-owning reference that dies at the unlock; removing gives it back. A top-5 of CPU time by exiting task took 76 instructions to verify and about a microsecond per exit to run, and each broken rule had its own refusal.
  • bpf_for (6.4) verifies in constant work and costs a kfunc call per iteration. cond_break (6.9) helps only when the verifier can’t see the bound: with a constant bound it cost 15N, with an unknown one 59, and its hidden budget cut a ten-million-round loop at 8,388,608. Part 4’s popcount loads in 42 instructions with one added line.
  • Exceptions (6.7) need the ORC unwinder on x86-64, which Ubuntu’s mainline 6.10 build doesn’t have, so bpf_throw is refused there.
  • The arena (6.9) is up to 4 GiB of pages shared with user space, where 32-bit offsets on the BPF side and full addresses in user space name the same bytes. User space walked a million-node list a BPF program built in about 2 ms, against about 350 ms through hash map lookups; an mmap-ed array reads as fast, but cannot grow or hold pointers.
  • bpf_wq (6.10) lets a program that may not sleep hand work to one that may, such as allocating arena pages.
  • The BPF token (6.9) delegates chosen commands, map and program types to a user namespace through a BPF filesystem mount, and libbpf 1.4 picks it up without code changes.

A note on the evidence

What I ran, and where. Every listing in this post is pasted from a real run, and every C file and the build script were extracted from this page and built and run as shown. The machine was a KVM virtual machine with 4 virtual CPUs and 4 GiB of memory, running nested inside another virtual machine, booting Ubuntu’s mainline build of Linux 6.10 (6.10.0-061000-generic) on a minimal Ubuntu 24.04 userland built from the release archive only: clang 18.1.3, libelf 0.190 and zlib 1.3. libbpf 1.4.5 and bpftool 7.4.0 were built from their release tags inside that userland and installed under /usr/local; the build links libbpf statically. The guest has no network, so the two curl lines of the build failed there and the selftests headers were copied in from the v6.10 source tarball instead; they are the tag’s, byte for byte (I compared their SHA-256 sums with the copies the curl lines fetch).

The timings. The loop timings, the arena walks and builds, and the on_exit cost came from one run, with conditions interleaved in rotated order. That run was meant to have the host to itself, but another test virtual machine may have been running beside it for part of the time, so I repeated it, unchanged, with nothing else running. The repeat agreed on every comparison: the arena walk took 2.16 ms against the mmap-ed array’s 2.29, the hash map 369 ms one lookup at a time and 182 ms by batch, and on_exit a median of 1,208 ns per exit (1,049 to 1,255, without the 3,162 ns outlier of the first run). The tables keep the first run’s numbers. The schedule of that run was: five rounds of the loops, three processes of five rounds each for the arena, five runs of topn 2000. Tables give medians and ranges. The loop timings are BPF_PROG_TEST_RUN’s own average per run; the walks are CLOCK_MONOTONIC in user space; the build times wrap one BPF_PROG_TEST_RUN call from user space, system call included; the on_exit cost is bpf_stats, which includes reading the clock twice per run. All of it ran in a nested virtual machine, where page faults and system calls cost more than on hardware, so the ratios between conditions are what I rely on, not the absolute numbers.

What I trimmed. Verifier logs are their last lines, from the instruction that matters; the figure’s states are copied from one level-2 log with kernel addresses replaced by the map’s name. PIDs and arena addresses are as printed in the run shown, and differ from run to run. The arenalist output shown is the first of the three processes in the timing run. The table of refusals quotes the last line of each variant’s log, and the variants differ from topn.bpf.c by exactly the change described. Those messages, and the popcount listing, come from a second, short run of the same object files, because the first run’s capture cut the messages off.

What I cited rather than ran. The version each feature arrived in, which I checked by asking which release tag first contains the commit that introduced it (the commits are listed in the timeline figure’s source). The 6.10 source for: what bpf_obj_new initialises; the may_goto rewrite and the widening of imprecise scalars (widen_imprecise_scalars in verifier.c); the arena’s address layout, fault handling and memory accounting (kernel/bpf/arena.c, and the exception-table handling in arch/x86/net/bpf_jit_comp.c); the ORC requirement for exceptions and how a throw is checked; the token’s capability checks (kernel/bpf/token.c, syscall.c). That 5.19 and 6.1 register no kptr destructor outside net/bpf/test_run.c I checked by searching their source trees. libbpf’s behaviour with /sys/fs/bpf and LIBBPF_BPF_TOKEN_PATH is from the 1.4.5 source, and seen working in the token run.

What I’d still change. I could not run an exception on this kernel; a build with CONFIG_UNWINDER_ORC=y would let me show bpf_assert returning through its callback, and bpf_throw refused while holding a reference. The arena comparison reads a list in allocation order, which is kind to every hardware prefetcher; a list linked in random order would be slower for the arena and the array alike, and is the next thing I would measure. And all of the timings come from one nested virtual machine.

More