Maps Are the Only Memory You Get

Contents
A hash map with room for a million entries cost 77.0 MiB of kernel memory on Linux 5.19 the moment it was created, before a single key went in, while the memory figure bpftool printed for it said 15.3 MiB. Four CPUs adding one to the same counter in a map took 140 nanoseconds per increment; giving each CPU its own copy of the counter took 1.5 nanoseconds. And a program that handed one small event to user space paid 54.8 nanoseconds for it through a ring buffer told not to wake the reader, and 4,838 nanoseconds, nearly five microseconds, when it woke the reader every time.
A BPF program has no heap, no globals in the usual sense and a 512-byte stack that is gone when the program returns. Everything it remembers, everything it shares with another CPU and everything it tells user space goes through maps. This post goes through the map types one at a time, each with a small program that was run, and then measures the two ways a program has of streaming events out.
This is Part 5 of a series on eBPF, written for C programmers who know what a process, a system
call and a socket are, and nothing about kernel internals. Everything here ran on Linux 5.19,
released on 31 July, under Ubuntu 22.04’s own userland: clang 14, libbpf 0.5 and the bpftool from
linux-tools-5.15.0-25-generic. The output is pasted from those runs, not reconstructed. The note at
the end says exactly where and how.
Why a program needs maps at all
Part 1 counted execve() calls in a hash map, and
Part 2 read the
instructions that did it. The program had eleven registers and 512 bytes of stack below r10, and
both are scratch space: when the program returns, they are gone. The next run starts from nothing.
A BPF program cannot call malloc, cannot take a pointer to kernel memory it was not handed, and
cannot keep a static variable in the way a C program does. If it needs to know anything on its
next run, the knowledge has to live somewhere else.
That somewhere is a map. A map is a data structure that lives in the kernel, has a type, a key
size, a value size and a maximum number of entries fixed when it is created, and is reachable from
two sides: BPF programs reach it through helpers such as bpf_map_lookup_elem, and user space
reaches it through the bpf() system call. A lookup from a program returns a pointer straight into
the map’s memory, which the program can read and write in place. That makes a map three things at
once: the program’s long-term memory, the only way two runs of a program on different CPUs can see
each other’s work, and the main channel between the program and user space.
On 5.19 there are 30 map types. Most of them are specialised: references to sockets, to network devices, to CPUs for XDP redirects, to programs for tail calls. This post covers the general-purpose ones, the ones you choose between when you write a tool: hash, array, their per-CPU versions, LRU hash, longest-prefix-match trie, queue and stack, bloom filter, maps of maps, the maps behind global variables, and the two that exist to move events to user space.
What a map is, from the kernel’s side
A map comes into being with BPF_MAP_CREATE, which returns a file descriptor. Inside the kernel
there is a struct bpf_map with a pointer to a table of operations, one table per map type:
lookup, update, delete, get-next-key, and a few more that only some types have. Everything that
follows in this post is, one way or another, a difference between those tables.
The map lives as long as something refers to it. The descriptor is one reference. Every loaded
program that uses the map holds another, which is why bpftool prog show prints map_ids for each
program. A pin in the BPF filesystem holds a third.
Part 3 used pins to make
programs outlive their loader; maps work the same way. When the last reference goes, the map is
freed.
Who pays for it. Up to 5.10, the memory a map used was charged against the creating user’s
RLIMIT_MEMLOCK, the limit on locked memory, which is why every BPF tool of that era starts by
raising it, and why Part 1’s libbpf 0.5 printed a misleading hint about it. Since 5.11 the memory is
charged to the memory cgroup of the process that created the map, like any other kernel memory that
process causes to be allocated. A container that creates a huge map now pays for it out of its own
memory limit. The old number survives as the memlock line in /proc/<pid>/fdinfo/<fd>, which
bpftool prints, but on 5.19 it is only an estimate: the key size plus the value size, rounded up
to 8 bytes, times the maximum number of entries, rounded up to a page.
It is a poor estimate, and the easiest way to see how poor is to make a large map and ask the
cgroup. This program creates a hash map of a million 8-byte keys and 8-byte values, fills it with
one batch call, and then reads it back two ways. It uses libbpf’s low-level API, which wraps the
bpf() system call one command at a time, so there is no BPF program in it at all:
// bigmap.c — what a million-entry hash map costs, and how fast you can read it back
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <linux/bpf.h>
#include <bpf/bpf.h>
#define N 1000000
static long long memcg_bytes(void) /* memory.current of our own cgroup */
{
char path[256] = "/sys/fs/cgroup", line[200];
long long v = -1;
FILE *f = fopen("/proc/self/cgroup", "r");
if (f && fgets(line, sizeof(line), f)) { /* "0::/p05" */
line[strcspn(line, "\n")] = 0;
strcat(path, strchr(line, '/'));
strcat(path, "/memory.current");
}
if (f)
fclose(f);
f = fopen(path, "r");
if (f && fscanf(f, "%lld", &v) != 1)
v = -1;
if (f)
fclose(f);
return v;
}
static long memlock(int fd) /* what bpftool's "memlock" column shows */
{
char path[64], line[128];
long v = -1;
FILE *f;
snprintf(path, sizeof(path), "/proc/self/fdinfo/%d", fd);
f = fopen(path, "r");
while (f && fgets(line, sizeof(line), f))
if (sscanf(line, "memlock: %ld", &v) == 1)
break;
if (f)
fclose(f);
return v;
}
static double now(void)
{
struct timespec t;
clock_gettime(CLOCK_MONOTONIC, &t);
return t.tv_sec + t.tv_nsec / 1e9;
}
int main(int argc, char **argv)
{
int noprealloc = argc > 1 && !strcmp(argv[1], "noprealloc");
__u64 *keys = calloc(N, 8), *vals = calloc(N, 8), k, v, out = 0;
struct bpf_create_map_attr attr = {
.name = "big", .map_type = BPF_MAP_TYPE_HASH,
.key_size = 8, .value_size = 8, .max_entries = N,
.map_flags = noprealloc ? BPF_F_NO_PREALLOC : 0,
};
long long m0, m1, m2;
__u32 count, total = 0;
void *prev = NULL;
double t;
int fd, err;
for (k = 0; k < N; k++)
keys[k] = k, vals[k] = k * 3; /* touch the arrays before measuring */
m0 = memcg_bytes();
fd = bpf_create_map_xattr(&attr); /* BPF_MAP_CREATE */
if (fd < 0) {
perror("BPF_MAP_CREATE");
return 1;
}
m1 = memcg_bytes();
count = N;
t = now();
err = bpf_map_update_batch(fd, keys, vals, &count, NULL);
printf("%s: update_batch of %u entries: %s, %.1f ms\n",
noprealloc ? "BPF_F_NO_PREALLOC" : "preallocated", count,
err ? strerror(errno) : "ok", (now() - t) * 1e3);
m2 = memcg_bytes();
printf("cgroup memory: +%.1f MiB at create, +%.1f MiB more filled; memlock says %.1f MiB\n",
(m1 - m0) / 1048576.0, (m2 - m1) / 1048576.0, memlock(fd) / 1048576.0);
/* read it all back, the old way: two syscalls per entry */
t = now();
while (bpf_map_get_next_key(fd, prev, &k) == 0) {
bpf_map_lookup_elem(fd, &k, &v);
prev = &k;
total++;
}
printf("get_next_key + lookup: %u entries, %.1f ms\n", total, (now() - t) * 1e3);
/* and with BPF_MAP_LOOKUP_BATCH, up to 10,000 entries per syscall */
t = now();
total = 0;
for (prev = NULL;; prev = &out) {
count = 10000;
err = bpf_map_lookup_batch(fd, prev, &out, keys, vals, &count, NULL);
total += count;
if (err)
break; /* ENOENT: walked off the end */
}
printf("lookup_batch: %u entries, %.1f ms (%s)\n", total,
(now() - t) * 1e3, strerror(errno));
return 0;
}
I ran it from a shell placed in its own cgroup, so that memory.current counts only what it
causes, three times each way, with a pause between runs so that the previous map had been freed:
# echo +memory > /sys/fs/cgroup/cgroup.subtree_control
# mkdir /sys/fs/cgroup/p05 && echo $$ > /sys/fs/cgroup/p05/cgroup.procs
# ./bigmap prealloc
preallocated: update_batch of 1000000 entries: ok, 267.7 ms
cgroup memory: +77.0 MiB at create, +0.0 MiB more filled; memlock says 15.3 MiB
get_next_key + lookup: 1000000 entries, 528.1 ms
lookup_batch: 1000000 entries, 167.7 ms (No such file or directory)
# ./bigmap noprealloc
BPF_F_NO_PREALLOC: update_batch of 1000000 entries: ok, 275.0 ms
cgroup memory: +16.0 MiB at create, +68.6 MiB more filled; memlock says 15.3 MiB
get_next_key + lookup: 1000000 entries, 523.8 ms
lookup_batch: 1000000 entries, 165.3 ms (No such file or directory)
The last line of each run ends with No such file or directory: that is ENOENT, the batch call’s
way of saying it has walked off the end of the map, not an error.
Take the preallocated map first. The kernel allocated 77.0 MiB when the map was created
and not a byte more when it was filled. The 15.3 MiB that memlock reports is the
16 bytes of key and value times a million. What the estimate leaves out is how a hash map is built.
Each element carries a 48-byte header in front of its key (list links for the bucket, the hash,
and room for LRU and free-list bookkeeping), so a 16-byte entry occupies 64 bytes. There are
slightly more elements than max_entries, one spare per possible CPU, so that an update can always
find a free element. And there is the bucket array: the number of entries rounded up to a power of
two, 1,048,576 buckets of 16 bytes each, 16 MiB. 64 bytes times a million plus 16 MiB is 77 MiB.
The 48-byte header is the one Part 1 met in the rewritten lookup, r0 += 64, which stepped over the
header and a 16-byte key to reach the value.
Preallocation, and why it is the default. A hash map allocates every element up front unless you
ask it not to, because a program can run where allocating memory is not safe. The commit that made
preallocation the default, in 4.6, gives the example: a kprobe on spin_unlock inside the slab
allocator fires while the allocator holds a lock, the program updates a map, the update calls
kmalloc, and kmalloc waits for the lock its own caller holds. With every element allocated in
advance, an update takes an element from a free list and never calls the allocator. The price is
memory spent on entries that may never be used. BPF_F_NO_PREALLOC turns it off: the bucket array
is allocated at creation (the 16.0 MiB above) and each element is allocated when
it is inserted (the 68.6 MiB that arrived during the fill). That is 72 bytes per
entry, not 64: memory-cgroup accounting charges each slab object its size plus the 8-byte pointer
the kernel keeps to know which cgroup to credit when the object is freed. For a map that is usually
mostly empty, no-prealloc is the right choice. For a map that a tracing program updates from
anywhere, preallocation is the safe one. Some types decide for you: an LRU hash is always
preallocated, and an LPM trie must be created with BPF_F_NO_PREALLOC.
Reading it back. The other half of the output is about getting data out. Part 1 walked its map
with bpf_map_get_next_key and bpf_map_lookup_elem, two system calls per entry. For a million
entries that took 521–547 ms. BPF_MAP_LOOKUP_BATCH, added in 5.6, copies many entries per call:
here 10,000 at a time, about a hundred calls in all, in 161–181 ms. The batch walk is not free of cost
either: the kernel still copies every key and value out under the bucket locks. But it removes
two million round trips across the system-call boundary, and anything that reads a large map
periodically, such as a monitoring agent exporting counters, should use it.
bpf_create_map_xattr is the libbpf 0.5 name for the create call. libbpf 0.6 added
bpf_map_create() with an options struct, the old functions have since been deprecated, and libbpf 1.0,
which is expected any day now, removes them. On Ubuntu 22.04 the old name is the one there is.
Hash and array: what the verifier does to a lookup
In Part 1, the kernel’s copy of the program did not call the helper the C code called. The verifier
knew at load time which map the lookup would touch, replaced the generic bpf_map_lookup_elem
with the hash table’s own lookup function, and inlined the step from the element to its value. How
much of a lookup can be inlined depends on the map type, and it is the clearest view there is of
how the types differ. Here is the same lookup, of key 3, against five kinds of map:
// lookups.bpf.c — the same lookup against five kinds of map
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#define MAP(kind, name) \
struct { \
__uint(type, kind); \
__uint(max_entries, 16); \
__type(key, __u32); \
__type(value, __u64); \
} name SEC(".maps")
MAP(BPF_MAP_TYPE_HASH, hash);
MAP(BPF_MAP_TYPE_ARRAY, array);
MAP(BPF_MAP_TYPE_PERCPU_ARRAY, pcpu);
MAP(BPF_MAP_TYPE_LRU_HASH, lru);
struct inner {
__uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, 16);
__type(key, __u32);
__type(value, __u64);
} inner0 SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_ARRAY_OF_MAPS);
__uint(max_entries, 4);
__type(key, __u32);
__array(values, struct inner);
} outer SEC(".maps") = { .values = { &inner0 } };
static __always_inline int get(void *map)
{
__u32 key = 3;
__u64 *val = bpf_map_lookup_elem(map, &key);
return val ? *val : 0;
}
SEC("xdp") int on_hash(struct xdp_md *ctx) { return get(&hash); }
SEC("xdp") int on_array(struct xdp_md *ctx) { return get(&array); }
SEC("xdp") int on_pcpu(struct xdp_md *ctx) { return get(&pcpu); }
SEC("xdp") int on_lru(struct xdp_md *ctx) { return get(&lru); }
SEC("xdp") int on_outer(struct xdp_md *ctx)
{
__u32 slot = 0;
void *in = bpf_map_lookup_elem(&outer, &slot);
return in ? get(in) : 0;
}
char LICENSE[] SEC("license") = "GPL";
__array(values, struct inner) declares a map of maps: outer is an array whose values are other
maps, here pre-populated with inner0 in slot 0. The get() helper is __always_inline, so each
program contains its own copy of the lookup with a constant map pointer, exactly what the verifier
needs to specialise it.
Every program is in a section called xdp. The type does not matter, since nothing is attached;
these programs only need to be loaded so the kernel’s version of them can be read. bpftool can load
an object and pin its programs (bpftool prog loadall), but the bpftool in Ubuntu 22.04 names each
pin after the program’s section, so five programs in one section collide. A twenty-line loader is
simpler. It loads every program in an object, prints their IDs and keeps them loaded for a while:
// hold.c — load every program in a BPF object, print their ids, keep them loaded a while
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
int main(int argc, char **argv)
{
struct bpf_object *obj;
struct bpf_program *prog;
if (argc < 2) {
fprintf(stderr, "usage: %s file.bpf.o [seconds]\n", argv[0]);
return 1;
}
obj = bpf_object__open_file(argv[1], NULL);
if (libbpf_get_error(obj) || bpf_object__load(obj))
return 1; /* libbpf has already printed the verifier's log */
bpf_object__for_each_program(prog, obj) {
struct bpf_prog_info info = {};
__u32 len = sizeof(info);
bpf_obj_get_info_by_fd(bpf_program__fd(prog), &info, &len);
printf("%s id %u\n", bpf_program__name(prog), info.id);
}
fflush(stdout);
sleep(argc > 2 ? atoi(argv[2]) : 30);
bpf_object__close(obj);
return 0;
}
Built with the commands at the end of the next section, run with ./hold lookups.bpf.o 4 &, and
read with bpftool while it waits. First the summary:
$ sudo bpftool prog show
4: xdp name on_hash tag 7003e4a9ff8df9a3 gpl
[loaded_at line trimmed]
xlated 112B jited 74B memlock 4096B map_ids 4
5: xdp name on_array tag 7003e4a9ff8df9a3 gpl
[loaded_at line trimmed]
xlated 144B jited 87B memlock 4096B map_ids 5
6: xdp name on_pcpu tag 7003e4a9ff8df9a3 gpl
[loaded_at line trimmed]
xlated 96B jited 65B memlock 4096B map_ids 6
7: xdp name on_lru tag 7003e4a9ff8df9a3 gpl
[loaded_at line trimmed]
xlated 136B jited 88B memlock 4096B map_ids 7
8: xdp name on_outer tag 8836cdbb61d61893 gpl
[loaded_at line trimmed]
xlated 264B jited 145B memlock 4096B map_ids 3
The four single lookups have the same tag. A program’s tag is a hash of its instructions as loaded, with the map references blanked out, and as far as the instructions go these four programs are identical: load a map, look up key 3. Their sizes after verification differ, from 96 to 144 bytes of BPF, because the verifier turned the same call into four different things.
The hash map:
$ sudo bpftool prog dump xlated name on_hash
int on_hash(struct xdp_md * ctx):
; SEC("xdp") int on_hash(struct xdp_md *ctx) { return get(&hash); }
0: (b7) r1 = 3
; __u32 key = 3;
1: (63) *(u32 *)(r10 -4) = r1
2: (bf) r2 = r10
;
3: (07) r2 += -4
; __u64 *val = bpf_map_lookup_elem(map, &key);
4: (18) r1 = map[id:4]
6: (85) call __htab_map_lookup_elem#199552
7: (15) if r0 == 0x0 goto pc+1
8: (07) r0 += 56
9: (bf) r1 = r0
10: (b7) r0 = 0
; return val ? *val : 0;
11: (15) if r1 == 0x0 goto pc+1
; return val ? *val : 0;
12: (79) r0 = *(u64 *)(r1 +0)
; SEC("xdp") int on_hash(struct xdp_md *ctx) { return get(&hash); }
13: (95) exit
This is Part 1’s rewrite again: a direct call to __htab_map_lookup_elem, which hashes the key and
walks the bucket, followed by two inlined instructions that step from the element to the value. The
offset is 56 this time, not 64: the 48-byte header plus a 4-byte key rounded up to 8.
The array:
$ sudo bpftool prog dump xlated name on_array
int on_array(struct xdp_md * ctx):
; SEC("xdp") int on_array(struct xdp_md *ctx) { return get(&array); }
0: (b7) r1 = 3
; __u32 key = 3;
1: (63) *(u32 *)(r10 -4) = r1
2: (bf) r2 = r10
;
3: (07) r2 += -4
; __u64 *val = bpf_map_lookup_elem(map, &key);
4: (18) r1 = map[id:5]
6: (07) r1 += 272
7: (61) r0 = *(u32 *)(r2 +0)
8: (35) if r0 >= 0x10 goto pc+3
9: (67) r0 <<= 3
10: (0f) r0 += r1
11: (05) goto pc+1
12: (b7) r0 = 0
13: (bf) r1 = r0
14: (b7) r0 = 0
; return val ? *val : 0;
15: (15) if r1 == 0x0 goto pc+1
; return val ? *val : 0;
16: (79) r0 = *(u64 *)(r1 +0)
; SEC("xdp") int on_array(struct xdp_md *ctx) { return get(&array); }
17: (95) exit
No call at all. An array’s key is an index, so a lookup is arithmetic: instruction 6 steps from the
struct bpf_array to its first value (272 bytes in), 7 loads the index from the stack, 8 checks it
against max_entries (16, so 0x10), 9 multiplies it by the value size (shift by 3 is times 8) and
10 adds it to the base. An out-of-range index produces NULL at 12, which is why the C code still
has to check the result: the verifier cannot know what index will arrive. An array is also
preallocated by nature, every entry exists from the start, zero-filled, and entries cannot be
deleted, only overwritten. When the keys are small dense integers, an array is strictly cheaper than
a hash.
The per-CPU array:
$ sudo bpftool prog dump xlated name on_pcpu
int on_pcpu(struct xdp_md * ctx):
; SEC("xdp") int on_pcpu(struct xdp_md *ctx) { return get(&pcpu); }
0: (b7) r1 = 3
; __u32 key = 3;
1: (63) *(u32 *)(r10 -4) = r1
2: (bf) r2 = r10
;
3: (07) r2 += -4
; __u64 *val = bpf_map_lookup_elem(map, &key);
4: (18) r1 = map[id:6]
6: (85) call percpu_array_map_lookup_elem#215424
7: (bf) r1 = r0
8: (b7) r0 = 0
; return val ? *val : 0;
9: (15) if r1 == 0x0 goto pc+1
; return val ? *val : 0;
10: (79) r0 = *(u64 *)(r1 +0)
; SEC("xdp") int on_pcpu(struct xdp_md *ctx) { return get(&pcpu); }
11: (95) exit
A call, not inlined. Each CPU has its own copy of every value, and finding this CPU’s copy needs the kernel’s per-CPU offset, which 5.19 does not inline for this map type. The call is still cheap, since it does no hashing, as the measurements below show.
The LRU hash:
$ sudo bpftool prog dump xlated name on_lru
int on_lru(struct xdp_md * ctx):
; SEC("xdp") int on_lru(struct xdp_md *ctx) { return get(&lru); }
0: (b7) r1 = 3
; __u32 key = 3;
1: (63) *(u32 *)(r10 -4) = r1
2: (bf) r2 = r10
;
3: (07) r2 += -4
; __u64 *val = bpf_map_lookup_elem(map, &key);
4: (18) r1 = map[id:7]
6: (85) call __htab_map_lookup_elem#199552
7: (15) if r0 == 0x0 goto pc+4
8: (71) r1 = *(u8 *)(r0 +35)
9: (55) if r1 != 0x0 goto pc+1
10: (72) *(u8 *)(r0 +35) = 1
11: (07) r0 += 56
12: (bf) r1 = r0
13: (b7) r0 = 0
; return val ? *val : 0;
14: (15) if r1 == 0x0 goto pc+1
; return val ? *val : 0;
15: (79) r0 = *(u64 *)(r1 +0)
; SEC("xdp") int on_lru(struct xdp_md *ctx) { return get(&lru); }
16: (95) exit
The same hash lookup, plus three inlined instructions that are the whole of the LRU’s bookkeeping on the fast path: if the byte at offset 35 of the element, its “referenced” bit, is still zero, set it to one. Checking before writing matters: a lookup that always wrote would dirty the cache line on every hit, and other CPUs reading the same hot element would pay for it. The section on LRU maps shows what the bit is for.
And the map of maps:
$ sudo bpftool prog dump xlated name on_outer
int on_outer(struct xdp_md * ctx):
; SEC("xdp") int on_outer(struct xdp_md *ctx)
0: (b7) r6 = 0
; __u32 slot = 0;
1: (63) *(u32 *)(r10 -8) = r6
2: (bf) r2 = r10
;
3: (07) r2 += -8
; void *in = bpf_map_lookup_elem(&outer, &slot);
4: (18) r1 = map[id:3]
6: (07) r1 += 272
7: (61) r0 = *(u32 *)(r2 +0)
8: (35) if r0 >= 0x4 goto pc+5
9: (67) r0 <<= 3
10: (0f) r0 += r1
11: (79) r0 = *(u64 *)(r0 +0)
12: (15) if r0 == 0x0 goto pc+1
13: (05) goto pc+1
14: (b7) r0 = 0
; return in ? get(in) : 0;
15: (15) if r0 == 0x0 goto pc+15
16: (b7) r1 = 3
; __u32 key = 3;
17: (63) *(u32 *)(r10 -4) = r1
18: (bf) r2 = r10
;
19: (07) r2 += -4
; __u64 *val = bpf_map_lookup_elem(map, &key);
20: (bf) r1 = r0
21: (07) r1 += 272
22: (61) r0 = *(u32 *)(r2 +0)
23: (35) if r0 >= 0x10 goto pc+3
24: (67) r0 <<= 3
25: (0f) r0 += r1
26: (05) goto pc+1
27: (b7) r0 = 0
28: (b7) r6 = 0
; return val ? *val : 0;
29: (15) if r0 == 0x0 goto pc+1
; return val ? *val : 0;
30: (79) r6 = *(u64 *)(r0 +0)
; return in ? get(in) : 0;
31: (bf) r0 = r6
32: (95) exit
Two inlined array lookups in a row. Instructions 4 to 10 are the array arithmetic on outer; 11
loads the pointer stored in that slot, which is the inner map; 20 to 25 are the array arithmetic
again, on whatever map that pointer turned out to be. The verifier allowed the second inlining
because every map stored in outer has to match the template it was created with, inner0’s type
and sizes. The point of a map of maps is that user space can build a new inner map off to the side
and swap it into the slot with one update, replacing a whole table atomically as far as the program
is concerned, which is how load balancers and firewalls change their configuration without a
half-updated state ever being visible.
One message from the loader is worth knowing about:
libbpf: Error in bpf_create_map_xattr(outer):Invalid argument(-22). Retrying without BTF.
libbpf 0.5 sends type information for the map’s key but none for its value, because the value is a map; the 5.19 kernel accepts type information only if it covers both, and refuses. libbpf retries without any, and the map works. It is noise, not a failure.
Which map for which job
The general-purpose map types on Linux 5.19. Pick a job to see which types fit it.
Any fixed-size key to a value.
- memory
- preallocated by default;
BPF_F_NO_PREALLOCallocates per insert - lookup on 5.19
- direct call to
__htab_map_lookup_elem, value offset inlined - measured
- 1M entries: 77 MiB at creation; memlock said 15.3 MiB
Index 0 … max_entries−1 to a value. Every entry exists, zeroed; no delete.
- memory
- always allocated at creation
- lookup on 5.19
- fully inlined: bounds check, shift, add; no call
- measured
- atomic add on 4 CPUs: 42 ns
A separate value per CPU under each key. No sharing, so no atomics.
- memory
- value size × possible CPUs per entry
- lookup on 5.19
- call (this CPU's copy needs the per-CPU offset)
- measured
- increment on 4 CPUs: 1.5 ns, against 139.8 ns shared
A hash that evicts the least recently used entries when full.
- memory
- always preallocated; evicts in batches
- lookup on 5.19
- hash call plus an inlined "referenced" bit
- measured
- sized 1,000: held 873–1000; looked-up keys survived
Longest-prefix match: key is a prefix length plus data, such as an IP address.
- memory
- must be
BPF_F_NO_PREALLOC - lookup on 5.19
- call; walks the trie
- measured
- 10.1.9.9 matched 10.1.0.0/16 over /8
No keys: push, pop, peek. Full means E2BIG unless pushed with BPF_EXIST.
- memory
- preallocated
- helpers
bpf_map_push_elem,pop,peek- measured
- queue 1 2 3 4, stack 4 3 2 1
"No" or "maybe": never a false no, sometimes a false maybe.
- memory
- bits = entries × hashes × 7/5, to a power of two
- helpers
- push to add, peek to test
- measured
- 0.318–0.325% false maybes (theory 0.32%); absent on 5.15
One buffer shared by all CPUs; reserve, write in place, submit.
- memory
- one power-of-two area, shared
- order
- records delivered in reservation order
- measured
- 1 producer, no wakeups: 54.8 ns per event
One perf ring per CPU; bpf_perf_event_output copies a record in.
- memory
- a ring per possible CPU, used or not
- order
- per CPU only
- measured
- 4 producers, wake every 64th: 15.14 M events/s
Values are other maps. Build a new inner map, then swap it in with one update.
- memory
- inner maps are separate objects
- lookup on 5.19
- array of maps: inlined, then the inner lookup
Global variables: each section is a one-entry array, mmap-able since 5.5.
- access
- a plain load from the program, a plain store from user space
- .rodata
- frozen, so the verifier removes branches it switches off
- measured
- one program, three modes: 272 / 432 / 488 bytes
Versions are the first mainline release containing the commit that added each type. "Lookup on 5.19" is what the verifier turned bpf_map_lookup_elem into, read with bpftool prog dump xlated. Green notes are measurements from this post, in an 8-vCPU virtual machine.
Many CPUs, one counter
The program in Part 1 incremented its counter with __sync_fetch_and_add, an atomic add, because
the same program can be running on several CPUs at the same moment. What does that atomic cost, and
what happens without it? The way to find out is to run the same few instructions on several CPUs
at once and count.
BPF_PROG_TEST_RUN, added in 4.12, runs a loaded program on demand: the caller hands it an input
(for XDP, a packet) and a repeat count, the kernel runs the program that many times in a loop on the
calling CPU, and reports the average time per run. Call it from several threads pinned to different
CPUs and you have the same program hammering the same map from several CPUs, with nothing else in
the way. Six programs, each counting differently:
// counter.bpf.c — six ways to count, one per program
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
struct locked {
struct bpf_spin_lock lock;
__u64 n;
};
#define MAP(kind, name, val) \
struct { \
__uint(type, kind); \
__uint(max_entries, 1); \
__type(key, __u32); \
__type(value, val); \
} name SEC(".maps")
MAP(BPF_MAP_TYPE_HASH, hash, __u64);
MAP(BPF_MAP_TYPE_ARRAY, array, __u64);
MAP(BPF_MAP_TYPE_ARRAY, locked, struct locked);
MAP(BPF_MAP_TYPE_PERCPU_ARRAY, pcpu, __u64);
SEC("xdp") int nothing(struct xdp_md *ctx)
{
return XDP_PASS;
}
SEC("xdp") int hash_plain(struct xdp_md *ctx)
{
__u32 key = 0;
__u64 *n = bpf_map_lookup_elem(&hash, &key);
if (n)
*n += 1; /* load, add, store */
return XDP_PASS;
}
SEC("xdp") int hash_atomic(struct xdp_md *ctx)
{
__u32 key = 0;
__u64 *n = bpf_map_lookup_elem(&hash, &key);
if (n)
__sync_fetch_and_add(n, 1); /* lock xadd */
return XDP_PASS;
}
SEC("xdp") int array_atomic(struct xdp_md *ctx)
{
__u32 key = 0;
__u64 *n = bpf_map_lookup_elem(&array, &key);
if (n)
__sync_fetch_and_add(n, 1);
return XDP_PASS;
}
SEC("xdp") int spin_lock(struct xdp_md *ctx)
{
__u32 key = 0;
struct locked *l = bpf_map_lookup_elem(&locked, &key);
if (l) {
bpf_spin_lock(&l->lock);
l->n++;
bpf_spin_unlock(&l->lock);
}
return XDP_PASS;
}
SEC("xdp") int percpu(struct xdp_md *ctx)
{
__u32 key = 0;
__u64 *n = bpf_map_lookup_elem(&pcpu, &key);
if (n)
*n += 1; /* this CPU's own copy */
return XDP_PASS;
}
char LICENSE[] SEC("license") = "GPL";
hash_plain and hash_atomic differ only in how they add: a load, an add and a store, against one
locked instruction. array_atomic is the same atomic on an array, to separate the cost of the map
type from the cost of sharing. spin_lock puts a struct bpf_spin_lock in the map value and takes
it around the increment. percpu gives every CPU its own counter. nothing measures the loop
itself.
The harness starts one thread per CPU, pins each to its own CPU, releases them together, and when they are done reads the counter back and compares it with the number of runs:
The build, for this program and every other one in this post:
bpftool btf dump file /sys/kernel/btf/vmlinux format c > vmlinux.h
for p in lookups locktp counter lru bufbench; do
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -c $p.bpf.c -o $p.bpf.o
done
for p in counter lru bufbench; do
bpftool gen skeleton $p.bpf.o > $p.skel.h
done
for p in hold counter lru bufbench bigmap zoo; do
cc -g -O2 -Wall $p.c -lbpf -lelf -lz -lpthread -o $p
done
I ran each program on 1, 2, 4 and 8 CPUs, a million runs per CPU, in a virtual machine with 8 virtual CPUs and nothing else running. The whole matrix was repeated five times, with the order of the programs rotated each round. One round on four CPUs looked like this:
nothing cpus 4 runs 4000000 counted 4000000 lost 0 1.0 ns/run 1569.6 M runs/s
hash_plain cpus 4 runs 4000000 counted 1857987 lost 2142013 50.0 ns/run 76.7 M runs/s
hash_atomic cpus 4 runs 4000000 counted 4000000 lost 0 139.8 ns/run 27.8 M runs/s
array_atomic cpus 4 runs 4000000 counted 4000000 lost 0 45.0 ns/run 81.5 M runs/s
spin_lock cpus 4 runs 4000000 counted 4000000 lost 0 522.0 ns/run 7.6 M runs/s
percpu cpus 4 runs 4000000 counted 4000000 lost 0 1.5 ns/run 1641.9 M runs/s
The results figure further down, in the section on buffers, has the ranges as well. The medians of the five rounds, in nanoseconds per run:
| program | 1 CPU | 2 CPUs | 4 CPUs | 8 CPUs | increments lost on 8 |
|---|---|---|---|---|---|
| nothing (the loop) | 1.0 | 1.0 | 1.0 | 1.0 | 0 |
| hash, plain add | 5.0 | 20 | 49 | 116 | 77.9% |
| hash, atomic add | 7.0 | 46 | 140 | 285 | 0 |
| array, atomic add | 5.0 | 18 | 42 | 88 | 0 |
array, bpf_spin_lock | 15 | 145 | 522 | 1087 | 0 |
| per-CPU array | 2.0 | 2.0 | 1.5 | 1.4 | 0 |
Three things stand out.
The plain add loses counts, and a lot of them. With one CPU, hash_plain is exact. With two or
more, two CPUs read the same value, both add one, both store, and one increment vanishes. On four
CPUs, 54.5% of the increments were lost, on eight, 77.9%. There is no warning
and nothing in the verifier can catch it: the program is perfectly safe, just wrong. On several CPUs it
is cheaper than the atomic version, and the saving buys nothing but a wrong answer.
Sharing is the cost, not the map type. On one CPU an atomic add costs a couple of nanoseconds
more than a plain one. On four, hash_atomic costs 140 ns and array_atomic 42 ns: the
array saves the hashing, but both spend their time waiting for the one cache line holding the
counter to travel from CPU to CPU. Adding CPUs makes every increment slower, so the total rate
barely moves: 125 million increments a second on one CPU,
27 million on eight.
Per-CPU counters scale. percpu costs 2.0 ns on one CPU and 1.4 on eight,
because no two CPUs ever touch the same cache line, and the total rate grows with the number of CPUs.
(The kernel reports the average in whole nanoseconds, so at this size the figures are at the limit of
what it can resolve; the point is that they do not grow.)
This is what per-CPU maps (hash and array, both in 4.6) are for: statistics that are written far more
often than they are read. The price is memory, a copy per possible CPU, and a little arithmetic in
whoever reads them.
bpf_spin_lock is the slowest of all, 522 ns on four CPUs, because each increment
now takes a lock, changes the value and releases it, while every other CPU spins on the same cache
line waiting for its turn. It arrived in 5.1, and it is not for counters. It is for values bigger than
one atomic instruction can update, such as a pair of fields that must change together, where the
alternative is a torn read. The verifier enforces strict rules around it: one lock held at a time,
no helper calls while holding it, unlock on every path, and the lock only in a hash, array, or one
of the local-storage maps. And on 5.19, not in tracing programs at all. Here is the same locked
counter on a tracepoint:
// locktp.bpf.c — a spin-locked counter in a tracing program
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
struct locked {
struct bpf_spin_lock lock;
__u64 n;
};
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, 1);
__type(key, __u32);
__type(value, struct locked);
} total SEC(".maps");
SEC("tracepoint/syscalls/sys_enter_getppid")
int count(void *ctx)
{
__u32 key = 0;
struct locked *l = bpf_map_lookup_elem(&total, &key);
if (l) {
bpf_spin_lock(&l->lock);
l->n++;
bpf_spin_unlock(&l->lock);
}
return 0;
}
char LICENSE[] SEC("license") = "GPL";
$ ./hold locktp.bpf.o 1
tracing progs cannot use bpf_spin_lock yet
processed 0 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0
libbpf: failed to load program 'count'
libbpf: failed to load object 'locktp.bpf.o'
The verifier rejects it before looking at a single instruction (“processed 0 insns”). The check is
on the program type: socket filters, tracing programs and sleepable programs cannot take a BPF spin
lock on this kernel. Networking programs, like the XDP one above, can. User space can join in from
its side with the BPF_F_LOCK flag (also 5.1) on lookup and update, which copies a value under
its lock so that it never sees half of an update.
LRU hash: a map that forgets
A plain hash map that is full refuses new keys: bpf_map_update_elem returns -E2BIG, and the
program has to decide what to do. For a cache, such as a table of recently seen connections, the
right behaviour is to forget the entry that has gone unused longest. That is the LRU hash (4.10).
The demonstration inserts 10,000 different keys, one per run, into an LRU hash and a plain hash, both sized for 1,000 entries. The key to insert comes from user space through a global variable, which, as a later section explains, is itself a map. A second variable decides whether each run also looks up keys 0 to 9, to keep them warm:
// lru.bpf.c — insert one key per run into an LRU hash and a plain hash, both sized 1,000
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#define MAP(kind, name) \
struct { \
__uint(type, kind); \
__uint(max_entries, 1000); \
__type(key, __u32); \
__type(value, __u32); \
} name SEC(".maps")
MAP(BPF_MAP_TYPE_LRU_HASH, lru);
MAP(BPF_MAP_TYPE_HASH, plain);
__u32 next_key; /* .bss: user space writes it through mmap */
__u32 touch_hot; /* 1: look up keys 0-9 on every run */
__u32 plain_full; /* inserts the plain hash refused */
SEC("xdp")
int insert(struct xdp_md *ctx)
{
__u32 key = next_key;
if (touch_hot)
for (int i = 0; i < 10; i++) {
__u32 hot = i;
bpf_map_lookup_elem(&lru, &hot);
}
bpf_map_update_elem(&lru, &key, &key, BPF_ANY);
if (bpf_map_update_elem(&plain, &key, &key, BPF_ANY))
plain_full++;
return XDP_PASS;
}
char LICENSE[] SEC("license") = "GPL";
// lru.c — push 10,000 keys through the 1,000-entry maps and see what survives
#include <stdio.h>
#include <stdlib.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "lru.skel.h"
static void survey(const char *what, int fd)
{
__u32 key, *prev = NULL, n = 0, lo = ~0u, hi = 0, hot = 0;
while (bpf_map_get_next_key(fd, prev, &key) == 0) {
n++;
if (key < lo) lo = key;
if (key > hi) hi = key;
if (key < 10) hot++;
prev = &key;
}
printf(" %-6s %4u entries, oldest key %u, newest %u, keys 0-9 present: %u\n",
what, n, lo, hi, hot);
}
int main(int argc, char **argv)
{
for (int touch = 0; touch <= 1; touch++) {
struct lru_bpf *skel = lru_bpf__open_and_load();
char pkt[64] = {};
DECLARE_LIBBPF_OPTS(bpf_test_run_opts, opts,
.data_in = pkt, .data_size_in = sizeof(pkt), .repeat = 1);
int fd;
if (!skel)
return 1;
fd = bpf_program__fd(skel->progs.insert);
skel->bss->touch_hot = touch;
for (__u32 k = 0; k < 10000; k++) {
skel->bss->next_key = k; /* a plain store into the map */
bpf_prog_test_run_opts(fd, &opts);
}
printf("touch_hot=%d, 10000 keys inserted:\n", touch);
survey("lru", bpf_map__fd(skel->maps.lru));
survey("plain", bpf_map__fd(skel->maps.plain));
printf(" plain hash refused %u inserts\n", skel->bss->plain_full);
lru_bpf__destroy(skel);
}
return 0;
}
Run on one CPU, taskset -c 0 ./lru:
touch_hot=0, 10000 keys inserted:
lru 888 entries, oldest key 9112, newest 9999, keys 0-9 present: 0
plain 1000 entries, oldest key 0, newest 999, keys 0-9 present: 10
plain hash refused 9000 inserts
touch_hot=1, 10000 keys inserted:
lru 888 entries, oldest key 0, newest 9999, keys 0-9 present: 10
plain 1000 entries, oldest key 0, newest 999, keys 0-9 present: 10
plain hash refused 9000 inserts
The plain hash kept the first 1,000 keys and refused the other 9,000 inserts. The LRU hash accepted
every insert and kept only recent keys: without the lookups, the oldest key left is 9,112, so keys 0
to 9 were long gone. With the lookups, keys 0 to 9 survived 9,990 later inserts, while nearly
everything inserted after them was evicted. Those lookups set the referenced bit seen in the xlated
listing, and the eviction code gives a referenced element a second chance: it moves it back to the
active list and clears the bit, instead of evicting it.
The LRU map holds 888 entries, not 1,000. An LRU hash does not evict one element at a
time. Each CPU keeps a small local list of free elements, and when that list runs dry the CPU
reclaims a batch, up to 128 elements in 5.19’s bpf_lru_list.c, from the cold end of the shared
list. Counting the entries after every one of the 10,000 inserts, the population after the first
1,000 never went below 873 or above 1,000. An LRU map sized for exactly the number of
entries you need will hold fewer than that most of the time. Size it with some slack.
The batching is also why the LRU has two flavours. By default the free and LRU lists are shared by
all CPUs, with per-CPU caches in front. BPF_F_NO_COMMON_LRU gives each CPU entirely separate lists
instead, which avoids the shared lock but means each CPU can only use its share of max_entries.
And there is BPF_MAP_TYPE_LRU_PERCPU_HASH (also 4.10), where every entry has a value per CPU, the
LRU equivalent of the per-CPU hash.
The other shapes: prefixes, queues and a bloom filter
Hashes and arrays answer “what is stored under this exact key?”. Three other types answer different questions, and all three can be driven entirely from user space, which makes them easy to try:
// zoo.c — four map types that are not key-to-value tables, driven from user space
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <linux/bpf.h>
#include <bpf/bpf.h>
#ifndef BPF_MAP_TYPE_BLOOM_FILTER
#define BPF_MAP_TYPE_BLOOM_FILTER 30 /* new in 5.16; jammy's headers are 5.15's */
#endif
static int make(const char *name, int type, int key, int value, int entries, int flags)
{
struct bpf_create_map_attr a = {
.name = name, .map_type = type, .key_size = key,
.value_size = value, .max_entries = entries, .map_flags = flags,
};
int fd = bpf_create_map_xattr(&a);
if (fd < 0)
printf("%s: BPF_MAP_CREATE failed: %s\n", name, strerror(errno));
return fd;
}
struct v4key {
__u32 prefixlen;
__u8 addr[4];
};
static void route(int fd, __u8 a, __u8 b, __u8 c, __u8 d)
{
struct v4key k = { 32, { a, b, c, d } };
__u32 v;
if (bpf_map_lookup_elem(fd, &k, &v) == 0)
printf(" %u.%u.%u.%u -> route %u\n", a, b, c, d, v);
else
printf(" %u.%u.%u.%u -> no route\n", a, b, c, d);
}
int main(void)
{
int lpm, q, s, bloom;
__u32 v, missed = 0, false_pos = 0;
/* longest-prefix match: three nested prefixes of 10.0.0.0/8 */
lpm = make("routes", BPF_MAP_TYPE_LPM_TRIE, 8, 4, 16, BPF_F_NO_PREALLOC);
if (lpm >= 0) {
struct v4key r[] = { { 8, { 10 } }, { 16, { 10, 1 } }, { 24, { 10, 1, 2 } } };
for (v = 0; v < 3; v++) {
__u32 id = v + 1;
bpf_map_update_elem(lpm, &r[v], &id, BPF_ANY);
}
printf("lpm_trie with 10.0.0.0/8 = 1, 10.1.0.0/16 = 2, 10.1.2.0/24 = 3:\n");
route(lpm, 10, 1, 2, 3);
route(lpm, 10, 1, 9, 9);
route(lpm, 10, 9, 9, 9);
route(lpm, 11, 0, 0, 1);
}
/* queue and stack: no keys; push is an update, pop is lookup-and-delete */
q = make("q", BPF_MAP_TYPE_QUEUE, 0, 4, 4, 0);
s = make("s", BPF_MAP_TYPE_STACK, 0, 4, 4, 0);
if (q >= 0 && s >= 0) {
for (v = 1; v <= 5; v++) {
int eq = bpf_map_update_elem(q, NULL, &v, BPF_ANY);
bpf_map_update_elem(s, NULL, &v, BPF_ANY);
if (eq)
printf("push %u: %s\n", v, strerror(errno));
}
printf("queue pops:");
while (bpf_map_lookup_and_delete_elem(q, NULL, &v) == 0)
printf(" %u", v);
printf("\nstack pops:");
while (bpf_map_lookup_and_delete_elem(s, NULL, &v) == 0)
printf(" %u", v);
printf("\n");
}
/* bloom filter: add 10,000 values, then ask about 100,000 it never saw */
bloom = make("seen", BPF_MAP_TYPE_BLOOM_FILTER, 0, 4, 10000, 0);
if (bloom >= 0) {
for (v = 0; v < 10000; v++) /* add: an update with no key */
bpf_map_update_elem(bloom, NULL, &v, BPF_ANY);
for (v = 0; v < 10000; v++) /* query: a lookup with no key */
if (bpf_map_lookup_elem(bloom, NULL, &v))
missed++;
for (v = 10000; v < 110000; v++)
if (bpf_map_lookup_elem(bloom, NULL, &v) == 0)
false_pos++;
printf("bloom_filter: added 10000, said no to %u of them, "
"said maybe to %u of 100000 never added (%.2f%%)\n",
missed, false_pos, false_pos / 1000.0);
}
return 0;
}
lpm_trie with 10.0.0.0/8 = 1, 10.1.0.0/16 = 2, 10.1.2.0/24 = 3:
10.1.2.3 -> route 3
10.1.9.9 -> route 2
10.9.9.9 -> route 1
11.0.0.1 -> no route
push 5: Argument list too long
queue pops: 1 2 3 4
stack pops: 4 3 2 1
bloom_filter: added 10000, said no to 0 of them, said maybe to 325 of 100000 never added (0.33%)
LPM trie (4.11) is longest-prefix match, the lookup a router does. Its key is a 32-bit prefix
length followed by the data, here four bytes of IPv4 address. Insert prefixes of different lengths;
look up with the full length, 32; get the value of the longest stored prefix that matches. 10.1.2.3
matched the /24, 10.1.9.9 only the /16, 10.9.9.9 only the /8 and 11.0.0.1 nothing. It is a trie,
so a lookup walks down a tree of prefixes rather than hashing once, and it must be created
with BPF_F_NO_PREALLOC. It is the natural home for a firewall’s or a load balancer’s address
ranges.
Queue and stack (4.20) have no keys at all. A push is an update with a NULL key, a pop is a
lookup-and-delete with a NULL key, and from a program the helpers are bpf_map_push_elem,
bpf_map_pop_elem and bpf_map_peek_elem. Both hold four values here, so the fifth push failed with
E2BIG; pushing with BPF_EXIST instead would make room by dropping the oldest. The queue gave the
values back in the order they went in, the stack in reverse. A queue is a convenient pool: user
space fills it with free resources (port numbers, IDs) and programs pop them.
Bloom filter (5.16) answers “have I seen this value?” with either “no” or “maybe”. It never says
no to a value that was added, and sometimes says maybe to one that was not. It is meant to sit in
front of an expensive lookup: if the filter says no, skip the lookup. Like the queue, it has no
key; values go in with an update and are tested with a lookup. The kernel sizes it from
max_entries and the number of hash functions, which defaults to five: 10,000 entries times 5
hashes, divided by ln 2 (approximated as times 7/5), is 70,000 bits, rounded up to a power of two,
131,072 bits or 16 KiB. The textbook false-positive rate for those numbers is
(1 − e^(−5·10000/131072))^5, 0.32%. Across three runs it said maybe to between
0.318% and 0.325% of values it had never seen (each run seeds the hashes randomly), and
said no to none of the values it had.
The bloom filter is the newest type here, and it shows. Ubuntu 22.04’s kernel headers are 5.15’s,
which predate it, hence the #define at the top of zoo.c. On Ubuntu’s own 5.15.0-25 kernel the
same binary does everything except the last part:
5.15.0-25-generic
lpm_trie with 10.0.0.0/8 = 1, 10.1.0.0/16 = 2, 10.1.2.0/24 = 3:
10.1.2.3 -> route 3
10.1.9.9 -> route 2
10.9.9.9 -> route 1
11.0.0.1 -> no route
push 5: Argument list too long
queue pops: 1 2 3 4
stack pops: 4 3 2 1
seen: BPF_MAP_CREATE failed: Invalid argument
and the stock 22.04 bpftool does not know the type’s name either (Error: unrecognized map type: bloom_filter). A bloom filter on 22.04 needs a newer kernel than the one it shipped with.
Global variables are maps too
lru.bpf.c declared three ordinary-looking global variables, next_key, touch_hot and
plain_full, and user space set them with an assignment through skel->bss. There is no memory a
BPF program can own outside a map, so since 5.2 the compiler’s sections for global data, .data,
.rodata and .bss, are turned into maps by the loader: each section becomes a one-entry array
whose single value is the whole section. While lru runs:
$ sudo bpftool map show
19: lru_hash name lru flags 0x0
key 4B value 4B max_entries 1000 memlock 8192B
btf_id 32
20: hash name plain flags 0x0
key 4B value 4B max_entries 1000 memlock 8192B
btf_id 32
21: array name lru.bss flags 0x400
key 4B value 12B max_entries 1 memlock 4096B
btf_id 32
lru.bss is an array of one 12-byte value, the three __u32s. Its flags, 0x400, are
BPF_F_MMAPABLE (5.5): user space can mmap the array’s memory, and the skeleton does, so
skel->bss->next_key = k in lru.c is a plain store into the map with no system call. The program
reads the same memory with an ordinary load from an address the kernel filled in at load time (in
the verifier’s log it appears as r1 = 0xffff… typed map_value), with no helper call at all. That
is the cheapest map access there is.
The benchmark later in this post uses the other variant. It declares its settings const volatile,
which puts them in .rodata, and user space fills them in after opening the object and before
loading it:
$ sudo bpftool map show
...
45: array name bufbench.rodata flags 0x480
key 4B value 16B max_entries 1 memlock 4096B
btf_id 38 frozen
Flags 0x480 add BPF_F_RDONLY_PROG (5.2) to BPF_F_MMAPABLE: programs may read the map but not
write it. And “frozen”: after writing the values, libbpf calls BPF_MAP_FREEZE (also 5.2), after
which user space cannot change them either. A map nobody can change is a constant, and the verifier
treats it as one. The benchmark’s program has one branch for each of three modes, chosen by a
.rodata variable, and the verifier deletes the branches that cannot run:
# while bufbench runs in mode none:
$ sudo bpftool prog show name produce | grep xlated
xlated 272B jited 164B memlock 4096B map_ids 52,49,50,51
# while bufbench runs in mode perf:
$ sudo bpftool prog show name produce | grep xlated
xlated 432B jited 248B memlock 4096B map_ids 59,56,57,58
# while bufbench runs in mode ringbuf:
$ sudo bpftool prog show name produce | grep xlated
xlated 488B jited 289B memlock 4096B map_ids 66,63,64,65
Same source, three sizes. That is the idiom for configuring a BPF program: settings in const volatile globals, filled in by the loader, and the dead code costs nothing. (volatile stops clang
from assuming the value it can see, zero, at compile time.)
Getting data out: two kinds of buffer
Everything so far has been a map that user space reads when it chooses. Many tools want the
opposite: a stream of events, one per execve() or packet or failed open(), delivered to user
space as they happen. There are two ways to do that on 5.19, and they make different promises.
The perf buffer. The older way borrows the ring buffers of the perf subsystem. The map,
BPF_MAP_TYPE_PERF_EVENT_ARRAY (4.3), holds one perf event per CPU, and each perf event owns a
ring buffer that user space maps into its address space. The program calls
bpf_perf_event_output (4.4), which copies a record into the ring of the CPU the program is running
on. User space waits in epoll on all the rings and drains whichever has data. Every CPU writes only
to its own ring, so producers never contend with each other. But user space reads the rings one at a
time, so two events on different CPUs come out in whatever order the reader happened to visit the
rings, not the order they happened in. And every CPU needs a ring big enough for its worst burst,
including the CPUs that never produce anything.
The ring buffer. BPF_MAP_TYPE_RINGBUF, added in 5.8, is one buffer shared by all CPUs, written
by many producers and read by one consumer. The commit that introduced it names its two motives:
memory efficiency, because one shared buffer absorbs bursts from whichever CPU has them, and
ordering, “preserving ordering of events that happen sequentially in time, even across multiple
CPUs”. Its main API is two steps. bpf_ringbuf_reserve takes a spinlock for a few instructions,
advances the producer position past a new record, writes an 8-byte header with a busy bit set, and
returns a pointer into the buffer itself. The program fills the record in place, with no copy and
no need to build the record on its 512-byte stack. bpf_ringbuf_submit clears the busy bit, without
any lock. The consumer reads records in the order they were reserved and stops at the first one that
is still busy, so a record reserved later cannot overtake one reserved earlier. The verifier tracks
every reservation like a reference it has to release: a program that reserves and then forgets to
submit or discard on some path is rejected.
Wakeups are the cost nobody sees in the API. The consumer sleeps in epoll; something has to wake
it. For the perf buffer that is the perf event’s wakeup_events setting, and libbpf 0.5’s
perf_buffer__new() sets it to 1: wake the reader after every single record. For the ring buffer,
bpf_ringbuf_submit takes a flag. With 0, it wakes the reader only if the reader has already caught
up to this record, on the theory that a reader that is behind will find the record anyway.
BPF_RB_FORCE_WAKEUP always wakes it. BPF_RB_NO_WAKEUP never does, and then the reader must poll
on its own schedule. In both buffers a wakeup is not done on the spot: it is queued as irq_work,
a self-interrupt that runs the wakeup as soon as the CPU can take one.
The stepper shows the two side by side on three CPUs.
Perf buffer and ring buffer, one event at a time
Three CPUs produce events A, B, C…; the letter's small number is when it happened. Illustrative sizes: 4 records per perf ring, 8 in the ring buffer.
Before anything happens
The perf buffer is one ring per CPU, each mapped into the reader's memory. The ring buffer is one area shared by every CPU, with two positions: the consumer's (C) and the producer's (P).
CPU 0: event A at time 1
Perf: bpf_perf_event_output copies A into CPU 0's ring, complete at once, and, with libbpf's default of waking on every record, queues a wakeup. Ring buffer: bpf_ringbuf_reserve takes the lock, moves P past one record and marks it busy. The program now writes A in place.
CPU 1: event B at time 2
Perf: B goes into CPU 1's own ring; no other CPU is involved. Ring buffer: B is reserved right after A. Both records are busy: A's program has not finished filling it in.
CPU 1 submits B first
Ring buffer: B's busy bit is cleared, without a lock. But the reader stops at the first busy record, and A is still busy, so B cannot be read yet. No wakeup: the consumer is waiting at A's position, not B's.
CPU 0 submits A
Ring buffer: A is ready, and the consumer position equals A's position, so the default flag queues a wakeup. A and B are now readable, in the order they were reserved.
CPU 0: events C and D at times 3 and 4
Perf: both land in CPU 0's ring, behind A. Ring buffer: reserved and submitted after B. The reader is behind, so no wakeups are needed: it will find them anyway.
The reader wakes and reads
Perf: the reader drains CPU 0's ring (A, C, D), then CPU 1's (B). B happened at time 2 but arrives after D, from time 4. Ring buffer: A, B, C, D, in reservation order, which here is time order.
A burst of five on CPU 2
Perf: CPU 2's ring holds four records, so the fifth is lost, while CPU 0's and CPU 1's rings sit empty. Ring buffer: the space the reader freed is shared, so all five fit. Per-CPU rings have to be sized for each CPU's worst burst; a shared one, for the sum.
Teal: a complete record. Dashed copper: reserved, still being written (busy). Grey: already read. Struck through: lost because the ring was full.
The worked example: one event per system call
To measure them, I needed a source of events I could turn up as far as it would go, on as many CPUs
as I chose. The program below fires on every getppid(), a system call that does almost nothing,
made by the benchmark’s own producer threads, and turns each one into a 24-byte event:
// bufbench.bpf.c — turn every getppid() of the benchmark into a 24-byte event
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
struct event {
__u64 ts; /* bpf_ktime_get_ns(), CLOCK_MONOTONIC */
__u64 seq; /* per-CPU sequence number, to spot gaps and reordering */
__u32 cpu;
__u32 pad;
};
const volatile __u32 tgid; /* .rodata: set by user space before loading */
const volatile __u32 mode; /* 0: count only, 1: perf buffer, 2: ring buffer */
const volatile __u64 rb_flags; /* 0, BPF_RB_NO_WAKEUP or BPF_RB_FORCE_WAKEUP */
struct {
__uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
__uint(key_size, sizeof(__u32));
__uint(value_size, sizeof(__u32));
} pb SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_RINGBUF);
__uint(max_entries, 4096); /* resized by user space before loading */
} rb SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
__uint(max_entries, 2); /* [0] sequence, [1] events dropped */
__type(key, __u32);
__type(value, __u64);
} stats SEC(".maps");
SEC("tracepoint/syscalls/sys_enter_getppid")
int produce(void *ctx)
{
__u32 k_seq = 0, k_drop = 1;
__u64 *seq, *drops;
struct event e, *r;
if (bpf_get_current_pid_tgid() >> 32 != tgid)
return 0;
seq = bpf_map_lookup_elem(&stats, &k_seq);
drops = bpf_map_lookup_elem(&stats, &k_drop);
if (!seq || !drops)
return 0;
*seq += 1;
if (mode == 1) {
e.ts = bpf_ktime_get_ns();
e.seq = *seq;
e.cpu = bpf_get_smp_processor_id();
e.pad = 0;
/* copies e into this CPU's buffer */
if (bpf_perf_event_output(ctx, &pb, BPF_F_CURRENT_CPU, &e, sizeof(e)))
*drops += 1;
} else if (mode == 2) {
/* claims space in the shared buffer; we write in place */
r = bpf_ringbuf_reserve(&rb, sizeof(*r), 0);
if (!r) {
*drops += 1;
return 0;
}
r->ts = bpf_ktime_get_ns();
r->seq = *seq;
r->cpu = bpf_get_smp_processor_id();
r->pad = 0;
bpf_ringbuf_submit(r, rb_flags);
}
return 0;
}
char LICENSE[] SEC("license") = "GPL";
Taking it apart:
- Three
const volatilesettings in.rodata: whosegetppid()calls to count, which buffer to write to, and the wakeup flag for the ring buffer. The verifier removes the two branches that the chosen mode cannot reach, as thexlatedsizes above showed. pbis the perf buffer map. It has nomax_entries: libbpf sets it to the number of CPUs. Its values are perf event descriptors, which user space fills in when it creates the buffers.rbis the ring buffer. Its size is inmax_entries, in bytes, and must be a power-of-two number of pages; the user-space side sets it before loading.statsis a per-CPU array: a sequence number per CPU, and a count of events that found the buffer full. Per-CPU, after the previous section, because every event updates it.- The filter
bpf_get_current_pid_tgid() >> 32 != tgidkeeps other processes’getppid()calls out. The upper half of that helper’s result is the process ID. - The perf path builds the event on the stack and copies it into this CPU’s ring with
BPF_F_CURRENT_CPU. A non-zero return means the ring was full and the record is lost. - The ring buffer path reserves first and fills the record in place. A NULL from
bpf_ringbuf_reservemeans no space, and the program must not touch the pointer, which the verifier enforces just as it did for map lookups in Part 1.bpf_ringbuf_submitpublishes it.
The user-space side starts N producer threads, one per CPU, that call getppid() in a loop for two
seconds, and one consumer thread, on the last CPU, that reads events back and checks them: whether
each CPU’s sequence numbers arrive without gaps or reversals, whether timestamps arrive in order
across CPUs, how long each event took from the program to the consumer, how often the consumer woke
up, and how much CPU time it used. For the perf buffer it does exactly what libbpf’s
perf_buffer__new() does, except that the wakeup setting is a parameter:
The conditions: no output at all (the cost of the program and the system call); the perf buffer with 256 KiB per CPU, waking the reader after every event and after every 64th; the ring buffer with 2 MiB, with each of the three wakeup policies; and then a smaller budget, 64 KiB in total: the perf buffer at 8 KiB per CPU, the ring buffer at 64 KiB. All with one producer, then four. Each condition ran five times, in rotated order, in one sitting with no other virtual machine running. One line of output, the ring buffer at its default setting with four producers:
mode=ringbuf kib=2048 wake=adaptive producers=4 secs=2.000 produced=8703035 got=8703035 dropped=0 perf_lost=0
gaps=0 backwards=0 inversions=65077
late_1us=57264 max_inv_us=185.7 lat_p50_us=2.3 lat_p99_us=40.5
wakeups=2056455 consumer_cpu_ms=1595.5 prog_ns=829.9 mem_kib=2256
The figure below and the tables have the medians. Events delivered per second and the cost to the program per event, with the range over the five rounds:
| condition | producers | delivered, M events/s | ns per event | dropped | median latency, µs |
|---|---|---|---|---|---|
| no output | 1 | — | 17.9 (17.8–18.5) | — | — |
| perf, 256 KiB/CPU, wake every event | 1 | 0.20 (0.18–0.20) | 4844 (4724–5065) | 0 | 4 |
| perf, 256 KiB/CPU, wake every 64th | 1 | 3.67 (3.63–3.67) | 185 (185–188) | 0 | 12.7 |
| ring buffer, 2 MiB, default | 1 | 0.80 (0.71–0.82) | 1153 (1122–1319) | 0 | 2.5 |
ring buffer, 2 MiB, BPF_RB_NO_WAKEUP | 1 | 7.11 (6.96–7.17) | 54.8 (54.4–56.3) | 0 | 558.7 |
ring buffer, 2 MiB, BPF_RB_FORCE_WAKEUP | 1 | 0.20 (0.19–0.20) | 4838 (4825–5051) | 0 | 3.8 |
| perf, 8 KiB/CPU, wake every 64th | 1 | 3.19 (3.11–3.22) | 220 (218–226) | 3.13% | 12.5 |
| ring buffer, 64 KiB, default | 1 | 0.74 (0.72–0.77) | 1249 (1208–1296) | 0.02% | 2.2 |
ring buffer, 64 KiB, BPF_RB_NO_WAKEUP | 1 | 1.88 (1.88–1.89) | 38.9 (38.7–39.6) | 76.58% | 954.7 |
| no output | 4 | — | 17.8 (17.7–17.8) | — | — |
| perf, 256 KiB/CPU, wake every event | 4 | 0.83 (0.80–0.87) | 4710 (4456–4860) | 0 | 4.7 |
| perf, 256 KiB/CPU, wake every 64th | 4 | 15.14 (15.10–15.30) | 175 (173–177) | 0 | 4.1 |
| ring buffer, 2 MiB, default | 4 | 4.43 (4.34–4.53) | 810 (795–830) | 0 | 2.3 |
ring buffer, 2 MiB, BPF_RB_NO_WAKEUP | 4 | 4.45 (4.38–4.49) | 812 (796–827) | 0 | 552.9 |
ring buffer, 2 MiB, BPF_RB_FORCE_WAKEUP | 4 | 4.70 (4.53–4.74) | 761 (751–791) | 0 | 2.2 |
| perf, 8 KiB/CPU, wake every 64th | 4 | 14.34 (13.14–14.74) | 186 (182–197) | 2.72% | 9.8 |
| ring buffer, 64 KiB, default | 4 | 4.58 (4.43–4.69) | 785 (755–811) | 0.01% | 1.6 |
ring buffer, 64 KiB, BPF_RB_NO_WAKEUP | 4 | 1.87 (1.86–1.88) | 670 (661–729) | 64.61% | 873.8 |
What sharing costs, measured
Median of five rounds (dot) and the range across them (bar), on a log scale. 5.19, 8 vCPUs.
The numbers as tables
| ns per run (median) | 1 CPU | 2 | 4 | 8 | lost at 8 |
|---|---|---|---|---|---|
| nothing (loop only) | 1 | 1 | 1 | 1 | 0% |
| hash, plain add | 5 | 20.5 | 49 | 115.6 | 77.9% |
| hash, atomic add | 7 | 46.5 | 139.8 | 285 | 0% |
| array, atomic add | 5 | 18 | 42 | 88.1 | 0% |
| array, bpf_spin_lock | 15 | 145 | 522 | 1086.8 | 0% |
| per-CPU array | 2 | 2 | 1.5 | 1.4 | 0% |
| events | producers | delivered M/s | ns/event | dropped | p50 µs | out of order |
|---|---|---|---|---|---|---|
| perf 256 KiB/CPU, wake every event | 1 | 0.2 | 4843.9 | 0% | 4 | 0% |
| perf 256 KiB/CPU, wake every 64th | 1 | 3.67 | 185 | 0% | 12.7 | 0% |
| ringbuf 2 MiB, default wakeup | 1 | 0.8 | 1152.8 | 0% | 2.5 | 0% |
| ringbuf 2 MiB, BPF_RB_NO_WAKEUP | 1 | 7.11 | 54.8 | 0% | 558.7 | 0% |
| ringbuf 2 MiB, BPF_RB_FORCE_WAKEUP | 1 | 0.2 | 4837.6 | 0% | 3.8 | 0% |
| perf 8 KiB/CPU, wake every 64th | 1 | 3.19 | 219.9 | 3.13% | 12.5 | 0% |
| ringbuf 64 KiB, default wakeup | 1 | 0.74 | 1248.8 | 0.02% | 2.2 | 0% |
| ringbuf 64 KiB, BPF_RB_NO_WAKEUP | 1 | 1.88 | 38.9 | 76.58% | 954.7 | 0% |
| perf 256 KiB/CPU, wake every event | 4 | 0.83 | 4710.2 | 0% | 4.7 | 45.86% |
| perf 256 KiB/CPU, wake every 64th | 4 | 15.14 | 175 | 0% | 4.1 | 74.22% |
| ringbuf 2 MiB, default wakeup | 4 | 4.43 | 809.9 | 0% | 2.3 | 0.75% |
| ringbuf 2 MiB, BPF_RB_NO_WAKEUP | 4 | 4.45 | 812.1 | 0% | 552.9 | 1.04% |
| ringbuf 2 MiB, BPF_RB_FORCE_WAKEUP | 4 | 4.7 | 760.8 | 0% | 2.2 | 0.82% |
| perf 8 KiB/CPU, wake every 64th | 4 | 14.34 | 186.5 | 2.72% | 9.8 | 74.63% |
| ringbuf 64 KiB, default wakeup | 4 | 4.58 | 784.7 | 0.01% | 1.6 | 0.83% |
| ringbuf 64 KiB, BPF_RB_NO_WAKEUP | 4 | 1.87 | 669.6 | 64.61% | 873.8 | 0.99% |
Counters: BPF_PROG_TEST_RUN's average per run, one million runs per CPU, the same program on every CPU at once. Events: each producer calls getppid() flat out for two seconds; "cost per event" is the kernel's bpf_stats time in the program, including any wakeup it raises. The guest runs nested in another VM, which inflates wakeups; compare conditions, not absolute values.
What the numbers say
A wakeup costs about 4.7 µs here, and it dominates everything. Two different mechanisms
agree on it. The perf buffer costs 4,844 ns per event when it wakes the reader on every event
and 185 ns when it wakes it on every 64th. The ring buffer costs 4,838 ns per
event with BPF_RB_FORCE_WAKEUP and 54.8 ns with BPF_RB_NO_WAKEUP. The difference
is about the same in both, between 4.6 and 4.8 µs, because the expensive part is the same in both: raising the self-interrupt
that runs the wakeup. That cost is the virtual machine’s more than the kernel’s. My guest runs
nested inside another virtual machine, and every self-interrupt there is a trip out to a hypervisor
and back. On bare metal the same wakeup is far cheaper. The shape survives, though: the upstream
benchmark that came with the ring buffer, run on a 28-core Xeon, measured the perf buffer at its
default setting delivering 0.93 million events a second from one producer, and 9.9 million when it
woke the reader on only one event in 500.
The ring buffer’s adaptive default wakes too often when the reader is fast. With one producer the
default flag cost 1,153 ns per event and woke the reader 324,060
times in two seconds: a consumer that keeps up is, by definition, always caught up, so most records
find it waiting and wake it. The ring buffer’s author says as much in the benchmark’s commit: an
“over zealous and fast consumer, which is almost always caught up, will make throughput numbers
smaller”. When events come in floods, BPF_RB_NO_WAKEUP plus a reader that polls every millisecond
delivered 7.1 million events a second from one producer, with 99 ms
of consumer CPU time in two seconds, against 1,299 ms for the default. The price is
latency: the median event waited 559 µs to be read instead of 2.5 µs.
With four producers, the shared buffer’s lock shows. The perf buffer, waking every 64th event, delivered 15.1 million events a second from four producers at 175 ns each: every CPU writes to its own ring, so they never meet. The ring buffer topped out at 4.5 million a second whatever the wakeup policy, at about 812 ns per event, because every reservation takes the same spinlock. One producer with no wakeups cost 54.8 ns; four cost 812 ns. The upstream benchmark saw the same effect on bare metal, though gentler: 10.9 million events a second from one producer, 3.9 million from four. A virtual CPU can also be descheduled by the host while it holds the lock, which makes contention worse in a guest than on hardware.
Ordering is where the ring buffer earns its place. With four producers and the perf buffer,
74% of events reached the reader after an event with a later timestamp, by as much
as 591 µs in the median round: the reader drains one CPU’s ring, then the next, and each ring holds events
from the same stretch of time. With the ring buffer, between 0.75% and 1.04% did. Those are not reordering
by the buffer, which hands records over strictly in reservation order. My program reads the clock
just after reserving, and a producer interrupted between the two (by an interrupt, or by the host
taking its virtual CPU away) stamps its record late. Within each CPU, neither buffer ever delivered
a sequence number out of order. For a tool that reconstructs what happened, a fork then an exec
then an exit of one process on three different CPUs, that difference decides whether the reader
has to sort events itself.
Memory, and drops. The perf buffer allocated a 256 KiB ring, plus a page of metadata, for each of
the 8 CPUs: 2,080 KiB, whether one CPU produced or four. With one producer, seven of the eight rings
sat empty. The ring buffer’s 2 MiB
was shared by whoever produced. In a typical round neither lost an event at those sizes. At 64 KiB in total the
difference is the reader. With the default wakeups the ring buffer dropped 236 events
of 1.48 million with one producer. With BPF_RB_NO_WAKEUP and a reader polling every
millisecond, it dropped 77% of them: a millisecond of events from a producer that
fast is more than 64 KiB, so the buffer has to hold one polling interval’s worth of events, plus a
margin. The perf buffer at 8 KiB per CPU, waking every 64th event, lost 3.13% of its events with one producer and 2.72% with four: 8 KiB is about 200 records, and a CPU that produces faster than the reader can switch to its ring overflows it, while the other rings sit idle.
So which one? On a kernel of 5.8 or later, the ring buffer by default: it keeps events in order,
shares its memory, lets the program write records in place, and its adaptive wakeups are right for
the common case of a modest event rate. When events come in floods, choose the wakeup policy
deliberately, with BPF_RB_NO_WAKEUP and a polling reader, or with the program forcing a wakeup
every so often. If many CPUs produce at once and order does not matter, several ring buffers in a
map of maps, one per group of CPUs, spread the lock; that topology is one of the reasons its commit
gives for making the ring buffer a map type at all. And the perf buffer remains the only choice on kernels older than 5.8,
which, for anyone shipping to Ubuntu 20.04’s 5.4, is still a real constraint.
What else is in the box
The types above are the ones a tool chooses between. The rest of the 30 are tied to one subsystem,
and later parts meet them in context: PROG_ARRAY for tail calls, where one program jumps into
another; DEVMAP, CPUMAP and XSKMAP, where an XDP program sends packets; SOCKMAP and
SOCKHASH, which hold sockets so that programs can redirect data between them; STACK_TRACE for
profilers; and the local-storage maps, socket (5.2), inode (5.10) and task (5.11), which attach a
value to a kernel object and free it when the object goes away, the way a profiler keeps per-thread
state without a hash keyed by thread ID that has to be cleaned up by hand. 5.19, the kernel this
post ran on, adds something new to map values themselves: a field can now hold a typed pointer to a
kernel object, a kptr, which the verifier tracks. That deserves a part of its own.
Two more facilities work on any map. bpf_for_each_map_elem (5.13) lets a program iterate over a
map with a callback, which the verifier checks once rather than once per element. And, as bigmap
showed, the batch commands let user space move thousands of entries per system call.
What we covered
- A BPF program’s registers and stack vanish when it returns. Maps are the only memory that lasts, the only memory shared between CPUs, and the main channel to user space. 5.19 has 30 types.
- A map is a kernel object with a descriptor and a reference count. Since 5.11 its memory is charged
to the creator’s memory cgroup. bpftool’s
memlockis an estimate: a million-entry hash map reported 15.3 MiB and cost 77.0 MiB, all at creation, because hash maps preallocate unless told not to, to stay safe in programs that run inside the allocator. - Batch lookups read a million entries in 161–181 ms against 521–547 ms for two system calls per entry.
- The verifier specialises lookups by map type: an array lookup becomes five instructions of arithmetic, a hash lookup a direct call, an LRU lookup a call plus a referenced bit, a map of maps two inlined array lookups.
- Sharing a counter across CPUs costs a cache line in flight: 140 ns per atomic add on
four CPUs against 1.5 ns per-CPU; a plain add lost 54.5% of the counts.
bpf_spin_lockprotects multi-field values and is refused in tracing programs on this kernel. - An LRU hash evicts the coldest entries in batches and gives recently looked-up ones a second chance; sized for 1,000, it held 873 to 1,000.
- LPM tries match prefixes, queues and stacks have no keys, and the bloom filter (5.16, too new for stock 22.04) answered “maybe” to about 0.32% of strangers, as theory predicts.
- Global variables are array maps;
.rodatais frozen, so the verifier deletes code that a setting turns off. - Perf buffer against ring buffer: wakeups dominate (about 4.7 µs each in this VM), the ring buffer’s lock limits it with many producers, the perf buffer scrambles the order across CPUs, and the ring buffer shares its memory and keeps the order.
Part 6 moves from the data to the types that describe it: BTF, how one compiled program can run on kernels whose structures differ, and what libbpf 1.0 changes.
A note on the evidence
What I ran, and where. Every listing in this post is pasted from a real run, and the C files and
the build commands were extracted from this page and built as shown. The machine was a KVM virtual
machine with 8 virtual CPUs and 4 GiB of memory, itself running nested inside another virtual
machine, booting the Ubuntu mainline build of Linux 5.19 (5.19.0-051900-generic #202207312230,
built from the v5.19 tag on release day) on a minimal Ubuntu 22.04 userland built from the release
archive only: clang 14.0.0-1ubuntu1, libbpf-dev 0.5.0-1, linux-libc-dev 5.15.0-25.25, and bpftool
v5.15.30 from linux-tools-5.15.0-25-generic. Ubuntu’s bpftool wrapper refuses to run on a kernel
it has no tools package for, so the bpftool in the build commands and sessions is that binary,
put first on the PATH. The timing runs used copies of the C files that I checked were byte-for-byte
identical to the ones extracted from the page. The one contrast run, the
bloom filter refused, booted Ubuntu 22.04’s own release kernel, 5.15.0-25-generic, on the same
userland.
The timings. Every timing came from runs with no other test VM running, with conditions
interleaved and repeated five times in rotated order; the tables give medians and the ranges are
minimum to maximum. The counter benchmark is BPF_PROG_TEST_RUN’s own per-run average, which
includes the loop around the program. The buffer benchmark’s per-event cost is the kernel’s
bpf_stats accounting, which includes the cost of reading the clock twice per run. Absolute numbers
from a nested VM do not transfer to hardware; above all the wakeup cost, which is inflated by the
nesting, and the occasional stall: in one of the five rounds of the perf buffer waking on every
event, with one producer, the reader was held up long enough to lose 43,829 events, where
the other four rounds lost none, and similar stalls account for the widest ranges in the figure. The
comparisons between conditions are what I rely on, and where upstream measured the same
thing on bare metal (the ring buffer benchmark in commit c97099b0f227, merged for 5.8) the shapes
agree.
What I trimmed. The loaded_at lines of bpftool prog show, which carry the time of the run,
are cut and marked. Program and map IDs are as printed. The verifier log for locktp is its last
lines; the full log adds only libbpf’s banner. bigmap printed three runs each way; one of each is
shown, and the other runs agreed to within 0.1 MiB on memory and a few tens of milliseconds on time. The
LRU’s population range came from a variant of lru.c, not printed here, that counts the entries after
every insert instead of once at the end.
What I cited rather than ran. The kernel version each feature arrived in, which I checked by
asking which release tag first contains the commit that introduced it: hash and array maps 3.19,
per-CPU maps and BPF_F_NO_PREALLOC 4.6, LRU 4.10, LPM trie 4.11, maps of maps and
BPF_PROG_TEST_RUN 4.12, queue and stack 4.20, bpf_spin_lock and BPF_F_LOCK 5.1, global data,
BPF_F_RDONLY_PROG and BPF_MAP_FREEZE 5.2, mmap-able arrays 5.5, batch operations 5.6, the ring
buffer 5.8, memory-cgroup accounting of maps 5.11, the bloom filter 5.16. The reason for
preallocation is quoted from its commit, as are the ring buffer’s motives and the upstream benchmark
figures. The element layout, the 128-element LRU batch and the bloom filter’s sizing rule are read
from the 5.19 sources (kernel/bpf/hashtab.c, bpf_lru_list.c, bloom_filter.c), and what
libbpf 0.5 does in perf_buffer__new() from its v0.5.0 source.
What I’d still change. The buffer benchmark’s producers do nothing but make events, which is the worst case for contention and wakeups; a real tool’s events are spread out, and at modest rates the default settings of either buffer are fine. And all of it ran in a nested virtual machine. The same matrix on bare metal, with more than four producers, is the measurement I would most like to add.
Maps Are the Only Memory You Get