Every Function Is a Hook

Contents
Attaching the same two-line BPF program to the getpid() system call made each call 7.4
nanoseconds slower when it went in through fentry, 27 through a kprobe, 89
through a kretprobe, and 310 when the kprobe had to fall back to a breakpoint instruction.
A uprobe on a two-instruction function in an ordinary program made each call of it
8.1 microseconds slower, about 27,000 times what the function costs on its
own. The program did the same thing every time: it added one to a counter. What changed was the road
the kernel took to reach it.
This post is about those roads: every way Linux lets a BPF program attach to code that is already running, what each one does at the level of machine instructions, what it costs when measured on one target, and which of them will still be there after the next kernel upgrade.
This is Part 9 of a series on eBPF, written for C programmers who know processes, system calls and sockets but not kernel internals. Everything here ran on Linux 6.2, released three weeks ago, in Ubuntu’s mainline build, with Ubuntu 22.04’s userland around it. 22.04 ships libbpf 0.5, which predates kprobe-multi and USDT support, so libbpf 1.1 and bpftool 7.1 were built from their release tags; bpftrace is 22.04’s 0.14. Output is pasted from those runs. The note at the end says exactly where and how.
Twelve ways into running code
Part 1 attached a program to a tracepoint and moved on. Tracing is where BPF started earning its keep, though, and the kernel now offers a whole family of attachment points for it. They answer the same question, “run my code when execution gets here”, and they differ in where “here” may be, what the program is told when it gets there, how much the trip costs, and how likely the spot is to exist on the next kernel.
| Hook | BPF since | Attaches to | The program receives |
|---|---|---|---|
| kprobe, kretprobe | 4.1 | almost any kernel instruction; a function’s return | the CPU registers |
| tracepoint | 4.7 | a fixed point a kernel developer placed | a copy of the event’s fields |
| perf event | 4.9 | a timer or hardware counter overflowing | the registers at that moment |
| raw tracepoint | 4.17 | the same fixed points, no copying | the tracepoint’s raw arguments |
| fentry, fexit | 5.5 | entry to and exit from a kernel function | the function’s arguments, typed; at exit, the return value too |
| tp_btf | 5.5 | tracepoints, through BTF | the raw arguments, typed |
| kprobe-multi | 5.18 | thousands of functions in one attachment | the registers |
| uprobe, uretprobe | 4.3 | any instruction in a user-space program | the user registers |
| USDT | (via uprobes) | markers compiled into a user-space program | the marker’s arguments |
The versions are those of the commits that added each to Linux, checked against the release tags. Several of the mechanisms underneath are much older than their BPF support: kprobes are already in the first release in the kernel’s git history, 2.6.12 in 2005, tracepoints arrived in 2.6.28 and uprobes in 3.5. BPF joined each of them later, as a new kind of handler on an existing hook.
The rest of the post takes them roughly in that order, kernel side first, then user space, then sampling, and then puts all of them into one experiment: one tiny program, attached through each hook in turn, timed on the same call.
kprobes: a breakpoint anywhere
A kprobe is the debugger’s trick applied to the kernel itself. To probe an instruction, the kernel
saves its first byte and overwrites it with int3, the one-byte x86 breakpoint, 0xcc. When a CPU
next executes that address, it traps. The trap handler, kprobe_int3_handler, looks the address up,
finds our probe, and calls its handler; for a BPF program that is kprobe_dispatcher, then
kprobe_perf_func, then trace_call_bpf, which runs the program with a pointer to the saved
registers as its context.
Then comes the awkward part: the instruction we overwrote still has to run. The kernel keeps a copy
of it in a small executable slot, and on this kernel it puts a second int3 straight after the copy.
It points the CPU at the slot, the copied instruction runs, the second breakpoint traps, and the
handler sends the CPU back to the instruction after the probe. A few instructions, jumps, calls and
returns among them, are emulated instead, since they would go wrong if run from a different address.
Everything else costs two traps per hit. (On a kernel without preemption, a copied instruction can be
followed by a jump back instead of a second breakpoint. This one is built with CONFIG_PREEMPTION,
which rules that out.)
Two optimisations take most probes off that slow path.
Jump optimisation, since 2.6.34. If the instructions around the probe point can be relocated, a
background worker replaces the breakpoint with a five-byte jmp to a detour buffer, which saves the
registers, calls the handler, runs the displaced instructions and jumps back. No trap at all.
kprobes on ftrace, since 3.7. The kernel is compiled with -pg -mfentry-style instrumentation:
the first instruction of almost every function is a five-byte call to __fentry__, which is patched
into a five-byte nop at boot. That is ftrace’s attach point, and when a kprobe is placed exactly on
a function’s entry, the kernel reuses it: the nop becomes a call to an ftrace trampoline that saves
the registers and calls kprobe_ftrace_handler. Again, no trap.
You can watch all three happen. Here is the start of the function that implements getpid() on
Linux 6.2, read from the running kernel through /proc/kcore with nothing attached, then with a
kprobe on its entry, then with a kprobe five bytes in, after the optimiser had run, and finally the
same probe with optimisation switched off:
# nothing attached
ffffffffac8fdd10: nopl 0x0(%rax,%rax,1)
ffffffffac8fdd15: push %rbp
ffffffffac8fdd16: xor %edx,%edx
# kprobe on __do_sys_getpid
ffffffffac8fdd10 k __do_sys_getpid+0x0 [FTRACE]
ffffffffac8fdd10: call 0xffffffffc0227000 <ftrace_trampoline>
ffffffffac8fdd15: push %rbp
# kprobe on __do_sys_getpid+0x5
ffffffffac8fdd15 k __do_sys_getpid+0x5 [OPTIMIZED]
ffffffffac8fdd10: nopl 0x0(%rax,%rax,1)
ffffffffac8fdd15: jmp 0xffffffffc028b204 <kprobe_optinsn_page+0x204>
ffffffffac8fdd1a: add %al,(%rax)
# the same, with debug.kprobes-optimization = 0
ffffffffac8fdd15 k __do_sys_getpid+0x5
ffffffffac8fdd10: nopl 0x0(%rax,%rax,1)
ffffffffac8fdd15: int3
ffffffffac8fdd16: xor %edx,%edx
The nopl at offset 0 is the patched-out __fentry__ call. With a probe on the entry it has become
a call into ftrace, and /sys/kernel/debug/kprobes/list marks the probe [FTRACE]. Five bytes in,
the probe is a jmp, marked [OPTIMIZED], and with debug.kprobes-optimization set to 0 it stays
a bare int3 over the first byte of push %rbp. The bytes after the jmp look like nonsense to
objdump because the jump has overwritten the start of the next instructions too; the detour buffer
holds the originals.
The ftrace trampoline is worth one look, because it explains why even the trap-free kprobe is not
free. Before it calls the handler, it builds a complete struct pt_regs, every general-purpose
register plus flags, since a kprobe handler is promised all of them:
ffffffffc0227000: pushf
ffffffffc0227001: push %rbp
ffffffffc0227002: push 0x18(%rsp)
ffffffffc0227006: push %rbp
ffffffffc0227007: mov %rsp,%rbp
ffffffffc022700a: push 0x20(%rsp)
ffffffffc022700e: push %rbp
ffffffffc022700f: mov %rsp,%rbp
ffffffffc0227012: sub $0xa8,%rsp
ffffffffc0227019: mov %rax,0x50(%rsp)
ffffffffc022701e: mov %rcx,0x58(%rsp)
ffffffffc0227023: mov %rdx,0x60(%rsp)
ffffffffc0227028: mov %rsi,0x68(%rsp)
ffffffffc022702d: mov %rdi,0x70(%rsp)
ffffffffc0227032: mov %r8,0x48(%rsp)
ffffffffc0227037: mov %r9,0x40(%rsp)
...
ffffffffc02270f2: call 0xffffffffac8ab570 <kprobe_ftrace_handler>
...
ffffffffc022716e: add $0xd0,%rsp
ffffffffc0227175: popf
ffffffffc0227176: ret
kretprobes add a return hook to the entry probe. On entry, the handler takes a record from a
pre-allocated pool, notes the real return address, and overwrites the return address on the stack
with the address of a trampoline. When the function returns, it “returns” into the trampoline,
which builds a pt_regs again, runs the return handler (the BPF program, which can read the return
value from ax) and then jumps to the real return address. Since 5.18 this machinery is called
rethook on x86, shared with the fprobe code below. Of the kernel hooks that do not trap, it is the most expensive
in the measurements below, and the reason is visible in the description: two probes, a pool
allocation, and a return that goes somewhere the CPU’s return-address predictor did not expect.
Every program on a single kprobe, whichever of the three mechanisms delivers it, goes through
trace_call_bpf. That function
increments a per-CPU counter, bpf_prog_active, and refuses to run a program if one is already
running on this CPU. A kprobe that fires inside another BPF program’s helper is silently skipped.
Tracepoints and raw tracepoints
A kprobe can go almost anywhere, which is its strength and its problem: what it attaches to is
whatever the compiler made of the kernel’s source this time. A tracepoint is the opposite, a
named hook that a kernel developer wrote into the source on purpose, with a declared list of
arguments, TP_PROTO, and a declared record layout for the event, TP_STRUCT__entry. When nothing
is attached, the tracepoint is a static branch that is patched to a nop; enabling it patches the
branch and makes it call each registered probe function in turn.
There are three ways for BPF to be one of those probe functions, and they differ in what the program gets.
A tracepoint program (4.7) goes through perf, the way Part 1’s did. The kernel fills in the
event’s record, the same one /sys/kernel/tracing/events/.../format describes, and the program
reads fields out of it. For system calls there is an extra layer: the syscalls:sys_enter_* events
are synthesised by one probe on the generic raw_syscalls:sys_enter tracepoint. On every system
call, that probe checks whether this particular call is wanted, and if it is, copies the arguments
into a perf buffer record before calling the program.
A raw tracepoint (4.17) skips all of that. The program is called straight from the tracepoint
with its raw TP_PROTO arguments as an array of 64-bit values: for sys_enter, a pointer to the
saved user registers and the system call number. Nothing is copied, and nothing is filtered: our
program sees every system call and has to pick out getpid itself.
A BTF tracepoint, tp_btf (5.5), attaches the same way but is typed: the kernel’s BTF tells the
verifier that argument 0 is a struct pt_regs * and argument 1 a long, so the program can name
them, and dereference kernel pointers directly instead of copying through a helper.
One cost is shared by all three when the tracepoint is sys_enter or sys_exit. Enabling either
sets a flag on every task in the system, which sends every system call through the slower entry path
that knows how to call tracepoints. It is a tax on all system calls, paid by processes that are
nowhere near your program, and it is included in the numbers below because the benchmark makes
nothing but system calls.
fentry and fexit: a trampoline built for one function
Every hook so far was built for something else first, debuggers, ftrace, perf, and BPF was taught to
use it. fentry and fexit, added in 5.5, were built for BPF. They use the same __fentry__ site
as an ftrace kprobe, but instead of calling a generic ftrace trampoline that saves everything and
looks the probe up, the kernel generates a BPF trampoline: a few dozen bytes of machine code made
for this one function and this set of programs, and points the nop straight at it.
Here is the one the kernel generated for an fentry program on __do_sys_getpid, again read back
from /proc/kcore, with the call targets named from /proc/kallsyms:
ffffffffc028d000: push %rbp
ffffffffc028d001: mov %rsp,%rbp
ffffffffc028d004: sub $0x20,%rsp
ffffffffc028d008: push %rbx
ffffffffc028d009: mov $0x1,%eax
ffffffffc028d00e: mov %rax,-0x10(%rbp)
ffffffffc028d012: mov %rdi,-0x8(%rbp)
ffffffffc028d016: xor %edi,%edi
ffffffffc028d018: mov %rdi,-0x20(%rbp)
ffffffffc028d01c: movabs $0xffffb56b00679000,%rdi
ffffffffc028d026: lea -0x20(%rbp),%rsi
ffffffffc028d02a: call 0xffffffffacaf0fb0 <__bpf_prog_enter_recur>
ffffffffc028d02f: mov %rax,%rbx
ffffffffc028d032: test %rax,%rax
ffffffffc028d035: je 0xffffffffc028d040 <bpf_trampoline_6442469144_0+0x40>
ffffffffc028d037: lea -0x8(%rbp),%rdi
ffffffffc028d03b: call 0xffffffffc00147dc <the fentry program>
ffffffffc028d040: movabs $0xffffb56b00679000,%rdi
ffffffffc028d04a: mov %rbx,%rsi
ffffffffc028d04d: lea -0x20(%rbp),%rdx
ffffffffc028d051: call 0xffffffffacaf12e0 <__bpf_prog_exit_recur>
ffffffffc028d056: mov -0x8(%rbp),%rdi
ffffffffc028d05a: pop %rbx
ffffffffc028d05b: leave
ffffffffc028d05c: ret
It saves the one argument the function takes (rdi) on its own stack, calls
__bpf_prog_enter_recur, which takes the RCU read lock, disables migration and checks a per-program
recursion counter, then calls the JIT-compiled program directly with a pointer to the saved arguments
as its context, then __bpf_prog_exit_recur, and returns into the function. There is no trap, no
pt_regs, no lookup: the address of the program is a constant in the code.
That is also why fentry programs can be typed. The kernel knows from BTF exactly what the function’s
arguments are, the verifier checks the program’s accesses against those types, and a pointer argument
such as a struct file * can be followed with a plain load, file->f_inode->i_mode, instead of a
bpf_probe_read_kernel copy. libbpf’s BPF_PROG macro unpacks the context into named arguments.
fexit is the same trampoline with more to do. To see the return value it has to be on the stack when the function returns, so it calls the function itself:
ffffffffc028f000: push %rbp
ffffffffc028f001: mov %rsp,%rbp
ffffffffc028f004: sub $0x28,%rsp
ffffffffc028f008: push %rbx
ffffffffc028f009: mov $0x1,%eax
ffffffffc028f00e: mov %rax,-0x18(%rbp)
ffffffffc028f012: mov %rdi,-0x10(%rbp)
ffffffffc028f016: movabs $0xffff8efbc1bd9400,%rdi
ffffffffc028f020: call 0xffffffffacaf1a70 <__bpf_tramp_enter>
ffffffffc028f025: mov -0x10(%rbp),%rdi
ffffffffc028f029: call 0xffffffffac8fdd15 <__x64_sys_getpid+0x5>
ffffffffc028f02e: mov %rax,-0x8(%rbp)
ffffffffc028f032: nopl 0x0(%rax,%rax,1)
ffffffffc028f037: xor %edi,%edi
ffffffffc028f039: mov %rdi,-0x28(%rbp)
ffffffffc028f03d: movabs $0xffffb56b00365000,%rdi
ffffffffc028f047: lea -0x28(%rbp),%rsi
ffffffffc028f04b: call 0xffffffffacaf0fb0 <__bpf_prog_enter_recur>
ffffffffc028f050: mov %rax,%rbx
ffffffffc028f053: test %rax,%rax
ffffffffc028f056: je 0xffffffffc028f061 <bpf_trampoline_6442469144_0+0x61>
ffffffffc028f058: lea -0x10(%rbp),%rdi
ffffffffc028f05c: call 0xffffffffc00147e4 <bpf_prog_8822343a8f08a4f3_fexit>
ffffffffc028f061: movabs $0xffffb56b00365000,%rdi
ffffffffc028f06b: mov %rbx,%rsi
ffffffffc028f06e: lea -0x28(%rbp),%rdx
ffffffffc028f072: call 0xffffffffacaf12e0 <__bpf_prog_exit_recur>
ffffffffc028f077: movabs $0xffff8efbc1bd9400,%rdi
ffffffffc028f081: call 0xffffffffacaf1ad0 <__bpf_tramp_exit>
ffffffffc028f086: mov -0x8(%rbp),%rax
ffffffffc028f08a: pop %rbx
ffffffffc028f08b: leave
ffffffffc028f08c: add $0x8,%rsp
ffffffffc028f090: ret
__bpf_tramp_enter and __bpf_tramp_exit hold a reference on the trampoline image, since a
trampoline that has a function’s body running inside it cannot be freed. The call to
__do_sys_getpid+0x5 runs the real body, skipping the patched entry. The fexit program then runs
with the arguments and the return value. Finally add $0x8,%rsp; ret throws away the trampoline’s
own return address into __do_sys_getpid and returns straight to whoever called it, a return the
CPU’s predictor did not see coming. Both fexit and kretprobe pay for that.
kprobe-multi, in 5.18, uses ftrace from the other side. It is built on fprobe, an ftrace-based
entry and exit probe that attaches one handler to any number of functions in one operation: the BPF
link takes an array of addresses, and libbpf accepts a glob such as SEC("kprobe.multi/tcp_*").
Attaching a kprobe program to a thousand functions used to mean a thousand kprobes and a thousand perf
events. Now it is one system call. The program still receives a pt_regs, so it is a kprobe program
in every way that matters to its author.
One call of getpid(), four ways to be watched
Each lane follows one call into __do_sys_getpid and back, with the probe's program attached.
kprobe at __do_sys_getpid+0x5, optimisation off
the traced function
The function starts, and its second instruction is a breakpoint
__do_sys_getpid+0x0: nopl 0x0(%rax,%rax,1) __do_sys_getpid+0x5: int3 ← was push %rbp __do_sys_getpid+0x6: xor %edx,%edx
The kprobe saved the first byte of push %rbp and wrote 0xcc over it.
exception 1
int3 traps; the handler finds the probe
exc_int3 → kprobe_int3_handler
p = get_kprobe(regs->ip - 1) found: __do_sys_getpid+0x5
set_current_kprobe(p)The CPU saves the interrupted state on the stack, switches to the exception entry code and calls the handler, which has a full pt_regs for free: the exception made one.
kernel tracing code
The pre-handler runs the BPF program
p->pre_handler = kprobe_dispatcher
→ kprobe_perf_func → trace_call_bpf
bpf_prog_active++ on this CPU, rcu_read_lock
→ kprobe_offset(ctx = regs) the program: one map lookup, one addA program already running on this CPU would make trace_call_bpf skip this one.
kernel tracing code
The displaced instruction is set up to run elsewhere
setup_singlestep:
regs->flags &= ~X86_EFLAGS_IF
regs->ip = slot slot: push %rbp ; int3push is not one of the instructions kprobes emulate, so it runs from a copy, followed by a second breakpoint. This kernel is preemptible, so the copy cannot end with a jump back.
exception 2
The copy runs, and traps again
slot+0: push %rbp
slot+1: int3 → exc_int3 → kprobe_int3_handler
resume_singlestep: regs->ip = __do_sys_getpid+0x6The second trap is recognised as the end of the single step, and the CPU is sent back to the instruction after the probe.
the traced function
The body continues as if nothing happened
__do_sys_getpid+0x6: xor %edx,%edx
...
retTwo exceptions for one hit. Measured cost per call: 310.3 ns.
kprobe at __do_sys_getpid+0x0, through ftrace
the traced function
The entry nop has become a call
__do_sys_getpid+0x0: call ftrace_trampoline ← was nopl 0x0(%rax,%rax,1) __do_sys_getpid+0x5: push %rbp
The five bytes the compiler reserved for __fentry__. /sys/kernel/debug/kprobes/list marks the probe [FTRACE].
ftrace trampoline
Build a full pt_regs
pushf push %rbp ... sub $0xa8,%rsp mov %rax,0x50(%rsp) mov %rcx,0x58(%rsp) mov %rdx,0x60(%rsp) mov %rsi,0x68(%rsp) mov %rdi,0x70(%rsp) mov %r8,0x48(%rsp) mov %r9,0x40(%rsp) mov %r15,(%rsp) ... mov %rbx,0x28(%rsp) call kprobe_ftrace_handler
No exception, but every register and the flags are saved, because a kprobe handler is promised a complete pt_regs.
kernel tracing code
Find the probe, pretend it was a breakpoint, run the program
kprobe_ftrace_handler:
p = get_kprobe(ip)
regs->ip = ip + 1 "as if int3 had hit"
p->pre_handler → kprobe_dispatcher → kprobe_perf_func
→ trace_call_bpf → kprobe_entry(ctx = regs)The same handler chain as the trapping probe, entered by a call.
the traced function
Restore everything and return into the function
mov 0x50(%rsp),%rax ... add $0xd0,%rsp popf ret → __do_sys_getpid+0x5
Nothing to single-step: the probed instruction was a nop. Measured cost per call: 26.8 ns.
fentry on __do_sys_getpid
the traced function
The entry nop calls a trampoline made for this function
__do_sys_getpid+0x0: call bpf_trampoline_6442469144_0 __do_sys_getpid+0x5: push %rbp
The number in the name is the BTF id of __do_sys_getpid. The trampoline was generated when the program was attached.
BPF trampoline
Save the one argument the function has
push %rbp mov %rsp,%rbp sub $0x20,%rsp push %rbx mov $0x1,%eax mov %rax,-0x10(%rbp) number of arguments mov %rdi,-0x8(%rbp) argument 0: regs
BTF says how many arguments there are and how wide, so only those are stored.
BPF trampoline
Enter, run the program, exit
movabs $<prog>,%rdi call __bpf_prog_enter_recur rcu_read_lock, migrate_disable, recursion check test %rax,%rax je skip lea -0x8(%rbp),%rdi ctx = the saved arguments call bpf_prog_..._fentry a direct call to the JIT-compiled program skip: call __bpf_prog_exit_recur
No lookup and no pt_regs: the program's address is a constant in the code.
the traced function
Return into the function
mov -0x8(%rbp),%rdi restore the argument pop %rbx leave ret → __do_sys_getpid+0x5
Measured cost per call: 7.4 ns.
fexit on __do_sys_getpid
the traced function
The same call to a trampoline
__do_sys_getpid+0x0: call bpf_trampoline_6442469144_0
fentry and fexit programs on one function share one trampoline; it is regenerated when either set changes.
BPF trampoline
Pin the trampoline, then call the function itself
mov %rdi,-0x10(%rbp) save the argument call __bpf_tramp_enter take a reference on this image mov -0x10(%rbp),%rdi call __do_sys_getpid+0x5 run the real body, past the patched entry mov %rax,-0x8(%rbp) keep the return value
The function's body now runs inside the trampoline's frame, which is why the image must not be freed meanwhile.
the BPF program
Run the fexit program with arguments and return value
call __bpf_prog_enter_recur lea -0x10(%rbp),%rdi ctx = argument, then return value call bpf_prog_..._fexit call __bpf_prog_exit_recur call __bpf_tramp_exit
The program sees regs and ret together, which no kretprobe can.
back to the caller
Skip the function's own return
mov -0x8(%rbp),%rax the function's return value pop %rbx leave add $0x8,%rsp drop the return address into __do_sys_getpid ret → do_syscall_64, directly
The CPU predicted a return into __do_sys_getpid and gets one into its caller. Measured cost per call: 27.4 ns.
Copper steps are exceptions, teal is kernel tracing code, green is the traced function's own instructions. Instructions are from the running kernel, abridged in places (the post shows the trampolines whole); the handler chains between them are the 6.2 source's. Costs are hookbench's medians.
Measuring them on one call
Descriptions of cost are cheap. I wanted numbers, for every hook, on the same target, in the same
run. The target is getpid(), about the cheapest system call there is, called two million times in a
tight loop. In the kernel, getpid() is a function called __do_sys_getpid, and the obvious name
__x64_sys_getpid is an alias of it: same address, and only one of the two names appears in
ftrace’s list of attachable functions. More on names at the end.
The BPF side is twelve programs with one body. Each adds one to a per-CPU counter, which costs a
map lookup and an increment, and each is marked ? so that libbpf loads only the one the loader asks
for:
// hooks.bpf.c — one tiny body behind twelve programs, one per kind of hook
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/usdt.bpf.h>
#define NR_getpid 39
struct {
__uint(type, BPF_MAP_TYPE_PERCPU_ARRAY);
__uint(max_entries, 1);
__type(key, __u32);
__type(value, __u64);
} hits SEC(".maps");
static __always_inline int hit(void)
{
__u32 zero = 0;
__u64 *n = bpf_map_lookup_elem(&hits, &zero);
if (n)
*n += 1;
return 0;
}
/* The kernel side: getpid(), whose body is the function __do_sys_getpid.
* The "?" stops libbpf loading a program until the loader asks for it. */
SEC("?kprobe/__do_sys_getpid")
int kprobe_entry(void *ctx) { return hit(); }
SEC("?kprobe/__do_sys_getpid+0x5")
int kprobe_offset(void *ctx) { return hit(); }
SEC("?kretprobe/__do_sys_getpid")
int kretprobe(void *ctx) { return hit(); }
SEC("?kprobe.multi/__do_sys_getpid")
int kprobe_multi(void *ctx) { return hit(); }
SEC("?fentry/__do_sys_getpid")
int BPF_PROG(fentry) { return hit(); }
SEC("?fexit/__do_sys_getpid")
int BPF_PROG(fexit, const struct pt_regs *regs, long ret) { return hit(); }
SEC("?tracepoint/syscalls/sys_enter_getpid")
int tracepoint(void *ctx) { return hit(); }
SEC("?raw_tp/sys_enter")
int raw_tp(struct bpf_raw_tracepoint_args *ctx)
{
if (ctx->args[1] != NR_getpid)
return 0;
return hit();
}
SEC("?tp_btf/sys_enter")
int BPF_PROG(tp_btf, struct pt_regs *regs, long id)
{
if (id != NR_getpid)
return 0;
return hit();
}
/* The user side: a function and a USDT probe in the benchmark itself.
* The loader supplies the binary and the function or probe name. */
SEC("?uprobe")
int uprobe(void *ctx) { return hit(); }
SEC("?uretprobe")
int uretprobe(void *ctx) { return hit(); }
SEC("?usdt")
int BPF_USDT(usdt, long i) { return hit(); }
char LICENSE[] SEC("license") = "GPL";
The user-space side attaches each program in turn, times a batch of calls, detaches, and moves on. Every round measures every hook, starting one hook further along each time, so slow drift in the machine is spread across all of them, and the extra cost of a hook is computed against the baseline of the same round. After the timed rounds come the same rounds again with the kernel’s own accounting switched on, for comparison:
// hookbench.c — time getpid() and a user function under each hook, in interleaved rounds
#define _GNU_SOURCE
#include <sched.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#include <sys/syscall.h>
#include <sys/sdt.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "hooks.skel.h"
#define N_SYS 2000000L /* getpid() calls per measurement */
#define N_USER 200000L /* user-function calls per measurement */
#define MAXR 32
enum target { SYS, FUNC, USDT };
struct mode {
const char *name;
enum target target;
struct bpf_program *prog; /* NULL: nothing attached, the baseline */
int int3; /* switch kprobe jump optimisation off */
double ns[MAXR]; /* ns per call, one per round */
double ns_on[MAXR]; /* the same with bpf_stats switched on */
double run_ns[MAXR]; /* bpf_stats: ns per run of the program */
__u64 runs; /* bpf_stats: runs in the last batch */
};
__attribute__((noinline)) int work(int x)
{
asm volatile("" ::: "memory");
return x + 1;
}
static volatile int sink;
static double now_ns(void)
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec * 1e9 + ts.tv_nsec;
}
static double run(enum target t)
{
long i, n = t == SYS ? N_SYS : N_USER;
int x = 0;
double t0 = now_ns();
for (i = 0; i < n; i++) {
if (t == SYS)
syscall(SYS_getpid);
else if (t == FUNC)
x = work(x);
else
DTRACE_PROBE1(hookbench, tick, i);
}
sink = x;
return (now_ns() - t0) / n;
}
static void set_optimisation(int on)
{
FILE *f = fopen("/proc/sys/debug/kprobes-optimization", "w");
if (f) {
fprintf(f, "%d\n", on);
fclose(f);
}
}
static struct bpf_link *attach(struct mode *m)
{
LIBBPF_OPTS(bpf_uprobe_opts, uo, .func_name = "work");
if (m->target == FUNC) {
uo.retprobe = strcmp(m->name, "uretprobe") == 0;
return bpf_program__attach_uprobe_opts(m->prog, 0, "/proc/self/exe", 0, &uo);
}
if (m->target == USDT)
return bpf_program__attach_usdt(m->prog, getpid(), "/proc/self/exe",
"hookbench", "tick", NULL);
return bpf_program__attach(m->prog);
}
/* Attach, time one batch of calls, detach. If the kernel is keeping
* bpf_stats, also record its figure for the average run of the program. */
static double measure(struct mode *m, int r)
{
struct bpf_prog_info a = {}, b = {};
__u32 len = sizeof(a);
struct bpf_link *link = NULL;
double ns;
if (m->int3)
set_optimisation(0);
if (m->prog && !(link = attach(m))) {
fprintf(stderr, "cannot attach %s\n", m->name);
exit(1);
}
if (link && m->target == SYS && !m->int3)
usleep(100000); /* give the kprobe optimiser time to run */
if (link)
bpf_obj_get_info_by_fd(bpf_program__fd(m->prog), &a, &len);
ns = run(m->target);
if (link) {
len = sizeof(b);
bpf_obj_get_info_by_fd(bpf_program__fd(m->prog), &b, &len);
m->runs = b.run_cnt - a.run_cnt;
if (m->runs)
m->run_ns[r] = (double)(b.run_time_ns - a.run_time_ns) / m->runs;
}
bpf_link__destroy(link);
if (m->int3)
set_optimisation(1);
return ns;
}
static int cmp(const void *a, const void *b)
{
double x = *(const double *)a, y = *(const double *)b;
return x < y ? -1 : x > y;
}
static double median(const double *v, int n)
{
double t[MAXR];
memcpy(t, v, n * sizeof(double));
qsort(t, n, sizeof(double), cmp);
return n % 2 ? t[n / 2] : (t[n / 2 - 1] + t[n / 2]) / 2;
}
int main(int argc, char **argv)
{
int rounds = argc > 1 ? atoi(argv[1]) : 11;
struct hooks_bpf *s;
cpu_set_t cpus;
int r, i, k, stats;
CPU_ZERO(&cpus);
CPU_SET(2, &cpus);
sched_setaffinity(0, sizeof(cpus), &cpus);
if (rounds < 1 || rounds > MAXR)
rounds = 11;
s = hooks_bpf__open();
if (!s)
return 1;
struct mode modes[] = {
{ "none", SYS, NULL },
{ "kprobe", SYS, s->progs.kprobe_entry },
{ "kprobe+5 (jmp)", SYS, s->progs.kprobe_offset },
{ "kprobe+5 (int3)", SYS, s->progs.kprobe_offset, 1 },
{ "kretprobe", SYS, s->progs.kretprobe },
{ "kprobe.multi", SYS, s->progs.kprobe_multi },
{ "fentry", SYS, s->progs.fentry },
{ "fexit", SYS, s->progs.fexit },
{ "tracepoint", SYS, s->progs.tracepoint },
{ "raw_tp", SYS, s->progs.raw_tp },
{ "tp_btf", SYS, s->progs.tp_btf },
{ "none (func)", FUNC, NULL },
{ "uprobe", FUNC, s->progs.uprobe },
{ "uretprobe", FUNC, s->progs.uretprobe },
{ "none (usdt)", USDT, NULL },
{ "usdt", USDT, s->progs.usdt },
};
int n = sizeof(modes) / sizeof(modes[0]);
for (i = 0; i < n; i++)
if (modes[i].prog)
bpf_program__set_autoload(modes[i].prog, true);
if (hooks_bpf__load(s))
return 1;
/* Interleaved: each round measures every mode, starting one further on.
* Timings come from rounds with the kernel's accounting off; then the
* same rounds again with it on, for bpf_stats' own figure per run. */
for (r = 0; r < rounds; r++)
for (k = 0; k < n; k++) {
i = (k + r) % n;
modes[i].ns[r] = measure(&modes[i], r);
}
stats = bpf_enable_stats(BPF_STATS_RUN_TIME);
for (r = 0; r < rounds; r++)
for (k = 0; k < n; k++) {
i = (k + r) % n;
modes[i].ns_on[r] = measure(&modes[i], r);
}
close(stats);
printf("%-16s %8s %8s %8s %8s | %8s %8s %8s\n", "hook", "ns/call", "extra",
"min", "max", "stats on", "ns/run", "runs");
for (i = 0; i < n; i++) {
struct mode *m = &modes[i];
struct mode *b = &modes[m->target == SYS ? 0 : m->target == FUNC ? 11 : 14];
double d[MAXR];
if (!m->prog) {
printf("%-16s %8.1f %26s | %8.1f\n", m->name,
median(m->ns, rounds), "", median(m->ns_on, rounds));
continue;
}
/* the extra cost: each round against the same round's baseline */
for (r = 0; r < rounds; r++)
d[r] = m->ns[r] - b->ns[r];
qsort(d, rounds, sizeof(double), cmp);
printf("%-16s %8.1f %8.1f %8.1f %8.1f | %8.1f %8.1f %8llu\n", m->name,
median(m->ns, rounds), median(d, rounds), d[0], d[rounds - 1],
median(m->ns_on, rounds), median(m->run_ns, rounds),
(unsigned long long)m->runs);
}
hooks_bpf__destroy(s);
return 0;
}
Three details in it matter. The kprobe five bytes into the function is attached twice: once left to
the optimiser, with a pause to let it run, and once with debug.kprobes-optimization switched off so
it stays an int3. The uprobe is placed on work() in the benchmark’s own executable, through
/proc/self/exe, for this process only. And the USDT probe is the DTRACE_PROBE1 macro from
<sys/sdt.h>, about which more below.
libbpf 1.1 and bpftool 7.1 came from their release tags, into /opt and /usr/local/sbin:
# build-libbpf.sh — libbpf 1.1.0 and bpftool 7.1.0, from their release tags
curl -sSLo libbpf-1.1.0.tar.gz https://github.com/libbpf/libbpf/archive/refs/tags/v1.1.0.tar.gz
curl -sSLo bpftool-7.1.0.tar.gz https://github.com/libbpf/bpftool/archive/refs/tags/v7.1.0.tar.gz
tar xzf libbpf-1.1.0.tar.gz && tar xzf bpftool-7.1.0.tar.gz
sudo make -C libbpf-1.1.0/src BUILD_STATIC_ONLY=y PREFIX=/opt/libbpf-1.1 \
LIBDIR=/opt/libbpf-1.1/lib install
rmdir bpftool-7.1.0/libbpf && cp -a libbpf-1.1.0 bpftool-7.1.0/libbpf
make -C bpftool-7.1.0/src
sudo install bpftool-7.1.0/src/bpftool /usr/local/sbin/bpftool
and the tool builds like every libbpf tool in this series:
# build-hooks.sh — vmlinux.h from the running kernel, then object, skeleton, loader
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.1/include \
-I/usr/include/x86_64-linux-gnu -c hooks.bpf.c -o hooks.bpf.o
bpftool gen skeleton hooks.bpf.o > hooks.skel.h
cc -g -O2 -Wall -I/opt/libbpf-1.1/include hookbench.c \
/opt/libbpf-1.1/lib/libbpf.a -lelf -lz -o hookbench
The -I/usr/include/x86_64-linux-gnu is for usdt.bpf.h, which includes <linux/errno.h>; without
the multiarch directory, clang’s BPF target cannot find <asm/errno.h> behind it. Eleven rounds,
in a virtual machine with four CPUs, the benchmark pinned to one of them and nothing else running:
$ sudo ./hookbench 11
hook ns/call extra min max | stats on ns/run runs
none 49.3 | 49.3
kprobe 76.2 26.8 25.5 29.6 | 103.7 15.6 2000000
kprobe+5 (jmp) 78.3 28.9 27.3 30.4 | 106.2 15.6 2000000
kprobe+5 (int3) 359.7 310.3 303.2 315.3 | 385.1 15.7 2000000
kretprobe 138.5 88.9 87.6 91.4 | 164.7 15.6 2000000
kprobe.multi 73.1 23.7 22.2 24.2 | 101.3 15.5 2000000
fentry 56.7 7.4 6.9 8.6 | 86.7 16.4 2000000
fexit 76.7 27.4 24.7 29.5 | 107.2 16.6 2000000
tracepoint 83.9 34.8 32.8 37.4 | 110.4 15.6 2000000
raw_tp 56.0 6.9 5.2 10.4 | 84.7 15.5 2000001
tp_btf 56.1 6.8 4.2 11.7 | 84.7 15.5 2000001
none (func) 0.3 | 0.3
uprobe 8135.7 8135.4 8029.5 10680.6 | 8117.4 18.2 200000
uretprobe 8594.7 8594.4 8539.3 9263.0 | 8547.4 26.7 200000
none (usdt) 0.2 | 0.2
usdt 303.9 303.8 300.3 309.6 | 333.9 21.7 200000
ns/call is the median over the eleven rounds. extra is the median of the per-round differences
from the baseline above it, and min and max are the smallest and largest of those differences:
the spread, not an error bar. The runs column is the kernel’s count of program runs in the last
batch, and the number of calls matches it, so every hook saw every call. (raw_tp and tp_btf ran
twice more than that, because they see every system call, including the two bpf() calls the
benchmark makes around each batch to read the statistics. The program filters them out, but it ran.)
What each hook adds to one call
The same two-instruction program behind every hook, on Linux 6.2 in a 4-vCPU VM. Median of 11 interleaved rounds; the thin line is the range of the rounds.
Kernel: getpid(), 2,000,000 calls per measurement, untraced 49.3 ns per call
User space: work() or a USDT marker, 200,000 calls per measurement
Extra time per call: the hook's cost plus the program's, over the untraced call measured in the same round.
The numbers as a table
| hook | ns/call | extra | min | max | stats on | ns/run |
|---|---|---|---|---|---|---|
| kprobe | 76.2 | 26.8 | 25.5 | 29.6 | 103.7 | 15.6 |
| kprobe+5 (jmp) | 78.3 | 28.9 | 27.3 | 30.4 | 106.2 | 15.6 |
| kprobe+5 (int3) | 359.7 | 310.3 | 303.2 | 315.3 | 385.1 | 15.7 |
| kretprobe | 138.5 | 88.9 | 87.6 | 91.4 | 164.7 | 15.6 |
| kprobe.multi | 73.1 | 23.7 | 22.2 | 24.2 | 101.3 | 15.5 |
| fentry | 56.7 | 7.4 | 6.9 | 8.6 | 86.7 | 16.4 |
| fexit | 76.7 | 27.4 | 24.7 | 29.5 | 107.2 | 16.6 |
| tracepoint | 83.9 | 34.8 | 32.8 | 37.4 | 110.4 | 15.6 |
| raw_tp | 56 | 6.9 | 5.2 | 10.4 | 84.7 | 15.5 |
| tp_btf | 56.1 | 6.8 | 4.2 | 11.7 | 84.7 | 15.5 |
| uprobe | 8135.7 | 8135.4 | 8029.5 | 10680.6 | 8117.4 | 18.2 |
| uretprobe | 8594.7 | 8594.4 | 8539.3 | 9263 | 8547.4 | 26.7 |
| usdt | 303.9 | 303.8 | 300.3 | 309.6 | 333.9 | 21.7 |
bpf_stats times the program alone, from just before it starts to just after it returns, and adds two clock reads to every run doing so. That is why its figure barely moves between hooks, and why it is larger than the whole extra cost of the cheapest ones.
Read from the bottom of the kernel half up:
- Raw tracepoints and tp_btf are the cheapest way in, about 6.9 and 6.8 ns per
call, and that includes the slow system-call entry path that any
sys_enterprogram switches on. The typed version costs nothing extra over the untyped one: the types are checked at load time and do not exist at run time. - fentry costs about the same, 7.4 ns. A direct call to a trampoline, two calls to the enter and exit functions, one to the program.
- kprobe-multi, an entry kprobe and fexit cluster between 24 and 28 ns. The first two pay for the
generic ftrace trampoline that saves a full
pt_regs; fexit pays for calling the function from the trampoline and the mispredicted return. - The perf tracepoint costs 35 ns, several times the raw one, for attaching to the same event: the copy into a perf record is the difference.
- The jump-optimised kprobe, 29 ns, is a little dearer than the ftrace one at the same function’s entry, because the detour has to run the displaced instructions as well.
- A kretprobe costs 89 ns, an entry probe and a return trampoline.
- A kprobe that traps costs 310 ns, more than six times the call it is attached to. That
is two
int3exceptions, each a round trip through the exception entry code.
The ns/run column is what bpf_stats reports: the kernel’s own average time per run of the program,
measured by reading the clock before and after it. It is about 16 ns for every kernel hook, which
says two things. First, it measures only the program, not the road to it, so it cannot tell a
7-nanosecond hook from a 310-nanosecond one. Second, 16 ns is more than the entire extra cost of the
cheapest hooks, so most of it is the measuring. The stats on column shows what switching the
accounting on did to the calls themselves: each became roughly 28 ns slower. bpf_stats
is the right tool for finding the expensive program among many, and the wrong one for timing a
cheap one.
User space: uprobes, uretprobes and USDT
The bottom of the table is a different world, and the reason is where the code runs. A uprobe puts an
int3 into a user-space program’s code, in a private copy of the page for each process the probe
applies to: here, only the benchmark itself. When the program hits it, the
CPU traps into the kernel, which finds the uprobe, runs the BPF program, and then must still execute
the instruction it replaced, in the process’s own address space. For that the kernel maps a page of
“execute out of line” slots into the process, labelled [uprobes] in /proc/<pid>/maps, copies the
instruction there, sets the trap flag and returns to user space; the CPU runs one instruction and
traps again; the kernel fixes up the instruction pointer and returns once more. Two exceptions and
two returns to user space per hit.
Unless the instruction can be emulated. The x86 uprobe code in 6.2 emulates nop, jumps, calls and
push of a register, and for those it adjusts the registers itself and returns once. Look at what
the probe was on:
$ objdump -d --no-show-raw-insn hookbench | grep -A3 '<work>:'
0000000000006950 <work>:
6950: endbr64
6954: lea 0x1(%rdi),%eax
6957: ret
work() starts with endbr64, the landing-pad instruction for Intel’s indirect-branch tracking,
which Ubuntu’s GCC emits at the start of every function by default (-fcf-protection). It is not on
the emulation list, so every hit is single-stepped. The USDT probe, on the other hand, is a nop.
Counting, with bpftrace, the calls to the kernel function that ends a single step and the results of
the one that decides whether to emulate, during one round of the benchmark:
$ sudo bpftrace -e 'kretprobe:arch_uprobe_skip_sstep { @emulated[retval] = count(); }
kprobe:arch_uprobe_post_xol { @stepped = count(); }'
Attaching 2 probes...
@emulated[1]: 400000
@emulated[0]: 800000
@stepped: 800000
hookbench 1 makes two passes, one timed and one with the statistics on, so the uprobe and the
uretprobe each saw 400,000 calls, and all 800,000 were single-stepped; the USDT probe saw 400,000,
and all of them were emulated. Same mechanism, same
program, and 8.1 µs against 304 ns, roughly 27 times
apart, decided by the first instruction of the probed function. Exceptions and returns to user space
are probably dearer in this VM than on bare metal, so treat the absolute numbers as this machine’s. The lesson travels: a
uprobe costs microseconds, not nanoseconds, and it is the wrong tool for a function called millions
of times a second.
uretprobes work like kretprobes: at the entry hit, the kernel replaces the return address on the
user stack with the address of a trampoline in the same [uprobes] page, and the return lands on a
breakpoint there. That trampoline breakpoint is handled without a single step, which is why a
uretprobe here cost only 459 ns more than the uprobe it is built on.
USDT, “user statically defined tracing”, is to uprobes what tracepoints are to kprobes: a hook
the program’s author put there on purpose. The DTRACE_PROBE1 macro from SystemTap’s <sys/sdt.h>
compiles to a single nop and an ELF note that records where the nop is and where each argument
will be at that moment:
$ readelf -n hookbench | grep -A4 stapsdt
Displaying notes found in: .note.stapsdt
Owner Data size Description
stapsdt 0x0000002f NT_STAPSDT (SystemTap probe descriptors)
Provider: hookbench
Name: tick
Location: 0x0000000000006aba, Base: 0x0000000000043771, Semaphore: 0x0000000000000000
Arguments: -8@%r13
-8@%r13 means “a signed 8-byte value, in r13”. Python, Node.js, the JVM and PostgreSQL can all be built
with such markers, and 22.04’s own libc.so.6 carries 84 of them. libbpf learned to attach to them in 0.8, last May:
bpf_program__attach_usdt() parses the notes, puts a uprobe on each nop, and stores each site’s
argument specification in a map, keyed by a BPF cookie, a 64-bit value attached to each link that
the program reads back with bpf_get_attach_cookie() (5.15). The BPF_USDT macro in usdt.bpf.h
does the lookup and fetches the arguments, so the program reads long i as if it were a function
parameter. On this machine it cost 304 ns per hit: the cheapest way into user space,
because a nop is the easiest instruction there is to emulate.
A worked example: how long does a read take?
Timings of mechanisms are one thing. Here is a real tool written both ways, to see what the choice of
hook changes in the code as well as the cost. The question: how long does vfs_read(), the function
behind every read(), take, and does it depend on what is being read?
The idea is the standard one for latency: note the time when the function is entered, keyed by thread, and at exit, subtract and add the result to a histogram. With fentry and fexit, the exit program also gets the function’s arguments, so it can look at the file it was reading and pick a histogram: one for regular files, one for pipes, one for everything else.
// readlat.bpf.c — how long vfs_read() takes, split by what is being read
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#include <bpf/bpf_tracing.h>
#include <bpf/bpf_core_read.h>
#define S_IFMT 0170000
#define S_IFREG 0100000
#define S_IFIFO 0010000
#define SLOTS 32
enum kind { REGULAR, PIPE, OTHER, KINDS };
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 10240);
__type(key, __u32); /* thread id */
__type(value, __u64); /* when its vfs_read() began */
} start SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, KINDS * SLOTS); /* a log2 histogram per kind */
__type(key, __u32);
__type(value, __u64);
} hist SEC(".maps");
static __always_inline void record(__u64 begin, umode_t mode)
{
__u64 delta = bpf_ktime_get_ns() - begin, *count;
__u32 kind, slot = 0;
while (delta > 1 && slot < SLOTS - 1) { /* slot = log2(ns) */
delta >>= 1;
slot++;
}
kind = (mode & S_IFMT) == S_IFREG ? REGULAR :
(mode & S_IFMT) == S_IFIFO ? PIPE : OTHER;
kind = kind * SLOTS + slot;
count = bpf_map_lookup_elem(&hist, &kind);
if (count)
__sync_fetch_and_add(count, 1);
}
/* fentry/fexit: the arguments are typed, and still there at exit. */
SEC("?fentry/vfs_read")
int BPF_PROG(read_entry)
{
__u32 tid = (__u32)bpf_get_current_pid_tgid();
__u64 now = bpf_ktime_get_ns();
bpf_map_update_elem(&start, &tid, &now, BPF_ANY);
return 0;
}
SEC("?fexit/vfs_read")
int BPF_PROG(read_exit, struct file *file, char *buf, size_t count,
loff_t *pos, ssize_t ret)
{
__u32 tid = (__u32)bpf_get_current_pid_tgid();
__u64 *begin = bpf_map_lookup_elem(&start, &tid);
if (!begin)
return 0;
record(*begin, file->f_inode->i_mode); /* a plain, typed load */
bpf_map_delete_elem(&start, &tid);
return 0;
}
/* kprobe/kretprobe: the return probe sees only the return value, so the
* entry probe must keep the file pointer, and reading through it is a copy. */
struct pending {
__u64 begin;
struct file *file;
};
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 10240);
__type(key, __u32);
__type(value, struct pending);
} kstart SEC(".maps");
SEC("?kprobe/vfs_read")
int BPF_KPROBE(kp_read_entry, struct file *file)
{
__u32 tid = (__u32)bpf_get_current_pid_tgid();
struct pending p = { bpf_ktime_get_ns(), file };
bpf_map_update_elem(&kstart, &tid, &p, BPF_ANY);
return 0;
}
SEC("?kretprobe/vfs_read")
int BPF_KRETPROBE(kp_read_exit, ssize_t ret)
{
__u32 tid = (__u32)bpf_get_current_pid_tgid();
struct pending *p = bpf_map_lookup_elem(&kstart, &tid);
struct file *file;
if (!p)
return 0;
file = p->file;
record(p->begin, BPF_CORE_READ(file, f_inode, i_mode));
bpf_map_delete_elem(&kstart, &tid);
return 0;
}
char LICENSE[] SEC("license") = "GPL";
The two halves are the same tool, and the differences are the point:
- The fexit program has the arguments.
read_exitis declared withvfs_read’s full signature plusret, and the trampoline hands them all over at exit. A kretprobe sees only the registers at the moment of return, and by then the argument registers hold whatever the function left in them. So the kprobe version has to save thestruct file *at entry, in a bigger map value, to use it at exit. - The fexit program reads through the pointer directly.
file->f_inode->i_modecompiles to two ordinary loads; the verifier allows them because BTF says whatfilepoints to, and the JIT wraps them so that a fault reads as zero instead of crashing. The kprobe version has an untyped number and must useBPF_CORE_READ, which is twobpf_probe_read_kernel()calls with relocatable offsets. - The kprobe version could not use
BPF_CORE_READ(p->file, ...)in one go. My first attempt did, and libbpf refused it withfailed to resolve CO-RE relocation <byte_off> [22] struct pending.file: CO-RE relocations are for kernel types, andstruct pendingis mine. Copying the pointer out of the map value first, as above, fixed it.
The loader picks a pair, sleeps, and prints the three histograms in powers of two of nanoseconds, the
way bpftrace’s hist() does (K and M are 1,024 and 1,048,576):
// readlat.c — attach the fentry/fexit pair (or, with -k, the kprobe pair) and print histograms
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "readlat.skel.h"
#define SLOTS 32
static const char *kinds[] = { "regular file", "pipe", "anything else" };
static void stop(int sig) { (void)sig; }
static void print_hist(int fd, int kind)
{
__u64 v[SLOTS], max = 0, total = 0;
__u32 i, key;
int first = -1, last = -1;
for (i = 0; i < SLOTS; i++) {
key = kind * SLOTS + i;
bpf_map_lookup_elem(fd, &key, &v[i]);
if (v[i]) {
if (first < 0)
first = i;
last = i;
total += v[i];
if (v[i] > max)
max = v[i];
}
}
printf("\n%s: %llu reads, ns\n", kinds[kind], (unsigned long long)total);
for (i = first; first >= 0 && (int)i <= last; i++) {
const char *unit[] = { "", "K", "M", "G" }; /* powers of 1024 */
char lo[16], hi[16];
snprintf(lo, sizeof(lo), "%u%s", 1u << (i % 10), unit[i / 10]);
snprintf(hi, sizeof(hi), "%u%s", 1u << ((i + 1) % 10), unit[(i + 1) / 10]);
printf(" [%4s, %4s) %8llu |%-40.*s|\n", lo, hi, (unsigned long long)v[i],
(int)(v[i] * 40 / max), "****************************************");
}
}
int main(int argc, char **argv)
{
int kprobes = argc > 1 && strcmp(argv[1], "-k") == 0;
int seconds = argc > 1 + kprobes ? atoi(argv[1 + kprobes]) : 10;
struct readlat_bpf *s = readlat_bpf__open();
int k;
if (!s)
return 1;
bpf_program__set_autoload(kprobes ? s->progs.kp_read_entry : s->progs.read_entry, true);
bpf_program__set_autoload(kprobes ? s->progs.kp_read_exit : s->progs.read_exit, true);
if (readlat_bpf__load(s) || readlat_bpf__attach(s)) {
fprintf(stderr, "failed to load or attach\n");
return 1;
}
signal(SIGINT, stop);
signal(SIGTERM, stop);
printf("timing vfs_read() with %s for %d s\n",
kprobes ? "kprobe/kretprobe" : "fentry/fexit", seconds);
fflush(stdout);
sleep(seconds); /* returns early on SIGINT or SIGTERM */
for (k = 0; k < 3; k++)
print_hist(bpf_map__fd(s->maps.hist), k);
readlat_bpf__destroy(s);
return 0;
}
# build-readlat.sh — same recipe, same vmlinux.h
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -I/opt/libbpf-1.1/include \
-c readlat.bpf.c -o readlat.bpf.o
bpftool gen skeleton readlat.bpf.o > readlat.skel.h
cc -g -O2 -Wall -I/opt/libbpf-1.1/include readlat.c \
/opt/libbpf-1.1/lib/libbpf.a -lelf -lz -o readlat
The workload reads three kinds of file in turn: 64 MiB from a file on tmpfs in 64 KiB reads, so
from memory; a hundred one-byte reads from a pipe whose writer sleeps 10 ms between bytes; and 1,024
reads of 64 KiB from /dev/zero:
# readlat-run.sh — three kinds of read, under each version of the tool
head -c 64M /dev/zero > /dev/shm/data
for flag in "" -k; do
sudo ./readlat $flag 6 &
sleep 1
dd if=/dev/shm/data of=/dev/null bs=64k 2>/dev/null
for i in $(seq 100); do sleep 0.01; printf x; done | dd of=/dev/null bs=1 2>/dev/null
dd if=/dev/zero of=/dev/null bs=64k count=1024 2>/dev/null
wait
done
Under the fentry/fexit pair:
timing vfs_read() with fentry/fexit for 6 s
regular file: 1545 reads, ns
[ 128, 256) 1 | |
[ 256, 512) 0 | |
[ 512, 1K) 0 | |
[ 1K, 2K) 0 | |
[ 2K, 4K) 0 | |
[ 4K, 8K) 952 |****************************************|
[ 8K, 16K) 61 |** |
[ 16K, 32K) 10 | |
[ 32K, 64K) 71 |** |
[ 64K, 128K) 415 |***************** |
[128K, 256K) 32 |* |
[256K, 512K) 3 | |
pipe: 105 reads, ns
[ 64, 128) 1 | |
[ 128, 256) 0 | |
[ 256, 512) 1 | |
[ 512, 1K) 0 | |
[ 1K, 2K) 1 | |
[ 2K, 4K) 0 | |
[ 4K, 8K) 0 | |
[ 8K, 16K) 0 | |
[ 16K, 32K) 0 | |
[ 32K, 64K) 0 | |
[ 64K, 128K) 1 | |
[128K, 256K) 0 | |
[256K, 512K) 0 | |
[512K, 1M) 0 | |
[ 1M, 2M) 0 | |
[ 2M, 4M) 0 | |
[ 4M, 8M) 0 | |
[ 8M, 16M) 7 |** |
[ 16M, 32M) 94 |****************************************|
anything else: 1024 reads, ns
[ 512, 1K) 1019 |****************************************|
[ 1K, 2K) 1 | |
[ 2K, 4K) 0 | |
[ 4K, 8K) 1 | |
[ 8K, 16K) 2 | |
[ 16K, 32K) 1 | |
The three kinds of read separate cleanly. A 64 KiB read from /dev/zero takes half a microsecond to
a microsecond: the kernel only has to clear the user’s buffer. The same amount from a tmpfs file
takes 4 to 8 µs, because now it is a copy out of the page cache. The pipe reads take 8 to 32 ms,
almost all of it asleep, waiting for a writer whose loop runs sleep 0.01 as a separate process
each time.
The other hump in the regular-file histogram, around 32 to 128 µs, was a surprise, so I asked bpftrace who was doing those reads (the query is in the note at the end):
Attaching 2 probes...
@slow[dd, libc.so.6]: 5
@slow[sleep, libc.so.6]: 420
Of those, 420 come from the hundred sleep processes: each one’s dynamic loader reads
libc.so.6 with read() when it starts. In this VM the root filesystem is a 9p share from the
host, so those reads are a round trip out of the guest. A histogram of every vfs_read() on the
machine shows you the machine, not just the program you meant to look at.
The kprobe pair, on the same workload:
timing vfs_read() with kprobe/kretprobe for 6 s
regular file: 1545 reads, ns
[ 128, 256) 1 | |
[ 256, 512) 0 | |
[ 512, 1K) 0 | |
[ 1K, 2K) 0 | |
[ 2K, 4K) 0 | |
[ 4K, 8K) 965 |****************************************|
[ 8K, 16K) 53 |** |
[ 16K, 32K) 5 | |
[ 32K, 64K) 100 |**** |
[ 64K, 128K) 386 |**************** |
[128K, 256K) 27 |* |
[256K, 512K) 7 | |
[512K, 1M) 1 | |
pipe: 105 reads, ns
[ 128, 256) 1 | |
[ 256, 512) 1 | |
[ 512, 1K) 1 | |
[ 1K, 2K) 0 | |
[ 2K, 4K) 1 | |
[ 4K, 8K) 0 | |
[ 8K, 16K) 0 | |
[ 16K, 32K) 0 | |
[ 32K, 64K) 0 | |
[ 64K, 128K) 0 | |
[128K, 256K) 0 | |
[256K, 512K) 0 | |
[512K, 1M) 0 | |
[ 1M, 2M) 0 | |
[ 2M, 4M) 0 | |
[ 4M, 8M) 1 | |
[ 8M, 16M) 13 |****** |
[ 16M, 32M) 85 |****************************************|
[ 32M, 64M) 2 | |
anything else: 1024 reads, ns
[ 512, 1K) 986 |****************************************|
[ 1K, 2K) 32 |* |
[ 2K, 4K) 1 | |
[ 4K, 8K) 1 | |
[ 8K, 16K) 0 | |
[ 16K, 32K) 3 | |
[ 32K, 64K) 1 | |
The same shape, as it should be: the two versions are measuring the same thing. Now the cost.
A million one-byte reads from /dev/zero (each also a write to /dev/null), untraced, under the
fentry pair, and under the kprobe pair, seven rounds interleaved:
# readlat-cost.sh — a million one-byte reads: untraced, fentry pair, kprobe pair
for round in 1 2 3 4 5 6 7; do
for mode in none fentry kprobe; do
case $mode in
fentry) sudo ./readlat 60 > /dev/null & ;;
kprobe) sudo ./readlat -k 60 > /dev/null & ;;
esac
sleep 1
dd if=/dev/zero of=/dev/null bs=1 count=1000000 2>&1 |
awk -v m=$mode '/copied/ { print m, $(NF - 3) }'
[ $mode = none ] || { sudo kill -INT $!; wait; }
done
done
none 0.173366
fentry 0.348016
kprobe 0.387943
none 0.170912
fentry 0.328939
kprobe 0.384416
none 0.167362
fentry 0.332163
kprobe 0.381027
none 0.17028
fentry 0.343714
kprobe 0.387287
none 0.170258
fentry 0.334751
kprobe 0.384322
none 0.172455
fentry 0.333752
kprobe 0.382142
none 0.168748
fentry 0.340642
kprobe 0.382556
That is 170 ns per read-and-write untraced, 335 with the fentry pair and 384 with the kprobe pair, medians of the seven rounds: tracing cost 164 ns per read with fentry and fexit, and 214 with the kprobe and kretprobe. The hooks are part of the difference; the rest is the program bodies, two clock reads, a hash insert, lookup and delete, and an atomic add, and they are the same in both. Choosing fentry saved about 23% of the tracing cost here, and more where the body is smaller.
Sampling: perf events and stack traces
Every hook so far fires when execution reaches a particular place. The last kind fires on a clock. A perf event program (4.9) is attached to a perf event, which can be a hardware counter overflowing (every n cache misses, every n cycles) or a software timer. Attach one to a timer on every CPU and you have the core of a sampling profiler: every tick, look at what the CPU was doing, and count. Do that a few hundred times a second for long enough and the counts are a picture of where the time goes.
“What the CPU was doing” means the call stack, and BPF has helpers for it. bpf_get_stackid()
walks the stack, kernel or user, and stores it in a map of type BPF_MAP_TYPE_STACK_TRACE (both
4.6), returning an ID; identical stacks get the same ID, so a program can count by ID cheaply.
bpf_get_stack() (4.18) copies the addresses into a buffer instead, for programs that want to send
them somewhere. Either way the program gets addresses. Turning them into names is user space’s job:
/proc/kallsyms for the kernel, and for user space, the process’s memory map and the symbol tables
of the files it maps.
How the kernel walks a user stack matters a great deal. It follows frame pointers: each function
that keeps one stores the caller’s frame pointer at [rbp] and its return address at [rbp+8], so
the walk is a linked list. A function compiled without a frame pointer uses rbp for something else,
and the walk either stops or follows garbage. There is no other unwinder for user space in this
kernel. Most distributions build their packages with -fomit-frame-pointer, GCC’s default at -O2
on x86-64, because the register is worth a few percent of speed.
Here is a complete profiler. The BPF half counts samples by process, kernel stack and user stack:
// profile.bpf.c — on every timer tick, record which stack the CPU was running
#include "vmlinux.h"
#include <bpf/bpf_helpers.h>
#define MAX_DEPTH 127
const volatile __u32 targ_tgid; /* set by the loader; 0 means everyone */
struct stack_key {
__u32 tgid;
__s32 kstack; /* ids into the stack map, or <0: none */
__s32 ustack;
char comm[16];
};
struct {
__uint(type, BPF_MAP_TYPE_STACK_TRACE);
__uint(max_entries, 16384);
__uint(key_size, sizeof(__u32));
__uint(value_size, MAX_DEPTH * sizeof(__u64));
} stacks SEC(".maps");
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 16384);
__type(key, struct stack_key);
__type(value, __u64);
} counts SEC(".maps");
SEC("perf_event")
int sample(struct bpf_perf_event_data *ctx)
{
__u32 tgid = bpf_get_current_pid_tgid() >> 32;
struct stack_key k = {};
__u64 one = 1, *n;
if (tgid == 0 || (targ_tgid && tgid != targ_tgid))
return 0; /* the idle task, or not ours */
k.tgid = tgid;
k.kstack = bpf_get_stackid(ctx, &stacks, 0);
k.ustack = bpf_get_stackid(ctx, &stacks, BPF_F_USER_STACK);
bpf_get_current_comm(k.comm, sizeof(k.comm));
n = bpf_map_lookup_elem(&counts, &k);
if (n)
__sync_fetch_and_add(n, 1);
else
bpf_map_update_elem(&counts, &k, &one, BPF_NOEXIST);
return 0;
}
char LICENSE[] SEC("license") = "GPL";
The user half opens a PERF_COUNT_SW_CPU_CLOCK event on each CPU at a chosen frequency, attaches
the program to each, sleeps, and then walks the counts map, turning each pair of stacks into one line
of folded output: the process name, then the frames from the outermost in, separated by
semicolons, then a count. Kernel frames get a _[k] suffix. That format was popularised by Brendan
Gregg’s FlameGraph scripts, and nearly every profiling tool reads or writes it.
// profile.c — sample a process's stacks on every CPU, print them as folded stacks
#include <fcntl.h>
#include <gelf.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <linux/perf_event.h>
#include <sys/syscall.h>
#include <bpf/libbpf.h>
#include <bpf/bpf.h>
#include "profile.skel.h"
#define MAX_DEPTH 127
struct stack_key { /* must match profile.bpf.c */
__u32 tgid;
__s32 kstack, ustack;
char comm[16];
};
struct sym { unsigned long addr, size; char *name; };
struct symtab { struct sym *s; int n, cap; };
struct mapping { /* one executable mapping of the target */
unsigned long start, end;
long delta; /* runtime address + delta = ELF address */
char *file;
struct symtab syms;
};
static struct symtab ksyms;
static struct mapping maps[64];
static int nmaps;
static void add_sym(struct symtab *t, unsigned long addr, unsigned long size, const char *name)
{
if (t->n == t->cap) {
t->cap = t->cap ? 2 * t->cap : 1024;
t->s = realloc(t->s, t->cap * sizeof(*t->s));
}
t->s[t->n++] = (struct sym){ addr, size, strdup(name) };
}
static int by_addr(const void *a, const void *b)
{
const struct sym *x = a, *y = b;
return x->addr < y->addr ? -1 : x->addr > y->addr;
}
static const char *find_sym(struct symtab *t, unsigned long addr)
{
int lo = 0, hi = t->n - 1, best = -1;
while (lo <= hi) { /* the last symbol at or below addr */
int mid = (lo + hi) / 2;
if (t->s[mid].addr <= addr) {
best = mid;
lo = mid + 1;
} else {
hi = mid - 1;
}
}
if (best < 0 || (t->s[best].size && addr >= t->s[best].addr + t->s[best].size))
return NULL;
return t->s[best].name;
}
/* Kernel addresses: /proc/kallsyms, text symbols only. */
static void load_kallsyms(void)
{
FILE *f = fopen("/proc/kallsyms", "r");
char name[256], type;
unsigned long addr;
while (f && fscanf(f, "%lx %c %255s%*[^\n]", &addr, &type, name) == 3)
if (type == 't' || type == 'T')
add_sym(&ksyms, addr, 0, name);
if (f)
fclose(f);
qsort(ksyms.s, ksyms.n, sizeof(struct sym), by_addr);
}
/* User addresses: the function symbols of the file behind the mapping. */
static void load_elf(struct mapping *m, unsigned long offset)
{
int fd = open(m->file, O_RDONLY);
Elf *e = fd < 0 ? NULL : elf_begin(fd, ELF_C_READ, NULL);
Elf_Scn *scn = NULL;
size_t i, n;
if (!e)
goto out;
/* Which segment was mapped here, and so how file offsets become ELF addresses */
elf_getphdrnum(e, &n);
for (i = 0; i < n; i++) {
GElf_Phdr ph;
gelf_getphdr(e, i, &ph);
if (ph.p_type == PT_LOAD && offset >= ph.p_offset &&
offset < ph.p_offset + ph.p_filesz)
m->delta = (long)(offset - ph.p_offset + ph.p_vaddr) - (long)m->start;
}
while ((scn = elf_nextscn(e, scn))) {
GElf_Shdr sh;
Elf_Data *d;
gelf_getshdr(scn, &sh);
if (sh.sh_type != SHT_SYMTAB && sh.sh_type != SHT_DYNSYM)
continue;
d = elf_getdata(scn, NULL);
for (i = 0; d && i < sh.sh_size / sh.sh_entsize; i++) {
GElf_Sym s;
gelf_getsym(d, i, &s);
if (GELF_ST_TYPE(s.st_info) == STT_FUNC && s.st_value)
add_sym(&m->syms, s.st_value, s.st_size,
elf_strptr(e, sh.sh_link, s.st_name));
}
}
qsort(m->syms.s, m->syms.n, sizeof(struct sym), by_addr);
elf_end(e);
out:
if (fd >= 0)
close(fd);
}
static void load_maps(int pid)
{
char path[64], line[512], file[400], perms[8];
unsigned long start, end, offset;
FILE *f;
snprintf(path, sizeof(path), "/proc/%d/maps", pid);
f = fopen(path, "r");
while (f && fgets(line, sizeof(line), f) && nmaps < 64) {
if (sscanf(line, "%lx-%lx %7s %lx %*s %*s %399s", &start, &end, perms,
&offset, file) != 5 || perms[2] != 'x' || file[0] != '/')
continue;
maps[nmaps] = (struct mapping){ .start = start, .end = end, .file = strdup(file) };
load_elf(&maps[nmaps++], offset);
}
if (f)
fclose(f);
}
static void print_user(unsigned long ip)
{
for (int i = 0; i < nmaps; i++) {
if (ip < maps[i].start || ip >= maps[i].end)
continue;
const char *name = find_sym(&maps[i].syms, ip + maps[i].delta);
const char *base = strrchr(maps[i].file, '/') + 1;
if (name)
printf(";%s", name);
else
printf(";[%s+0x%lx]", base, ip + maps[i].delta);
return;
}
printf(";[unknown]");
}
int main(int argc, char **argv)
{
int pid = argc > 1 ? atoi(argv[1]) : 0;
int seconds = argc > 2 ? atoi(argv[2]) : 5;
int hz = argc > 3 ? atoi(argv[3]) : 99;
int ncpu = libbpf_num_possible_cpus(), cpu, sfd, cfd;
struct perf_event_attr attr = {
.type = PERF_TYPE_SOFTWARE,
.config = PERF_COUNT_SW_CPU_CLOCK, /* a timer: no hardware PMU needed */
.size = sizeof(attr),
.sample_freq = hz,
.freq = 1,
};
struct profile_bpf *s = profile_bpf__open();
struct stack_key k, next, *prev = NULL;
__u64 ips[MAX_DEPTH], count;
if (!s)
return 1;
s->rodata->targ_tgid = pid;
if (profile_bpf__load(s))
return 1;
for (cpu = 0; cpu < ncpu; cpu++) { /* one sampling event per CPU */
int pfd = syscall(__NR_perf_event_open, &attr, -1, cpu, -1, 0);
if (pfd < 0 || !bpf_program__attach_perf_event(s->progs.sample, pfd)) {
fprintf(stderr, "cannot sample on CPU %d\n", cpu);
return 1;
}
}
sleep(seconds);
elf_version(EV_CURRENT);
load_kallsyms();
if (pid)
load_maps(pid);
sfd = bpf_map__fd(s->maps.stacks);
cfd = bpf_map__fd(s->maps.counts);
while (bpf_map_get_next_key(cfd, prev, &next) == 0) {
k = next;
prev = &k;
bpf_map_lookup_elem(cfd, &k, &count);
printf("%s", k.comm);
/* user frames, outermost first, then the kernel's */
memset(ips, 0, sizeof(ips));
if (k.ustack >= 0 && bpf_map_lookup_elem(sfd, &k.ustack, ips) == 0)
for (int i = MAX_DEPTH - 1; i >= 0; i--)
if (ips[i])
print_user(ips[i]);
memset(ips, 0, sizeof(ips));
if (k.kstack >= 0 && bpf_map_lookup_elem(sfd, &k.kstack, ips) == 0)
for (int i = MAX_DEPTH - 1; i >= 0; i--)
if (ips[i]) {
const char *name = find_sym(&ksyms, ips[i]);
printf(";%s_[k]", name ? name : "[unknown]");
}
printf(" %llu\n", (unsigned long long)count);
}
profile_bpf__destroy(s);
return 0;
}
The symbol lookup is the longest part, and it is the simplest version that works: for an address in a
mapped file, work out the offset in the file, find which loadable segment that offset is in, convert
to the address the ELF symbol table uses, and binary-search the function symbols of .symtab, or of
.dynsym if the file is stripped. Real profilers add caching, debuginfo lookups by build ID,
demangling and support for JIT-compiled code, but none of that changes the idea.
The target is a program whose shape we know in advance. It loops over three jobs: read 256 KiB from
/dev/zero, hash a 4 KiB buffer six times, and sort 256 integers with the C library’s qsort().
It is built with frame pointers, -fno-omit-frame-pointer, and with -mno-omit-leaf-frame-pointer
too, which asks for them even in functions that call nothing:
// burn.c — a program whose time we can account for in advance
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#define N 4096
static unsigned char buf[N];
static int keys[256];
static char big[65536];
volatile unsigned long sink;
__attribute__((noinline)) static unsigned long hash(const unsigned char *p, int n)
{
unsigned long h = 5381;
for (int i = 0; i < n; i++)
h = h * 33 + p[i];
return h;
}
__attribute__((noinline)) static void parse(void)
{
for (int i = 0; i < 6; i++)
sink += hash(buf, N);
}
static int cmp(const void *a, const void *b)
{
return *(const int *)a - *(const int *)b;
}
__attribute__((noinline)) static void sort_keys(void)
{
for (int i = 0; i < 256; i++)
keys[i] = (i * 7919) & 1023;
qsort(keys, 256, sizeof(int), cmp);
}
__attribute__((noinline)) static void load(int fd)
{
for (int i = 0; i < 4; i++)
sink += read(fd, big, sizeof(big));
}
int main(void)
{
int fd = open("/dev/zero", O_RDONLY);
memset(buf, 'x', N);
for (;;) {
load(fd);
parse();
sort_keys();
}
}
# build-profile.sh — the profiler, and a target built with frame pointers
clang -g -O2 -target bpf -D__TARGET_ARCH_x86 -I/opt/libbpf-1.1/include \
-c profile.bpf.c -o profile.bpf.o
bpftool gen skeleton profile.bpf.o > profile.skel.h
cc -g -O2 -Wall -I/opt/libbpf-1.1/include profile.c \
/opt/libbpf-1.1/lib/libbpf.a -lelf -lz -o profile
cc -O2 -fno-omit-frame-pointer -mno-omit-leaf-frame-pointer burn.c -o burn
# profile-run.sh — ten seconds of burn at 99 samples a second, then the totals
./burn &
sleep 1
sudo ./profile $! 10 99 > burn.folded
kill $!
awk '{ n[$1] += $2 } END { for (s in n) print n[s], s }' burn.folded | sort -rn
The VM’s virtual CPU is a model this kernel’s perf driver does not recognise (it says “no PMU driver, software events only” at boot), so there are no hardware counters to sample on, and the profiler uses the software CPU clock. That is also why the program asks for nothing but a timer. Ten seconds at 99 Hz:
$ sh profile-run.sh
653 burn;[libc.so.6+0x29d90];main;hash.constprop.0
145 burn;[libc.so.6+0x29d90];main;__read;entry_SYSCALL_64_after_hwframe_[k];do_syscall_64_[k];__x64_sys_read_[k];ksys_read_[k];vfs_read_[k];read_zero_[k]
22 burn;[libc.so.6+0x4453f]
21 burn;cmp
17 burn;[libc.so.6+0x1a09c5]
13 burn;[libc.so.6+0x29d90];main;__read
9 burn;[libc.so.6+0x44704]
8 burn;[libc.so.6+0x29d90];main;__read;entry_SYSCALL_64_after_hwframe_[k];do_syscall_64_[k];__x64_sys_read_[k];ksys_read_[k];vfs_read_[k];__fsnotify_parent_[k]
8 burn;[libc.so.6+0x1a09a6]
6 burn;[libc.so.6+0x4454b]
6 burn;[libc.so.6+0x29d90];sort_keys
5 burn;[libc.so.6+0x44710]
5 burn;[libc.so.6+0x44557]
4 burn;[libc.so.6+0x44700]
4 burn;[libc.so.6+0x29d90];main;__read;entry_SYSCALL_64_after_hwframe_[k];do_syscall_64_[k];syscall_enter_from_user_mode_[k]
4 burn;[libc.so.6+0x1a0951]
... 53 more lines of 1 to 3 samples each, 65 samples in all
995 samples: 99 a second for a little over ten seconds, since the timers keep firing while the profiler reads its maps back. The counts are all there. The picture is less tidy:
Where burn's time went, as the profiler saw it
995 samples at 99 Hz, ten seconds and a little more. Width is share of samples; each box sits on the function that called it.
The source says main calls load, parse and sort_keys, and parse calls hash. The graph has main calling hash and __read directly, and the sort as stumps on the root: frame-pointer unwinding loses the caller of a function that keeps no frame, and cannot walk through glibc at all.
A flame graph draws those stacks as a picture. Each box is a function; its width is the fraction of samples in which it was on the stack; the box above it is what it called. The x-axis is not time: siblings are sorted by name, so the widths are all that mean anything. The widest towers are where the time goes, and a wide box with nothing above it is a function spending its own time, not its callees'.
Reading this one: hash is 66% of the samples, two thirds, which is the answer a profiler is for. The
kernel’s share, the read() of /dev/zero, is 17%, nearly all of it in read_zero. And three
things are wrong, each of them instructive:
parseis missing. The stack goesmain, thenhash. Even with both flags, GCC 11 compiledhash()without touchingrbp(its disassembly startslea, notpush %rbp), so while the CPU is inhash,rbpstill points toparse’s frame, whose return address is inmain. The walk reports the leaf from the instruction pointer and then jumps straight from it toparse’s caller. The function that called a frameless leaf disappears.loadis missing too, for the same reason one level down: the libcread()wrapper keeps no frame, somain;__readskips the function that called it.qsortis in pieces. The thin towers standing directly onburn, each one frame tall, and the lonecmp, are samples taken inside glibc’s sort. Ubuntu builds glibc without frame pointers, so from there the walk follows whateverrbphappens to hold, gets nowhere, and each sample is filed under a stack of one frame. About 16% of the samples are in sorting, and the flame graph cannot say whose. Those frames have no names either: glibc’s internal sort functions are local symbols, and a stripped library keeps only its exported ones in.dynsym. The profiler prints such a frame as the file and the address in the file’s own numbering, whichobjdumpor a debug-symbol package can name later; the frame betweenburnandmainis the same, glibc’s__libc_start_call_main.
None of this is a bug in the profiler. It is what frame-pointer unwinding gives you on a system whose
libraries were built without frame pointers, which is nearly every system, and it is the reason
profiling is having an argument about compiler flags this year. In January, Fedora’s steering
committee approved building the coming Fedora 38 with -fno-omit-frame-pointer and
-mno-omit-leaf-frame-pointer by default, to be re-evaluated by Fedora 40, after a long debate about
the cost. The other answer is to unwind without frame pointers, from the DWARF call-frame information
that compilers emit for exceptions and debuggers. perf record --call-graph dwarf does that by
copying a slice of the stack with every sample and unwinding it later, in user space. Doing it
inside a BPF program, within the verifier’s limits, is harder, and it is exactly what Parca’s agent
switched on by default in version 0.13, released on 28 February.
Continuous profiling, March 2023
The profiler above is a toy, but it is the same design as the tools that run it all day on every machine, which is called continuous profiling: sample all the time at a low rate, ship the stacks somewhere, and look at a week of flame graphs when something gets slow.
- Parca, open-sourced by Polar Signals in October 2021, is a server plus an agent. The agent is a BPF sampling profiler for the whole machine, and with 0.13 it walks the stacks of programs without frame pointers itself, in BPF, using unwind tables generated from their DWARF information.
- Pixie, a CNCF sandbox project since 2021, includes an always-on CPU profiler built on exactly the pieces above, perf events and a stack-trace map, sampling every CPU about every 10 ms. Its authors wrote up getting its overhead down to about 0.3% of CPU in 2021.
- Pyroscope added an eBPF-based agent in 2021, built on BCC, and replaced it with a CO-RE one that needs neither Python nor a compiler on the target in August 2022 (0.26). The current release is 0.37.
All three exist because the profiler needs no cooperation from what it profiles: no restart, no instrumentation, no agent inside the process. That is BPF’s whole argument, applied to performance.
Which hooks will still be there next year
The fast hooks and the stable hooks are not the same list, and that is the trade the rest of this section is about.
A tracepoint is a promise, of sorts. Kernel developers avoid changing them, because tools depend on them, though they do not treat them as a fixed ABI either. A kprobe or fentry target is a promise of nothing: it is a function name in this particular build of this particular kernel. Here is how many of those there are on 6.2, and what bpftrace offers:
$ wc -l < /sys/kernel/tracing/available_filter_functions
50852
$ sudo bpftrace -l 'kprobe:*' | wc -l
49482
$ sudo bpftrace -l 'kfunc:*' | wc -l
47190
$ sudo bpftrace -l 'tracepoint:*' | wc -l
1582
Fifty thousand functions to choose from, and 1,582 tracepoints. Each of those fifty thousand exists in the binary only because the compiler kept it there. Three kinds of thing remove a function from under a probe.
It is renamed. Linux 6.2 renamed del_timer() to timer_delete(), and del_timer_sync() to
timer_delete_sync(), keeping the old names as inline wrappers so that callers still compile. A tool
that probed del_timer worked on 6.1 and does not attach on 6.2:
$ uname -r
6.1.0-060100-generic
$ sudo bpftrace -l 'kprobe:del_timer*'
kprobe:del_timer
kprobe:del_timer_sync
$ sudo bpftrace -l 'kprobe:timer_delete*'
$ uname -r
6.2.0-060200-generic
$ sudo bpftrace -l 'kprobe:del_timer*'
$ sudo bpftrace -l 'kprobe:timer_delete*'
kprobe:timer_delete
kprobe:timer_delete_sync
$ sudo bpftrace -e 'kprobe:del_timer { @ = count(); }'
stdin:1:1-17: WARNING: del_timer is not traceable (either non-existing, inlined, or marked as "notrace"); attaching to it will likely fail
kprobe:del_timer { @ = count(); }
~~~~~~~~~~~~~~~~
Attaching 1 probe...
cannot attach kprobe, probe entry may not exist
ERROR: Error attaching probe: 'kprobe:del_timer'
It is made inline. In 5.15, blk_account_io_start() was an ordinary function in blk-core.c, and
BCC’s biosnoop and biolatency put a kprobe on it to see each block I/O begin. 5.17 moved it into
blk-mq.c as a static inline wrapper around a new __blk_account_io_start():
$ uname -r
5.15.0-25-generic
$ sudo bpftrace -l 'kprobe:*blk_account_io_*'
kprobe:blk_account_io_done
kprobe:blk_account_io_merge_bio
kprobe:blk_account_io_start
$ uname -r
6.2.0-060200-generic
$ sudo bpftrace -l 'kprobe:*blk_account_io_*'
kprobe:__blk_account_io_done
kprobe:blk_account_io_merge_bio
The source still has a blk_account_io_start(). The binary does not, because every call to it was
compiled into its callers. BCC 0.26, from December, already knows this: both tools now look for
__blk_account_io_start first and fall back to the old name. On this 6.2 build neither exists.
__blk_account_io_start is an ordinary static void function, not marked inline, and GCC inlined it
anyway, while its twin __blk_account_io_done, in the same file and written the same way, survived
as a function. Nothing in the source asked for either outcome. The same thing can happen to any
static function in any release, depending on the compiler and the configuration.
It is cloned. When GCC specialises a function, it renames it: finish_task_switch on this kernel
is finish_task_switch.isra.0 (an interprocedural scalar replacement of aggregates clone, with
a changed signature), and 6.2 has 1,590 such suffixed names among its attachable functions. A
probe on the plain name finds nothing, and a probe on the suffixed name breaks the day the compiler
makes a different choice.
And syscalls have one more trap, which the benchmark above walked into: __x64_sys_getpid and
__do_sys_getpid are the same function under two names, and the tools list only one. libbpf 1.0
added SEC("ksyscall/getpid") partly for this, resolving the architecture-specific name at load
time.
The practical rules that fall out:
- Prefer a tracepoint when one exists, and attach to it with
tp_btfor a raw tracepoint, which are both the cheapest and the most stable way in. Falco’s new CO-RE probe, shipped as experimental in 0.34 last month, is built this way: its system-call programs aretp_btf/sys_enterandtp_btf/sys_exit. - When you need a function, prefer fentry and fexit to kprobes: cheaper, typed, and with the arguments at exit. They need BTF and an ftrace-able function, which nearly every function on a modern distribution kernel is.
- Use kprobes for what nothing else reaches: an instruction in the middle of a function, a kernel without BTF, or thousands of functions at once with kprobe-multi.
- Check that the target exists before relying on it, in code: libbpf will tell you at attach
time, but a tool that probes
blk_account_io_startshould look for it inavailable_filter_functionsfirst, and have a plan for when it is not there, such as theblock:block_rq_issuetracepoint. - In user space, prefer USDT to uprobes on functions, and do not put either on a hot path.
What we covered
- BPF can attach to running code in a dozen ways. kprobes and kretprobes (4.1), tracepoints (4.7),
perf events (4.9), raw tracepoints (4.17), fentry, fexit and
tp_btf(5.5), kprobe-multi (5.18), uprobes (4.3) and USDT on top of them. - A kprobe is an
int3with a single-stepped copy of the instruction it replaced, unless the kernel can turn it into ajmp(2.6.34) or, at a function’s entry, an ftrace call (3.7). A kretprobe hijacks the return address. - Tracepoints are fixed, declared hooks. The perf-based program gets a copied record; a raw or
tp_btfprogram gets the arguments themselves, untyped or typed. - fentry and fexit run through a trampoline generated for one function. fexit calls the function itself so that it can see the return value.
- On
getpid()on Linux 6.2, the extra cost per call was about 6.9 ns for a raw tracepoint, 7.4 for fentry, 24 to 29 for kprobe-multi, ftrace and jump kprobes and fexit, 35 for a perf tracepoint, 89 for a kretprobe and 310 for a trapping kprobe. bpf_stats reported about 16 ns per run for all of them. - A uprobe on a function starting with
endbr64cost 8.1 µs per call in this VM, because the instruction is single-stepped; a USDT probe, on an emulatednop, cost 304 ns. - A
vfs_read()latency histogram is simpler and cheaper with fentry/fexit than with kprobe/kretprobe: typed arguments at exit, direct pointer loads, 164 against 214 ns per read. - A sampling profiler is a perf event, a stack-trace map and a symbol table. Its flame graph is only as good as the frame pointers in the code it samples.
- Function names come and go:
del_timerin 6.2,blk_account_io_startin 5.17,.israclones whenever the compiler likes. Tracepoints are the stable choice.
The next part turns from watching the kernel to policing it: BPF programs attached to the kernel’s security hooks, which can say no.
A note on the evidence
What I ran, and where. Everything ran in a KVM virtual machine with 4 virtual CPUs and 4 GiB of
memory, booted by virtme-ng on Ubuntu’s mainline build of Linux 6.2, 6.2.0-060200-generic #202302191831, with a minimal Ubuntu 22.04 userland built from the release archive: clang 14, GCC 11,
glibc 2.35, bpftrace 0.14.0, and systemtap-sdt-dev 4.6 for <sys/sdt.h>. libbpf 1.1.0 and bpftool
7.1.0 were built from their release tags as shown, in that userland; bpftool’s own libbpf submodule
is pinned one commit after libbpf’s v1.1.0 tag, a CI-only change, so I used the 1.1.0 tarball for it.
I did not build bpftrace 0.17, released in January: 22.04’s 0.14 already has kfunc, kretfunc and everything else used
here. Every C file and script in this post was extracted from the page, built and run as shown. The
listings of blk_account_io_* and del_timer* on 5.15 and 6.1 come from the same userland booted on
Ubuntu’s 22.04 release kernel, 5.15.0-25-generic, and on Ubuntu’s mainline 6.1 build.
The timings. hookbench and readlat-cost.sh ran under an exclusive lock that kept every
other test VM on the host off the machine, interleaved as described, and the tables are their own
output. An earlier complete run of both overlapped a period in which that lock was not being
respected; I discarded it and re-ran both, and the numbers here are from the second run (the first run’s medians
were within 2 ns of these for every kernel hook but the trapping kprobe, 7 ns, and within 2% for
the user-space ones). Medians are reported with the spread
of the per-round differences beside them. They are one virtual machine’s numbers: exceptions and
returns to user space are more expensive under virtualisation, so the trapping kprobe and the
uprobes in particular should be cheaper on bare metal. Ratios between hooks are the more portable
result. The host’s CPU sets retbleed and Spectre v2 mitigations to enhanced IBRS in this kernel,
which keeps returns cheap; on CPUs that need retpolines or return thunks, every one of these paths
gets dearer, the trampolines included.
What I trimmed. The disassembly listings are objdump -d --no-show-raw-insn of /proc/kcore at
the addresses in /proc/kallsyms, with call targets annotated with their symbol names by a small
script, and cut where marked .... One annotation is mine: in the fentry trampoline, the lookup
missed the program’s own symbol and named an unrelated module function, so I wrote <the fentry program> in its place; in the fexit listing the same lookup found bpf_prog_…_fexit. They come from one boot, so the addresses are consistent within
each listing; KASLR moves them between boots. The bpftrace outputs have their blank lines squeezed.
The profiler’s raw output had 97 lines, several with the same frames and different
stack IDs (different return addresses inside the same functions); the awk in profile-run.sh
merges them, and the flame graph is drawn from the merged totals. The bpftrace query behind the
“who is reading slowly” table was:
kfunc:vfs_read { @start[tid] = nsecs; } kretfunc:vfs_read /@start[tid]/ { if ((args->file->f_inode->i_mode & 0170000) == 0100000 && nsecs - @start[tid] > 16000) { @slow[comm, str(args->file->f_path.dentry->d_name.name)] = count(); } delete(@start[tid]); }.
What I cited rather than ran. The version in which each hook and helper arrived, checked by asking
which release tag first contains the introducing commit: kprobes in 2.6.12’s tree, optprobes
(c0f7ac3a9edd) in 2.6.34, ftrace-based kprobes (ae6aa16fdc16) in 3.7, tracepoints
(97e1c18e8d17) in 2.6.28, uprobes in 3.5, BPF on kprobes 4.1, uprobes 4.3 (04a22fae4cbc),
tracepoints 4.7, perf events 4.9, the stack-trace map 4.6 (d5a3b1f69186), bpf_get_stack 4.18
(c195651e565a), raw tracepoints 4.17, fentry/fexit and tp_btf 5.5, bpf_get_attach_cookie 5.15
(7adfc6c9b315), fprobe (cad9931f64dc) and kprobe-multi 5.18, kretprobes on rethook for x86
(f3a112c0c40d) 5.18, kfree_skb_reason 5.17 (c504e5c2f964), the move of
blk_account_io_start (450b7879e345) 5.17, and the del_timer rename (bb663f0f3c39) 6.2. How
each mechanism works is from the 6.2 source: arch/x86/kernel/kprobes/core.c, kprobes/ftrace.c,
kernel/bpf/trampoline.c, kernel/trace/trace_syscalls.c, kernel/tracepoint.c,
arch/x86/kernel/uprobes.c. The continuous-profiling projects are described from their release
notes and their authors’ posts as of today; Fedora’s decision is from the steering committee’s
minutes of 3 January.
What I’d still change. The uprobe explanation rests on counting single steps, not on timing an
emulated function entry against a stepped one in the same build; GCC would not give me a frame
pointer in work() to probe. The readlat comparison measures whole programs, so it mixes the cost
of the hooks with the cost of what the programs do. And everything is one virtual machine, one CPU
model and one kernel; on bare metal and other CPUs the order should hold and the gaps will not.
Every Function Is a Hook