Three Ways to Load a Program

Contents
On a stock Ubuntu 22.04, the same 27-instruction BPF program, a counter of every execve() call on the machine, took 282 milliseconds to start counting when its loader was BCC and 97 when it was bpftrace. Compiled ahead of time and loaded from C or from Go, it was counting in under 2 milliseconds. The BCC version peaked at 129 MB of memory and needed 355 MB of packages on the machine it ran on, a compiler and the kernel’s headers among them. The C version peaked at 1.3 MB and needed half a megabyte.
All four loaders ended up making the same system call and holding the same kind of handle, a file descriptor. This post measures what separates them, then goes underneath to the object model they share: why a BPF program normally dies with the process that loaded it, and how pinning one object in a special filesystem kept the counter counting after its loader had exited.
This is Part 3 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, bpftrace 0.14, BCC 0.18, libbpf 0.5, and Go
1.18 with cilium/ebpf 0.9.0. The output is pasted from those runs, not reconstructed. The note at
the end says exactly where and how.
One program, four front ends
Part 1 built one small tool and followed it into the
kernel: a BPF program that runs on every
execve() and counts calls by the name of the calling process. It wrote that tool twice, as a
bpftrace one-liner and as C with libbpf, and both printed sh 13 after a shell had started
thirteen programs. It didn’t ask what the two versions cost, or why anyone would pick one over
the other. This part does.
The kernel half of the tool, the part that runs on each execve(), is the small part. The rest is
a loader: an ordinary user-space program that turns a description of the BPF program into
bpf() system calls, attaches the result to a hook, and reads the map back. Every BPF tool has
one, and they differ far more than the programs they load. In 2022 there are three common ways to
get one, plus a fourth that is quickly becoming common:
- bpftrace, where you write a script and bpftrace is the loader. It compiles the script on the spot, inside its own process.
- BCC, the BPF Compiler Collection, where you write the kernel half in C, embed it as a string in a Python program, and BCC compiles it with clang when the Python program starts, on the machine it is running on.
- libbpf, where you compile the kernel half once, on your own machine, and ship the compiled object inside an ordinary C program.
- cilium/ebpf, a pure Go library on the same model as libbpf: compile once, embed the object, load it from Go.
I wrote the counter all four ways and ran each on the same stock Ubuntu 22.04 virtual machine,
then measured what you’d want to know before choosing: how long each takes from being started to
actually counting, how much memory it needs, and what has to be installed on the machine it runs
on. Then I watched each one under strace, because the differences are all in user space, and
the system calls show exactly where the time goes.
The second half of the post goes underneath all four. However a loader is written, it ends up making the same few system calls, and what it gets back is the same kind of thing: file descriptors. A BPF program lives as long as something holds a reference to it, and the rules for that explain why a program normally dies with its loader, how you can give it a name in a special filesystem, and what it takes for a program to keep running after the loader has exited.
bpftrace: the compiler is the tool
Here is Part 1’s one-liner again:
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_execve { @[comm] = count(); }'
and its output, after a shell ran /bin/true ten times and ls three times and bpftrace was sent
the Ctrl-C signal:
Attaching 1 probe...
@[sh]: 13
On the surface that is the whole story. Underneath, bpftrace did a lot of work to produce those lines, and almost all of it happened before the probe was attached. Ubuntu 22.04’s bpftrace is version 0.14, and three of the shared libraries it loads at start-up tell you most of what it is:
/lib/x86_64-linux-gnu/libbcc.so.0
/lib/x86_64-linux-gnu/libclang-cpp.so.11
/lib/x86_64-linux-gnu/libLLVM-11.so.1
libLLVM is the LLVM compiler infrastructure, the same back end clang uses, including its BPF
target. libclang-cpp is clang itself, as a library. And libbcc is BCC’s library: bpftrace 0.14
uses BCC’s code to load and attach programs. In other words, bpftrace carries a C compiler and
another BPF toolkit inside itself. Note the version: Ubuntu 22.04’s default clang is 14, but its
bpftrace and BCC packages are built against LLVM 11, so installing either pulls in a second,
older copy of LLVM.
A trace of the system calls it made shows the steps in order.
- It parses the one-liner into a syntax tree. No system calls; this is quick.
- It works out the tracepoint’s arguments. A tracepoint program receives a pointer to a
structure laid out by the kernel, and bpftrace makes those fields available as
args->.... To learn the layout it reads the tracepoint’s description, a file calledformatin the tracepoint’s directory under/sys/kernel/debug/tracing/events/, writes a C structure from it, and hands that to clang to parse. It also reads the kernel’s BTF, the type information from/sys/kernel/btf/vmlinuxthat Part 1 used to makevmlinux.h, and generates a header from it for the same parse. Our one-liner never usesargs, but bpftrace does this work anyway. In the trace, clang’s set-up (which includes a hunt for a GCC installation) shows up again and again, each time in a new thread: six threads in all. - It generates code. bpftrace walks the syntax tree and emits LLVM’s intermediate
representation, which LLVM compiles to BPF instructions, all in memory. No compiler process
is started:
execveappears once in the trace, for bpftrace itself. - It creates maps and loads the program. The map
@becomes a BPF map, and a second map and four perf events are set up for output, of which more below. - It attaches, with a perf event and an
ioctl, as we’ll see below. Then it waits for Ctrl-C, reads the map and prints it.
The kernel ends up with this, as bpftool prog show and bpftool map show printed it while all
four versions of the tool were running at once:
$ sudo bpftool prog show
[the other three tools' programs trimmed]
19: tracepoint name sys_enter_execv tag 6da3b410ac490c74 gpl
[loaded_at line trimmed]
xlated 216B jited 128B memlock 4096B map_ids 16
$ sudo bpftool map show
[the other tools' maps trimmed]
16: percpu_hash name AT_ flags 0x0
key 16B value 8B max_entries 4096 memlock 196608B
17: perf_event_array name printf flags 0x0
key 4B value 4B max_entries 4 memlock 4096B
bpftrace sent the kernel 27 instructions, by coincidence exactly as many as clang produced from our C in Part 1, and the kernel kept all 27 (216 bytes). It turned our 27 into 29, the 29 that Part 2 read one by one, by inlining the hash map lookup, and that inlining exists for ordinary hash maps; this map is a different kind. Three details are particular to bpftrace:
- The name is cut short. bpftrace named the program after its probe,
sys_enter_execve, and the kernel keeps at most 15 characters of a program’s name, so it becamesys_enter_execv. - There is no
btf_id. bpftrace 0.14 doesn’t upload type information for what it generates, sobpftool prog dump xlatedhas no source lines to show next to the instructions. - The map is per-CPU.
count()is apercpu_hashcalledAT_(for@), with 4,096 entries. Each CPU has its own copy of every value, so incrementing needs no atomic instruction and CPUs never contend for a counter, and bpftrace sums the copies when it prints. That is why its memlock, 196,608 bytes, is eight times the 24,576 of our 1,024-entry hash map: four times the entries, and every value stored once per CPU. Theprintfmap is aperf_event_array, one slot per CPU, which bpftrace sets up forprintf()and other output even when the script never prints anything.
BCC: a compiler on every target
BCC came first. It is where most of today’s BPF tracing tools began, and Ubuntu packages its
collection of them as bpfcc-tools, with names like execsnoop-bpfcc and opensnoop-bpfcc. With
BCC the kernel half of the tool is C, held as a string in a Python program, and the BCC library
compiles it when the Python program runs:
#!/usr/bin/env python3
# execcount.py — the same counter with BCC; the C below is compiled when this runs
import signal
from bcc import BPF
prog = r"""
#include <linux/sched.h>
struct comm_key {
char comm[TASK_COMM_LEN];
};
BPF_HASH(counts, struct comm_key, u64, 1024);
TRACEPOINT_PROBE(syscalls, sys_enter_execve)
{
struct comm_key key = {};
bpf_get_current_comm(&key.comm, sizeof(key.comm));
counts.increment(key);
return 0;
}
"""
b = BPF(text=prog) # compile, load and attach, all in here
print("counting execve(), Ctrl-C to stop", flush=True)
signal.signal(signal.SIGINT, lambda sig, frame: None) # Ctrl-C ends pause()
signal.pause()
for k, v in b["counts"].items():
print("%-16s %d" % (k.comm.decode(), v.value))
The C in the string is not quite C. BCC rewrites it before compiling, and three of its macros do most of the work:
BPF_HASH(counts, struct comm_key, u64, 1024)declares the same hash map as Part 1’s.mapsstruct: 16-byte keys, 8-byte values, 1,024 entries.TRACEPOINT_PROBE(syscalls, sys_enter_execve)declares a function that BCC loads as a tracepoint program and attaches automatically, the moment theBPFobject is created.counts.increment(key)looks like a method call on a map, which C doesn’t have. BCC’s rewriter turns it into a lookup that inserts zero if the key is absent, followed by an atomic add. It is the same logic as Part 1’s C, without having to write it.
On the Python side, BPF(text=prog) compiles, loads and attaches in one call, and
b["counts"].items() walks the map. The signal.signal line deserves a word. Python normally
turns Ctrl-C into a KeyboardInterrupt exception, but only if SIGINT wasn’t being ignored when
Python started, and a shell starting a program in the background with & does ignore it. Setting
a handler explicitly makes Ctrl-C (and kill -INT) end the pause() either way.
Run on a fresh Ubuntu 22.04 with python3-bpfcc installed, it fails before it gets that far:
$ sudo python3 execcount.py
modprobe: FATAL: Module kheaders not found in directory /lib/modules/5.15.0-25-generic
chdir(/lib/modules/5.15.0-25-generic/build): No such file or directory
Unable to find kernel headers. Try rebuilding kernel with CONFIG_IKHEADERS=m (module) or installing the kernel development package for your running kernel version.
Traceback (most recent call last):
File "/tmp/gt/x/execcount.py", line 25, in <module>
b = BPF(text=prog) # compile, load and attach, all in here
File "/usr/lib/python3/dist-packages/bcc/__init__.py", line 364, in __init__
raise Exception("Failed to compile BPF module %s" % (src_file or "<text>"))
Exception: Failed to compile BPF module <text>
BCC compiles the program against the running kernel’s own headers, and it looks for them in two
places. The first is /lib/modules/$(uname -r)/build, which is where the linux-headers package
for the running kernel puts them. The second is the kernel itself: a kernel built with
CONFIG_IKHEADERS can carry its headers in a module called kheaders, as a compressed archive,
and BCC tries to load that module and unpack it. Ubuntu’s kernel is built that way, but the
module lives in linux-modules-extra, which a minimal install doesn’t have, hence the
modprobe error at the top. After apt install linux-headers-$(uname -r) it works:
$ sudo python3 execcount.py
In file included from <built-in>:2:
In file included from /virtual/include/bcc/bpf.h:12:
In file included from include/linux/types.h:6:
In file included from include/uapi/linux/types.h:14:
In file included from include/uapi/linux/posix_types.h:5:
In file included from include/linux/stddef.h:5:
In file included from include/uapi/linux/stddef.h:2:
In file included from include/linux/compiler_types.h:80:
include/linux/compiler-clang.h:41:9: warning: '__HAVE_BUILTIN_BSWAP32__' macro redefined [-Wmacro-redefined]
#define __HAVE_BUILTIN_BSWAP32__
^
<command line>:4:9: note: previous definition is here
#define __HAVE_BUILTIN_BSWAP32__ 1
^
[the same warning for __HAVE_BUILTIN_BSWAP64__ and __HAVE_BUILTIN_BSWAP16__ trimmed]
3 warnings generated.
counting execve(), Ctrl-C to stop
sh 13
The three warnings come from compiling the 5.15 kernel headers with BCC’s flags: BCC defines
__HAVE_BUILTIN_BSWAP16__ and its 32- and 64-bit siblings on its command line, and the kernel’s
compiler-clang.h defines them again. They are harmless, and they appear on every run.
What did that compile involve? Under strace the BCC library switches its working directory to
the headers and then opens them one by one by relative path:
chdir("/lib/modules/5.15.0-25-generic/build") = 0
[python and BCC start-up trimmed]
openat(AT_FDCWD, "././include/linux/kconfig.h", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "arch/x86/include/generated/autoconf.h", O_RDONLY|O_CLOEXEC) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "include/generated/autoconf.h", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "include/linux/types.h", O_RDONLY|O_CLOEXEC) = 3
openat(AT_FDCWD, "include/uapi/linux/types.h", O_RDONLY|O_CLOEXEC) = 3
[971 more successful opens of .h files, and 201 more that failed, trimmed]
That is the cost model of BCC in one line: every time the tool starts, on every machine it runs on, clang parses the kernel’s headers and LLVM compiles the program, from scratch. The result reached the kernel like this:
20: tracepoint name syscalls__sys_e tag a6898cb00e5eddce gpl
[loaded_at line trimmed]
xlated 280B jited 158B memlock 4096B map_ids 18
btf_id 40
18: hash name counts flags 0x0
key 16B value 8B max_entries 1024 memlock 24576B
btf_id 40
BCC sent 33 instructions where clang and libbpf sent 27, because its increment takes a slightly
longer path than the C we wrote by hand, and after the kernel’s rewriting 35 remain (280 bytes). The
program is named after the function BCC generated for TRACEPOINT_PROBE,
syscalls__sys_enter_execve, cut to 15 characters. And there is type information (btf_id),
because BCC uploads the BTF that clang produced for the program.
libbpf: compile once, ship the object
The third way is Part 1’s. The kernel half is unchanged:
// 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";
The user-space half changes in one way: instead of counting for a fixed number of seconds, it counts until Ctrl-C, like the other three versions, so that all four can be started and stopped the same way.
// execcount.c — load, attach, count until Ctrl-C, print the map
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "execcount.skel.h"
static volatile sig_atomic_t stop;
static void on_sigint(int sig) { stop = 1; }
int main(void)
{
struct execcount_bpf *skel;
char key[16], next[16], *prev = NULL;
__u64 count;
int fd;
signal(SIGINT, on_sigint);
skel = execcount_bpf__open_and_load();
if (!skel || execcount_bpf__attach(skel)) {
fprintf(stderr, "failed to load or attach\n");
return 1;
}
printf("counting execve(), Ctrl-C to stop\n");
fflush(stdout);
while (!stop)
pause();
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;
}
and it builds exactly as before:
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 difference from the other two is where this happens. Those four commands run on the
developer’s machine, which needs clang, libbpf’s headers and bpftool. What goes to the machine
that runs the tool is one file, execcount, 29,648 bytes, with the compiled BPF object inside it:
the skeleton embedded the object as a byte array. It needs two shared libraries that a minimal
system lacks, libbpf.so.0 and libelf.so.1, and nothing else:
$ ls -l execcount execpin | awk '{print $5, $9}'
29648 execcount
28224 execpin
$ ldd execcount | awk '{print $1}'
linux-vdso.so.1
libbpf.so.0
libc.so.6
libelf.so.1
libz.so.1
/lib64/ld-linux-x86-64.so.2
It counted the same thirteen calls:
counting execve(), Ctrl-C to stop
sh 13
Go: the same object, from cilium/ebpf
The fourth way keeps libbpf’s model but swaps the language of the loader. cilium/ebpf is a Go
library, maintained under the Cilium networking project’s GitHub organisation, that does what libbpf does
without any C: it parses the ELF object, creates the maps, fixes up the instructions and makes
the bpf() calls, all in Go. It has a companion tool, bpf2go, which plays the part of
bpftool gen skeleton: it runs clang on the C and generates Go code that embeds the object and
gives the maps and programs typed names.
The Go version lives in a directory called go next to the C files and reuses the very same
execcount.bpf.c from one level up:
// main.go — the same counter in Go, with cilium/ebpf
package main
import (
"bytes"
"fmt"
"log"
"os"
"os/signal"
"github.com/cilium/ebpf/link"
)
//go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc clang -cflags "-O2 -g -D__TARGET_ARCH_x86" execcount ../execcount.bpf.c
func main() {
stop := make(chan os.Signal, 1)
signal.Notify(stop, os.Interrupt)
var objs execcountObjects
if err := loadExeccountObjects(&objs, nil); err != nil {
log.Fatal(err)
}
defer objs.Close()
tp, err := link.Tracepoint("syscalls", "sys_enter_execve", objs.CountExecve, nil)
if err != nil {
log.Fatal(err)
}
defer tp.Close()
fmt.Println("counting execve(), Ctrl-C to stop")
<-stop
var key [16]byte
var count uint64
it := objs.Counts.Iterate()
for it.Next(&key, &count) {
fmt.Printf("%-16s %d\n", bytes.TrimRight(key[:], "\x00"), count)
}
}
The //go:generate line is the build step. bpf2go compiles ../execcount.bpf.c with clang and
writes execcount_bpfel.go, which declares execcountObjects with a field per program and map
(CountExecve, Counts) and the loadExeccountObjects function that loads them. By default it
compiles twice, for little-endian and big-endian BPF, and the Go build picks the right one for
the target. link.Tracepoint attaches the program and returns a link, and the map is walked with
an iterator, much as in C. With Ubuntu 22.04’s Go, which is 1.18, the build is:
cd go
go mod init execcount
go get github.com/cilium/ebpf@v0.9.0
go generate
go build -o execcount-go .
The result is a statically linked executable of 3,443,518 bytes. It needs nothing on the target at all, not even a C library:
$ ldd go/execcount-go
not a dynamic executable
and it counted the same thirteen:
counting execve(), Ctrl-C to stop
sh 13
Under strace, it makes its own feature probes, different from libbpf’s. It creates two small
array maps to test map features, loads two BTF fragments and two tiny programs, and tries a
BPF_LINK_CREATE on a bad descriptor, the same trick libbpf uses to find out whether the kernel
has perf links. Then it does the real work, which is libbpf’s call for call, except that it opens
the perf event already enabled, so it needs no ioctl to switch it on:
bpf(BPF_BTF_LOAD, {..., btf_size=934, ...}, 32) = 3
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, ...}, 32) = 4
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_TRACEPOINT, insn_cnt=27, license="GPL", ..., prog_name="count_execve", ...}, 32) = 5
perf_event_open({type=PERF_TYPE_TRACEPOINT, config=716, ...}, -1, 0, -1, PERF_FLAG_FD_CLOEXEC) = 3
bpf(BPF_LINK_CREATE, {link_create={prog_fd=5, target_fd=3, attach_type=BPF_PERF_EVENT, flags=0}}, 32) = 9
Under every loader, one system call
Strip away the compilers and the languages, and the four loaders did the same thing. Every one of
them made the same handful of calls to create the map, load the program and attach it, and every
one of them used the same system call for most of it: bpf(). Its first argument is a command,
and the second a union of structures, one per command. This is the whole of what the kernel
offers a loader, so it is worth seeing the commands this post’s tools used in one place:
bpf() command | what it does | used here by |
|---|---|---|
BPF_BTF_LOAD | upload type information; returns a descriptor | BCC, libbpf, Go |
BPF_MAP_CREATE | create a map; returns a descriptor | all four |
BPF_PROG_LOAD | verify, JIT and load a program; returns a descriptor | all four |
BPF_LINK_CREATE | attach a program to a hook, as a link (5.7; perf events 5.15) | libbpf, Go |
BPF_MAP_LOOKUP_ELEM, BPF_MAP_GET_NEXT_KEY | read a map from user space | all four |
BPF_OBJ_PIN, BPF_OBJ_GET | give an object a path in the BPF filesystem; open it again by path (4.4) | execpin, bpftool |
BPF_PROG_GET_FD_BY_ID, BPF_MAP_GET_FD_BY_ID | open an object by its ID (4.13) | bpftool |
BPF_OBJ_GET_INFO_BY_FD | ask about an object you have a descriptor for (4.13) | bpftool |
The attach step is the one place where the four split into two camps. bpftrace 0.14 and BCC
0.18 attach a tracepoint program the way it has been done since 4.7: open a perf event for the
tracepoint, then hand it the program with an ioctl. Here is BCC doing it:
perf_event_open({type=PERF_TYPE_TRACEPOINT, config=716, ...}, -1, 0, -1, PERF_FLAG_FD_CLOEXEC) = 6
ioctl(6, PERF_EVENT_IOC_SET_BPF, 5) = 0
ioctl(6, PERF_EVENT_IOC_ENABLE, 0) = 0
libbpf 0.5 and cilium/ebpf 0.9.0 do the first step the same way, then make a link instead of
the ioctl, after checking that the kernel supports it. Here is libbpf:
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, flags=0}}, 128) = 7
Both work, and for as long as the tool runs, nothing distinguishes them. The difference only shows when the tool stops, and to see it we need the object model the rest of this post is about.
File descriptors are the handles
Every one of those calls that creates something returns a file descriptor, and that is not a detail of the API. It is the design. A BPF program, a map, a piece of BTF, a link: each is a kernel object, and a process holds it the way it holds an open file, through an entry in its descriptor table. Here are the four tools’ tables, filtered to the kernel objects, while all four were running at once:
bpftrace (pid 650)
3 -> anon_inode:bpf-map
4 -> anon_inode:bpf-map
5 -> anon_inode:[eventpoll]
6 -> anon_inode:[perf_event]
7 -> anon_inode:[perf_event]
8 -> anon_inode:[perf_event]
9 -> anon_inode:[perf_event]
10 -> anon_inode:[perf_event]
11 -> anon_inode:bpf-prog
python3 (pid 651)
3 -> anon_inode:btf
4 -> anon_inode:bpf-map
5 -> anon_inode:bpf-prog
6 -> anon_inode:[perf_event]
execcount (pid 652)
3 -> anon_inode:btf
4 -> anon_inode:bpf-map
5 -> anon_inode:bpf-prog
6 -> anon_inode:[perf_event]
7 -> anon_inode:bpf_link
execcount-go (pid 653)
3 -> anon_inode:[perf_event]
4 -> anon_inode:bpf-map
5 -> anon_inode:bpf-prog
6 -> anon_inode:[eventpoll]
9 -> anon_inode:bpf_link
Read it as an inventory. Each process holds one program (bpf-prog) and one or more maps. The
tools that uploaded BTF hold it, except Go, which closed its BTF descriptor once the map and
program were loaded; the type information lives on because the map and the program still refer to
it. bpftrace holds five perf events: one for the tracepoint, and four for its printf channel,
one per CPU. The two tools that made links hold one each (bpf_link). The eventpoll
descriptors are each runtime’s own machinery for waiting on events, not BPF objects.
Because these are file descriptors, everything that applies to file descriptors applies to them.
close() releases one. fork() copies them into the child, and the program is then held by both
processes. They can be passed to another process over a Unix socket. And /proc can describe
them: fdinfo for the libbpf tool’s program and link reads
$ cat /proc/652/fdinfo/5
prog_type: 5
prog_jited: 1
prog_tag: 2ef1c7a420d19e5e
memlock: 4096
prog_id: 17
run_time_ns: 0
run_cnt: 0
$ cat /proc/652/fdinfo/7
link_type: perf
link_id: 4
prog_tag: 2ef1c7a420d19e5e
prog_id: 17
prog_type 5 is BPF_PROG_TYPE_TRACEPOINT in the kernel’s enum, and the two run counters are zero
because the kernel’s run-time statistics are off, as they are by default; Part 1 switched them on
to time the program. The link’s link_type is
perf, the kind of link 5.15 introduced for perf events, and it names the program it holds by ID.
IDs are not handles
Each object also has a system-wide ID: 17 for that program, 4 for that link. IDs are what
bpftool lists, and they look like handles, but they hold nothing. An ID is a name the kernel
gives an object so that other processes can find it. To do anything with an object, a process
needs a descriptor, and bpftool gets one by asking for it. Here is bpftool prog show id 12, the
Go tool’s program, under strace:
$ sudo strace -e trace=bpf bpftool prog show id 12
bpf(BPF_PROG_GET_FD_BY_ID, {prog_id=12, next_id=0, open_flags=0}, 128) = 3
bpf(BPF_OBJ_GET_INFO_BY_FD, {info={bpf_fd=3, info_len=216, info=0x7ffe33503450}}, 128) = 0
12: tracepoint name count_execve tag 2ef1c7a420d19e5e gpl
[loaded_at line trimmed]
bpf(BPF_OBJ_GET_INFO_BY_FD, {info={bpf_fd=3, info_len=216, info=0x7ffe33503320}}, 128) = 0
xlated 232B jited 141B memlock 4096B map_ids 13
btf_id 33
bpf(BPF_OBJ_GET_INFO_BY_FD, {info={bpf_fd=3, info_len=216, info=0x7ffe33503320}}, 128) = 0
bpf(BPF_OBJ_GET_INFO_BY_FD, {info={bpf_fd=3, info_len=216, info=0x7ffe33503320}}, 128) = 0
bpf(BPF_MAP_GET_FD_BY_ID, {map_id=13, next_id=0, open_flags=0}, 128) = 4
bpf(BPF_OBJ_GET_INFO_BY_FD, {info={bpf_fd=4, info_len=80, info=0x7ffe335032d0}}, 128) = 0
+++ exited with 0 +++
BPF_PROG_GET_FD_BY_ID turns the ID into a descriptor of bpftool’s own, 3, which now holds the
program as firmly as the loader’s descriptor does. bpftool asks about it with
BPF_OBJ_GET_INFO_BY_FD, does the same for the map it uses, prints, and exits, and exiting
closes the descriptors. Opening an object by ID needs CAP_SYS_ADMIN, so this is an
administrator’s view, not a way for one tool to reach into another’s maps.
Reference counts: what keeps a program alive
Here is the rule underneath everything in Part 1’s teardown: every BPF object has a reference count, and the kernel frees the object when the count reaches zero. There is no “unload” command. A program goes away when the last thing referring to it lets go.
Several kinds of things hold references:
- A file descriptor holds one reference to its object, in whichever process has it.
- A program holds its maps, every map its instructions refer to, from the moment it is loaded. A map can’t disappear from under a program that uses it.
- Programs and maps hold their BTF.
- An attachment holds its program. For the
ioctlstyle, the perf event holds it; for a link, the link holds both the program and, for a perf link, the perf event. - A pin in the BPF filesystem holds one reference. That’s the next section.
Run that against Part 1’s teardown and it explains everything. When the loader exits, its
descriptors close. If those were the only references, the counts fall to zero in a cascade:
closing the link releases the perf event and the program, releasing the program releases the map
and the BTF, and everything is gone. Nothing was unloaded; everything was let go. The same holds
for bpftrace’s and BCC’s ioctl attachments: the perf event descriptor holds the program, the
process exiting closes it, and the program dies with it.
So to keep a program running after its loader has gone, something other than the loader has to hold a reference to the right object. The figure steps through the two ways the rest of this post tries, and shows which object holds which after each step.
What holds a reference, step by step
A kernel object lives while anything holds a reference to it. Step through two ways of ending the loader's process.
Pin the link · 1
open_and_load(): three objects, three descriptors
bpf(BPF_BTF_LOAD, ...) = 3
bpf(BPF_MAP_CREATE, {map_name="counts", btf_fd=3, ...}) = 4
bpf(BPF_PROG_LOAD, {prog_name="count_execve", prog_btf_fd=3, ...}) = 5Each object is held by the descriptor that created it. The program also holds the map it uses and its type information, and the map holds its type information too. Nothing is attached, so nothing runs.
Pin the link · 2
attach(): a perf event and a link
perf_event_open({type=PERF_TYPE_TRACEPOINT, config=716, ...}) = 6
bpf(BPF_LINK_CREATE, {prog_fd=5, target_fd=6, attach_type=BPF_PERF_EVENT}) = 7The link holds the program and the perf event. Every execve() now runs the program.
Pin the link · 3
Pin the link and the map
bpf(BPF_OBJ_PIN, {pathname="/sys/fs/bpf/execcount_link", bpf_fd=7}) = 0
bpf(BPF_OBJ_PIN, {pathname="/sys/fs/bpf/execcount_counts", bpf_fd=4}) = 0A pin is a file in the BPF filesystem that holds one more reference. Nothing else changes.
Pin the link · 4
The loader exits
+++ exited with 0 +++
All five descriptors close, and five references go. Every object still has another holder: the pin holds the link, the link holds the program and the event, the program holds the map. The counter keeps counting with no process behind it.
Pin the link · 5
Unpin the link
rm /sys/fs/bpf/execcount_link
The link's last reference goes, so the link is freed. Freeing it detaches the program and drops its references to the program and the event. Those were their last references too, so both are freed, and the program's reference to the map goes with it. The map survives, held by its own pin, with the counts frozen.
Pin the link · 6
Unpin the map
rm /sys/fs/bpf/execcount_counts
The last reference to the map, and through it to the type information. Nothing is left. There was never an "unload" call: removing a file was enough.
Pin only the program · 1
The tool loads and attaches, as before
./execcount & fds 3 BTF, 4 map, 5 prog, 6 perf event, 7 link
The same five objects, held the same way. The program runs on every execve().
Pin only the program · 2
bpftool pins the program by its ID
bpftool prog pin id 51 /sys/fs/bpf/execcount_prog
bpftool, a different process, asks for a descriptor by ID, pins it and exits. The pin is now a holder of the program.
Pin only the program · 3
Ctrl-C: the tool exits
kill -INT %1
The link had one holder, descriptor 7, so it is freed, and freeing it detaches the program. The program itself survives, held by the pin, along with the map it holds. It is loaded, and it runs on nothing: the counts stop moving.
Pin only the program · 4
Unpin the program
rm /sys/fs/bpf/execcount_prog
The program's last reference goes, and with it the program's references to the map and the type information. Everything is freed.
Process descriptors
Kernel objects · held by
/sys/fs/bpf
The descriptor numbers are from the post's run. The holders are not measured, because the kernel does not show its reference counts; they are read from the 5.15 sources. Green is a holder added at this step, copper a pin.
Pinning: giving an object a name
The obvious way to hold a reference without a process is to put it in a file. That is what the
BPF filesystem is for. It is a special filesystem, conventionally mounted at /sys/fs/bpf
(systemd mounts it at boot on Ubuntu; in my minimal VM I mounted it myself with
mount -t bpf bpf /sys/fs/bpf), and any BPF object can be pinned in it: given a path, with
BPF_OBJ_PIN. The pinned file holds one reference to the object for as long as the file exists.
Any process with permission can later open it again by path with BPF_OBJ_GET and get a fresh
descriptor. Removing the file with plain rm drops the reference. Pinning arrived in 4.4, the
same release that first let unprivileged users load socket filters.
bpftool can pin any program by ID, so I tried the obvious thing first: start the C tool, pin its program, and stop the tool.
$ sudo ./execcount > /dev/null &
$ sudo bpftool prog pin id 51 /sys/fs/bpf/execcount_prog
$ # (ten /bin/true and three ls)
$ sudo bpftool map dump id 40
[{
"key": {
"comm": "sh"
},
"value": 19
},{
"key": {
"comm": "bpftool"
},
"value": 12
}
]
$ sudo kill -INT %1
$ sudo bpftool prog show
51: tracepoint name count_execve tag 2ef1c7a420d19e5e gpl
[loaded_at line trimmed]
xlated 232B jited 141B memlock 4096B map_ids 40
btf_id 73
$ sudo bpftool link show
$ # (ten /bin/true and three ls again)
$ sudo bpftool map dump id 40
[{
"key": {
"comm": "sh"
},
"value": 19
},{
"key": {
"comm": "bpftool"
},
"value": 12
}
]
$ sudo rm /sys/fs/bpf/execcount_prog
$ sudo bpftool prog show
$ sudo bpftool map show
$
The program survived. bpftool prog show still lists it after the tool has exited, held by the
pin. But the counts in its map stopped moving: thirteen more execve() calls after the tool
exited, and the map still says what it said before. The program is loaded and attached to
nothing.
That’s what the reference counting predicts. The pin held the program. The attachment was the link, and the link’s only reference was the tool’s descriptor 7. When the tool exited, the link was freed, and freeing a link detaches its program. A pinned program is a loaded program, ready to be attached again, but not a running one. To keep the tool counting, the thing to pin is the attachment.
bpf_link: an attachment you can hold
For most of BPF’s history, an attachment wasn’t an object at all. It was a state of some other
kernel object: a perf event with a program set on it by ioctl, a network interface with an XDP
program installed, a cgroup with a program in its list. You couldn’t hold a reference to that state,
and the rules for who could remove it varied by hook. For XDP and cgroups, an attachment made by
one process outlived it and could be silently replaced by another.
Linux 5.7 (May 2020) added bpf_link, an object that is an attachment: one program, one
hook, with its own descriptor, its own ID and its own reference count. Close the last reference
and the program is detached; hold one, and it stays attached. Cgroups got links first, in 5.7
along with the command BPF_LINK_CREATE itself. Raw tracepoints and tracing programs got them in
the same release, XDP in 5.9, and perf events, the kind of attachment a tracepoint program
uses, in 5.15. So on Ubuntu 22.04’s kernel, our counter’s attachment can be a link, and libbpf
and cilium/ebpf make it one.
Because a link is an object, it can be pinned, and a pinned link keeps the program attached with no process at all. Here is a loader that does exactly that, using the skeleton from before:
// execpin.c — load and attach the counter, pin it, and exit
#include <stdio.h>
#include <bpf/libbpf.h>
#include "execcount.skel.h"
int main(void)
{
struct execcount_bpf *skel = execcount_bpf__open_and_load();
if (!skel || execcount_bpf__attach(skel)) {
fprintf(stderr, "failed to load or attach\n");
return 1;
}
if (bpf_link__pin(skel->links.count_execve, "/sys/fs/bpf/execcount_link") ||
bpf_map__pin(skel->maps.counts, "/sys/fs/bpf/execcount_counts")) {
fprintf(stderr, "failed to pin\n");
return 1;
}
printf("pinned; exiting\n");
return 0; /* no __destroy(): exit closes every descriptor anyway */
}
skel->links.count_execve is the link the skeleton’s attach made for the program of that name.
bpf_link__pin and bpf_map__pin are libbpf’s wrappers around BPF_OBJ_PIN. Pinning the map
isn’t needed to keep the program running, since the program holds its map, but without a pin
there would be no easy way for anything else to find the counts. Under strace the end of its
life looks like this:
$ sudo strace -e trace=bpf ./execpin
[feature probes, BTF, map and program loads trimmed]
bpf(BPF_LINK_CREATE, {link_create={prog_fd=7, target_fd=-1, attach_type=BPF_PERF_EVENT, flags=0}}, 128) = -1 EBADF (Bad file descriptor)
bpf(BPF_LINK_CREATE, {link_create={prog_fd=5, target_fd=6, attach_type=BPF_PERF_EVENT, flags=0}}, 128) = 7
bpf(BPF_OBJ_PIN, {pathname="/sys/fs/bpf/execcount_link", bpf_fd=7, file_flags=0}, 128) = 0
bpf(BPF_OBJ_PIN, {pathname="/sys/fs/bpf/execcount_counts", bpf_fd=4, file_flags=0}, 128) = 0
pinned; exiting
+++ exited with 0 +++
The process has exited. Here is what the kernel is still holding, and the counter at work with nobody running it:
$ sudo bpftool link show
9: type 7 prog 46
$ sudo bpftool prog show
46: tracepoint name count_execve tag 2ef1c7a420d19e5e gpl
[loaded_at line trimmed]
xlated 232B jited 141B memlock 4096B map_ids 39
btf_id 67
$ ls /sys/fs/bpf
execcount_counts
execcount_link
$ # (the shell runs /bin/true ten times and ls three times)
$ sudo bpftool map dump pinned /sys/fs/bpf/execcount_counts
[{
"key": {
"comm": "sh"
},
"value": 18
},{
"key": {
"comm": "bpftool"
},
"value": 9
}
]
Two more things in that output. The map counts bpftool as well as sh. On Ubuntu, bpftool
is a shell script that finds the binary matching the running kernel, and it makes three execve()
calls of its own each time (uname, basename, then the real bpftool), all under the name
bpftool. Three invocations so far, nine calls: the counter can’t tell instrumentation from work.
The other is that bpftool link show prints type 7 rather than a name. The kernel’s own fdinfo
called it perf earlier: 7 is BPF_LINK_TYPE_PERF_EVENT, new in 5.15, and the bpftool built from
the 5.15 tree has no name for it in its table, which stops at netns, so XDP links get a number
too.
Removing it is removing files:
$ sudo rm /sys/fs/bpf/execcount_link
$ sudo bpftool prog show | grep -v loaded_at
$ sudo bpftool link show
$ # (ten /bin/true and three ls again)
$ sudo bpftool map dump pinned /sys/fs/bpf/execcount_counts
[{
"key": {
"comm": "sh"
},
"value": 21
},{
"key": {
"comm": "bpftool"
},
"value": 10
}
]
$ sudo rm /sys/fs/bpf/execcount_counts
$ sudo bpftool map show
$
rm /sys/fs/bpf/execcount_link dropped the link’s last reference. The link was freed, which
detached the program and released it, and since the link had been the program’s only holder, the
program was freed too: bpftool prog show prints nothing. The map outlived it, held by its own
pin. Removing that pin freed the map. At no point was there an “unload” call; there isn’t one.
Look closely at the second dump, though. Between the two dumps the shell ran thirteen more
programs, and none of them was counted, but sh went from 18 to 21 and bpftool from 9 to 10.
Those are rm itself, then the bpftool and grep of the next command line, and the first
thing Ubuntu’s bpftool wrapper runs, uname. The program was still attached for a few
milliseconds after rm had returned. That is the 5.15 code doing what it says: the BPF
filesystem drops its reference when the inode is freed, and inodes are freed from an RCU
callback, after a grace period, not during the unlink() call. The link’s release is then pushed
to a work queue. Removing a pin detaches the program soon after, not at once.
This is how BPF programs run as part of a system rather than as a tool. A loader runs at boot, loads and attaches, pins the links and maps it wants to keep, and exits, and an agent can be restarted or upgraded without the programs it manages ever being detached. The pins are the state, and they live in a filesystem whose contents disappear at reboot, which is the right lifetime for something attached to a running kernel.
Measured side by side
Four loaders, one program, the same thirteen counts. What did each cost? I measured three things.
Time until it is counting. Not until it prints a banner, because bpftrace prints Attaching 1 probe... before it has attached anything, but until the kernel is actually running the program
on every execve(). The harness below measures that from outside. It starts the tool, then calls
execve() itself over and over, sleeping half a millisecond between calls, on a path that doesn’t
exist. Each call fails at
once with ENOENT, but the tracepoint fires on entry, before the kernel has even looked at the
path, so the tool counts it, under the harness’s own name, startlat. After a few seconds the
harness stops the tool with SIGINT and reads how many calls it counted. If it made 9,000 calls
and the tool counted 3,000, the first one counted was the 6,001st, and the harness knows when it
made that one. The resolution is the gap between two calls, which averaged 0.64 ms.
Peak memory: the tool’s VmHWM, the high-water mark of its resident set, read from
/proc/<pid>/status while it was counting, in a separate boot, three rounds per tool. The harness
also gets a peak from wait4(), with the CPU time the tool used, but for a forked child that peak
includes the child’s peak before it called execve(), when it was still a copy of the harness:
exec_mmap() in fs/exec.c carries it over. That added about a megabyte to the two small tools, so for memory I use
VmHWM, and wait4() only for CPU time.
What has to be installed on the target: the growth, measured with du, of a minimal Ubuntu
22.04 system (debootstrap --variant=minbase, release pocket only) after apt-get install --no-install-recommends of what each tool needs at run time, plus the tool’s own file.
I ran it in rounds, each round running every tool once, with the starting tool rotated so no tool always ran first, for 10 rounds, with no other virtual machine running on the host. The bpftrace one-liner ran twice per round: once as installed, and once with the kernel headers hidden, to see whether their presence changes its start-up.
There is a catch with the virtual machine, and it is big enough to change the answer. Its root filesystem is the host’s directory, shared over 9p, a network-style protocol in which every file lookup is a round trip to the host. bpftrace and BCC look up thousands of files at start-up and map more than a hundred megabytes of LLVM, and 9p makes all of that slow in a way a local disk wouldn’t. So after three rounds on the 9p root, I copied the root filesystem into memory (a tmpfs inside the guest) and ran 10 rounds there, which is closer to a real machine with a warm page cache. The figure and the table use the tmpfs numbers; the 9p numbers are below them.
One program, four loaders: what it costs to start
The same 27-instruction execve() counter, loaded by each tool on Ubuntu 22.04. Start-up bars are medians of 10 interleaved rounds, with whiskers from the fastest to the slowest; memory bars are medians of three.
Time until counting
Peak memory (VmHWM)
MBInstalled on the target
MBStart-up: medians of 10 interleaved rounds from a tmpfs copy of the root in a KVM guest (4 vCPU) on Ubuntu 22.04’s 5.15.0-25 kernel; whiskers span all 10. Memory: VmHWM, median of 3 rounds. “Installed” is the growth of a minimal Ubuntu 22.04 after installing what the tool needs at run time, plus the tool itself: for BCC that includes the kernel headers.
| bpftrace 0.14 | BCC 0.18 | C, libbpf 0.5 | Go, cilium/ebpf 0.9.0 | |
|---|---|---|---|---|
| time until counting, median | 97 ms | 282 ms | 1.8 ms | 1.9 ms |
| fastest–slowest of 10 | 92–108 | 266–307 | 1.2–1.9 | 1.7–6.2 |
| CPU time, median | 106 ms | 289 ms | 2.0 ms | 6.0 ms |
| peak RSS (VmHWM), median of 3 | 101.0 MB | 128.6 MB | 1.27 MB | 2.05 MB |
| installed on a minimal 22.04 | 199.3 MB, 12 packages | 355.4 MB, 26 packages | 0.49 MB, 2 packages | 3.44 MB, none |
| time until counting on the 9p root, median of 3 | 2,223 ms | 3,142 ms | 14 ms | 27 ms |
bpf() calls / all system calls, under strace | 12 / 8,425 | 6 / 16,787 | 17 / 111 | 14 / 402 |
The compilers dominate start-up, and it is CPU time. On the tmpfs root, each of the two compiling loaders used about as much CPU as it took to start: bpftrace 106 ms of CPU for 97 ms to counting, BCC 289 ms for 282 ms. That is time spent compiling, on one core, before the program can be loaded: repeated clang runs and a code generator for bpftrace; for BCC, clang reading 325 distinct kernel headers (2.2 MB of them, three passes) and LLVM compiling the result. Hiding the kernel headers from bpftrace took its median from 97 to 75 ms and its peak memory, by wait4()’s measure, from 101.3 to 91.1 MB, so a bpftrace that finds headers uses them whether the script needs them or not.
The compiled loaders are at the limit of the harness. The C and Go versions were counting by the second or third marker call, at 1.8 and 1.9 ms, and with a marker every 0.64 ms or so all I can say is that both start in under 2 ms and that this harness can’t tell them apart. What they do in that time is the twenty-odd system calls traced above. Go’s runtime shows in the CPU time, 6.0 ms against 2.0, and in a larger peak, 2.05 MB against 1.27.
Memory is mostly compiler. bpftrace peaked at 101.0 MB and BCC at 128.6 MB. Most of it is not the tools’ own data. The same /proc/<pid>/status that gives the peak splits the resident set into anonymous memory, which the process allocated itself, and pages of files mapped into it. bpftrace’s anonymous memory was 35.3 MB and BCC’s 52.9 MB; the rest, 66 and 69 MB, was pages of the libraries mapped into them, of which LLVM’s are by far the largest. The libbpf tool had 0.12 MB of anonymous memory and the Go tool 0.5 MB. How many library pages count as resident depends on the filesystem underneath: on the 9p root the same tools had the same anonymous memory to within a fraction of a percent but only 37 and 42 MB of mapped files, which is why their peaks there were lower. Mapped library pages are shared with any other process using the same libraries, so the anonymous figure is closer to what each extra running copy of a tool costs.
On the target, the compiler is the cost. bpftrace brought 12 packages and 199 MB: LLVM 11 and clang 11 as libraries, BCC’s library, and ICU and libxml2 for LLVM. BCC brought all of that except clang’s C API, plus Python, which a minimal system lacks but any ordinary Ubuntu install already has (32.8 MB of the total), plus the kernel headers, 151 MB of them on disk, which must match the running kernel exactly and so must be reinstalled with every kernel update. The C tool needed libbpf0 and libelf1, 0.49 MB with the binary. Go needed nothing but its own 3.44 MB binary, which makes it the second smallest rather than the smallest: a statically linked Go program carries its runtime and every library it uses, where the C tool borrows libc, libelf and libbpf from the system.
Slow storage makes the compiling loaders much slower. On the VM’s 9p root, where every file lookup is a round trip to the host, bpftrace took 2,223 ms to start and BCC 3,142 ms, more than ten times their tmpfs times, while using only 567 and 1,002 ms of CPU. The difference is waiting: for thousands of lookups (most of bpftrace’s 2,608 failed openat() calls were clang searching for a GCC installation it doesn’t need) and for over a hundred megabytes of LLVM to be paged in. The C and Go tools went from under 2 ms to 14 and 27 ms. Neither filesystem is a real disk: a first run after boot would add however long that disk takes to deliver the same files, and I didn’t measure one.
Which one, in June 2022
None of the four is wrong. They answer different questions, and the measurements say which.
bpftrace is for questions you ask once, at a terminal, on a machine you are allowed to install things on. Its start-up, a tenth of a second here and two seconds from slow storage, and its LLVM are the price of not writing a loader at all, and for a one-liner that price is nothing. It is a poor fit for something that runs on every machine in a fleet, all the time, because every one of those machines then carries a compiler.
BCC pays bpftrace’s price and more: a compiler, a Python runtime and the kernel’s headers on
every machine, and a fresh compile of the program, against that machine’s headers, every time a
tool starts. Compiling on the target did solve a real problem when BCC was designed, because a
program compiled against one kernel’s structure layouts could break on another, and compiling on
the target always gets the layouts right. Its value today is its collection of ready-made tools.
For new work, the BCC project itself is rewriting those tools on libbpf, in its libbpf-tools
directory.
libbpf moves the compiler to the developer’s machine and leaves a small binary and half a megabyte
of libraries on the target. It starts in about the time it takes to make its twenty-odd system calls.
The cost moves to the build: clang, bpftool, a vmlinux.h. Our program reads nothing from kernel
structures, only a helper’s result, so its compiled object runs on any kernel with this
tracepoint. A program that reads fields of kernel structures needs more than that to stay
portable between kernel versions, and a later part covers how libbpf does it without a compiler
on the target.
cilium/ebpf gives the same model to Go, and the binary carries everything, so there is nothing to install at all, at the cost of a few megabytes and a Go runtime’s appetite for memory. The library grew out of the Cilium project, and Tetragon, the security observability agent that Isovalent open-sourced in May, is built on it.
The tools themselves are moving quickly. libbpf 0.8, released on 16 May, added USDT probes,
attaching uprobes by function name, and support for the kprobe_multi link that Linux 5.18 (22
May) added, which attaches one program to many kernel functions at once. bpftrace 0.15, on 24 May,
gained support for LLVM 14, which should let distributions build it against their current LLVM
rather than an older copy. cilium/ebpf 0.9.0 followed on 25 May. None of those is in Ubuntu 22.04,
and everything in this post is what the release ships.
What we covered
- A BPF tool is a kernel program plus a loader. The kernel program is small and nearly the same whichever tool you use: 27 instructions from bpftrace, 27 from clang via libbpf or Go, 33 from BCC. The loaders are what differ.
- bpftrace and BCC compile on the machine they run on, with an LLVM they carry (LLVM 11 on Ubuntu 22.04). BCC also needs the running kernel’s headers: it opened 325 header files, 2.2 MB of them, three times each, on every start.
- libbpf and cilium/ebpf compile once and ship the object inside the executable.
- Measured on Ubuntu 22.04 in a VM, median time until counting: BCC 282 ms, bpftrace 97 ms, C and Go under 2 ms. Peak memory 129, 101, 1.27 and 2.05 MB. Installed on a minimal system: 355 MB for BCC, 199 MB for bpftrace, 0.49 MB for C and 3.44 MB for Go.
- Under all four is one system call,
bpf(), and its results are file descriptors. Objects also have IDs, which name them but don’t hold them. - Every BPF object is reference-counted. Descriptors, programs (holding their maps), links, perf events and pins all hold references, and an object is freed when the last goes. There is no unload.
- Pinning in
/sys/fs/bpf(4.4) holds a reference in a file. Pinning a program keeps it loaded but not attached. - A
bpf_link(5.7; perf events since 5.15) is an attachment as an object. Pinning the link kept the counter counting after its loader exited, and removing the pin detached it, a few milliseconds later.
A note on the evidence
What I ran, and where. Every listing in this post is pasted from a real run. The machine was
a KVM virtual machine started with virtme-ng, 4 virtual CPUs, booting Ubuntu 22.04’s release
kernel, 5.15.0-25-generic #25-Ubuntu SMP Wed Mar 30 15:54:22 UTC 2022, on a minimal 22.04
userland built from the release archive only, so every package is at its release-day version:
bpftrace 0.14.0-1, bpfcc-tools and python3-bpfcc 0.18.0+ds-2, libbpf-dev 0.5.0-1, clang
14.0.0-1ubuntu1, linux-headers-5.15.0-25-generic, golang-go 2:1.18~0ubuntu2 (Go 1.18.1) and
bpftool v5.15.30 from linux-tools-5.15.0-25-generic. The C, Python and Go in this post were
extracted from the page, built and run as shown. The Go modules (cilium/ebpf v0.9.0 and the
golang.org/x/sys version it requires) were fetched by the post’s go mod init and go get lines
run in the same userland on the host, which has a network; go generate and go build then ran
inside the virtual machine with the module proxy switched off. Go’s linker can’t map its output
file on the VM’s 9p root, so the builds and the listings ran in a tmpfs copy of the working
directory. Everything ran as root; the sudo in the listings is how you’d type it on a real
machine.
What I trimmed. strace lines are cut to their meaningful arguments, marked ..., and runs of
lines are cut where marked. The loaded_at lines of bpftool prog show are cut, as marked,
because they carry the date of the run. The descriptor listings are readlink of each entry in
/proc/<pid>/fd, filtered to the anonymous inodes and sorted by number; the fdinfo listings
keep the BPF lines and drop the generic ones (pos, flags, mnt_id, ino). BCC’s three
compiler warnings are identical but for the macro name, so two are cut. The commands around the
pinning demonstrations ran from a script; the listings show them as you would type them, and
“ten /bin/true and three ls” marks where the script ran those. The failing BCC run was made by
renaming the /lib/modules/5.15.0-25-generic/build link for one run; an earlier run, before
linux-headers had been installed at all, failed with the same message.
The measurements. Start-up and CPU time are from the startlat harness above, run
under an exclusive lock so that no other virtual machine ran on the host at the time, in one boot
of the VM given 6 GB for the tmpfs copy. Each round ran all five configurations (four tools, plus
bpftrace with the kernel headers hidden) with a rotating start, three rounds on the 9p root and
then 10 from the tmpfs copy, made with tar from the same root minus the Go toolchain,
/usr/share, clang 14’s private directory and the package cache, none of which any of the four
tools reads at run time. Medians and full ranges are given; every round’s raw line is in
data/ebpf_part03.json. The marker calls came every 0.64 ms on average, which bounds the
resolution. Peak memory is VmHWM (and the split into RssAnon, RssFile and RssShmem) from
/proc/<pid>/status, read two seconds after each tool started on the tmpfs copy and six seconds
after on the 9p root, when all four were counting, three rounds per tool per filesystem, in a second
boot of the same VM; memory doesn’t depend on what else the host is doing, so that boot didn’t take
the exclusive lock. The disk figures are du -sx --block-size=1
of a fresh debootstrap --variant=minbase jammy root before and after apt-get install -y --no-install-recommends of the packages named, with apt-get clean both times, plus the size of
each tool’s own file.
What I cited rather than ran. The kernel versions in which pinning, the ID commands,
bpf_link, and perf-event and XDP links arrived come from the commits that introduced them and
from checking which release tag of Linus Torvalds’s tree first contains each command in
include/uapi/linux/bpf.h. The explanation of the delayed detach is from reading the 5.15
sources (kernel/bpf/inode.c, fs/inode.c, bpf_link_put in kernel/bpf/syscall.c), not from
tracing it. The “held by” lists in the lifetime figure are read from the same sources, because
the kernel doesn’t expose reference counts. Release dates of libbpf 0.8, bpftrace 0.15,
cilium/ebpf 0.9.0 and Tetragon are from the projects’ release pages, and Tetragon’s use of
cilium/ebpf from its go.mod at the first open-source release. That systemd mounts the BPF
filesystem at boot I know but didn’t see here: the VM has no systemd.
What I’d still change. One virtual machine with 4 virtual CPUs, and a filesystem that I had to work around. The tmpfs numbers stand in for a real machine with a warm page cache. A cold start from a real disk, the first run after boot, would be slower for bpftrace and BCC by however long the disk takes to deliver the parts of their libraries and headers they touch, and I didn’t measure that on real hardware. The memory figures are peaks, taken while each tool was counting; a tool that runs for days may settle lower once start-up is over, and I didn’t measure the steady state.
Three Ways to Load a Program