← Writing

Compile Once, Run on Every Kernel

55 min readSystemsEbpfLinuxKernelCBtfLibbpf
Contents

On Linux 5.13 the process ID in the kernel’s struct task_struct sits 2,336 bytes from the start of the structure. On Ubuntu 22.04’s 5.15 kernel it is at byte 2,384, and on 5.19 at byte 2,496. I compiled one small BPF program on Ubuntu 22.04 that reads the field two ways, and loaded the same object file on all three kernels. Read at the offset the compiler had chosen, the process ID came back right on 5.15, as 0 on 5.19, and as -2,136,733,376 on 5.13. Read the other way, it was right on all three, because a moment before the program was loaded, libbpf had rewritten that one instruction for the kernel in front of it.

That rewrite is called a CO-RE relocation, and it is the reason a modern BPF tool can ship as one binary instead of a compiler. This post builds it up from the bottom: why struct layouts move, how BCC dodged the problem by compiling on every machine, how the kernel came to describe its own types, and what exactly clang writes down and libbpf patches. libbpf 1.0 came out last month, so the post also covers what that release took away.

This is Part 6 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 built on Ubuntu 22.04 as it shipped (clang 14), with libbpf 1.0.0 and bpftool 7.0.0 built from their release tags, and run on three kernels: Ubuntu’s own 5.15.0-25, and Ubuntu’s mainline builds of 5.13 and 5.19. The output is pasted from those runs. The note at the end says exactly where and how.

A struct is a list of offsets

Part 1 counted execve() calls with a tracepoint, and the program never looked inside a kernel data structure. Most tracing tools do. A tool that asks “which tasks keep losing the CPU, and why?” has to read the task that just stopped running: its process ID, its name, and the state it was in when it stopped. All three live in struct task_struct, the kernel’s record of a thread.

In C you write prev->pid. The compiler turns that into a load from an address: the pointer plus the offset of pid inside the structure, which it works out from the structure’s definition in the headers. Once compiled, the name is gone. What is left is an instruction like this one, from the program later in this post:

r1 = *(u32 *)(r6 + 2384)

“Load 4 bytes from 2,384 bytes past the pointer in r6.” That is correct for exactly the kernels on which pid is at byte 2,384. Kernel structures are not a stable interface. Fields are added, removed, reordered and renamed from one release to the next, and the same release builds differently depending on its configuration: switch on a feature and its fields appear in the middle of task_struct, pushing everything after them along. I asked each of the three kernels in this post for its own layout of task_struct:

task_struct5.135.15.0-255.19
size, bytes9,4729,5369,792
members231240253
state fieldstate__state__state
its typelongu32u32
its offset242424
pid offset2,3362,3842,496
comm offset2,8082,8562,968

(5.15.0-25 is Ubuntu 22.04’s kernel. The old field was a volatile long, 8 bytes; the new one is an unsigned int, 4.)

Three kernels released within thirteen months of each other, and no two agree on where the process ID is. The state field is worse: it is at the same offset in all three, but between 5.13 and 5.15 it changed its name and its size. That was deliberate. In June 2021 Peter Zijlstra renamed it from state to __state and shrank it from a volatile long to an unsigned int (commit 2f064a59a11f, merged for 5.14). His commit message gives the reason: rename it “in order to find all uses such that we can use READ_ONCE/WRITE_ONCE as appropriate”. A renamed field makes every direct use fail to compile, so none can be missed. Code outside the kernel tree that reads the field, such as a BPF program, breaks the same way, as a side effect.

A kernel module has the same problem, and solves it by being compiled against the exact kernel it will be loaded into. A BPF program could do the same. That is what BCC does.

How BCC handles it: compile on the target

BCC, the BPF Compiler Collection, is where most people met BPF tracing tools. A BCC tool is a Python script with the BPF program inside it as a string of C. When you run the tool, BCC compiles that string there and then, with a copy of clang and LLVM linked into BCC’s own library, against the kernel headers of the running kernel, found under /lib/modules/$(uname -r)/build. Whatever the layout of task_struct on this machine, the compiler sees it, because it is reading this machine’s headers. Here is the tool from this post written that way:

#!/usr/bin/python3
# taskstate_bcc.py — the same counter, BCC style: the C is compiled here, now
import sys, time
from bcc import BPF

prog = r"""
#include <linux/sched.h>

struct key_t { char comm[TASK_COMM_LEN]; };
struct val_t { u64 preempted, sleeping, blocked, other; };
BPF_HASH(counts, struct key_t, struct val_t, 10240);

RAW_TRACEPOINT_PROBE(sched_switch)
{
    struct task_struct *prev = (struct task_struct *)ctx->args[1];
    struct key_t key = {};
    struct val_t zero = {}, *v;
    unsigned int state = prev->__state;

    if (prev->pid == 0)
        return 0;
    bpf_probe_read_kernel_str(&key.comm, sizeof(key.comm), prev->comm);
    v = counts.lookup_or_try_init(&key, &zero);
    if (!v)
        return 0;
    if (state == TASK_RUNNING)
        __sync_fetch_and_add(&v->preempted, 1);
    else if (state & TASK_INTERRUPTIBLE)
        __sync_fetch_and_add(&v->sleeping, 1);
    else if (state & TASK_UNINTERRUPTIBLE)
        __sync_fetch_and_add(&v->blocked, 1);
    else
        __sync_fetch_and_add(&v->other, 1);
    return 0;
}
"""

t0 = time.monotonic()
b = BPF(text=prog)
print("compiled, loaded and attached in %.2f s" % (time.monotonic() - t0), flush=True)
time.sleep(int(sys.argv[1]) if len(sys.argv) > 1 else 2)

rows = sorted(b["counts"].items(),
              key=lambda kv: -(kv[1].preempted + kv[1].sleeping + kv[1].blocked + kv[1].other))
print("%-16s %10s %10s %10s %8s" % ("COMM", "PREEMPTED", "SLEEPING", "BLOCKED", "OTHER"))
for k, v in rows[:8]:
    print("%-16s %10d %10d %10d %8d" % (k.comm.decode(), v.preempted, v.sleeping, v.blocked, v.other))

prev->__state and prev->pid look like ordinary pointer dereferences. BCC rewrites them into bpf_probe_read_kernel() calls before compiling, which is one of the conveniences that made it popular. The program attaches to the raw sched_switch tracepoint, which fires each time a CPU switches from one task to another; args[1] is the task leaving the CPU.

The price is paid on the machine where the tool runs. On a fresh Ubuntu 22.04, which ships BCC 0.18, the first attempt fails, because the headers aren’t installed:

$ sudo python3 taskstate_bcc.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.

The traceback that follows is trimmed. The kernel is built with CONFIG_IKHEADERS=m, which packs the headers into a module, and BCC tried to load it first, but on 22.04 that module lives in linux-modules-extra, which a minimal install doesn’t have. With linux-headers-5.15.0-25-generic installed, the tool works, and every start compiles the C from scratch. Six starts, from the timing run described at the end:

compiled, loaded and attached in 2.39 s
compiled, loaded and attached in 2.35 s
compiled, loaded and attached in 2.40 s
compiled, loaded and attached in 2.48 s
compiled, loaded and attached in 2.31 s
compiled, loaded and attached in 2.37 s

Between 2.31 and 2.48 seconds, every time, to compile a program of a few dozen lines; counted from launching Python to the tool being ready, about 3.3 seconds. Each start held about 97 MiB of memory at its peak, nearly all of it the compiler.

And a target-side compiler only solves the offsets. It does not solve names. Ubuntu 22.04’s own copy of BCC’s runqlat, a standard tool that measures how long runnable tasks wait for a CPU, does not run on Ubuntu 22.04’s own kernel:

$ sudo runqlat-bpfcc 1 1
/virtual/main.c:54:15: error: no member named 'state' in 'struct task_struct'
    if (prev->state == TASK_RUNNING) {
        ~~~~  ^
3 warnings and 1 error generated.
Traceback (most recent call last):
  File "/sbin/runqlat-bpfcc", line 251, in <module>
    b = BPF(text=bpf_text)
  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 0.18 was released in January 2021, before the rename, and its runqlat still says state. The compiler on the target did its job perfectly: it read the 5.15 headers and reported, correctly, that state no longer exists. To run on both sides of the rename, the tool itself has to look at the kernel and choose which C to compile. BCC fixed runqlat that way in November 2021: the script now asks whether task_struct has a __state field and edits its program text to match before compiling it. To ask, it reads the kernel’s BTF, the subject of the next section. 22.04 simply shipped an older BCC.

So BCC’s answer costs a compiler and over two hundred megabytes of headers and libraries on every machine, and two and a half seconds and a hundred megabytes of memory on every start, and the renames still need handling by hand. What a tool really wants is to be compiled once, on the developer’s machine, and to find out about the target’s layout when it is loaded. For that, the loader needs a description of the running kernel’s types that is always present and costs nothing to read. The kernel now carries one.

BTF: the kernel describes its own types

BTF, the BPF Type Format, is a compact encoding of C types, designed for BPF. It arrived in 4.18 to describe the types in a program’s own maps. In 5.2 the kernel build learnt to generate BTF for the whole kernel (CONFIG_DEBUG_INFO_BTF), and in 5.4 the result became readable at run time as a file, /sys/kernel/btf/vmlinux. Ubuntu builds its kernels with it from 20.10 onwards, so every 22.04 machine has the file. We used it in Part 1 without looking inside, to generate vmlinux.h. Here is what is inside.

BTF is a table of numbered type records. Each record has a kind, usually a name, and, where it refers to other types, their numbers. bpftool prints the table:

$ bpftool btf dump file /sys/kernel/btf/vmlinux | head -3
[1] INT 'long unsigned int' size=8 bits_offset=0 nr_bits=64 encoding=(none)
[2] CONST '(anon)' type_id=1
[3] PTR '(anon)' type_id=5

Type 1 is an integer, 8 bytes, unsigned. Type 2 is “const of type 1”. Type 3 is “pointer to type 5”. Everything in C is built this way: integers at the leaves, and pointers, arrays, const, volatile, typedefs, structs, unions, enums and function prototypes built on top, each referring to the types it is made of by number. On Ubuntu’s 5.15.0-25 kernel, task_struct is type 130:

[130] STRUCT 'task_struct' size=9536 vlen=240
	'thread_info' type_id=343 bits_offset=0
	'__state' type_id=6 bits_offset=192
	'stack' type_id=83 bits_offset=256
	'usage' type_id=500 bits_offset=320

That’s 9,536 bytes and 240 members (vlen), each with a name, a type number and an offset in bits, so that bitfields can be described too. __state is at bit 192, byte 24. Following the numbers from pid downwards gives a chain of records that ends at a leaf:

	'pid' type_id=52 bits_offset=19072
[52] TYPEDEF 'pid_t' type_id=37
[37] TYPEDEF '__kernel_pid_t' type_id=17
[17] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED

pid is a pid_t, which is a __kernel_pid_t, which is a 4-byte signed int, at bit 19,072, byte 2,384. That is everything a compiler needs to know to read it, and it is everything libbpf will need. Follow the chain yourself in the figure, including the pointer that leads from task_struct back to task_struct:

Following task_struct.pid through the kernel's BTF

Each type is a numbered record; each reference to another type is a number. Click one to follow it.

struct · 9,536 bytes · 240 members (5 shown)

[130] STRUCT 'task_struct' size=9536 vlen=240
	'thread_info' type_id=343 bits_offset=0
	'__state' type_id=6 bits_offset=192
	…
	'pid' type_id=52 bits_offset=19072
	…
	'real_parent' type_id=131 bits_offset=19200
	…
	'comm' type_id=338 bits_offset=22848

A member is a name, a type ID and an offset in bits. 19,072 bits is byte 2,384: where pid lives on this kernel and on no other in this post.

struct · 24 bytes

[343] STRUCT 'thread_info' size=24 vlen=3
	'flags' type_id=1 bits_offset=0
	'syscall_work' type_id=1 bits_offset=64
	'status' type_id=27 bits_offset=128

The first 24 bytes of every task. It is why __state starts at bit 192, byte 24.

pointer

[131] PTR '(anon)' type_id=130

A pointer to type 130, which is task_struct again. The graph has cycles, which is why BTF refers to types by number instead of nesting them.

array

[338] ARRAY '(anon)' type_id=4 index_type_id=17 nr_elems=16

Sixteen elements of type 4. This is char comm[16].

typedef

[52] TYPEDEF 'pid_t' type_id=37

A name for another type, and nothing else.

typedef

[37] TYPEDEF '__kernel_pid_t' type_id=17

A typedef of a typedef, exactly as the C headers declare it.

typedef

[27] TYPEDEF 'u32' type_id=18

The kernel's own short name.

typedef

[18] TYPEDEF '__u32' type_id=6

The user-space-visible name, which in turn is plain unsigned int.

integer · leaf

[17] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED

The bottom of the chain: four bytes, signed. So pid is an int at byte 2,384, which is everything a load instruction needs to know.

integer · leaf

[6] INT 'unsigned int' size=4 bits_offset=0 nr_bits=32 encoding=(none)

On 5.13 the field at byte 24 was volatile long state, eight bytes. 5.14 renamed it and made it this.

integer · leaf

[4] INT 'char' size=1 bits_offset=0 nr_bits=8 encoding=(none)

One byte.

integer · leaf

[1] INT 'long unsigned int' size=8 bits_offset=0 nr_bits=64 encoding=(none)

Type 1, the first record in the kernel's BTF. There are 119,957.

IDs, sizes and offsets are Ubuntu 22.04's 5.15.0-25 kernel's, from bpftool btf dump. Another kernel numbers its types differently: there, task_struct is [132] (5.13) or [326] (5.19).

References by number are what let BTF describe a graph with cycles, like a task pointing to its parent task, without nesting anything. They are also what keeps it small. The whole kernel’s BTF on 5.15.0-25 is 119,957 records, and nearly half of them are functions:

  53956 FUNC
  28485 FUNC_PROTO
  14455 PTR
  10253 STRUCT
   3537 ARRAY
   2951 CONST
   2073 ENUM
   2037 TYPEDEF
   1598 UNION
    380 VAR
    190 FWD
     22 VOLATILE
     15 INT
      2 RESTRICT
      2 FLOAT
      1 DATASEC

The kernel only has fifteen integer types, and every pointer to task_struct in the whole kernel is the same record, 131. That’s the work of pahole, the tool that generates BTF during the kernel build. It reads the compiler’s debugging information, the DWARF, for every compilation unit, converts it to BTF, and deduplicates: the definition of task_struct that appears in thousands of object files becomes one record. The result is 5,169,768 bytes, and the kernel keeps it in memory, where /sys/kernel/btf/vmlinux reads it.

For comparison, I fetched the DWARF for the same kernel build from Ubuntu’s debug-symbol package, linux-image-unsigned-5.15.0-25-generic-dbgsym, a 1 GB download. Its vmlinux carries 276,235,378 bytes of DWARF sections, and 209,100,709 of them are .debug_info, where the type descriptions live alongside every variable, parameter and inlined call. The same file also carries the .BTF section, at 5,169,768 bytes, byte for byte the size of the sysfs file. BTF keeps only types, function signatures and the kernel’s per-CPU variables, each of them once: it is about one fortieth of .debug_info alone, and one fifty-third of all the DWARF. That ratio is why every kernel can afford to carry it, and DWARF stays in a separate package that most machines never install.

The kernel’s modules have BTF too, since 5.11, one file per loaded module under /sys/kernel/btf/. A module’s BTF is split: it contains only the module’s own types and refers to the kernel’s by number, so its numbering starts where the kernel’s ends. On 5.15.0-25 the kernel’s last type is 119,957, and the 9p module’s first is the next one:

$ bpftool btf dump file /sys/kernel/btf/9p | head -4
[119958] STRUCT 'p9_qid' size=16 vlen=3
	'type' type_id=23 bits_offset=0
	'version' type_id=27 bits_offset=32
	'path' type_id=29 bits_offset=64

Type 23 is the kernel’s u8; the module didn’t need its own copy. And vmlinux.h, the header from Part 1, is this same table printed back out as C: 131,147 lines, every type in the running kernel, each struct with its fields in the order and at the offsets of that kernel. Near its top is one line that matters more than all the others, and we’ll get to it.

CO-RE: the compiler writes it down, the loader fixes it up

CO-RE, “compile once, run everywhere”, is the name Andrii Nakryiko gave to the scheme that puts BTF to work. libbpf has implemented it since August 2019 (its relocation algorithm shipped with the 5.4 tools), and his write-up BPF Portability and CO-RE, from February 2020, is still the best introduction. It has three parts, and each is simple:

  1. clang records instead of deciding. When an access is marked for it, clang still emits the load with the offset from the headers it compiled against, but it also writes down what the access meant: “field pid of struct task_struct, at this instruction”. These records go into a section of the object file called .BTF.ext, next to the program’s own BTF in .BTF.
  2. The kernel describes itself, in /sys/kernel/btf/vmlinux.
  3. libbpf matches the two at load time. For each record it finds the type with the same name in the kernel’s BTF, finds the field with the same name in it, computes that field’s offset on this kernel, and writes it into the instruction. Then it loads the program.

The marking is a clang builtin, __builtin_preserve_access_index(), or the same thing as a type attribute, preserve_access_index, which marks every access through that type. This is the line at the top of vmlinux.h:

$ grep -n preserve_access_index vmlinux.h
5:#pragma clang attribute push (__attribute__((preserve_access_index)), apply_to = record)

Every struct and union in the file gets the attribute, so every field access through a type from vmlinux.h is recorded. Nothing in the C has to change. That is the whole trick, and the rest of this post is the trick taken apart.

The worked example

The tool answers the question from earlier: when tasks leave the CPU, why? A task stops running for one of three reasons, and its state field says which. If the state is still TASK_RUNNING (0), it didn’t want to stop: the scheduler took the CPU away, which is preemption. If it is TASK_INTERRUPTIBLE (1), the task went to sleep waiting for something, such as input, a timer or a child process. If it is TASK_UNINTERRUPTIBLE (2), it is waiting for something it can’t abandon, usually disk I/O or a lock: the D state in ps. The program counts the three per task name. Here is all of the kernel half:

// taskstate.bpf.c — why do tasks leave the CPU? One object for every kernel since 5.5
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>

#define TASK_RUNNING		0x0000
#define TASK_INTERRUPTIBLE	0x0001
#define TASK_UNINTERRUPTIBLE	0x0002

/* task_struct as kernels before 5.14 declared the field we want */
struct task_struct___pre514 {
	volatile long state;
} __attribute__((preserve_access_index));

struct comm_key {
	char comm[16];
};

struct reasons {
	__u64 preempted;	/* still runnable: the scheduler took the CPU away */
	__u64 sleeping;		/* TASK_INTERRUPTIBLE: waiting for an event */
	__u64 blocked;		/* TASK_UNINTERRUPTIBLE: waiting on I/O or a lock */
	__u64 other;
};

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

static __always_inline unsigned int task_state(struct task_struct *t)
{
	if (bpf_core_field_exists(t->__state))
		return BPF_CORE_READ(t, __state);

	struct task_struct___pre514 *old = (void *)t;
	return BPF_CORE_READ(old, state);
}

SEC("tp_btf/sched_switch")
int BPF_PROG(on_switch, bool preempt, struct task_struct *prev, struct task_struct *next)
{
	struct comm_key key = {};
	struct reasons zero = {}, *r;
	unsigned int state;

	if (prev->pid == 0)		/* the idle task */
		return 0;

	state = task_state(prev);
	BPF_CORE_READ_STR_INTO(&key.comm, prev, comm);

	r = bpf_map_lookup_elem(&counts, &key);
	if (!r) {
		bpf_map_update_elem(&counts, &key, &zero, BPF_NOEXIST);
		r = bpf_map_lookup_elem(&counts, &key);
		if (!r)
			return 0;
	}
	if (state == TASK_RUNNING)
		__sync_fetch_and_add(&r->preempted, 1);
	else if (state & TASK_INTERRUPTIBLE)
		__sync_fetch_and_add(&r->sleeping, 1);
	else if (state & TASK_UNINTERRUPTIBLE)
		__sync_fetch_and_add(&r->blocked, 1);
	else
		__sync_fetch_and_add(&r->other, 1);
	return 0;
}

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

The map and the counting are Part 1’s pattern again: look up, insert if missing, add atomically. What’s new is how the program reads the kernel.

  • SEC("tp_btf/sched_switch") attaches to the same scheduler tracepoint as the BCC version, as a BTF-enabled tracepoint (5.5). The kernel uses its own BTF to give the program typed arguments: prev is not a number to be cast but a struct task_struct * the verifier knows the type of. That is what lets the program write prev->pid and read the field directly. The verifier checks the load against the kernel’s real task_struct, and we’ll see it refuse a bad one. BPF_PROG, from bpf_tracing.h, unpacks the tracepoint’s raw argument array into named, typed parameters. The first three arguments of sched_switch are the same on all three kernels. (5.18 added a fourth, prev_state, at the end, so it doesn’t disturb these.)
  • prev->pid is a plain C field access through a type from vmlinux.h, so it carries the preserve_access_index attribute and clang records it. This is the instruction from the top of the post.
  • BPF_CORE_READ(t, __state), from bpf_core_read.h, reads a field through bpf_probe_read_kernel(), with the address computed under __builtin_preserve_access_index. It works in any program type, including kprobes and plain tracepoints, where the pointer is just a number and direct loads aren’t allowed. BPF_CORE_READ(a, b, c) follows a chain of pointers, a->b->c, with a relocation and a safe read at each step.
  • BPF_CORE_READ_STR_INTO is the string version: it copies prev->comm into the key.
  • bpf_core_field_exists(t->__state) compiles to a constant that libbpf fills in at load time: 1 if the running kernel’s task_struct has a __state, 0 if not. It is how one object handles the rename.
  • struct task_struct___pre514 is a flavour. When libbpf looks for a type, it ignores everything from a triple underscore onwards, so this matches the kernel’s task_struct, but it lets the program declare the old field, volatile long state, which vmlinux.h (made from a 5.15 kernel) doesn’t have. Cast the pointer, read through the flavour, and libbpf relocates state against whatever kernel it finds, or reports that there is no such field.

The if in task_state() is the important part. On a kernel with __state, the first branch runs and reads 4 bytes. On a kernel with state, the second runs and reads 8. Both branches are compiled into the object, and only one of them can be valid on any given kernel. The other one names a field that doesn’t exist there. We’ll see what libbpf and the verifier do with it.

The user-space half is Part 1’s loader with a sorted table at the end, and three changes worth naming:

// taskstate.c — load the program, count for N seconds, print the busiest tasks
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/utsname.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "taskstate.skel.h"

struct comm_key { char comm[16]; };
struct reasons { __u64 preempted, sleeping, blocked, other; };
struct row { struct comm_key k; struct reasons r; __u64 total; };

static int verbose;

static int print_libbpf(enum libbpf_print_level level, const char *fmt, va_list ap)
{
	if (level == LIBBPF_DEBUG && !verbose)
		return 0;
	return vfprintf(stderr, fmt, ap);
}

static int by_total(const void *a, const void *b)
{
	const struct row *x = a, *y = b;
	return x->total < y->total ? 1 : x->total > y->total ? -1 : 0;
}

int main(int argc, char **argv)
{
	static struct row rows[10240];
	struct comm_key *prev = NULL, next;
	struct taskstate_bpf *skel;
	struct utsname u;
	int seconds = 2, n = 0, fd, i;
	LIBBPF_OPTS(bpf_object_open_opts, opts);

	for (i = 1; i < argc; i++) {
		if (!strcmp(argv[i], "-v"))
			verbose = 1;			/* print libbpf's debug log */
		else if (!strcmp(argv[i], "-b") && i + 1 < argc)
			opts.btf_custom_path = argv[++i]; /* kernel BTF from a file */
		else
			seconds = atoi(argv[i]);
	}
	libbpf_set_print(print_libbpf);

	skel = taskstate_bpf__open_opts(&opts);
	if (!skel || taskstate_bpf__load(skel)) {
		fprintf(stderr, "failed to open and load the BPF object\n");
		taskstate_bpf__destroy(skel);
		return 1;
	}
	if (taskstate_bpf__attach(skel)) {
		fprintf(stderr, "failed to attach\n");
		taskstate_bpf__destroy(skel);
		return 1;
	}
	uname(&u);
	printf("kernel %s, counting for %d s\n", u.release, seconds);
	fflush(stdout);
	sleep(seconds);

	fd = bpf_map__fd(skel->maps.counts);
	while (n < 10240 && bpf_map_get_next_key(fd, prev, &next) == 0) {
		rows[n].k = next;
		bpf_map_lookup_elem(fd, &next, &rows[n].r);
		rows[n].total = rows[n].r.preempted + rows[n].r.sleeping +
				rows[n].r.blocked + rows[n].r.other;
		prev = &rows[n].k;
		n++;
	}
	qsort(rows, n, sizeof(rows[0]), by_total);
	printf("%-16s %10s %10s %10s %8s\n", "COMM", "PREEMPTED", "SLEEPING", "BLOCKED", "OTHER");
	for (i = 0; i < n && i < 8; i++)
		printf("%-16s %10llu %10llu %10llu %8llu\n", rows[i].k.comm,
		       rows[i].r.preempted, rows[i].r.sleeping,
		       rows[i].r.blocked, rows[i].r.other);

	taskstate_bpf__destroy(skel);
	return 0;
}

The changes: libbpf_set_print() installs a callback for libbpf’s log, and -v lets its debug messages through, which is where the relocations are reported. LIBBPF_OPTS declares an options struct for opening the object, and -b sets one option in it, btf_custom_path, which we’ll need near the end. And the skeleton is opened and loaded in two steps instead of one, because the options go to the open step and __open_and_load() takes none.

Building it with libbpf 1.0

Ubuntu 22.04 ships libbpf 0.5. libbpf 1.0.0 was released on 22 August and bpftool 7.0.0, its matching bpftool, on 1 September, and neither is packaged for 22.04, so I built both from their release tags. bpftool’s source tarball leaves out libbpf, which it normally carries as a git submodule. The commit the submodule pins differs from libbpf’s v1.0.0 tag only in the README, so I used the release tarball in its place:

# libbpf v1.0.0 and bpftool v7.0.0 from their release tags, on Ubuntu 22.04
curl -sSfL -o libbpf-1.0.0.tar.gz https://github.com/libbpf/libbpf/archive/refs/tags/v1.0.0.tar.gz
curl -sSfL -o bpftool-7.0.0.tar.gz https://github.com/libbpf/bpftool/archive/refs/tags/v7.0.0.tar.gz
tar xzf libbpf-1.0.0.tar.gz && tar xzf bpftool-7.0.0.tar.gz
rmdir bpftool-7.0.0/libbpf && cp -a libbpf-1.0.0 bpftool-7.0.0/libbpf
make -C libbpf-1.0.0/src BUILD_STATIC_ONLY=1 PREFIX=/opt/libbpf-1.0 install install_uapi_headers
make -C bpftool-7.0.0/src && cp bpftool-7.0.0/src/bpftool /usr/local/sbin/bpftool

BUILD_STATIC_ONLY builds only libbpf.a, so the tool links libbpf into itself and doesn’t care which libbpf, if any, the target has. install_uapi_headers installs libbpf’s own copy of the kernel’s BPF definitions, which are newer than 22.04’s. The new bpftool goes in /usr/local/sbin, ahead of Ubuntu’s wrapper on the PATH; that wrapper only works on the kernel whose linux-tools package is installed, and two of our three kernels have none.

$ bpftool version
bpftool v7.0.0
using libbpf v1.0
features: libbpf_strict

The tool then builds the way Part 1’s did, plus one step:

# on the build machine: Ubuntu 22.04, kernel 5.15.0-25
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -I/opt/libbpf-1.0/include -c taskstate.bpf.c -o taskstate.bpf.o
llvm-strip -g taskstate.bpf.o
bpftool gen skeleton taskstate.bpf.o > taskstate.skel.h
cc -g -O2 -Wall -I/opt/libbpf-1.0/include taskstate.c /opt/libbpf-1.0/lib64/libbpf.a -lelf -lz -o taskstate

The new step is llvm-strip -g. clang’s -g produces BTF, which CO-RE needs, and also full DWARF, which nothing at run time reads. Our object came out of clang at 698,576 bytes, nearly all of it DWARF for the vmlinux.h types the program touches. Stripped, it is 30,848 bytes, with .BTF (27,584 bytes) and .BTF.ext (620 bytes) intact. Since the skeleton embeds the object whole, stripping decides whether the tool carries 31 KB of program or 700. The result is one executable that needs only libelf and zlib from the target, which every distribution has:

$ ldd taskstate
	linux-vdso.so.1 (address trimmed)
	libelf.so.1 => /lib/x86_64-linux-gnu/libelf.so.1 (address trimmed)
	libz.so.1 => /lib/x86_64-linux-gnu/libz.so.1 (address trimmed)
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (address trimmed)
	/lib64/ld-linux-x86-64.so.2 (address trimmed)

What clang wrote down

clang compiled prev->pid into exactly the instruction from the start of the post. Here are the first instructions of the program, disassembled from the object file:

$ llvm-objdump -d --no-show-raw-insn taskstate.bpf.o
       0:	r6 = *(u64 *)(r1 + 8)
       ...
       8:	r1 = *(u32 *)(r6 + 2384)
       9:	if r1 == 0 goto +62 <LBB0_13>
      10:	r1 = 1
      11:	if r1 == 0 goto +9 <LBB0_3>
      12:	r1 = 24
      ...
      21:	r1 = 0
      ...
      29:	r1 = 2856

Instruction 0 loads prev from the context (the second 8-byte argument). Instruction 8 loads prev->pid from byte 2,384, the 5.15 offset, straight from vmlinux.h. Instruction 10 is the existence check, compiled as “r1 = 1, then branch if r1 is 0”: clang can’t fold the branch away, because it knows the 1 is only a placeholder. Instruction 12 is __state’s offset, 24, which BPF_CORE_READ adds to the pointer. Instruction 21 is the old state’s offset in our one-field flavour struct, 0, which is plainly wrong for any real kernel. Instruction 29 is comm’s offset, 2,856.

None of the instructions is special. A loader that ignored CO-RE could load these as they are, and on 5.15.0-25 they’d even be right. What makes them relocatable is in .BTF.ext. No standard tool prints that section’s CO-RE records, so here is a short script that does, by reading the ELF section headers and then the record format libbpf parses:

# coreinfo.py — print the CO-RE records clang left in a BPF object's .BTF.ext
import struct, sys

data = open(sys.argv[1], 'rb').read()

# ELF64: find the section headers, then each section by name
shoff, = struct.unpack_from('<Q', data, 0x28)
shentsize, shnum, shstrndx = struct.unpack_from('<HHH', data, 0x3a)
def header(i):
    return struct.unpack_from('<IIQQQQIIQQ', data, shoff + i * shentsize)
names = header(shstrndx)[4]
secs = {}
for i in range(shnum):
    h = header(i)
    nm = data[names + h[0]:data.index(b'\0', names + h[0])].decode()
    secs[nm] = data[h[4]:h[4] + h[5]]
btf, ext = secs['.BTF'], secs['.BTF.ext']

# .BTF header: magic, version, flags, hdr_len, type_off, type_len, str_off, str_len
_, _, _, hdr_len, _, _, str_off, str_len = struct.unpack_from('<HBBIIIII', btf)
strs = btf[hdr_len + str_off:hdr_len + str_off + str_len]
def string(off):
    return strs[off:strs.index(b'\0', off)].decode()

# .BTF.ext header: magic, version, flags, hdr_len, then offset and length of
# func_info, line_info and core_relo, each counted from the end of the header
hdr = struct.unpack_from('<HBBIIIIIII', ext)
hlen, core_off, core_len = hdr[3], hdr[8], hdr[9]
KINDS = ['byte_off', 'byte_sz', 'field_exists', 'signed', 'lshift_u64',
         'rshift_u64', 'local_type_id', 'target_type_id', 'type_exists',
         'type_size', 'enumval_exists', 'enumval_value', 'type_matches']

p, end = hlen + core_off, hlen + core_off + core_len
rec_size, = struct.unpack_from('<I', ext, p)
p += 4
while p < end:
    sec, n = struct.unpack_from('<II', ext, p)
    p += 8
    print(f'section {string(sec)}: {n} CO-RE records')
    for _ in range(n):
        insn_off, type_id, access, kind = struct.unpack_from('<IIII', ext, p)
        p += rec_size
        print(f'  insn {insn_off // 8:3}  type [{type_id}]  access "{string(access)}"  {KINDS[kind]}')
$ python3 coreinfo.py taskstate.bpf.o
section tp_btf/sched_switch: 5 CO-RE records
  insn   8  type [20]  access "0:74"  byte_off
  insn  10  type [20]  access "0:1"  field_exists
  insn  12  type [20]  access "0:1"  byte_off
  insn  21  type [333]  access "0:0"  byte_off
  insn  29  type [20]  access "0:108"  byte_off
$ bpftool btf dump file taskstate.bpf.o | grep -E "^\[(20|333)\] "
[20] STRUCT 'task_struct' size=9536 vlen=240
[333] STRUCT 'task_struct___pre514' size=8 vlen=1

Five records, one per marked instruction. Each says which instruction, which type (a number in the object’s own BTF, where task_struct is 20), what kind of fact the instruction depends on, and an access string. The access string is the path from the type to the field, as indices: 0:74 means “element 0 of the pointer, then member number 74”, and member 74 of the task_struct that vmlinux.h describes is pid. 0:1 is member 1, __state; 0:108 is comm. The record does not carry the offset. It carries the question, and the answer gets filled in later. Every record is 16 bytes. The program’s whole portability, five records, is 80 bytes of .BTF.ext.

What libbpf did at load time

At load, libbpf reads /sys/kernel/btf/vmlinux, takes each record, looks up the local type’s name in the kernel’s BTF (with any ___flavour suffix removed), walks the access string by member name rather than number, and patches the instruction. With -v, it says what it did. Here is record 0, the pid load, on 5.13:

libbpf: CO-RE relocating [20] struct task_struct: found target candidate [132] struct task_struct in [vmlinux]
libbpf: prog 'on_switch': relo #0: <byte_off> [20] struct task_struct.pid (0:74 @ offset 2384)
libbpf: prog 'on_switch': relo #0: matching candidate #0 <byte_off> [132] struct task_struct.pid (0:69 @ offset 2336)
libbpf: prog 'on_switch': relo #0: patched insn #8 (LDX/ST/STX) off 2384 -> 2336

Read it line by line. Our type 20 is called task_struct, and the kernel’s BTF has a task_struct too, type 132. Locally, pid is member 74 at byte 2,384. In the kernel’s task_struct, the member called pid is number 69, at byte 2,336: five fewer members precede it on 5.13. So libbpf rewrote instruction 8’s offset from 2,384 to 2,336. The match is by name at every step, which is why the numbers in the access string can differ between the program and the kernel without anything going wrong.

The five relocations on each kernel, from the same log:

5.13.0-051300-generic
libbpf: prog 'on_switch': relo #0: patched insn #8 (LDX/ST/STX) off 2384 -> 2336
libbpf: prog 'on_switch': relo #1: patched insn #10 (ALU/ALU64) imm 1 -> 0
libbpf: prog 'on_switch': relo #2: substituting insn #12 w/ invalid insn
libbpf: prog 'on_switch': relo #3: patched insn #21 (ALU/ALU64) imm 0 -> 24
libbpf: prog 'on_switch': relo #4: patched insn #29 (ALU/ALU64) imm 2856 -> 2808

5.15.0-25-generic
libbpf: prog 'on_switch': relo #0: patched insn #8 (LDX/ST/STX) off 2384 -> 2384
libbpf: prog 'on_switch': relo #1: patched insn #10 (ALU/ALU64) imm 1 -> 1
libbpf: prog 'on_switch': relo #2: patched insn #12 (ALU/ALU64) imm 24 -> 24
libbpf: prog 'on_switch': relo #3: substituting insn #21 w/ invalid insn
libbpf: prog 'on_switch': relo #4: patched insn #29 (ALU/ALU64) imm 2856 -> 2856

5.19.0-051900-generic
libbpf: prog 'on_switch': relo #0: patched insn #8 (LDX/ST/STX) off 2384 -> 2496
libbpf: prog 'on_switch': relo #1: patched insn #10 (ALU/ALU64) imm 1 -> 1
libbpf: prog 'on_switch': relo #2: patched insn #12 (ALU/ALU64) imm 24 -> 24
libbpf: prog 'on_switch': relo #3: substituting insn #21 w/ invalid insn
libbpf: prog 'on_switch': relo #4: patched insn #29 (ALU/ALU64) imm 2856 -> 2968

Two kinds of patch are visible. For the direct load, libbpf rewrote the instruction’s offset field (LDX, a load). For the BPF_CORE_READs, which compute an address and pass it to a helper, it rewrote an immediate: the constant that gets added to the pointer (ALU). The existence check is an immediate too, 1 or 0.

And then there is “substituting insn w/ invalid insn”. On 5.13 there is no __state, so record 2, the offset of __state, has no answer. libbpf doesn’t fail the load. It replaces the instruction with one that is deliberately invalid: if the verifier ever reaches it, the program is rejected with a message naming the failed relocation. On 5.15 and 5.19 the same happens to record 3, the old state. Whether the verifier reaches the poisoned instruction depends on record 1, which libbpf set to a constant: on 5.13, r1 = 0; if r1 == 0 goto ... always jumps over the __state branch. The verifier works that out (it tracks the constant in r1; Part 4 is about how), never visits the branch, and removes it as dead code. You can see the result in what the kernel kept:

$ bpftool prog dump xlated name on_switch       # on 5.13
; if (prev->pid == 0)		/* the idle task */
   8: (61) r1 = *(u32 *)(r6 +2336)
; if (prev->pid == 0)		/* the idle task */
   9: (15) if r1 == 0x0 goto pc+56
  10: (b7) r1 = 0
; return BPF_CORE_READ(t, __state);
  11: (b7) r1 = 24
  12: (bf) r3 = r6
  13: (0f) r3 += r1
  14: (bf) r1 = r10
; return BPF_CORE_READ(old, state);
  15: (07) r1 += -8
  16: (b7) r2 = 8
  17: (85) call bpf_probe_read_kernel#-64784
$ bpftool prog dump xlated name on_switch       # on 5.19
   8: (61) r1 = *(u32 *)(r6 +2496)
; if (prev->pid == 0)		/* the idle task */
   9: (15) if r1 == 0x0 goto pc+56
  10: (b7) r1 = 1
; if (bpf_core_field_exists(t->__state))
  11: (b7) r1 = 24
  12: (bf) r3 = r6
  13: (0f) r3 += r1
  14: (bf) r1 = r10
;
  15: (07) r1 += -8
; return BPF_CORE_READ(t, __state);
  16: (b7) r2 = 4
  17: (85) call bpf_probe_read_kernel#-73616

Same 68 instructions on both, different programs. On 5.13 the load at 8 uses offset 2,336, the existence check is 0, the conditional branch after it is gone, and what follows is the old branch: offset 24, 8 bytes, a volatile long. On 5.19 the check is 1 and what follows is the new branch: offset 24, 4 bytes, an unsigned int. (The source-line annotations attached to the surviving instructions are a little confused on 5.13, since the line table was written for the full program; the instructions are what matter.) The figure puts the five relocations on the three kernels side by side:

One object file, three kernels

taskstate.bpf.o was compiled once, against Ubuntu 22.04's headers. Pick the kernel it is loaded on to see where libbpf pointed its five relocated instructions.

relo #0 · insn 8 · byte_offtask_struct.pid, read directly
as compiled: r1 = *(u32 *)(r6 + 2384)
5.13r6 + 2336
5.15.0-25r6 + 2384
5.19r6 + 2496
relo #1 · insn 10 · field_existsdoes task_struct.__state exist?
as compiled: r1 = 1
5.13r1 = 0
5.15.0-25r1 = 1
5.19r1 = 1
relo #2 · insn 12 · byte_offtask_struct.__state, 4 bytes
as compiled: r1 = 24
5.13invalid insn (dead branch, removed)
5.15.0-25r1 = 24
5.19r1 = 24
relo #3 · insn 21 · byte_offtask_struct___pre514.state, 8 bytes
as compiled: r1 = 0
5.13r1 = 24
5.15.0-25invalid insn (dead branch, removed)
5.19invalid insn (dead branch, removed)
relo #4 · insn 29 · byte_offtask_struct.comm, address for a string read
as compiled: r1 = 2856
5.13r1 = 2808
5.15.0-25r1 = 2856
5.19r1 = 2968

Green: libbpf changed the value. Teal: the kernel matched the headers. Copper: libbpf found no such field and planted an invalid instruction, which is safe only because the field-exists check before it makes that branch unreachable, and the verifier removes it. The dashed marker is byte 2,384, the offset a compiler without CO-RE would have used everywhere.

It works

The same taskstate binary, copied from the 5.15 machine, run for two seconds on each kernel while six busy loops competed for four CPUs, a shell loop slept in 20 ms steps, and dd wrote with synchronous I/O:

$ sudo ./taskstate 2
kernel 5.13.0-051300-generic, counting for 2 s
COMM              PREEMPTED   SLEEPING    BLOCKED    OTHER
yes                    5325          0          0        0
sleep                     3         54       2054       56
sh                       14         54       1730        0
dd                        0          0        910        0
rcu_sched                 0          0        269        0
cat                       0         55          0        0
kworker/1:1               0          0         35        0
kworker/3:0               0          0          9        0
$ sudo ./taskstate 2
kernel 5.15.0-25-generic, counting for 2 s
COMM              PREEMPTED   SLEEPING    BLOCKED    OTHER
yes                    4560          0          0        0
sleep                     1         49       1869       50
sh                       15         51       1599        0
dd                        0          0        406        1
rcu_sched                 0          0        288        2
cat                       0         50          0        0
kworker/0:1               0          0         21        0
kworker/1:1               0          0          8        0
$ sudo ./taskstate 2
kernel 5.19.0-051900-generic, counting for 2 s
COMM              PREEMPTED   SLEEPING    BLOCKED    OTHER
yes                    4280          0          0        0
sleep                     6         47       1682       48
sh                       13         48       1502        1
dd                        1          0        400        1
rcu_preempt               0          0        309        3
cat                       0         46          0        0
kworker/0:2               0          0         20        0
kworker/3:1               0          0          8        0

The pattern is the same on all three, and it is the right one: yes never chose to stop, so all its switches were preemptions; cat, reading from a pipe that only gets a line every 20 ms, slept about fifty times a second; dd, waiting for each synchronous write, was blocked. The sleep and sh rows need a word. The shell loop starts /bin/sleep a hundred times, and in these virtual machines the root filesystem is a share from the host, so every exec blocks while pages of the binary are read in: hence about two thousand uninterruptible waits for fifty short-lived processes, and one “other” each, the last switch away from a task that has exited, whose state is TASK_DEAD. On 5.19 the RCU thread is called rcu_preempt rather than rcu_sched, because that mainline build has a preemptible kernel and Ubuntu’s 5.15 doesn’t. That is the configuration difference from the start of this post, showing up in a thread’s name.

What happens without the relocation

To see what CO-RE prevents rather than take it on trust, I wrote a second small program that reads pid both ways in the same run. The first way takes the offset with offsetof, which is a compile-time constant that clang does not relocate, and reads with a plain bpf_probe_read_kernel(). That is what a BPF program compiled against fixed headers does. The second way uses BPF_CORE_READ. A helper, bpf_get_current_pid_tgid(), provides the right answer to compare against. While it’s at it, the program asks the kernel a few more questions, one for each of the other kinds of relocation:

// kfacts.bpf.c — ask the running kernel about itself, one relocation at a time
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_core_read.h>

/* task_struct before 5.14, and a type from 5.19 that a 5.15 vmlinux.h lacks */
struct task_struct___pre514 {
	volatile long state;
} __attribute__((preserve_access_index));

struct bpf_dynptr_kern {
	void *data;
	__u32 size;
	__u32 offset;
} __attribute__((preserve_access_index));

const volatile int target_tgid = 0;	/* set by user space before loading */

int true_pid;			/* from a helper: the right answer */
int baked_off, baked_pid;	/* offset fixed by the compiler */
int core_off, core_pid;		/* offset fixed by libbpf at load time */
int has_state, has___state, has_timer, has_dynptr, max_helper_id;

SEC("raw_tp/sys_enter")		/* every system call, from every process */
int kfacts(void *ctx)
{
	struct task_struct *task = (void *)bpf_get_current_task();
	__u64 id = bpf_get_current_pid_tgid();

	if ((id >> 32) != target_tgid)
		return 0;
	true_pid = (__u32)id;

	baked_off = __builtin_offsetof(struct task_struct, pid);
	bpf_probe_read_kernel(&baked_pid, sizeof(baked_pid), (void *)task + baked_off);

	core_off = bpf_core_field_offset(task->pid);
	core_pid = BPF_CORE_READ(task, pid);

	has___state = bpf_core_field_exists(task->__state);
	has_state = bpf_core_field_exists(((struct task_struct___pre514 *)task)->state);
	has_timer = bpf_core_type_exists(struct bpf_timer_kern);
	has_dynptr = bpf_core_type_exists(struct bpf_dynptr_kern);
	max_helper_id = bpf_core_enum_value(enum bpf_func_id, __BPF_FUNC_MAX_ID);
	return 0;
}

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

Beyond field offsets and field existence, there are relocations for whole types and for enum values:

  • bpf_core_type_exists(T) is 1 if the kernel’s BTF has a type with that name and kind. struct bpf_timer_kern is the kernel’s side of BPF timers, which arrived in 5.15, and struct bpf_dynptr_kern is the kernel’s side of dynptrs, new in 5.19. The second isn’t in our 5.15 vmlinux.h, so the program declares it; for an existence check only the name and kind matter.
  • bpf_core_enum_value(E, V) is the value of enumerator V on the running kernel. Enums get renumbered when someone adds a member in the middle, and the value a program was compiled with can be wrong elsewhere. I picked __BPF_FUNC_MAX_ID from enum bpf_func_id, the number one past the last BPF helper, which is a neat way to ask a kernel how many helpers it has.
  • bpf_core_field_offset is the offset itself, as a number, for printing.

target_tgid is const volatile, a read-only global that user space sets before loading, so the program only records its own system calls. The user-space half sets it, loads, makes one system call to run the program, and prints what the program recorded:

// kfacts.c — set a read-only global, load, trigger once, read the answers back
#include <errno.h>	/* skel_internal.h in libbpf 1.0 uses errno without including it */
#include <stdio.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/utsname.h>
#ifdef LIGHT
#include "kfacts.lskel.h"
#else
#include "kfacts.skel.h"
#endif

int main(void)
{
	struct kfacts_bpf *skel;
	struct utsname u;
	int err;

	skel = kfacts_bpf__open();
	if (!skel) {
		fprintf(stderr, "open failed\n");
		return 1;
	}
	skel->rodata->target_tgid = getpid();	/* only possible before load */

	err = kfacts_bpf__load(skel);
	if (!err)
		err = kfacts_bpf__attach(skel);
	if (err) {
		fprintf(stderr, "load/attach failed: %d\n", err);
		kfacts_bpf__destroy(skel);
		return 1;
	}
	syscall(SYS_getppid);			/* run the program once */

	uname(&u);
	printf("kernel             %s\n", u.release);
	printf("pid (helper)       %d\n", skel->bss->true_pid);
	printf("pid @ %-4d baked   %d\n", skel->bss->baked_off, skel->bss->baked_pid);
	printf("pid @ %-4d CO-RE   %d\n", skel->bss->core_off, skel->bss->core_pid);
	printf("has state          %d\n", skel->bss->has_state);
	printf("has __state        %d\n", skel->bss->has___state);
	printf("has bpf_timer_kern %d\n", skel->bss->has_timer);
	printf("has bpf_dynptr_kern %d\n", skel->bss->has_dynptr);
	printf("__BPF_FUNC_MAX_ID  %d\n", skel->bss->max_helper_id);

	kfacts_bpf__destroy(skel);
	return 0;
}

It builds like taskstate, plus a second skeleton and a second executable that the light skeleton section, further down, explains; the LIGHT branch and the errno.h comment are for that one:

# kfacts, with a full skeleton and a light one
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -I/opt/libbpf-1.0/include -c kfacts.bpf.c -o kfacts.bpf.o
llvm-strip -g kfacts.bpf.o
bpftool gen skeleton kfacts.bpf.o > kfacts.skel.h
bpftool gen skeleton -L kfacts.bpf.o > kfacts.lskel.h
cc -g -O2 -Wall -I/opt/libbpf-1.0/include kfacts.c /opt/libbpf-1.0/lib64/libbpf.a -lelf -lz -o kfacts
cc -g -O2 -Wall -DLIGHT -I/opt/libbpf-1.0/include kfacts.c -o kfacts-light

Run on the three kernels:

$ sudo ./kfacts                 # on 5.13
kernel             5.13.0-051300-generic
pid (helper)       253
pid @ 2384 baked   -2136733376
pid @ 2336 CO-RE   253
has state          1
has __state        0
has bpf_timer_kern 0
has bpf_dynptr_kern 0
__BPF_FUNC_MAX_ID  166
$ sudo ./kfacts                 # on 5.15.0-25
kernel             5.15.0-25-generic
pid (helper)       274
pid @ 2384 baked   274
pid @ 2384 CO-RE   274
has state          0
has __state        1
has bpf_timer_kern 1
has bpf_dynptr_kern 0
__BPF_FUNC_MAX_ID  176
$ sudo ./kfacts                 # on 5.19
kernel             5.19.0-051900-generic
pid (helper)       257
pid @ 2384 baked   0
pid @ 2496 CO-RE   257
has state          0
has __state        1
has bpf_timer_kern 1
has bpf_dynptr_kern 1
__BPF_FUNC_MAX_ID  204

The baked read is right only on the kernel whose headers it was compiled against. On 5.19, byte 2,384 is inside rss_stat, a small block of per-task memory counters, and the value there was 0. On 5.13 it is the sibling list link, a kernel pointer, and the 4 bytes read were half of one. Neither run reported an error. Nothing failed: bpf_probe_read_kernel() was asked to read 4 readable bytes and did. A tool built this way prints wrong process IDs and has no way to know.

The CO-RE read is right everywhere, at three different offsets. The two existence checks flip exactly at the 5.14 rename. The type checks mark 5.15’s timers and 5.19’s dynptrs. And the enum says 5.13 knows 165 helpers, 5.15 knows 175 (Part 1 counted the same 175 on this kernel) and 5.19 knows 203: the program was compiled against the value 176, and libbpf replaced it with each kernel’s own.

Flavours, and what CO-RE cannot do

The ___pre514 suffix deserves a closer look, because it is how a program describes kernels its vmlinux.h didn’t come from. libbpf’s rule is simply that name___anything matches name. A program can carry several flavours of one struct, each declaring the fields some range of kernels has, and use bpf_core_field_exists to pick between them. BCC’s own collection of libbpf-based tools has done exactly this for the state rename since October 2021, in a header called core_fixes.bpf.h, with two flavours named task_struct___o and task_struct___x.

The same mechanism handles fields that change size: each flavour declares its own type for the field, BPF_CORE_READ reads sizeof of that type, and bpf_core_field_size() asks the kernel directly if needed. For direct loads, libbpf can also adjust a load’s width to the kernel’s field size, within limits. Bitfields have their own pair of macros, BPF_CORE_READ_BITFIELD() and BPF_CORE_READ_BITFIELD_PROBED(), built on the lshift_u64, rshift_u64 and signed relocations that the script’s table lists.

What CO-RE can’t do is understand meaning. If a field moves to a different structure, or a value changes units, or a tracepoint’s arguments change order, relocation can at best tell you that the old field is gone. The program needs a branch for each case, as task_state() has. A field that exists under the same name with different semantics will be relocated happily and read wrongly. CO-RE makes the mechanical differences between kernels disappear, which is most of them, and leaves the rest visible.

Skeletons, in depth

Part 1 used a skeleton without looking at it. It is worth looking now, because the skeleton is where CO-RE meets the program’s own data. bpftool gen skeleton reads the object and writes a header with three things in it.

A struct with a field for everything in the object. For kfacts, trimmed:

struct kfacts_bpf {
	struct bpf_object_skeleton *skeleton;
	struct bpf_object *obj;
	struct {
		struct bpf_map *rodata;
		struct bpf_map *bss;
	} maps;
	struct {
		struct bpf_program *kfacts;
	} progs;
	struct {
		struct bpf_link *kfacts;
	} links;
	struct kfacts_bpf__rodata {
		int target_tgid;
	} *rodata;
	struct kfacts_bpf__bss {
		int true_pid;
		int baked_off;
		int baked_pid;
		...
		int max_helper_id;
	} *bss;
	...
};

Global variables in a BPF program live in maps, one per section: .bss for zero-initialised data, .data for initialised data, .rodata for constants. The skeleton gives user space a typed pointer into each, skel->bss->true_pid, so the two halves of the tool share variables by name. libbpf maps the .bss map’s memory into the process, so reading skel->bss->true_pid after the program has run is an ordinary memory read with no system call.

Functions for each stage of the object’s life. __open() parses the object and prepares everything without touching the kernel. __load() does the CO-RE relocations, creates the maps and loads the programs. __attach() attaches every program that has an attach point in its SEC() name. __destroy() undoes all of it. __open_and_load() is the first two together.

The split between open and load is what kfacts.c uses. Between them, skel->rodata points at the initial contents of the .rodata map, still in user memory, and writing target_tgid there changes the value the map will be created with. At load, libbpf creates the map, copies the value in and freezes it, so that nobody can change it again. The verifier then treats the value as a known constant, exactly like an existence check, and can prune branches on it. A filter such as “only my process” costs a comparison against a constant, and a feature switched off in .rodata is removed from the program entirely.

The object itself. At the bottom of the header is the whole object file as a string literal, which is why the tool needs no .o file at run time. For kfacts that literal is the 37,080-byte stripped object. Unstripped, it would have been 704,816 bytes of mostly DWARF.

The light skeleton

bpftool gen skeleton -L makes a light skeleton instead, added in 5.14. Alexei Starovoitov’s cover letter for it calls it “a first step towards signed bpf programs”: for a signature to mean anything, the thing that was signed has to be the thing that runs, and a regular skeleton runs libbpf, which rewrites the program on the way in. A light skeleton doesn’t contain the object. It contains a small BPF program, the loader, of the type BPF_PROG_TYPE_SYSCALL (also 5.14), whose job is to make the bpf() calls that libbpf would have made: create the maps, load the programs. User space loads the loader, runs it once, and gets back descriptors. The header needs no libbpf at run time:

$ ldd kfacts-light
	linux-vdso.so.1 (address trimmed)
	libc.so.6 => /lib/x86_64-linux-gnu/libc.so.6 (address trimmed)
	/lib64/ld-linux-x86-64.so.2 (address trimmed)

The same kfacts.c, built with -DLIGHT against the light skeleton, gives 76,712 bytes of executable that depends on nothing but libc. Its API is the same except at the edges: kfacts.c needed errno.h included by hand, because libbpf 1.0’s skel_internal.h uses errno without including it, and I had to attach the program to a raw tracepoint rather than a classic one, because the light skeleton only auto-attaches program types that attach with a single bpf() call; for a tracepoint/ program its generated attach function contains the comment /* auto-attach not supported */.

The interesting edge is CO-RE. In a light skeleton, nobody in user space reads /sys/kernel/btf/vmlinux, so who does the relocations? The kernel does. Since 5.17, BPF_PROG_LOAD accepts the CO-RE records themselves, and the kernel runs the same relocation algorithm against its own BTF. On a kernel without that, there’s nobody to do it:

$ sudo ./kfacts-light           # on 5.19
kernel             5.19.0-051900-generic
pid (helper)       258
pid @ 2384 baked   0
pid @ 2496 CO-RE   258
has state          0
has __state        1
has bpf_timer_kern 1
has bpf_dynptr_kern 1
__BPF_FUNC_MAX_ID  204
$ sudo ./kfacts-light           # on 5.15.0-25
load/attach failed: -7
$ sudo strace -e trace=bpf ./kfacts-light
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_SYSCALL, insn_cnt=242, ..., prog_flags=BPF_F_SLEEPABLE,
    prog_name="__loader.prog", ..., fd_array=...}, 128) = 4
$ sudo ./kfacts-light           # on 5.13
load/attach failed: -7
$ sudo strace -e trace=bpf ./kfacts-light
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_SYSCALL, insn_cnt=242, ..., prog_flags=BPF_F_SLEEPABLE,
    prog_name="__loader.prog", ..., fd_array=...}, 128) = -1 E2BIG (Argument list too long)

On 5.19, the light skeleton works and prints the same answers as the full one. On 5.15 the loader program loads (5.15 has the program type), runs, and its own inner BPF_PROG_LOAD fails with -7, E2BIG: it passed the CO-RE fields, which 5.15 doesn’t know, and the kernel refuses any attribute it doesn’t understand. On 5.13 it fails one step earlier, when loading the loader itself, for the same reason with a different field: fd_array, which 5.14 added in the same series so that a program refers to its maps by index rather than by a descriptor patched into its instructions, again so that a signature stays valid. So a light skeleton of a CO-RE program needs 5.17; without CO-RE, 5.14.

What libbpf 1.0 took away

libbpf 1.0.0, released on 22 August, is the release that finally removed everything 0.x had deprecated. Its release notes open with “All deprecated APIs and features removed!”, and the list is long. The ones most code will meet:

  • Legacy map definitions. struct bpf_map_def in a section called maps is gone. Only the BTF-defined maps in .maps, the form every program in this series has used, are accepted.
  • The old loaders and constructors. bpf_prog_load() with its old signature, bpf_object__open(), bpf_object__open_buffer(), bpf_create_map() and its relatives, bpf_load_program(), bpf_prog_test_run(), and others, each replaced by an OPTS-based version that libbpf introduced in 0.6 or 0.7.
  • Strict mode is the only mode. Since 0.5, programs could opt into the 1.0 behaviour with libbpf_set_strict_mode() and LIBBPF_STRICT_ALL. In 1.0 the function is still there, so that code which opted in still compiles, but its header says it now has no effect. The behaviours it used to switch on are the defaults: functions return NULL and set errno instead of returning an encoded error pointer, low-level functions return -errno directly, a SEC() name libbpf doesn’t recognise is an error, and libbpf raises RLIMIT_MEMLOCK itself on kernels that still charge BPF memory to it (before 5.11), so tools no longer need the setrlimit() call that used to open every BPF program’s main().
  • AF_XDP moved out. The AF_XDP socket helpers, xsk.h and xsk.c, now live in libxdp.

Part 1 mentioned the older map syntax in passing. Here is Part 1’s counter written that way, as countless examples on the web still are:

// legacy.bpf.c — Part 1's counter with the map declared the pre-BTF way
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>

struct bpf_map_def SEC("maps") counts = {
	.type		= BPF_MAP_TYPE_HASH,
	.key_size	= 16,
	.value_size	= sizeof(__u64),
	.max_entries	= 1024,
};

SEC("tracepoint/syscalls/sys_enter_execve")
int count_execve(void *ctx)
{
	char comm[16] = {};
	__u64 one = 1, *val;

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

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

And a loader that opens any object file and loads it, built twice, against 22.04’s libbpf 0.5 and against 1.0:

// loadobj.c — open and load any BPF object file, and report what libbpf says
#include <stdio.h>
#include <bpf/libbpf.h>

int main(int argc, char **argv)
{
	struct bpf_object *obj;
	int err;

	obj = bpf_object__open_file(argv[1], NULL);
	if (libbpf_get_error(obj)) {
		printf("%s: open failed\n", argv[1]);
		return 1;
	}
	err = bpf_object__load(obj);
	printf("%s: load %s (%d)\n", argv[1], err ? "failed" : "ok", err);
	bpf_object__close(obj);
	return err != 0;
}
# legacy map, built with 22.04's own headers; one loader per libbpf
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -c legacy.bpf.c -o legacy.bpf.o
cc -O2 loadobj.c -lbpf -o loadobj-0.5
cc -O2 -I/opt/libbpf-1.0/include loadobj.c /opt/libbpf-1.0/lib64/libbpf.a -lelf -lz -o loadobj-1.0
$ sudo ./loadobj-0.5 legacy.bpf.o
legacy.bpf.o: load ok (0)
$ sudo ./loadobj-1.0 legacy.bpf.o
libbpf: elf: legacy map definitions in 'maps' section are not supported by libbpf v1.0+
legacy.bpf.o: open failed

libbpf 1.0 doesn’t get as far as loading. It refuses the object when opening it, as soon as it finds the section, with a message that says exactly what is wrong. Compiling the same source against 1.0’s headers instead of 0.5’s gets a warning first, because 1.0 keeps the struct’s declaration only so that it can attach a deprecation message to it:

$ clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -I/opt/libbpf-1.0/include -c legacy.bpf.c -o legacy.bpf.o
legacy.bpf.c:5:8: warning: 'bpf_map_def' is deprecated: use BTF-defined maps in .maps section [-Wdeprecated-declarations]
struct bpf_map_def SEC("maps") counts = {
       ^
/opt/libbpf-1.0/include/bpf/bpf_helpers.h:173:18: note: 'bpf_map_def' has been explicitly marked deprecated here
} __attribute__((deprecated("use BTF-defined maps in .maps section")));
                 ^
1 warning generated.

The fix is mechanical, and Part 1’s version shows it: a struct of __uint and __type fields in SEC(".maps"). The BTF-defined form isn’t just newer syntax. Because the key and value are types rather than sizes, the map carries BTF, which is what lets bpftool print a map’s contents as structs and what lets maps hold spin locks, timers and the 5.19 kernel pointers, all of which the kernel only allows where it can see the value’s type.

bpftool moved along with it. Its 7.0.0 release, on 1 September, is built on libbpf 1.0 and started a new numbering: from now on bpftool’s major version is libbpf’s plus six, so 7.0 pairs with 1.0.

When the kernel has no BTF

All of this depends on /sys/kernel/btf/vmlinux. Ubuntu 22.04 has it, and so do most distributions released in the last two years. But Ubuntu 20.04’s 5.4 kernel was built without it, because the pahole in 20.04 was too old to generate it, and plenty of machines in service in 2022 run kernels like that. For them, libbpf can take the kernel’s BTF from a file instead: the btf_custom_path open option, added in libbpf 0.5, which is what taskstate’s -b sets. The file can be generated from the distribution’s debug-symbol package for that exact kernel build, with pahole, the same way the kernel build makes it.

Generating BTF for every kernel a tool might meet is a chore, so it has become a service: BTFHub, which Aqua Security started in 2021, collects BTF files for the released kernels of the common distributions that ship without it, generated from their debug packages. A full kernel’s BTF is several megabytes, though, and a tool only needs the handful of types its programs touch. This year bpftool learnt to cut one down: bpftool gen min_core_btf (merged in February, by Mauricio Vásquez) reads a kernel’s BTF and a BPF object and writes out only the types and fields the object’s CO-RE records refer to. For taskstate, on each kernel:

$ bpftool gen min_core_btf /sys/kernel/btf/vmlinux min-5.13.btf taskstate.bpf.o     # on 5.13
$ bpftool gen min_core_btf /sys/kernel/btf/vmlinux min-5.15.btf taskstate.bpf.o     # on 5.15.0-25
$ bpftool gen min_core_btf /sys/kernel/btf/vmlinux min-5.19.btf taskstate.bpf.o     # on 5.19
$ stat -c '%s %n' min-*.btf
247 min-5.13.btf
241 min-5.15.btf
241 min-5.19.btf
$ bpftool btf dump file min-5.13.btf
[1] INT 'char' size=1 bits_offset=0 nr_bits=8 encoding=(none)
[2] INT 'int' size=4 bits_offset=0 nr_bits=32 encoding=SIGNED
[3] INT 'long int' size=8 bits_offset=0 nr_bits=64 encoding=SIGNED
[4] VOLATILE '(anon)' type_id=3
[5] TYPEDEF '__kernel_pid_t' type_id=2
[6] TYPEDEF 'pid_t' type_id=5
[7] STRUCT 'task_struct' size=9472 vlen=3
	'state' type_id=4 bits_offset=192
	'pid' type_id=6 bits_offset=18688
	'comm' type_id=8 bits_offset=22464
[8] ARRAY '(anon)' type_id=1 index_type_id=2 nr_elems=16

Eight records and 247 bytes, against 5,186,588 for the whole of 5.13’s BTF: a task_struct with three members, the three the program reads, at 5.13’s offsets, and the types beneath them. Fed to taskstate -b on 5.13, it relocates exactly as the full BTF did. Files that small can be carried inside the tool, one per supported kernel, and chosen at start-up. On a kernel without BTF, a BTF-enabled tracepoint like taskstate’s still won’t attach, because the kernel itself needs its BTF for that, but kprobes and classic tracepoints with BPF_CORE_READ work, and that is what tools that support old kernels use.

The file has to describe the kernel the program runs on, exactly. Given the 5.13 file on a 5.19 kernel, libbpf relocated pid to 5.13’s offset without complaint, and it was the verifier, reading the real kernel’s types, that stopped it, as the box above showed.

Who needs what, and when

Put side by side, the two approaches differ in where the work happens. BCC does everything at the target, every time. CO-RE moves the compiling to the developer’s machine and leaves the target one cheap step, matching names against a table the kernel already holds:

BCC and CO-RE: who needs what, and when

The same tool, the scheduler-switch counter from this post, built and run both ways on Ubuntu 22.04.

developer's machine

1 · Write

BCC

C inside a Python string, written against kernel headers by name: prev->__state, prev->pid.

CO-RE

A .bpf.c file against vmlinux.h, generated once from one kernel's BTF. Flavours and existence checks for the fields that differ between kernels.

developer's machine

2 · Build

BCC

Nothing to build. The script is the product.

CO-RE

clang compiles the program once and records five relocations in .BTF.ext; the object, stripped of DWARF, is embedded in a skeleton and linked with a static libbpf.

object, with DWARF698,576 B
stripped30,848 B

target machine, installed

3 · What the target must have

BCC

BCC's Python bindings and library, its own LLVM and clang, and headers matching the running kernel exactly.

kernel headers96.7 MiB
LLVM 11 + clang 11123.5 MiB
libbpfcc + python3-bpfcc3.5 MiB

CO-RE

One executable, which needs libelf and zlib, and a kernel built with BTF.

taskstate, stripped307 KiB
kernel BTF (already in the kernel)4.9 MiB

target machine, every start

4 · Start

BCC

Rewrite the C, compile it against this machine's headers, load, attach.

launch to attached3.26 s (3.19–3.33)
peak memory97.3 MiB

CO-RE

Read /sys/kernel/btf/vmlinux, patch five instructions, load, attach.

launch to attached37.5 ms (27–38)
peak memory11.8 MiB

target machine, a kernel that renamed a field

5 · The kernel changes

BCC

The compiler, reading the new headers, rejects the old name. 22.04's own runqlat-bpfcc: no member named 'state' in 'struct task_struct'. The fix is a new release of the tool.

CO-RE

bpf_core_field_exists() becomes 0 or 1 at load time; the branch for the other kernel is poisoned and removed. The same binary ran on 5.13, 5.15 and 5.19.

Bars compare like with like within a row group: bytes with bytes, milliseconds with milliseconds. Start-up figures are the median of six starts, with the range; sizes are dpkg's installed sizes and file sizes on disk.

Measured on the same 5.15.0-25 machine, six starts each, alternating: the BCC version took a median of 3.26 seconds from launch to attached (3.19 to 3.33), of which about 2.4 was compiling, and peaked at about 97 MiB of memory. The CO-RE version took a median of 37.5 milliseconds (27 to 38) and peaked at under 12 MiB. On disk, BCC needed 224 MiB of packages on the target: 97 MiB of kernel headers, 124 MiB of LLVM and clang libraries, and 3.5 MiB of BCC itself. The CO-RE tool is one executable of 314,032 bytes once stripped, and the kernel BTF it reads was already there.

Take the ratio from those numbers, not the seconds. These starts ran from the virtual machine’s root filesystem, which is shared from the host, so every one of the hundreds of header files BCC reads at start-up crosses to the host and back. Part 3 timed BCC both ways: 3.1 seconds from that shared filesystem, 282 milliseconds from a copy in memory. On a real disk with a warm cache, expect the smaller order of magnitude, and the same gap between compiling at the target and not.

What we covered

  • A compiled BPF program reads kernel structures at fixed offsets, and those offsets differ between kernels: task_struct.pid is at byte 2,336, 2,384 and 2,496 on 5.13, 5.15 and 5.19. Fields also get renamed, as state became __state in 5.14.
  • BCC avoids the offset problem by compiling on the target against its headers, at the cost of a compiler, headers and seconds of CPU at every start, and renames still break its tools: 22.04’s runqlat-bpfcc fails on 22.04’s kernel.
  • BTF is a compact, deduplicated table of the kernel’s types, 119,957 records and about 5 MB on 5.15.0-25, exposed at /sys/kernel/btf/vmlinux since 5.4, with split BTF for modules since 5.11.
  • CO-RE has clang record each marked field access as a type and an access path in .BTF.ext, and libbpf match those records by name against the running kernel’s BTF and patch the offsets, existence checks, type checks and enum values into the instructions before loading.
  • One object built on 22.04 loaded and counted correctly on 5.13, 5.15 and 5.19. Where a field doesn’t exist, libbpf plants an invalid instruction, and the verifier removes it as dead code because an existence check guards it.
  • Skeletons give user space typed access to maps, programs and globals; .rodata set before load becomes a constant the verifier can prune on. The light skeleton (5.14) needs no libbpf, and for CO-RE needs the kernel to relocate (5.17).
  • libbpf 1.0 removed legacy bpf_map_def maps and the deprecated APIs, and made strict mode the only mode.
  • Kernels without BTF can use BTF from a file; bpftool gen min_core_btf cuts it to a few hundred bytes per kernel.

The next part goes to Windows, and to Microsoft’s port of eBPF, a year and a half after it was announced.

A note on the evidence

What I ran, and where. Every listing in this post is pasted from a real run. The machines were KVM virtual machines with 4 virtual CPUs and 4 GiB of memory, started with virtme-ng on a minimal Ubuntu 22.04 userland built from the release archive only: clang 14.0.0-1ubuntu1, BCC 0.18.0, and linux-headers-5.15.0-25-generic installed from the same archive for the BCC runs. The three kernels were Ubuntu 22.04’s release kernel, 5.15.0-25-generic #25-Ubuntu SMP Wed Mar 30 15:54:22 UTC 2022, and Ubuntu’s mainline builds 5.13.0-051300-generic and 5.19.0-051900-generic, built from the unmodified upstream releases. All three expose /sys/kernel/btf/vmlinux. libbpf v1.0.0 and bpftool v7.0.0 were built from their GitHub release tags inside that userland, by the commands shown; bpftool’s libbpf submodule was replaced by the v1.0.0 tarball, which differs from the commit it pins only in README.md. Every program was built once, on 5.15.0-25, and the same files were run on all three kernels. The C, Python and build commands in this post were extracted from the page and run as shown.

What I trimmed. ldd addresses (they change on every run), and the arguments of the two strace lines, cut to the ones that matter and marked .... libbpf’s debug log is reduced to its relocation lines, and the xlated listings to the instructions around the relocated ones. The llvm-objdump listing shows the relocated instructions and the ones that explain them, with ... where I cut. The skeleton struct is trimmed where marked. The verifier log in the box is its last four lines.

The measurements. The BCC and CO-RE start-up figures come from one run of six alternating pairs on 5.15.0-25 with no other virtual machine running: “ready” is wall-clock time from starting the process until its first line of output, which each prints after attaching; memory is the process’s VmHWM read at that moment. BCC’s compile time is its own measurement around BPF(), which also includes loading and attaching. Package sizes are dpkg’s Installed-Size. The taskstate counts are from a 2-second run on each kernel under a synthetic load; they show that the program works and classifies sensibly, not anything about the kernels. The DWARF sizes are readelf -S of the vmlinux in Ubuntu’s linux-image-unsigned-5.15.0-25-generic-dbgsym_5.15.0-25.25_amd64.ddeb, downloaded from ddebs.ubuntu.com.

What I cited rather than ran. The kernel versions in which features arrived (BTF 4.18, vmlinux BTF 5.2, /sys/kernel/btf/vmlinux 5.4, module BTF 5.11, the state rename 5.14, the light skeleton and BPF_PROG_TYPE_SYSCALL 5.14, kernel-side CO-RE 5.17, the sched_switch argument change 5.18) were checked by finding the first release tag that contains each introducing commit. The libbpf 1.0 and bpftool 7.0 changes are from their release notes and the v1.0.0 source tree. Ubuntu 20.04’s lack of BTF, BTFHub’s start in 2021, and the date of BCC’s core_fixes.bpf.h are from the projects’ own pages and repositories.

What I’d still change. Three kernels are a small sample, chosen to straddle one rename. A kernel with a different configuration of the same version would move offsets too, and the interesting test of CO-RE is a distribution kernel with options I didn’t choose. And the light skeleton deserves a part of its own once signed BPF programs, the use it was built for, are further along.

More