← Writing

A Program the Kernel Agreed to Run

35 min readSystemsEbpfLinuxKernelCTracing
Contents

On a freshly installed Ubuntu 22.04, a program of 27 instructions counted every process the kernel started, from inside the kernel, with no kernel module, no reboot and no recompiled kernel. Before it ran even once, the kernel read all 27 instructions and proved to itself that none could crash it, loop forever or read memory it had no business reading. It then rewrote the program’s map lookup, added two instructions of its own, and compiled the result into 141 bytes of x86-64 machine code. In the virtual machine I tried it on, each run cost about 0.7 microseconds.

That program is the subject of this post, and the technology behind it, eBPF, is the subject of the series this post begins. It starts at the very beginning: what eBPF is, why it exists, and what actually happens, one system call at a time, between typing a command and having code run inside the kernel.

This is Part 1 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 was run on Ubuntu 22.04 as it shipped in April: kernel 5.15.0-25-generic, clang 14, libbpf 0.5, bpftrace 0.14 and the bpftool from linux-tools-5.15.0-25-generic. The output is pasted from those runs, not reconstructed. The note at the end says exactly where and how.

The problem: you want to ask the kernel a question

Suppose you want to know which programs are being started on a machine and how often. It sounds like a question with an easy answer, and on most systems it isn’t one.

The kernel knows. Every new program goes through the execve() system call, so the kernel sees every one of them. The trouble is getting that knowledge out. Until recently you had three options, and each of them is bad in its own way.

Ask from the outside. Poll /proc every few milliseconds and diff the list of processes. You’ll miss anything that starts and exits between two polls, which is most short-lived commands, and you pay for every poll whether anything happened or not. Or attach strace to a process, which stops the traced process on every system call and switches to the tracer and back. That works for one process and is ruinous for a whole machine.

Change the kernel. Add a counter to execve(), rebuild, reboot. It’s precise and cheap at run time, and it takes years to reach anyone else: the change has to be accepted upstream, released, picked up by a distribution and installed. And then it answers exactly one question. The next question needs another patch.

Load a kernel module. A module is code you write and load into a running kernel. It can hook almost anything, and it runs with the full privileges of the kernel. That is precisely the problem. A module that dereferences a bad pointer doesn’t crash itself. It crashes the machine. Modules are compiled against one kernel’s internal layout, so they break between versions, and a production team that is asked to load someone’s module into every server should, and usually will, say no.

What you actually want is a fourth option: the precision and cost of the kernel patch, with the safety of a user-space program and the deployment story of a shell command. That is what eBPF is.

What eBPF is, in one paragraph

eBPF lets you hand the kernel a small program, written in a restricted instruction set, together with a description of where to run it: on every execve(), on every packet arriving at a network card, every time a particular kernel function is entered. Before accepting the program, the kernel runs a verifier over it, a static analyser that walks every path through the code and proves the program terminates, only touches memory it is allowed to touch, and only calls kernel functions it is allowed to call. If the proof fails, the program is rejected and nothing has been touched. If it succeeds, a JIT compiler translates the program to native machine code and the kernel attaches it to the hook you asked for. From then on, the kernel runs your code every time the event happens, at close to the cost of a function call. To pass results back to user space, the program writes into maps, key–value stores that both the program and ordinary user-space code can read and write.

That paragraph contains every concept the rest of this post depends on, so the next section takes it apart. First, though, the name, because it’s misleading.

From a packet filter to a general-purpose engine

BPF stands for Berkeley Packet Filter, and for twenty years that’s all it was.

In December 1992, Steven McCanne and Van Jacobson at Lawrence Berkeley Laboratory wrote The BSD Packet Filter: A New Architecture for User-level Packet Capture, presented at the USENIX Winter conference in January 1993. The problem they solved was the one tcpdump had: to show you the packets you asked for, it copied every packet from the kernel into user space and threw most of them away there. Their fix was to send the filter into the kernel instead. tcpdump compiles an expression like tcp port 80 into a program for a tiny virtual machine, with one accumulator, one index register and a scratch area, and the kernel runs that program on each packet, copying out only the ones it accepts. The machine was simple enough to check before running: no backward jumps, so every program terminates, and every packet access is bounds-checked.

Linux took the design for its socket filters, and there it might have stayed. What changed it was a rework by Alexei Starovoitov, merged in stages through 2014:

  • 3.15 (June 2014) replaced the kernel’s internal BPF interpreter with a new instruction set: ten general-purpose 64-bit registers instead of two 32-bit ones, a stack, and calls into the kernel. User space still spoke classic BPF; the kernel translated it.
  • 3.16 gave the new instruction set a JIT for x86-64.
  • 3.18 (December 2014) added the bpf() system call, which let user space load programs in the new format directly, together with the verifier and the interface for maps. That is the release usually given as eBPF’s birth. The first map types, hash and array, followed in 3.19.
  • 3.19 gave those programs their first attach point, sockets. Then the hooks came quickly: 4.1 kprobes (any kernel function), 4.7 tracepoints, 4.8 XDP (packets in the network driver, before the kernel has even built its sk_buff, the structure every packet normally travels in), 4.9 perf events, and so on through every release since.

The “e” is for “extended”, and what it extended was the instruction set. Today the name is a historical accident: eBPF filters packets about as much as C formats teletypes. People mostly say “BPF” for the new thing and “classic BPF” or “cBPF” for the old one, and so will I.

The five pieces

Every BPF program you will ever write involves the same five pieces. They are worth having as separate ideas, because most of the confusion in BPF comes from mixing them up.

1. The program. A sequence of instructions for the BPF virtual machine. It has eleven 64-bit registers, r0 to r10. r10 is a read-only frame pointer, and below it sits a stack of 512 bytes. That is all the local memory a program gets, and it is why the program in this post keeps its data in a map. Nobody writes the instructions by hand. You write C (or a higher-level language, as we’ll see) and compile it with clang, whose bpf backend emits the instructions into an ordinary ELF object file. Part 2 reads them one by one.

2. The hook, and the program type. A program doesn’t run on its own. It runs when something happens, and the program type says what that something is, which in turn decides what the program receives as input and what it is allowed to do. A BPF_PROG_TYPE_XDP program receives a packet and returns a verdict: drop it, pass it, send it back out. A BPF_PROG_TYPE_TRACEPOINT program receives the arguments of a kernel tracepoint and its return value is ignored. The kernel I’m using knows 31 program types, which the figure below groups by where they hook in.

3. Maps. Key–value stores that live in the kernel. A program reads and writes them through helper calls, and user space reads and writes the same maps through the bpf() system call. They are the only way a program keeps state between runs, and the main way it talks to user space. There are hash maps, arrays, per-CPU variants of both, LRU caches, longest-prefix-match tries for IP routes, queues, stacks, ring buffers and more: 29 types on this kernel.

4. Helpers. A program cannot call arbitrary kernel functions. It can call helpers, a fixed menu of kernel functions designed for BPF, each with a number and a signature the verifier knows: bpf_map_lookup_elem, bpf_get_current_comm (the name of the current process), bpf_ktime_get_ns, bpf_probe_read_kernel, and so on. This kernel has 175. Which ones a program may call depends on its type. A packet filter can’t read the current task’s memory, and a tracing program can’t redirect packets.

5. The verifier and the JIT. The two gatekeepers between “here is a program” and “the kernel runs it”. The verifier proves safety. The JIT makes it fast. Most of what is distinctive about writing BPF comes from the verifier, and a whole later part is given to it. For now one rule is enough: the verifier must be able to prove, by looking at the code alone, that every memory access is safe on every path. We will break that rule on purpose near the end of this post.

Where a BPF program can run, and since when

Drag through kernel releases: each hook lights up in the release that merged it.

Linux 5.15 · Oct 2021
user-space code
uprobes 4.3
system calls
syscall tracepoints 4.7 raw tracepoints 4.17
any kernel function
kprobes 4.1 fentry / fexit 5.5
scheduler, memory, disks…
tracepoints 4.7 perf events 4.9 iterators 5.8
security decisions
LSM hooks 5.7
kernel policy
struct_ops (TCP congestion control) 5.6
sockets and cgroups
socket filters 3.19 cgroup skb / sock 4.10 sock_ops 4.13 sockmap 4.14 sk_msg 4.17 sk_lookup 5.9
traffic control
tc classifier 4.1 tc direct-action 4.4
network driver
XDP 4.8 AF_XDP 4.18
closer to user spacecloser to the hardware ↓

Green is the hook this post's program uses: the tracepoint on entry to execve(). Versions are the first mainline release containing the commit that added each hook. This is not every program type (the kernel in this post knows 31), only the main families.

First contact: one line of bpftrace

The fastest way to run a BPF program is not to write one. bpftrace is a tracing language in the spirit of awk: you write a probe and an action, and it compiles them into a BPF program, loads it, attaches it and prints the results. Ubuntu 22.04 has it as a package (apt install bpftrace, version 0.14.0).

Here is the whole question from the start of this post, “which programs are being started, and how often?”, as one line:

sudo bpftrace -e 'tracepoint:syscalls:sys_enter_execve { @[comm] = count(); }'

Read it left to right:

  • tracepoint:syscalls:sys_enter_execve is the hook: the tracepoint the kernel fires on entry to the execve() system call. Tracepoints are fixed instrumentation points that kernel developers placed deliberately and try hard to keep stable, unlike arbitrary kernel functions, which can be renamed or inlined away in any release.
  • { ... } is the action, compiled into the program that runs on each hit.
  • comm is the name of the process making the call: whoever is calling execve(), so usually the shell, not the program being started.
  • @[comm] = count() declares a map, @, keyed by that name, and adds one to the entry. bpftrace creates the map, and when you press Ctrl-C it reads the map back and prints it.

While that ran, a shell ran /bin/true ten times and ls three times. Then bpftrace was interrupted, which is what Ctrl-C does, and printed its map on the way out:

Attaching 1 probe...


@[sh]: 13

Thirteen calls to execve(), all from sh. That’s exactly the thirteen commands. It is a toy, and it is also a complete answer to a question that /proc polling can only approximate.

bpftrace hides every step between the one-liner and the answer. To see those steps, we have to write the program ourselves.

The same program, written out

The serious way to write BPF in 2022 is C plus libbpf, the loader library maintained alongside the kernel. A libbpf tool has two halves: a BPF program that runs in the kernel, and an ordinary C program that loads it, attaches it and reads its results. Here is the kernel half, the whole of it:

// execcount.bpf.c — runs in the kernel, once per execve()
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>

#define TASK_COMM_LEN 16

struct comm_key {
	char comm[TASK_COMM_LEN];
};

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

SEC("tracepoint/syscalls/sys_enter_execve")
int count_execve(void *ctx)
{
	struct comm_key key = {};
	__u64 one = 1, *val;

	bpf_get_current_comm(&key.comm, sizeof(key.comm));

	val = bpf_map_lookup_elem(&counts, &key);
	if (val)
		__sync_fetch_and_add(val, 1);
	else
		bpf_map_update_elem(&counts, &key, &one, BPF_NOEXIST);
	return 0;
}

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

Line by line, because nearly every line is doing something specific to BPF:

  • vmlinux.h is a header containing every type defined in the running kernel, generated from the kernel itself (we’ll make it in a moment). It saves including dozens of kernel headers, and matching their versions to the kernel by hand.
  • bpf_helpers.h, from libbpf, declares the helpers and the SEC() and __uint() macros.
  • The map definition is a struct that is never instantiated as data. Its fields encode the map’s type, size, key type and value type in the debug information, and SEC(".maps") puts it in a section of the object file where libbpf looks for map definitions. This is the “BTF-defined” map syntax. Older examples use a struct bpf_map_def in a section called maps. libbpf has deprecated that form, so new code should use this one.
  • SEC("tracepoint/syscalls/sys_enter_execve") names the hook. libbpf reads the section name to work out both the program type (BPF_PROG_TYPE_TRACEPOINT) and what to attach to.
  • bpf_get_current_comm is a helper that copies the current task’s name into our key. The key is zeroed first (= {}), because the hash map compares all 16 bytes, and stale stack bytes after the name would make “sh” a different key each time. As we’ll see, the verifier would also refuse to let us pass uninitialised stack memory as a key.
  • bpf_map_lookup_elem returns a pointer into the map’s own memory, or NULL if the key is absent. If it is present we increment in place, with an atomic add, because the same program may be running on several CPUs at once.
  • If it is absent we insert 1. BPF_NOEXIST means “only if still absent”. Two CPUs that both miss and both insert would otherwise overwrite each other. With the flag, the loser’s insert fails and that one count is lost. For an exact count you would retry the lookup. For a tool like this, one lost count in a race that needs two simultaneous first execve()s from the same process name is a trade worth making.
  • The licence matters. Some helpers are only available to GPL-compatible programs, and the kernel checks this string at load time.

And the user-space half:

// execcount.c — the user-space half: load, attach, wait, read the map
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "execcount.skel.h"

#define TASK_COMM_LEN 16

int main(int argc, char **argv)
{
	int seconds = argc > 1 ? atoi(argv[1]) : 5;
	struct execcount_bpf *skel;
	char key[TASK_COMM_LEN], next[TASK_COMM_LEN];
	char *prev = NULL;
	__u64 count;
	int fd;

	skel = execcount_bpf__open_and_load();   /* BPF_MAP_CREATE, BPF_PROG_LOAD */
	if (!skel) {
		fprintf(stderr, "failed to open and load the BPF object\n");
		return 1;
	}
	if (execcount_bpf__attach(skel)) {        /* perf_event_open + ioctl */
		fprintf(stderr, "failed to attach\n");
		execcount_bpf__destroy(skel);
		return 1;
	}

	printf("counting execve() for %d s\n", seconds);
	fflush(stdout);
	sleep(seconds);

	fd = bpf_map__fd(skel->maps.counts);
	while (bpf_map_get_next_key(fd, prev, next) == 0) {
		bpf_map_lookup_elem(fd, next, &count);
		printf("%-16s %llu\n", next, (unsigned long long)count);
		memcpy(key, next, sizeof(key));
		prev = key;
	}

	execcount_bpf__destroy(skel);
	return 0;
}

The interesting include is execcount.skel.h, a skeleton. bpftool generates it from the compiled BPF object. It embeds the whole object file as a byte array and wraps it in typed functions: execcount_bpf__open_and_load(), __attach(), __destroy(), and a skel->maps.counts field so user space can refer to the map by name instead of looking it up. The loop at the end walks the map with bpf_map_get_next_key, the user-space equivalent of iterating a hash table you can’t see inside: give it a key and it returns the next one, give it NULL and it returns the first.

Building it takes four commands. On Ubuntu 22.04, bpftool comes from the linux-tools-generic package (and linux-tools-$(uname -r)); clang, libbpf-dev and libelf-dev are packages of the same names:

bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -c execcount.bpf.c -o execcount.bpf.o
bpftool gen skeleton execcount.bpf.o > execcount.skel.h
cc -g -O2 -Wall execcount.c -lbpf -lelf -lz -o execcount

The first command reads /sys/kernel/btf/vmlinux. This file is the kernel’s own description of every type it contains, in a compact format called BTF (BPF Type Format). Ubuntu 22.04’s kernel is built with it, so the header always matches the kernel you’re running. (BTF is the foundation of a lot more than header generation, and it gets its own part.) The second compiles the C to BPF instructions. -target bpf selects clang’s BPF backend, -g keeps the debug information that carries the map definition and line numbers, and -O2 is effectively required: unoptimised BPF code spills and reloads values in patterns the verifier often can’t follow, and gets rejected. The third generates the skeleton. The fourth is an ordinary build.

Running it while the same thirteen commands were typed:

$ sudo ./execcount 6
counting execve() for 6 s
sh               13

The same answer as bpftrace. Now for what happened in between.

Following it through the kernel

Everything a loader does to the kernel goes through system calls, so strace sees all of it. I ran the tool under strace -f -e trace=bpf,perf_event_open,ioctl and got 20 lines. The figure steps through all of them in order, alongside the steps that happen without a system call. The text below takes them by what they are for, trimmed to the arguments that matter.

Loading one BPF program, as the kernel saw it

All 20 system calls libbpf made to load, attach, read and remove the counter, plus the steps that happen inside them.

before any syscall

clang has produced an ELF object

clang -g -O2 -target bpf -c execcount.bpf.c -o execcount.bpf.o

The object holds 27 BPF instructions in a section named tracepoint/syscalls/sys_enter_execve, a map description in .maps, the licence string, and BTF type information. bpftool has embedded all of it in the skeleton, so the tool carries its program inside itself.

libbpf probe · bpf_object__probe_loading

Can this process load anything at all?

bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_SOCKET_FILTER, insn_cnt=2, prog_name="", ...}) = 3

A two-instruction program, r0 = 0; exit. If this fails, nothing else will work, which is the check that produces the misleading RLIMIT_MEMLOCK message when an unprivileged user runs the tool. Descriptor 3 is closed straight away.

libbpf probes · BTF features

Five tiny BTF uploads, then the real one

bpf(BPF_BTF_LOAD, {btf_size=45, ...}) = 3
bpf(BPF_BTF_LOAD, {btf_size=81, ...}) = 3
bpf(BPF_BTF_LOAD, {btf_size=89, ...}) = 3
bpf(BPF_BTF_LOAD, {btf_size=43, ...}) = 3
bpf(BPF_BTF_LOAD, {btf_size=81, ...}) = 3
bpf(BPF_BTF_LOAD, {btf_size=938, ...}) = 3

The first five each test whether the kernel understands one kind of BTF record, and are closed. The sixth, 938 bytes, is the object's own type information: struct comm_key, the map's key and value types, and count_execve with its line table. It stays open as descriptor 3.

libbpf probe · probe_kern_prog_name

Does the kernel accept program names?

bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_SOCKET_FILTER, insn_cnt=2, prog_name="test", ...}) = 4

It does, so libbpf will send count_execve as the name. That is why bpftool prog show can print it.

the program's map

The map is created

bpf(BPF_MAP_CREATE, {map_type=BPF_MAP_TYPE_HASH, key_size=16, value_size=8,
    max_entries=1024, map_name="counts", btf_fd=3, ...}) = 4

The struct in .maps becomes a real hash table in kernel memory, sized for 1,024 entries, typed by the BTF in descriptor 3. It is descriptor 4.

libbpf probe · probe_kern_exp_attach_type

Does the kernel take an expected attach type?

bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_CGROUP_SOCK,
    expected_attach_type=BPF_CGROUP_INET_SOCK_CREATE, insn_cnt=2, ...}) = 5

Another probe, closed at once. Our program doesn't need the answer, but libbpf asks on its way to loading any program.

inside libbpf · no syscall

The map relocation is patched

10: r1 = <map "counts">   →   r1 = map fd 4

The compiled program refers to counts, which did not exist at compile time. libbpf writes descriptor 4 into that 16-byte instruction and marks it as a map reference.

the program

The program is loaded, verified and compiled

bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_TRACEPOINT, insn_cnt=27, license="GPL",
    prog_name="count_execve", prog_btf_fd=3, ...}) = 5

Inside this one call, the kernel copies in 27 instructions, runs the verifier over every path, swaps the map descriptor for the map's address, specialises the lookup (27 becomes 29 instructions), JIT-compiles 141 bytes of x86-64, and returns descriptor 5. Had the proof failed, the call would have returned an error and nothing would have run.

the hook

A perf event for tracepoint 716

perf_event_open({type=PERF_TYPE_TRACEPOINT, config=716, ...}, -1, 0, -1, PERF_FLAG_FD_CLOEXEC) = 6

716 is the ID of syscalls/sys_enter_execve, read from /sys/kernel/debug/tracing/events/syscalls/sys_enter_execve/id. -1 means any process.

libbpf probe · probe_perf_link · fails on purpose

Are perf links supported?

bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_TRACEPOINT, insn_cnt=2, ...}) = 7
bpf(BPF_LINK_CREATE, {link_create={prog_fd=7, target_fd=-1, attach_type=BPF_PERF_EVENT}}) = -1 EBADF

A deliberately bad descriptor, -1. EBADF means the kernel understood the command and only objected to the descriptor, so perf links exist on this kernel. An older one would have said EINVAL, and libbpf would fall back to an ioctl.

the attachment

Program 5 is linked to event 6, and the event switched on

bpf(BPF_LINK_CREATE, {link_create={prog_fd=5, target_fd=6, attach_type=BPF_PERF_EVENT}}) = 7
ioctl(6, PERF_EVENT_IOC_ENABLE, 0) = 0

Descriptor 7 is the link: the program attached to the hook. From this moment every execve() on the machine runs the program.

in the kernel · no syscall from us

Thirteen execs, thirteen runs

sh → execve("/bin/true")  →  count_execve()  →  counts["sh"] += 1   (×13)

The shell calls execve(), the tracepoint fires, and our 141 bytes run in the calling process's context, before the new program replaces it. Nothing crosses to user space.

reading the results

Walk the map from user space

bpf(BPF_MAP_GET_NEXT_KEY, {map_fd=4, key=NULL, ...}) = 0
bpf(BPF_MAP_LOOKUP_ELEM, {map_fd=4, ...}) = 0
bpf(BPF_MAP_GET_NEXT_KEY, {map_fd=4, ...}) = -1 ENOENT

First key (sh), its value (13), then ENOENT: no more keys.

teardown

Disable, close, exit

ioctl(6, PERF_EVENT_IOC_DISABLE, 0) = 0
+++ exited with 0 +++

There is no unload call. Closing the last descriptor that refers to the link, the program, the map and the BTF frees each of them, and the process exiting closes them all.

Descriptors held

Green steps are the program's own work, grey are libbpf asking the kernel what it supports, teal happens without a system call, and copper is the one failure, which is intended.

Probing the kernel. Four of the five BPF_PROG_LOAD calls load programs that do nothing: two instructions, r0 = 0; exit.

bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_SOCKET_FILTER, insn_cnt=2, ...}) = 3

libbpf is asking the kernel what it supports. The first asks whether this process can load a program at all. That check fails for an unprivileged user, as we’ll see. The others ask whether the kernel accepts a program name, an “expected attach type”, and links to perf events. Each answer is a load that succeeds or fails, and each probe program is closed straight away, which is why the same descriptor numbers keep coming back. Five of the six BPF_BTF_LOAD calls are the same idea for BTF features. The sixth, 938 bytes, uploads our object’s real type information: struct comm_key, the map’s key and value types, and the function count_execve with its line-number table. That upload is why bpftool can show C source next to the instructions later.

Creating the map.

bpf(BPF_MAP_CREATE, {map_type=BPF_MAP_TYPE_HASH, key_size=16, value_size=8,
    max_entries=1024, map_name="counts", btf_fd=3, ...}) = 4

The struct in the .maps section has become a real hash map: 16-byte keys, 8-byte values, room for 1,024 entries, now file descriptor 4 in this process. The kernel allocates its memory now, before any program has run.

Fixing up the program. Between those two calls libbpf did something strace can’t show. The compiled program refers to the map counts, but when clang compiled it, the map didn’t exist, so the object file contains a relocation: “this instruction needs the address of the map called counts”. libbpf patches the instruction with the new file descriptor, 4, and marks it as a map reference. The kernel will translate that descriptor into the map’s real address during verification.

Loading the program.

bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_TRACEPOINT, insn_cnt=27, license="GPL",
    prog_name="count_execve", prog_btf_fd=3, ...}) = 5

This one call is where most of the work in this post happens. Inside it the kernel:

  1. copies the 27 instructions in;
  2. runs the verifier over them: every path, every register, every memory access;
  3. rewrites some of them: map file descriptors become map addresses, and the hash map lookup is replaced by something faster (we’ll see what);
  4. JIT-compiles the result to x86-64; and
  5. returns a file descriptor, 5, which is the program as far as user space is concerned.

If the verifier had objected, this call would have failed with EACCES and a log explaining why, and nothing else would have happened. That is the whole safety model: the check happens here, once, before the program has run.

Attaching. A loaded program runs nowhere until it’s attached. For a tracepoint, attaching goes through perf, the kernel’s performance-monitoring subsystem:

perf_event_open({type=PERF_TYPE_TRACEPOINT, config=716, ...}, -1, 0, -1, PERF_FLAG_FD_CLOEXEC) = 6
bpf(BPF_LINK_CREATE, {link_create={prog_fd=5, target_fd=6, attach_type=BPF_PERF_EVENT}}) = 7
ioctl(6, PERF_EVENT_IOC_ENABLE, 0) = 0

config=716 is the tracepoint’s numeric ID, which libbpf read from /sys/kernel/debug/tracing/events/syscalls/sys_enter_execve/id. On this kernel that file holds 716. perf_event_open creates an event for that tracepoint on every CPU (-1). BPF_LINK_CREATE binds our program to it and returns a link, file descriptor 7: an object that represents “this program attached to this hook”. The ioctl switches the event on. From this moment, every execve() on the machine runs our 141 bytes of machine code.

The trace has one more BPF_LINK_CREATE just before the successful one. It fails with EBADF, on purpose. libbpf loads a two-instruction tracepoint program and tries to link it to an invalid descriptor. If the kernel complains about the descriptor rather than the command, the kernel supports perf links, and libbpf uses them. Older kernels would get the older PERF_EVENT_IOC_SET_BPF ioctl instead.

Reading the results.

bpf(BPF_MAP_GET_NEXT_KEY, {map_fd=4, key=NULL, ...}) = 0
bpf(BPF_MAP_LOOKUP_ELEM, {map_fd=4, ...}) = 0
bpf(BPF_MAP_GET_NEXT_KEY, {map_fd=4, ...}) = -1 ENOENT (No such file or directory)

The first key, its value, and then ENOENT: no more keys. One entry, sh, thirteen.

Tearing down. execcount_bpf__destroy() closes the descriptors. There is no “unload” call. The kernel keeps a reference count on every program, map and link, and frees each object when the last reference is gone. The program dies when the process that loaded it does, unless something else holds a reference to it. Holding it some other way, so that a program outlives its loader, is one of the subjects of Part 3.

What the kernel actually runs

While the program was attached, bpftool showed it from the kernel’s side:

$ sudo bpftool prog show
10: tracepoint  name count_execve  tag 2ef1c7a420d19e5e  gpl
	[loaded_at line trimmed]
	xlated 232B  jited 141B  memlock 4096B  map_ids 5
	btf_id 32
$ sudo bpftool map show
5: hash  name counts  flags 0x0
	key 16B  value 8B  max_entries 1024  memlock 24576B
	btf_id 32

Two sizes are worth noticing. xlated 232B is the program as the kernel holds it after verification: 29 instructions of 8 bytes each. jited 141B is the native code the JIT produced. We sent 27 instructions and the kernel keeps 29. Here are the 29, with the C source lines the BTF upload let bpftool attach:

$ sudo bpftool prog dump xlated id 10
int count_execve(void * ctx):
; int count_execve(void *ctx)
   0: (b7) r1 = 0
; struct comm_key key = {};
   1: (7b) *(u64 *)(r10 -8) = r1
   2: (7b) *(u64 *)(r10 -16) = r1
   3: (b7) r7 = 1
; __u64 one = 1, *val;
   4: (7b) *(u64 *)(r10 -24) = r7
   5: (bf) r6 = r10
;
   6: (07) r6 += -16
; bpf_get_current_comm(&key.comm, sizeof(key.comm));
   7: (bf) r1 = r6
   8: (b7) r2 = 16
   9: (85) call bpf_get_current_comm#160480
; val = bpf_map_lookup_elem(&counts, &key);
  10: (18) r1 = map[id:5]
  12: (bf) r2 = r6
  13: (85) call __htab_map_lookup_elem#176816
  14: (15) if r0 == 0x0 goto pc+1
  15: (07) r0 += 64
; if (val)
  16: (15) if r0 == 0x0 goto pc+2
; __sync_fetch_and_add(val, 1);
  17: (db) lock *(u64 *)(r0 +0) += r7
  18: (05) goto pc+8
  19: (bf) r2 = r10
;
  20: (07) r2 += -16
  21: (bf) r3 = r10
  22: (07) r3 += -24
; bpf_map_update_elem(&counts, &key, &one, BPF_NOEXIST);
  23: (18) r1 = map[id:5]
  25: (b7) r4 = 1
  26: (85) call htab_map_update_elem#189104
; return 0;
  27: (b7) r0 = 0
  28: (95) exit

Part 2 reads this instruction by instruction. Three things are visible even without that:

  • The stack. r10 is the frame pointer, and everything at r10 -8, -16, -24 is our local variables: the 16-byte key at -16 and the constant 1 at -24. The zeroing of the key is instructions 0–2. A helper can’t take a pointer to a register, so one has to live on the stack for its address to be passed to bpf_map_update_elem at 21–22.
  • The map reference. Instruction 10 is a 16-byte instruction, a “load 64-bit immediate”, which is why the numbering skips 11. In our object file it held a placeholder that libbpf filled with the map’s file descriptor. Here it holds the map itself.
  • The rewrite. Our code called the helper bpf_map_lookup_elem. The kernel’s code calls __htab_map_lookup_elem directly and then does two instructions of its own, 14 and 15: if the result isn’t NULL, add 64 to it. Since the verifier knows at load time exactly which map this call will touch, it has replaced the generic helper with the hash table’s internal lookup and inlined the last step: moving from the start of the element, past its 48-byte header and our 16-byte key, to the value, 64 bytes in. Those two extra instructions are why 27 became 29.

The JIT’s output, the 141 bytes, is one step further than the stock 22.04 bpftool will go: bpftool prog dump jited answers Error: No libbfd support, because Ubuntu builds it without the binutils library it uses to disassemble. Part 2 gets the bytes out another way.

Breaking the rule on purpose

Earlier I gave the verifier’s one rule: every memory access must be provably safe on every path. Here is what happens when you break it. Delete the NULL check, so the program increments whatever the lookup returned:

	val = bpf_map_lookup_elem(&counts, &key);
	__sync_fetch_and_add(val, 1);	/* no NULL check */

clang compiles this without a murmur. To clang, it’s valid C. The kernel refuses to load it. Here is the end of the log libbpf prints on failure:

; val = bpf_map_lookup_elem(&counts, &key);
8: (18) r1 = 0xffff968b84842000
10: (bf) r2 = r6
11: (85) call bpf_map_lookup_elem#1
12: (b7) r1 = 1
; __sync_fetch_and_add(val, 1);	/* no NULL check */
13: (db) lock *(u64 *)(r0 +0) += r1
R0 invalid mem access 'map_value_or_null'
processed 13 insns (limit 1000000) max_states_per_insn 0 total_states 1 peak_states 1 mark_read 1

Read the second-to-last line as the verifier speaking. At instruction 13, register r0 holds a value of type map_value_or_null: the verifier tracked the return type of bpf_map_lookup_elem and knows it might be NULL. Dereferencing something that might be NULL is an invalid memory access, so the whole program is rejected. The program never ran. The verifier didn’t wait for a key to be missing and the machine to crash. It saw that a path existed on which it could go wrong, and that was enough.

The last line says how much work the proof was: 13 instructions processed out of a budget of a million. That number becomes interesting when programs have branches and loops, because the verifier explores paths, not lines, and the number of paths can grow very quickly. That, and the many other ways to be refused, is the subject of a later part.

Who is allowed to do this

Every command above ran as root. Here is the same tool as an ordinary user:

$ sysctl kernel.unprivileged_bpf_disabled
kernel.unprivileged_bpf_disabled = 2
$ ./execcount 1
libbpf: Error in bpf_object__probe_loading():Operation not permitted(1). Couldn't load trivial BPF
program. Make sure your kernel supports BPF (CONFIG_BPF_SYSCALL=y) and/or that RLIMIT_MEMLOCK is
set to big enough value.

Two things to note. The first is the sysctl. For years, unprivileged users could load some program types, mostly socket filters, and the verifier was the only line of defence. Then the verifier itself became the attack surface, through bugs in its range tracking and through Spectre-style speculative execution, where a bounds check is respected architecturally but bypassed speculatively. Kernel 5.16, released in January, made 2 the default (unprivileged loading off, and only root can turn it back on), and Ubuntu had already set it that way. On this machine BPF is an administrator’s tool. Since 5.8 the right capability is CAP_BPF (plus CAP_PERFMON for tracing), not full CAP_SYS_ADMIN, so a service can be given BPF without being given everything else.

The second is the message, which is wrong. It isn’t a memlock problem. The kernel said EPERM. Before 5.11, BPF memory was charged against RLIMIT_MEMLOCK, and the default limit was small enough to make loads fail, so libbpf’s message guesses at that. On 5.11 and later, memory is charged to the cgroup instead and the limit doesn’t apply. Newer libbpf releases handle this themselves. Ubuntu 22.04 ships libbpf 0.5, from September 2021, which predates that change, hence the misleading hint. If you see it on a modern kernel, read it as “permission denied”.

What it costs

The kernel can time BPF programs for you. With kernel.bpf_stats_enabled=1, it records how many times each program ran and the total time spent in it, and bpftool prog show prints both. I enabled it, attached the counter and ran /bin/true a thousand times:

15: tracepoint  name count_execve  tag 2ef1c7a420d19e5e  gpl run_time_ns 740893 run_cnt 1005

1,005 runs: the thousand /bin/trues, plus the five execs it took to start bpftool and filter its output, which the counter dutifully counted too. 740,893 nanoseconds in total, about 737 ns per run. An earlier run of the same experiment gave 652. Both include the stats bookkeeping itself, which reads a clock before and after every run, and both were measured in a virtual machine, so treat “about 0.7 µs” as the right order of magnitude rather than a benchmark.

For comparison, a single execve() of /bin/true in the same VM took about 5 milliseconds, seen from the shell. I timed 2,000 of them per round, three rounds without the counter and three with it, alternating. Without, the averages were 4.77, 4.62 and 5.01 ms. With, 4.86, 5.04 and 4.91 ms. The two sets overlap: whatever the program costs, it is lost in the round-to-round variation of starting a process. Seven-tenths of a microsecond is invisible next to the process creation it is counting.

That’s the trade the series is about. The program is precise: it saw thirteen of thirteen, where polling would have missed most. It’s cheap: about a microsecond, and only when the event happens. It’s safe enough to load on a production machine: the kernel proved it before running it. And it needed no reboot, no new kernel and no module.

What’s in the box in 2022

The ecosystem around this is already large, and the names come up constantly, so here is the map as it stands in May 2022.

Ways to write programs. bpftrace for one-liners and short scripts. BCC, the BPF Compiler Collection (0.24 in January), which compiles C embedded in Python at run time on the target machine. It needs clang and kernel headers on every machine it runs on, and the community is moving its tools to libbpf for exactly that reason. libbpf in C, as above, which is where the kernel developers’ own effort goes; the 1.0 release is being prepared, and is removing the deprecated APIs. cilium/ebpf (0.8 this year) for loaders written in Go. Part 3 builds the same tool all three ways and compares them.

Things built on it. Cilium (1.11) uses BPF for Kubernetes networking, and can replace kube-proxy’s iptables rules entirely. Katran, the layer-4 load balancer built on XDP that Facebook (now Meta) open-sourced in 2018, sits in front of its data centres. Falco uses a BPF probe to watch system calls for security rules. Continuous profilers such as Parca (open-sourced in October) and Pixie sample stacks across whole fleets. The eBPF Foundation, founded in August 2021 under the Linux Foundation, gives the companies that depend on BPF a neutral place to fund and coordinate work on it. And Microsoft announced in May 2021 that it is porting eBPF to Windows, verifier and all.

The kernel itself. 5.17 came out in March with bpf_loop, a helper that runs a callback a bounded number of times without the verifier having to walk every iteration. 5.18 is in release candidates. Distributions are catching up: Ubuntu 22.04’s 5.15 has BTF built in, which is what made vmlinux.h a one-liner above, and older distributions without it can’t run tools built the way we built this one.

What we covered

  • eBPF lets user space load a small program into the running kernel and attach it to an event. The kernel verifies the program, compiles it and runs it on every occurrence of the event, with no module, no patch and no reboot.
  • It began as the 1992 BSD Packet Filter, an in-kernel virtual machine for tcpdump’s filters. It was rebuilt between Linux 3.15 and 3.18 into a general-purpose engine with eleven 64-bit registers, a 512-byte stack, maps, helpers, a verifier and a JIT.
  • Five pieces: the program; its type and hook; maps for state and communication; helpers, the only kernel functions it can call; and the verifier and JIT that stand between loading and running.
  • One question, “which programs start, and how often?”, answered with one bpftrace line and with about sixty lines of C and libbpf. Both counted all thirteen calls.
  • Under strace, loading became a sequence: probe the kernel’s features, upload type information, create the map, patch the program with the map’s descriptor, load it (verify, rewrite, JIT), open a perf event for tracepoint 716, link the program to it, enable it, and read the map back.
  • The kernel ran 29 instructions where we sent 27, because the verifier specialised the map lookup.
  • Removing a NULL check was rejected at load time with R0 invalid mem access 'map_value_or_null': the proof failed, so the program never ran.
  • On Ubuntu 22.04, BPF is root-only (unprivileged_bpf_disabled = 2), and each run of the counter cost about 650 ns.

Part 2 opens the program up: the instruction encoding, what each of those 29 lines does to the registers, how a call works, and the 141 bytes of x86-64 the JIT turned them into.

A note on the evidence

What I ran, and where. Every listing in this post is pasted from a real run. Nothing is described that wasn’t seen. The machine was a KVM virtual machine with 4 virtual CPUs and 4 GiB of memory. It booted 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, so every package is at its release-day version: clang 14.0.0-1ubuntu1, libbpf-dev 0.5.0-1, bpftrace 0.14.0, and bpftool v5.15.30 from linux-tools-5.15.0-25-generic. The C in this post was extracted from the page, compiled and run as shown.

What I trimmed. strace lines are cut to their meaningful arguments, marked .... Instruction addresses, program and map IDs, and file descriptor numbers are as printed, and the show and xlated listings come from one load of the program. The loaded_at line of bpftool prog show is cut, as marked. The verifier log is its last lines, from the first instruction that mentions the map. The full log starts at instruction 0 and adds one BTF diagnostic line about the void *ctx argument that doesn’t affect the result.

The counts. The thirteen execve() calls were generated by a script that ran /bin/true ten times and ls three times while the counter was attached. Both bpftrace and the C tool counted thirteen, all from sh. bpftrace was stopped with SIGINT, the signal Ctrl-C sends. The cost figure is bpf_stats’ own accounting, 740,893 ns over 1,005 runs (652 ns per run in an earlier identical experiment), in a virtual machine, and it includes the overhead of the accounting. The exec timings were 2,000 /bin/trues per round in a shell loop, three rounds without and three with the program, alternating: 4.77, 4.62, 5.01 ms against 4.86, 5.04, 4.91 ms per exec. They overlap, so all I claim is that the counter’s cost was too small to see at that scale.

What I cited rather than ran. The history: the 1992 paper’s date and venue, and the kernel versions in which each feature landed, which I checked against the commits that introduced them in Linus Torvalds’s tree. The reasons for unprivileged_bpf_disabled = 2 are from the kernel commit that made it the default in 5.16. The ecosystem paragraph names projects as they stood on the date of this post.

What I’d still change. The cost measurement comes from one virtual machine and one program. Programs that do more per run cost more, and a later part measures the overhead of different kinds of hook against each other properly, on the same machine, one at a time.

More