Skip to content
Linux system performance · Chapter 16 of 21 Day 14: eBPF with bpftrace and bcc

Day 14: eBPF with bpftrace and bcc

Goal: ask the kernel your own questions – with bpftrace one-liners, histograms and small scripts –, understand what runs in the kernel while you do and what it costs, and follow a latency spike from the application down to the disk · Duration: about 3 hours · Prerequisite: Day 0–13

Where we start

bpftrace, the bcc tools and bpftool are installed on perf1, and the extra disk is mounted at /daten (Day 9).

# on perf1
bpftrace --version

Expected:

bpftrace v0.20.2
# on perf1
sudo bpftool version

Expected (excerpt – the first line):

bpftool v7.4.0
# on perf1
findmnt -n -o SOURCE,TARGET /daten
  • findmnt shows mounted file systems; -n without a header line, -o SOURCE,TARGET only device and target.

Expected:

/dev/sdb /daten

Introduction

Yesterday you used ready-made tracers: trace-cmd, perf, funccount, strace. Each answers a certain kind of question. With eBPF you ask your own question: “Count the system calls per process”, “Show me every file cat opens”, “Give me the latency of every block request as a histogram, per disk”. The kernel computes the answer itself, and only the result comes to you.

There are two tool families: bpftrace for quick questions in one line or a small script, and bcc, a collection of more than 100 ready-made tools (execsnoop, opensnoop, biolatency, runqlat …), some of which you already used on Days 7 to 9.

Today you learn:

  • what happens when an eBPF program starts and how to see it with bpftool,
  • to read and write bpftrace one-liners: filters, counters, sums, output,
  • to measure and interpret latencies as a histogram,
  • to write your own bpftrace script,
  • why eBPF hardly slows down the measured program – and what happens instead when it gets too much,
  • to follow a latency spike from the request through the system call down to the disk.

Background

The picture for today: a programmable measuring station

Yesterday the kernel was a road network with built-in counting points, cameras and police checks. Today you build your own measuring station and set it up at the roadside.

  • Your eBPF program is the measuring station. You decide what it measures: count, time, note license plates – only for trucks, only in the left lane.
  • The verifier is the city’s inspection. Before the station may go onto the road, an authority checks that it can never hold up traffic and cannot fall over. A station that can’t guarantee that is rejected.
  • Maps are the tally sheets in the station. Counting happens on site; at the end you only collect the finished sheet.
  • bpftrace is a kit – set up in a minute. bcc are ready-made stations from the catalog – with many features, but each takes about 12 seconds to set up.
  • And if the station is supposed to send you a photo of every car? Then at some point the memory is full, and it throws photos away – it never blocks the road. That is the big difference from the police check strace.

The terms

Term Meaning in the picture
eBPF program small program the kernel runs at a probe point measuring station
Verifier checks before loading: does the program end, does it only read what is allowed? the city’s inspection
JIT compiles the verified program into machine code station gets mounted for good
Map table in the kernel, e.g. “process name → count” tally sheet
bpftrace concise language for one-liners and small scripts kit
bcc collection of ready-made tools with embedded C code station from the catalog
Lost … events events that were dropped because the buffer was full photos thrown away

Remember: eBPF computes in the kernel and never stops the measured program. If it gets too much, events are lost – not performance.

What eBPF is

eBPF is a small virtual machine in the kernel. You load a short program into it and attach it to a probe point – a tracepoint, a kprobe or a uprobe from Day 13. Every time the probe point is reached, your program runs, in the kernel, without any process having to be stopped or woken up. It can store values in maps. A tool in user space reads the maps at the end (or in between).

Before a program may run, the verifier in the kernel checks that it is safe: it must end, may only read allowed memory and must not crash the kernel. Then the kernel compiles it into machine code (JIT).

bpftrace and bcc

  • bpftrace has its own concise language. A program consists of blocks of the form MESSPUNKT /FILTER/ { AKTION } (probe point, filter, action). It starts in one to two seconds.
  • bcc tools are Python programs with embedded C code. At startup clang compiles the C code – that takes about 12 seconds on perf1. In return they have many options and ready-made output.

Important bpftrace building blocks

Building block Meaning
tracepoint:GRUPPE:NAME, kprobe:FUNKTION, kretprobe:FUNKTION, uprobe:DATEI:FUNKTION probe points (group, function, file)
args.FELD fields of a tracepoint, bpftrace -lv shows them
pid, tid, comm, nsecs process ID, thread ID, process name, time in nanoseconds
@name[schlüssel] = count() map: count per key
sum(x), hist(x) sum, histogram in powers of two
/bedingung/ filter: the action runs only if the condition is true
printf(…), str(zeiger) output; fetch a string from the program’s memory

At the end (Ctrl+C), bpftrace prints all maps automatically.

Security

eBPF programs can read everything in the kernel, including passwords in other processes. That is why they are reserved for root. Ubuntu sets kernel.unprivileged_bpf_disabled = 2: normal users may not load eBPF programs. bpftrace checks this right at startup.

Drill 1: What happens in the kernel at startup

Where you are: in two terminals on perf1.

What you have afterwards: seen that bpftrace needs root, which fields a tracepoint has and what the loaded program looks like in the kernel.

Step 1 – The directory for today.

# on perf1
mkdir -p ~/tag14
# on perf1
cd ~/tag14

Step 2 – Without root. Try the smallest possible bpftrace program as a normal user:

# on perf1
bpftrace -e 'BEGIN { exit(); }'
  • -e '…' passes the program directly on the command line. BEGIN is a special probe point that fires once at startup; exit() ends bpftrace immediately.

Expected:

ERROR: bpftrace currently only supports running as the root user.

Why? The setting behind it:

# on perf1
sysctl kernel.unprivileged_bpf_disabled

Expected:

kernel.unprivileged_bpf_disabled = 2

2 means: normal users may not load eBPF programs.

Step 3 – Find probe points.

# on perf1
sudo bpftrace -l 'tracepoint:syscalls:sys_enter_open*'
  • -l MUSTER lists matching probe points; the quotes protect the asterisk from the shell.

Expected:

tracepoint:syscalls:sys_enter_open
tracepoint:syscalls:sys_enter_open_by_handle_at
tracepoint:syscalls:sys_enter_open_tree
tracepoint:syscalls:sys_enter_openat
tracepoint:syscalls:sys_enter_openat2

Step 4 – The fields of a probe point.

# on perf1
sudo bpftrace -lv tracepoint:syscalls:sys_enter_openat
  • -lv also lists the fields (verbose).

Expected:

tracepoint:syscalls:sys_enter_openat
    int __syscall_nr
    int dfd
    const char * filename
    int flags
    umode_t mode

The field filename is a pointer into the program’s memory, not finished text. That is why you need str(args.filename) later.

Step 5 – Set up a station. In terminal 1, start a counter: how often does which process call openat?

# on perf1, terminal 1
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat { @[comm] = count(); }'
  • @[comm] = count() counts in a map without a name (@), the key is the process name.

Step 6 – Look at the station in the kernel. In terminal 2:

# on perf1, terminal 2
sudo bpftool prog list
  • bpftool prog list lists all loaded eBPF programs, the most recently loaded one is at the bottom.

Expected (excerpt – the last four lines):

613: tracepoint  name tracepoint_syscalls_sys_enter_openat  tag afe1b01453072a6e  gpl
    loaded_at 2026-11-30T19:42:29+0000  uid 0
    xlated 232B  jited 139B  memlock 4096B  map_ids 153
    btf_id 148
Field Value Meaning
Type tracepoint attached to a tracepoint
xlated 232B eBPF code after verification
jited 139B machine code compiled from it
map_ids 153 this program’s tally sheet

Without your program, perf1 lists 14 programs – systemd uses eBPF, for example, for device access in cgroups.

Step 7 – Collect the tally sheet. End bpftrace in terminal 1 with Ctrl+C.

Expected (excerpt – the counts come from the seconds in which you used bpftool):

@[bpftool]: 55
@[sudo]: 140

Running sudo bpftool prog list again no longer shows the program: bpftrace cleans up when it ends.

Remember: bpftool prog list shows every measuring station currently in the kernel. bpftrace takes its own down again when it ends.

Save your progress? Sign up for free

Drill 2: One-liners

Where you are: in two terminals on perf1.

What you have afterwards: used three one-liners that are needed again and again in practice: who makes system calls, which files does a program open, who writes to the disk?

Step 1 – System calls per process.

# on perf1
sudo bpftrace -e 'tracepoint:raw_syscalls:sys_enter { @[comm] = count(); }'

After a few seconds, Ctrl+C. Expected (excerpt, quiet system):

@[systemd-network]: 46
@[bpftrace]: 94
@[qemu-ga]: 264

On a quiet server it is a few hundred per second. If a process shows tens of thousands here, it is worth a look as on Day 13.

Step 2 – Which files does a program open? Yesterday perf trace couldn’t show the file names, and strace was expensive. bpftrace can do both:

# on perf1, terminal 1
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat /comm == "cat"/ { printf("%d %s %s\n", pid, comm, str(args.filename)); }'
  • /comm == "cat"/ is the filter: only calls from processes named cat.
  • printf("%d %s %s\n", …) prints a number, text, text and a line break.
  • str(args.filename) fetches the file name from the program’s memory.

In terminal 2:

# on perf1, terminal 2
cat /etc/hostname

Expected in terminal 1 (excerpt):

Attaching 1 probe...
13552 cat /etc/ld.so.cache
13552 cat /lib/x86_64-linux-gnu/libc.so.6
13552 cat 
13552 cat /usr/share/locale/locale.alias
13552 cat /usr/lib/locale/C.UTF-8/LC_IDENTIFICATION
13552 cat /usr/lib/locale/C.utf8/LC_IDENTIFICATION

The third line is empty – /usr/lib/locale/locale-archive should have been there (compare Day 13, Drill 2). That is a known limit: if the text is not yet in memory (the page has never been used), an eBPF program may not fault it in and gets nothing. That is enough for overviews; if you need every name, use strace briefly. End bpftrace with Ctrl+C.

Step 3 – Who writes to the disk? Start the count:

# on perf1, terminal 1
sudo bpftrace -e 'tracepoint:block:block_rq_issue { @[comm] = sum(args.bytes); }'
  • block:block_rq_issue fires when a request is sent to the disk; args.bytes is its size.
  • sum() adds up the bytes per process name.

In terminal 2, write 100 MB directly to the extra disk:

# on perf1, terminal 2
dd if=/dev/zero of=/daten/test.bin bs=1M count=100 oflag=direct status=none
  • oflag=direct bypasses the page cache so the data goes to the disk right away.

If /daten still belongs to root, take over the directory once with sudo chown $USER /daten.

# on perf1, terminal 2
rm /daten/test.bin

Expected in terminal 1 after Ctrl+C (excerpt):

@[kworker/2:1H]: 4096
@[kworker/u8:2]: 12312
@[jbd2/sdb-8]: 32768
@[dd]: 104857600

Exactly 100 MiB from dd, plus the file system journal (jbd2/sdb-8) and kernel threads (kworker) that handle deferred writes. Careful when interpreting: with normal (not direct) writes, a kworker usually shows up there instead of the application, because the kernel writes the data from the page cache later (Day 8).

Remember: Three building blocks cover most questions: count() for “how often”, sum() for “how much”, printf with a filter for “which” – the latter only if there are few events.

If it doesn’t work:

  • ERROR: Unknown field 'filename': args.filename belongs to sys_enter_openat, not to sys_exit_openat. bpftrace -lv shows the fields.
  • The output only comes after Ctrl+C: That is intended for maps; only printf prints right away.

Save your progress? Sign up for free

Drill 3: Histograms – how long do processes wait for the CPU?

Where you are: in two terminals on perf1.

What you have afterwards: measured the wait for a CPU as a histogram, once without and once with overload, and learned to read a histogram.

An average hides outliers. A histogram shows the whole distribution. runqlat measures how long a runnable thread has to wait until it gets a CPU (the run queue latency, Day 4).

Step 1 – Quiet system.

# on perf1
sudo runqlat-bpfcc -m 10 1
  • -m prints milliseconds instead of microseconds.
  • 10 1: one interval of 10 seconds, once. For the first 12 seconds or so, bcc compiles the program.

Expected:

Tracing run queue latency... Hit Ctrl-C to end.

     msecs               : count     distribution
         0 -> 1          : 401      |****************************************|

Every thread got its turn in less than a millisecond.

Step 2 – Create overload. In terminal 1, start eight computing processes on the four CPUs:

# on perf1, terminal 1
stress-ng --cpu 8 --timeout 40s
  • --cpu 8 eight workers that each want to keep one CPU fully busy; --timeout 40s stop after 40 seconds.

Step 3 – Measure under overload. Right after that, in terminal 2:

# on perf1, terminal 2
sudo runqlat-bpfcc -m 10 1

Expected:

Tracing run queue latency... Hit Ctrl-C to end.

     msecs               : count     distribution
         0 -> 1          : 854      |**                                      |
         2 -> 3          : 12675    |****************************************|
         4 -> 7          : 347      |*                                       |
         8 -> 15         : 8        |                                        |

How to read the histogram:

  • Each line is a range in powers of two: 2 -> 3 means 2 to 3 milliseconds.
  • count is the number of events in that range, the asterisks show it relative to the largest.
  • Under load most values are at 2–3 ms: twice as many threads as CPUs, so each waits about as long as another one computes. The few values at 8–15 ms are the outliers an average would have swallowed – and that a user feels as stutter.

Remember: A histogram shows what an average conceals: the rare long waits at the very bottom of the table.

If it doesn’t work:

  • No output for a long time: bcc is still compiling. The 10 seconds only count after Tracing run queue latency….

Save your progress? Sign up for free

Drill 4: Your own script

Where you are: in two terminals on perf1, in the directory ~/tag14.

What you have afterwards: a bpftrace script blocklat.bt that shows the latency of every block request as a histogram per disk, and the comparison with the ready-made biolatency.

On Day 9 you built bioschau.bt, which prints every block request individually. For many requests a histogram is better. For that you measure the time between two tracepoints: block_rq_issue (request goes to the disk) and block_rq_complete (disk reports done).

Step 1 – Create the script.

# on perf1
cd ~/tag14
# on perf1
nano blocklat.bt
~/tag14/blocklat.bt new file
// Latenz jeder Blockanfrage als Histogramm, getrennt nach Gerät (über stabile Tracepoints)
tracepoint:block:block_rq_issue
{
    @start[args.dev, args.sector] = nsecs;
}

tracepoint:block:block_rq_complete
/@start[args.dev, args.sector]/
{
    @us[args.dev >> 20, args.dev & 0xfffff] = hist((nsecs - @start[args.dev, args.sector]) / 1000);
    @kb[args.dev >> 20, args.dev & 0xfffff] = sum(args.nr_sector / 2);
    delete(@start[args.dev, args.sector]);
}

END { clear(@start); }

Line by line:

  • Line 1 is a comment (it says, in German: latency of every block request as a histogram, per device, via stable tracepoints).
  • Lines 2–5: when a request is sent, the script stores the start time in the map @start. The key is device and sector – so the request can be found again when it completes.
  • Line 8: the filter only lets through completions for which there is a start time (requests that were already in flight before the script started drop out).
  • Line 10: the duration in microseconds goes into a histogram @us. The key is the device number, split into major and minor (args.dev >> 20 and args.dev & 0xfffff) – the same notation as 8:16 in lsblk.
  • Line 11: @kb sums up the amount of data in KiB (one sector is 512 bytes, so nr_sector / 2).
  • Line 12: delete removes the start entry so the map does not grow.
  • Line 15: END runs at the end; clear(@start) keeps bpftrace from printing the helper map.

Step 2 – Measure. In terminal 1:

# on perf1, terminal 1
sudo bpftrace ~/tag14/blocklat.bt

In terminal 2, as soon as Attaching 3 probes... appears:

# on perf1, terminal 2
dd if=/dev/zero of=/daten/test.bin bs=1M count=100 oflag=direct status=none
# on perf1, terminal 2
rm /daten/test.bin

Then Ctrl+C in terminal 1. Expected (excerpt):

@kb[8, 0]: 552
@kb[8, 16]: 102432

@us[8, 16]: 
[256, 512)             2 |@                                                   |
[512, 1K)             36 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@                       |
[1K, 2K)              64 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|

Step 3 – Which disk is 8, 16?

# on perf1
lsblk -o NAME,MAJ:MIN,MOUNTPOINTS /dev/sda /dev/sdb

Expected:

NAME    MAJ:MIN MOUNTPOINTS
sda       8:0   
├─sda1    8:1   /
├─sda14   8:14  
├─sda15   8:15  /boot/efi
└─sda16 259:0   /boot
sdb       8:16  /daten

102,432 KiB on sdb: the 100 MiB from dd plus a little journal. 102 requests of 1 MiB each, all between 0.25 and 2 ms. bpftrace writes histograms in the form [1K, 2K) – from 1,024 to below 2,048 microseconds.

Step 4 – The comparison with the ready-made tool. bcc offers the same as biolatency:

# on perf1, terminal 1
sudo biolatency-bpfcc

Wait for Tracing block device I/O..., write the same 100 MB with dd again in terminal 2 and delete the file, then Ctrl+C in terminal 1.

Expected (excerpt):

     usecs               : count     distribution
       256 -> 511        : 2        |                                        |
       512 -> 1023       : 100      |*************************************   |
      1024 -> 2047       : 106      |****************************************|

The ready-made tool counts across all disks together (-D separates by disk) – hence the higher numbers. When do you use which? For standard questions, the ready-made tool. Your own script when you need something different (a different breakdown, a filter on a process, a combination) – or when the ready-made tool does not work on your kernel, like biosnoop on Day 9. Scripts on tracepoints survive kernel updates; scripts on kprobes do not always.

Remember: Two tracepoints and a map with start times give you any latency you need. Ready-made tools first, your own scripts for the questions the catalog doesn’t cover.

If it doesn’t work:

  • biolatency shows almost nothing: dd ran before the tool had finished compiling (about 12 s).
  • Error in line N: bpftrace reports line and column. Often a ; or } is missing.

Save your progress? Sign up for free

Drill 5: What eBPF costs

Where you are: in two terminals on perf1, in the directory ~/tag14.

What you have afterwards: repeated the experiment from Day 13, Drill 4 with bpftrace and seen what happens when an eBPF program is supposed to output too many events.

As a reminder: dd with 100,000 one-byte copies took about 0.26 s without a tracer, 49 s with strace.

Step 1 – Count in the kernel. In terminal 1:

# on perf1, terminal 1
sudo bpftrace -e 'tracepoint:raw_syscalls:sys_enter /comm == "dd"/ { @ = count(); }'

In terminal 2, the same command twice:

# on perf1, terminal 2
/usr/bin/time -f "%e s" dd if=/dev/zero of=/dev/null bs=1 count=100000 status=none

Expected: 0.30 s and 0.38 s – within the normal fluctuation (without a tracer we measured 0.22 to 0.38 s). After Ctrl+C in terminal 1:

@: 400244

Twice 200,122 system calls, counted exactly, without a measurable slowdown.

Step 2 – Output every event. Now bpftrace is supposed to write one line for every system call – the station is supposed to photograph every car. Terminal 1:

# on perf1, terminal 1
sudo bpftrace -e 'tracepoint:raw_syscalls:sys_enter /comm == "dd"/ { printf("%d\n", args.id); }' > ausgeben.out
  • > ausgeben.out redirects the output into a file. args.id is the number of the system call.

Terminal 2, the same dd once. Expected: 0.38 s – again hardly slower. End bpftrace with Ctrl+C.

Step 3 – What arrived?

# on perf1
wc -l < ausgeben.out
  • wc -l counts lines; < ausgeben.out feeds the file as input, so wc prints only the number.

Expected:

66652
# on perf1
grep Lost ausgeben.out

Expected:

Lost 133474 events

Of 200,122 events, only about a third arrived. That is the fundamental difference from strace: an eBPF program never stops the observed program. It writes into a buffer; when that is full, it drops events and reports this at the end. strace, on the other hand, gets every event because it stops the program for as long as it takes.

Remember: Counting, summing and building histograms in the kernel – cheap and exact. Output individual events only when there are few (program starts, slow requests, errors).

If it doesn’t work:

  • No Lost: Your system was fast enough. Increase count to 500,000.

Save your progress? Sign up for free

Diagnosis task

A till service (Kasse) on perf1 normally answers in a few milliseconds. Every now and then, however, a request takes almost a second, and nobody knows why. The CPU is not busy.

Setup. Create the service:

# on perf1
cd ~/tag14
# on perf1
nano kasse.py
~/tag14/kasse.py new file
import os
from http.server import BaseHTTPRequestHandler, HTTPServer

ARCHIV = "/daten/kasse-archiv.bin"
anfragen = 0

def archivieren():
    with open(ARCHIV, "wb") as f:
        f.write(bytes(256 * 1024 * 1024))
        f.flush()
        os.fsync(f.fileno())

class Kasse(BaseHTTPRequestHandler):
    def do_GET(self):
        global anfragen
        anfragen += 1
        if anfragen % 200 == 0:
            archivieren()
        antwort = b"ok\n"
        self.send_response(200)
        self.send_header("Content-Length", str(len(antwort)))
        self.end_headers()
        self.wfile.write(antwort)

    def log_message(self, *args):
        pass

HTTPServer(("", 8081), Kasse).serve_forever()

Please read the source code closely only in the solution. The service needs write access to /daten:

# on perf1
sudo chown $USER /daten
# on perf1
nohup python3 kasse.py > kasse.log 2>&1 &
  • nohup … & starts the service in the background, output goes to kasse.log.

Measure the symptom. The load comes from last1: one connection, one request after the other, for one minute, with percentiles:

# on last1
wrk -t1 -c1 -d60s --latency http://perf1:8081/
  • -t1 -c1 one thread, one connection – the requests come one after the other; --latency shows percentiles.

Expected (excerpt):

    Latency   175.06ms  266.28ms   1.29s    80.68%
  Latency Distribution
     50%    1.57ms
     75%  324.64ms
     90%  633.07ms
     99%  914.90ms
  9869 requests in 1.00m, 1.07MB read
Requests/sec:    164.37

Half the requests are done in 1.6 ms. But from the 75th percentile on it takes hundreds of milliseconds, the slowest request 1.29 seconds. The average (175 ms) describes not a single real request – that is exactly why you look at percentiles (Day 1).

Task (25 minutes): Follow the slow requests down to the event in the kernel that holds them up, and fix the cause without taking away the service’s function.

Solution path

For the analysis you need continuous load. Start a longer load on last1:

# on last1
wrk -t1 -c1 -d300s http://perf1:8081/

That is five minutes; you can stop it with Ctrl+C.

Step 1 – The PID.

# on perf1
pgrep -f "python3 [k]asse.py"
  • [k]asse is again the trick from Days 11 and 13 so that pgrep does not find itself.

Expected: a number, 72856 in the lab. Use yours instead of PID in the following commands.

Step 2 – Which system call is slow? syscount from bcc counts a process’s system calls and sums up their duration with -L:

# on perf1
sudo syscount-bpfcc -L -p PID -d 20
  • -L (latency) shows the total time per system call, -p the process, -d 20 measures for 20 seconds.

Expected (excerpt):

SYSCALL                   COUNT        TIME (us)
fsync                        19      3662530.524
poll                       3800      3133222.513
openat                       19      2493270.304
sendto                     7600       209898.195
shutdown                   3800       128365.955
accept4                    3800       102923.440
recvfrom                   3800        82753.393
close                      3819        71328.548
munmap                       19        50460.588

How to read the table: thousands of poll, sendto, accept4, recvfrom – that is the normal work, one connection per request (poll is waiting for the next one). Two lines stand out with few calls and a lot of time: 19 fsync taking 3.7 seconds in total and 19 openat taking 2.5 seconds – about 190 and 130 ms each. 19 times in 20 seconds something big happens.

One line is missing, though: write. In the lab it did not show up even with -T 15 (the 15 most frequent instead of 10) – although, as the next step shows, write takes the longest of all. A tool can be wrong; therefore check a finding with a second one.

Step 3 – When exactly? Your own script prints every one of these calls that takes longer than 20 ms:

# on perf1
nano langsam.bt
~/tag14/langsam.bt new file
// openat, write und fsync eines Prozesses, die länger als 20 ms dauern
// Aufruf: sudo bpftrace langsam.bt PID
tracepoint:syscalls:sys_enter_openat,
tracepoint:syscalls:sys_enter_write,
tracepoint:syscalls:sys_enter_fsync
/pid == $1/
{
    @start[tid] = nsecs;
}

tracepoint:syscalls:sys_exit_openat,
tracepoint:syscalls:sys_exit_write,
tracepoint:syscalls:sys_exit_fsync
/pid == $1 && @start[tid]/
{
    $ms = (nsecs - @start[tid]) / 1000000;
    if ($ms >= 20) {
        time("%H:%M:%S ");
        printf("%-35s %5d ms\n", probe, $ms);
    }
    delete(@start[tid]);
}

END { clear(@start); }
  • Lines 3–5 and 11–13: a block can hang on several probe points, separated by commas.
  • $1 is the first argument when calling the script, here the PID. In bpftrace, pid is the process ID, tid the thread – the start time is stored per thread.
  • $ms is a variable that only applies within this block (unlike maps with @).
  • time() prints the time of day, probe the name of the probe point that just fired.

Why not simply all system calls with sys_enter_*? That is more than 700 probe points; by default bpftrace attaches to at most 512. syscount named two suspects; you add write because between opening and syncing a file there is almost always writing.

# on perf1
sudo bpftrace langsam.bt PID

Expected (excerpt, Ctrl+C after about 20 seconds):

22:54:39 tracepoint:syscalls:sys_exit_openat   139 ms
22:54:39 tracepoint:syscalls:sys_exit_write    489 ms
22:54:39 tracepoint:syscalls:sys_exit_fsync    163 ms
22:54:40 tracepoint:syscalls:sys_exit_openat   140 ms
22:54:40 tracepoint:syscalls:sys_exit_write    546 ms
22:54:40 tracepoint:syscalls:sys_exit_fsync    187 ms
22:54:41 tracepoint:syscalls:sys_exit_openat   141 ms
22:54:42 tracepoint:syscalls:sys_exit_write    571 ms
22:54:42 tracepoint:syscalls:sys_exit_fsync    207 ms

A bit more than once per second the same sequence: openat (about 140 ms), write (400–570 ms), fsync (about 190 ms) – about 0.8 s together. Since wrk sends the next request right away, 200 requests are done in about 0.3 s; then archiving comes again. That matches the slow requests – and write is the biggest chunk, the one syscount didn’t show.

Step 4 – Which file? A one-liner with a filter on the PID:

# on perf1
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_openat /pid == PID/ { printf("%s\n", str(args.filename)); }'

Expected:

Attaching 1 probe...
/daten/kasse-archiv.bin
/daten/kasse-archiv.bin
/daten/kasse-archiv.bin

Every line is one archiving run. End bpftrace after a few lines with Ctrl+C.

Step 5 – What happens on the disk? Your script from Drill 4, for ten seconds:

# on perf1
sudo bpftrace ~/tag14/blocklat.bt

Expected (excerpt, Ctrl+C after ten seconds):

@kb[8, 0]: 380
@kb[8, 16]: 2090464

@us[8, 16]: 
[256, 512)            12 |@                                                   |
[512, 1K)              7 |                                                    |
[1K, 2K)              70 |@@@@@@                                              |
[2K, 4K)             128 |@@@@@@@@@@@@                                        |
[4K, 8K)             229 |@@@@@@@@@@@@@@@@@@@@@@                              |
[8K, 16K)            415 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@             |
[16K, 32K)           524 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@  |
[32K, 64K)           540 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|
[64K, 128K)           73 |@@@@@@@                                             |

About 2 GiB on sdb (8:16) in ten seconds – eight archives of 256 MiB each. Most requests take 8 to 64 ms: the disk writes nonstop, requests wait behind requests. On sda (8:0) hardly anything happens.

The chain is complete:

Level Finding Tool
Application p75 325 ms, p99 915 ms, median 1.6 ms wrk --latency
System calls openat, write, fsync together ~0.8 s syscount -L (without write), langsam.bt
File /daten/kasse-archiv.bin one-liner with str(args.filename)
Disk ~2 GiB in 10 s on sdb, requests 8–64 ms blocklat.bt

And the source code confirms it: on every 200th request, do_GET calls the function archivieren() (“archive”). open(…, "wb") truncates the old 256 MB file (that is the slow openat – the kernel frees the blocks), write copies 256 MB into the page cache, fsync waits until everything is on the disk. All that time the customer waits.

Step 6 – Repair. Archiving doesn’t have to go away, it just must not hold up the request. Stop the continuous load on last1 with Ctrl+C and stop the service:

# on perf1
pkill -f "python3 [k]asse.py"

Then let archivieren() run in its own thread:

# on perf1
nano kasse.py
~/tag14/kasse.py changes in green
import os
import threading
from http.server import BaseHTTPRequestHandler, HTTPServer

ARCHIV = "/daten/kasse-archiv.bin"
anfragen = 0

def archivieren():
    with open(ARCHIV, "wb") as f:
        f.write(bytes(256 * 1024 * 1024))
        f.flush()
        os.fsync(f.fileno())

class Kasse(BaseHTTPRequestHandler):
    def do_GET(self):
        global anfragen
        anfragen += 1
        if anfragen % 200 == 0:
            threading.Thread(target=archivieren).start()
        antwort = b"ok\n"
        self.send_response(200)
        self.send_header("Content-Length", str(len(antwort)))
        self.end_headers()
        self.wfile.write(antwort)

    def log_message(self, *args):
        pass

HTTPServer(("", 8081), Kasse).serve_forever()
  • Line 2: the module for threads.
  • Line 19: threading.Thread(target=archivieren).start() starts archivieren() in a new thread and returns immediately. The response goes to the customer without waiting.

Step 7 – Follow-up. Restart the service:

# on perf1
nohup python3 kasse.py > kasse.log 2>&1 &

and measure as in the setup:

# on last1
wrk -t1 -c1 -d60s --latency http://perf1:8081/

Expected (excerpt):

    Latency     1.17ms    1.55ms  46.78ms   96.64%
     50%    0.92ms
     99%    4.94ms
  37936 requests in 1.00m, 4.12MB read
Requests/sec:    631.51

p99 4.9 ms instead of 915 ms, the slowest request 47 ms instead of 1.29 s, and almost four times as many requests per second. The outliers have not completely disappeared: the archive thread competes for the same CPU and disk. Archiving still happens: under load, langsam.bt keeps showing openat, write and fsync with hundreds of milliseconds every few seconds – just no longer in the thread that answers the request. (A real service should additionally prevent two archiving runs at the same time.)

Step 8 – Stop and clean up.

# on perf1
pkill -f "python3 [k]asse.py"
# on perf1
rm -f /daten/kasse-archiv.bin

Remember: You follow a latency spike level by level: request → system call (syscount -L) → point in time (your own script) → file (str(args.filename)) → disk (blocklat.bt). And cross-check every finding with a second tool.

If it doesn’t work

  • PermissionError: [Errno 13] Permission denied: '/daten/kasse-archiv.bin' in kasse.log: the chown from the setup is missing.
  • pgrep finds two PIDs: an old service is still running. Never use pgrep -x python3 – that also hits Ubuntu’s Python services such as unattended-upgrade-shutdown. Always search by script name.
  • Can't attach to 713 probes: you used sys_enter_* instead of the three probe points.

Challenge

Write a one-liner that shows how long fsync calls take on perf1 – as a histogram, per process name. Test it with the till service from the diagnosis task (old version without a thread or new one, both work).

Solution path:

# on perf1
sudo bpftrace -e 'tracepoint:syscalls:sys_enter_fsync { @s[tid] = nsecs; } tracepoint:syscalls:sys_exit_fsync /@s[tid]/ { @ms[comm] = hist((nsecs - @s[tid]) / 1000000); delete(@s[tid]); }'
  • Two blocks in one line: on entry, store the start time per thread; on exit, put the duration in milliseconds into the histogram of the process name.

Expected (25 seconds under wrk load with the old version, after Ctrl+C):

@ms[python3]: 
[128, 256)            21 |@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@|

21 archiving runs, every fsync between 128 and 256 ms. No other process called fsync during that time. Don’t forget to stop the service again afterwards.

Save your progress? Sign up for free

Checkpoint

# on perf1
pgrep -f "python3 [k]asse.py"

Expected: no output – the service is stopped.

# on perf1
sudo bpftool prog list | grep -c "^[0-9]"
  • Every program starts in bpftool prog list with a line beginning with its number; grep -c "^[0-9]" counts these lines.

Expected: the same number as before the chapter (14 on perf1) – no eBPF program from today is loaded anymore.

# on perf1
ls ~/tag14/blocklat.bt ~/tag14/langsam.bt

Expected: both files – you still need them in the final case.

Test yourself

  1. Why can’t a normal user start bpftrace on Ubuntu?
  2. What does the verifier check before an eBPF program may run?
  3. Why do you need str(args.filename), and why can the result sometimes be empty?
  4. A histogram shows 12,675 values at 2–3 ms and 8 at 8–15 ms. What does that tell you that an average doesn’t?
  5. bpftrace is supposed to print a line for each of 200,000 system calls. What happens – and what happens with strace in the same case?
  6. How do you follow a latency spike from the request down to the disk?

Answers:

  1. eBPF can read all of kernel memory; kernel.unprivileged_bpf_disabled = 2 forbids it for normal users.
  2. That the program ends, only reads allowed memory and cannot crash the kernel.
  3. filename is only a pointer into the program’s memory. If the page is not yet in memory, eBPF may not fault it in – then the text stays empty.
  4. Almost all wait 2–3 ms, but a few wait 8–15 ms – the outliers users feel. An average would be about 2–3 ms and would hide them.
  5. eBPF drops events when the buffer is full (Lost … events), the program runs at full speed. strace gets every event but stops the program for it – it becomes many times slower.
  6. Measure the request (wrk --latency), system calls with duration (syscount -L), point in time of the slow calls (your own script), file (str(args.filename)), disk (blocklat.bt).

Interview Note

“What is the difference between strace and an eBPF tool?” – strace works with ptrace and stops the program at every system call; it sees everything, but can slow things down by two orders of magnitude. eBPF runs in the kernel, aggregates there (counters, sums, histograms) and never stops the program; when too many events are supposed to be output, events get lost rather than performance. If you can also explain the verifier, maps and the difference between tracepoints (stable) and kprobes (not stable), and can read a histogram, you are well prepared for any performance role.

Enterprise Note

eBPF is the foundation of many products today: Cilium for networking and security in Kubernetes, Falco and Tetragon for security monitoring, Pixie and Parca for observability. If you understand bpftrace, you understand what these tools do in the kernel – and what they cost. For operations: eBPF needs root or CAP_BPF/CAP_PERFMON; the right to load eBPF is the right to read everything. Give it to tools, not people, and log who runs bpftrace on production systems. After every analysis, check with bpftool prog list that nothing was left behind.

Summary

  • eBPF runs small programs checked by the verifier in the kernel, at tracepoints, kprobes and uprobes. Results are kept in maps. bpftool prog list shows what is loaded.
  • bpftrace: MESSPUNKT /FILTER/ { AKTION }, starts in seconds. bcc: ready-made tools, start after about 12 seconds of compiling.
  • One-liners: system calls per process (count()), opened files (str(args.filename), can be empty for pages not yet loaded), disk bytes per process (sum(args.bytes)).
  • Histograms show outliers: run queue latency under overload mostly 2–3 ms, a few 8–15 ms.
  • Your own script blocklat.bt: latency per disk from two tracepoints.
  • Cost: counting in the kernel does not slow things down measurably and is exact. Too much output → Lost … events instead of a slowdown.
  • Diagnosis: every 200th request archived 256 MB synchronously (openat + write + fsync ≈ 0.8 s); syscount missed the long write, langsam.bt showed it. In its own thread: p99 4.9 ms instead of 915 ms.

Commands at a glance

Command What it does Parameters
bpftrace -e 'PROGRAMM' run a bpftrace one-liner -e program on the command line
bpftrace DATEI [ARG] run a bpftrace script $1 = first argument
bpftrace -l 'MUSTER' / bpftrace -lv MESSPUNKT search probe points / show their fields –
bpftool prog list loaded eBPF programs –
sysctl kernel.unprivileged_bpf_disabled may normal users load eBPF? 2 = no
runqlat-bpfcc -m INTERVALL ANZAHL wait for the CPU as a histogram -m milliseconds
biolatency-bpfcc [-D] latency of block requests as a histogram -D per disk
syscount-bpfcc -L -p PID -d SEK count a process’s system calls, with total duration -L latency
lsblk -o NAME,MAJ:MIN,MOUNTPOINTS device numbers of the disks –
wrk -t1 -c1 -d60s --latency URL requests one after the other, with percentiles -c1 one connection
wc -l < DATEI count the lines of a file –

Contents

More