The lab: a Fedora 44 host laptop running the Aya build plus Podman containers (the otel-lgtm stack, Python clients, and Java/Python app targets), a target KVM VM where eBPF loads and attaches, and an optional peer KVM VM for two-host networking tests. The host scp's the built binary to the target and runs it under sudo; the target exports OTLP back to the stack; the target and peer exchange test traffic over the libvirt network.
Figure 2.1. The lab at a glance: what runs where
Download .excalidraw source
·
Edit on excalidraw.com
Data path: an eBPF program writes to a map; the Aya loader reads the map and emits OTLP/HTTP metrics to the otel-lgtm stack, which Grafana visualizes.
Figure 3.1. From kernel counter to Grafana panel
Download .excalidraw source
·
Edit on excalidraw.com
The opensnoop openat probe in the guest kernel writes counts and latency into a per-CPU map. The user-space loader reads the map and produces two faces of output: it prints a live table to your terminal (what chapters tell you to watch), and it pushes ebpf_* metrics via OTLP on port 4318 to the otel-lgtm stack, which stores them and charts them in Grafana on port 3000 over time. The program runs in the guest while the stack runs on your laptop, so the loader pushes out via OTLP.
Figure 3.2. One probe, two faces of output: a live terminal table and ebpf_* metrics in Grafana
Download .excalidraw source
·
Edit on excalidraw.com
The three-crate workspace: a common crate of shared types, an ebpf crate kept out of the default build (compiled instead by build.rs via aya-build into a BPF object), and a loader crate that embeds the object with include_bytes_aligned.
Figure 4.1: the three-crate workspace and build flow
Download .excalidraw source
·
Edit on excalidraw.com
eBPF program lifecycle: Rust source compiles to BPF bytecode, is loaded and verified, JIT-compiled to native code, and attached to a hook (kprobe, tracepoint, uprobe, perf_event, XDP/tc/LSM) that fires it.
Figure 5.1: load, verify, JIT, attach
Download .excalidraw source
·
Edit on excalidraw.com
At runtime, the loader binary in user space loads and attaches the program once. Then in the kernel a hook (kprobe, XDP, tracepoint) fires the eBPF program, which writes to a map (RingBuf or HashMap); the loader reads that map and reports to Grafana over OTLP. The map is the only channel between kernel and user space.
Figure 5.2: at runtime, the hook fires the program, which writes a map the loader reads
Download .excalidraw source
·
Edit on excalidraw.com
The BPF subsystem. In user space you generate BPF bytecode and (2) load it into the kernel, where the verifier checks it and hands it to the BPF runtime; the BPF program attaches to event sources (kprobes, uprobes, tracepoints, perf_events) and reads and writes maps. Data returns to user space two ways: perf_output streams per-event data, and the loader does async reads of map contents for statistics. Maps and perf/ring output are the only channels between kernel and user space.
Figure 5.3: generate, load, verify, attach; talk to user space only via maps and perf/ring output
Download .excalidraw source
·
Edit on excalidraw.com
Linux events and BPF support. Around the kernel stack (applications, system libraries, the system call interface, VFS/sockets/scheduler, file systems/TCP-UDP/virtual memory, block/net devices, device drivers), eBPF can attach via dynamic tracing (uprobes for user space, kprobes for the kernel, spanning the whole stack), static tracepoints (syscalls, sched, signal, timer, block, net, skb, irq, ext4, sock, kmem, vmscan, writeback, workqueue), hardware PMCs on the CPU (cycles, instructions, branch and cache counters, with a memory bus to DRAM), and software events (cpu-clock, context switches, migrations, page faults). Each became available in a specific kernel version.
Figure 5.4: what eBPF can observe (dynamic tracing, tracepoints, PMCs, and software events) across the stack
Download .excalidraw source
·
Edit on excalidraw.com
RingBuf event path: an eBPF program reserves and submits an event into a ring-buffer map in the kernel; the user-space loader drains it, decodes the bytes into a struct, and prints or exports it.
Figure 6.1: the RingBuf event path (kernel to user space)
Download .excalidraw source
·
Edit on excalidraw.com
Entry/exit correlation: a probe at function entry stashes an argument or timestamp in a HashMap keyed by pid_tgid; a probe at return reads it back to pair the two events.
Figure 8.1. The entry/exit correlation pattern (reused throughout the book)
Download .excalidraw source
·
Edit on excalidraw.com
Correlating two probes: an fentry program on vfs_unlink captures pid/uid/comm/filename at entry and stores it in an INFLIGHT HashMap keyed by pid_tgid; the paired fexit program looks that entry up at return, attaches the return value, emits the completed UnlinkEvent to a ring buffer, and clears the entry.
Figure 8.1. fentry captures arguments, fexit captures the return; a pid_tgid-keyed map bridges them
Download .excalidraw source
·
Edit on excalidraw.com
User vs kernel memory: an eBPF program may not dereference raw pointers; it copies bytes from the process's user memory with bpf_probe_read_user and from kernel memory with bpf_probe_read_kernel.
Figure 9.1. Reading user vs kernel memory (the basis for chapters 9–12)
Download .excalidraw source
·
Edit on excalidraw.com
How a trace works: a process calls execve, a tracepoint fires, the eBPF program reads the event's fields by offset (and argv in a bounded loop), and ships the result to user space via a ring buffer.
Figure 11.1: anatomy of a trace
Download .excalidraw source
·
Edit on excalidraw.com
User-space probing surfaces: an eBPF uprobe can attach to an executable symbol, a shared-library symbol, or a USDT marker; an entry probe sees arguments and a return probe sees results.
Figure 13.1: the user-space probing menu
Download .excalidraw source
·
Edit on excalidraw.com
Reading a struct argument: the uprobe takes the pointer argument and copies the struct with bpf_probe_read_user into a repr(C) mirror whose field layout must match the target's: a layout BTF can recover.
Figure 15.1: struct-argument read and the BTF layout contract
Download .excalidraw source
·
Edit on excalidraw.com
Observing a containerized target: the VM kernel sees every container's processes; eBPF attaches by host PID or overlay path and scopes to one container by its cgroup id.
Figure 16.1: observing a process inside a container
Download .excalidraw source
·
Edit on excalidraw.com
TLS boundary capture: the wire carries ciphertext, but plaintext is present at SSL_write's buffer on entry and SSL_read's buffer on return, where sslsniff's uprobes read it.
Figure 17.1. Capturing plaintext at the TLS boundary
Download .excalidraw source
·
Edit on excalidraw.com
Goroutine state machine: goroutines move between idle, runnable, running, waiting, and dead; runtime.casgstatus is called on every transition, so one uprobe observes the whole machine.
Figure 19.1: the goroutine state machine
Download .excalidraw source
·
Edit on excalidraw.com
Go register ABI vs C ABI: the C ABI puts arg0/arg1/arg2 in RDI/RSI/RDX, but Go's ABIInternal uses RAX/RBX/RCX, so ctx.arg(2) reads the wrong register and newval must be read from RCX.
Figure 19.2: why ctx.arg(n) is wrong for Go (register ABI)
Download .excalidraw source
·
Edit on excalidraw.com
Fedora's stock OpenJDK ships no hotspot USDT gc markers, so instead of a USDT probe we resolve G1CollectedHeap::do_collection_pause_at_safepoint from libjvm.so's unstripped .symtab and attach a uprobe at its entry (record start) plus a uretprobe at its return (pause = now − start).
Figure 20.1: no USDT markers on a stock JDK, so uprobe the G1 collector from libjvm's symbol table
Download .excalidraw source
·
Edit on excalidraw.com
The JVM (libjvm.so) exposes HotSpot USDT probes across its subsystems: garbage collector (gc__begin/gc__end), memory pools, JIT compiler (method__compile), threads (thread__start/stop), monitors/locks (monitor__contended), allocation (object__alloc) and class loading (class__loaded). Each is reachable as an eBPF uprobe at the probe's offset.
Download .excalidraw source
·
Edit on excalidraw.com
Run-queue latency: sched_wakeup stamps when a task becomes runnable; it waits on the run queue; sched_switch records the wait when it comes on-CPU, bucketed into an in-kernel log2 histogram.
Figure 21.1. Measuring run-queue latency across the sched tracepoints
Download .excalidraw source
·
Edit on excalidraw.com
Sampling profiler pipeline: a perf_event timer fires at 99 Hz per CPU; each tick captures a stack with bpf_get_stackid into a StackTrace map; user space folds and symbolizes for a flame graph or Pyroscope.
Figure 23.1. The sampling profiler pipeline
Download .excalidraw source
·
Edit on excalidraw.com
Leak tracking: malloc records each allocation's pointer, size, and call stack; free removes it; whatever remains outstanding is a candidate leak, grouped by the stack that allocated it.
Figure 24.1: tracking outstanding allocations by call site
Download .excalidraw source
·
Edit on excalidraw.com
Sequential vs random I/O: on each block_rq_issue, if the request's starting sector equals the previous request's end sector it is sequential, otherwise random, tallied per device in a kernel HashMap.
Figure 25.1. Classifying block I/O as sequential or random
Download .excalidraw source
·
Edit on excalidraw.com
Energy attribution: system power (from RAPL, or a model on VMs) is split by each task's CPU-time share to estimate per-process power, exported as estimated_power_watts per comm.
Figure 26.1: attributing system power to processes
Download .excalidraw source
·
Edit on excalidraw.com
The network path from NIC driver through XDP, tc/tcx, the IP/TCP stack, to the socket and application, showing where each eBPF program type attaches: XDP and tc/tcx before the stack for drop/redirect/rewrite, kprobes in the TCP stack, and sockops/filters at the socket.
Figure 27.1: where eBPF attaches along the network path
Download .excalidraw source
·
Edit on excalidraw.com
A kprobe on tcp_v4_connect stamps t0 keyed by the struct sock pointer when the client sends SYN; the SYN-ACK returns from the server; a kprobe on tcp_rcv_state_process computes the delta and emits the connection latency.
Figure 27.2: connection latency across two kprobes
Download .excalidraw source
·
Edit on excalidraw.com
The TCP state machine: CLOSE to SYN_SENT on connect, SYN_SENT to ESTABLISHED on SYN-ACK, ESTABLISHED to closing states, and LISTEN for passive opens. All transitions reported by the sock:inet_sock_set_state tracepoint with addresses and ports.
Figure 28.1: the TCP state machine via one tracepoint
Download .excalidraw source
·
Edit on excalidraw.com
A socket filter receives each packet, walks the Ethernet, IPv4, and TCP headers to find the TCP payload, checks whether it begins with an HTTP method or HTTP/ response, captures the first line, and emits it to user space via a ring buffer.
Figure 29.1. Parsing HTTP out of packets with a socket filter
Download .excalidraw source
·
Edit on excalidraw.com
A sock_ops program attached to a cgroup is called back by the TCP stack at lifecycle moments: connect, active/passive established, RTT and state-change callbacks, and it can also act by setting socket options, congestion control, and callback flags.
Figure 30.1: sock_ops, the stack calls back into your program
Download .excalidraw source
·
Edit on excalidraw.com
The clsact qdisc on an interface carries a tc ingress hook and a tc egress hook. Packets received from the wire pass through the ingress classifier on the way up to the network stack; packets sent by the stack pass through the egress classifier on the way down to the wire. Each #[classifier] program operates on the sk_buff and returns a verdict: TC_ACT_OK to pass, TC_ACT_SHOT to drop, or TC_ACT_REDIRECT to send to another interface.
Figure 31.1: tc runs on the sk_buff, in both directions, and returns a verdict
Download .excalidraw source
·
Edit on excalidraw.com
The RX path drawn vertically. At the bottom, the NIC driver's RX ring. Immediately above it sits the XDP hook (#[xdp], raw frame, no sk_buff): the earliest hook. From XDP, XDP_PASS continues up to where the sk_buff is allocated, then to the tc/clsact hook from Chapter 31, then to IP and sockets (Chapters 27-30) at the top. Branching off the XDP hook: XDP_DROP discards the packet immediately, and XDP_TX / XDP_REDIRECT bounce or forward it. The XDP hook runs in the driver, before sk_buff, making it the earliest and fastest hook; tc and the socket hooks all sit higher.
Figure 32.1: XDP runs first, in the driver, before any sk_buff exists
Download .excalidraw source
·
Edit on excalidraw.com
A frame arrives at the NIC RX path and enters the XDP capture program, which parses and filters it in the kernel. Matching packets (TCP SYN/FIN/RST) have a small record copied into a RingBuf that user space drains into tcpdump-style lines. Every packet, matching or not, continues up the network stack via XDP_PASS. The point: capture is read-only and filters in-kernel, shipping only matching records, so you never send every packet to user space.
Figure 33.1. Filter in the kernel, ship only the matches
Download .excalidraw source
·
Edit on excalidraw.com
A client on the peer sends UDP datagrams to a virtual port (VIP:8080) on the target. The XDP load balancer rewrites the destination port round-robin using BACKENDS[idx % N], sending roughly one third each to backend :9001, :9002, and :9003. XDP_PASS delivers locally; XDP_REDIRECT would forward to backends on other hosts.
Figure 34.1: One virtual port fanned out across backends by rewriting the UDP dest port
Download .excalidraw source
·
Edit on excalidraw.com
A synthetic packet built as a byte array (Ethernet + IPv4 + ICMP or TCP) is passed as data_in to BPF_PROG_TEST_RUN, which runs the loaded program. It returns the verdict (retval: XDP_DROP or XDP_PASS), an output buffer (data_out), the run duration, and any map side-effects. You assert on the verdict and map state in a test you can run anywhere with privileges.
Figure 35.1: Run the real program against a packet you build
Download .excalidraw source
·
Edit on excalidraw.com
An ingress packet enters a tcx chain (a kernel-ordered, bpf_link-based sequence of classifier programs, prog A then prog B) and the result goes up to the network stack. tcx attaches via bpf_link with several programs in a kernel-managed order and no clsact qdisc, unlike the legacy approach in Chapter 31 which used a clsact qdisc plus a single tc filter attached and ordered by hand.
Figure 36.1: tcx, a kernel-ordered chain of programs via bpf_link, no clsact qdisc
Download .excalidraw source
·
Edit on excalidraw.com
A process calls connect(), which reaches the LSM hook security_socket_connect. The attached BPF LSM program decides: if the caller's cgroup is OK it returns 0 (allow) and the connect proceeds; if the caller is in a confined cgroup it returns -EPERM (deny) and the connect is blocked. The program's return value decides; here the decision is scoped by cgroup id, confining one container while leaving the host untouched.
Figure 37.1: The LSM program's return value decides: 0 allows, negative denies
Download .excalidraw source
·
Edit on excalidraw.com
A process calls execve on /tmp/forbidden-something. A tracepoint on sys_enter_execve reads the filename; if it matches the forbidden prefix, the program calls bpf_send_signal(SIGKILL) and the process dies before the exec completes. React, don't just watch: a signal program is lab-only offense that illuminates defense.
Figure 38.1: React, don't just watch; kill the process the moment it execs a forbidden binary
Download .excalidraw source
·
Edit on excalidraw.com
getdents64 in the kernel writes directory entries into a user buffer. An eBPF exit hook uses bpf_probe_write_user to splice out the target /proc/PID entry before ps or ls /proc reads it, so the entry is gone from userspace's view. The process still exists; it is edited out of what userspace is allowed to see. Defense: bpf_probe_write_user taints the kernel, and you can compare /proc against the real task list.
Figure 39.1: The process still exists; it is edited out of what userspace can see
Download .excalidraw source
·
Edit on excalidraw.com
A write or truncate of a protected file reaches the LSM inode_permission hook, which checks whether the inode's i_ino equals the protected inode. If the access requests MAY_WRITE on the protected inode, the program returns -EPERM and the change is blocked; reads and accesses to other files return 0 and proceed, so the file stays readable. This is the defensive counterpart to Chapter 39; portable field reads come with CO-RE in Part 9.
Figure 40.1: Deny writes to one inode, even for root
Download .excalidraw source
·
Edit on excalidraw.com
sudo calls read on /etc/sudoers. An eBPF read-exit hook checks whether the current process is named sudo and the returned buffer begins with the sudoers header, and if so overwrites that buffer in memory. sudo then sees an injected line and grants root. The file on disk is never touched: only the bytes sudo reads into memory. Defense: the same tells as Chapter 39 (kernel taint, loaded programs), and an LSM can block bpf_probe_write_user.
Figure 41.1: The file on disk is never touched; only the bytes sudo reads are forged
Download .excalidraw source
·
Edit on excalidraw.com
Three kernel hooks, execve (new process), ptrace (inject or debug), and setuid (privilege change), each emit a SecEvent (type, pid, comm) into a single RingBuf. User space reads the stream and sends it to Grafana as events by type and severity, and optionally feeds a shield that blocks via LSM. This is the sensor layer of a runtime-security tool, built in eBPF: observe many attacker-relevant operations as one stream, then optionally shield.
Figure 42.1: Many hooks, one event stream, the sensor layer of a runtime-security tool
Download .excalidraw source
·
Edit on excalidraw.com
A runnable task enters your BPF scheduler, which implements sched_ext_ops via struct_ops with callbacks select_cpu, enqueue, and dispatch. The scheduler enqueues the task onto a dispatch queue (DSQ), and the kernel dispatches it from there to a CPU to run. You implement the callbacks; the kernel calls them to place and run every task. A misbehaving scheduler is auto-evicted by the watchdog, and the kernel falls back to the default scheduler.
Figure 43.1: You implement the callbacks; the kernel places and runs tasks through them
Download .excalidraw source
·
Edit on excalidraw.com
Tasks flow into the scx_nest policy, which keeps work on warm cores. A primary nest of warm, high-frequency cores (CPU0, CPU1, CPU2) is busy, while a reserve of idle or demoted cores (CPU3, CPU4) stays idle. The scheduler prefers placing tasks in the nest. The idea: concentrate work on a few warm cores with high frequency and hot caches rather than spreading it thin; cores idle too long are demoted out of the nest, and the nest grows under load.
Figure 44.1: Concentrate work on a few warm cores instead of spreading it thin
Download .excalidraw source
·
Edit on excalidraw.com
A client sends HTTP requests to an nginx worker running in a container. A uprobe on ngx_http_process_request records a start timestamp into STARTS keyed by the request pointer; nginx handles the request; a uprobe on ngx_http_finalize_request computes now minus start and adds it to a latency histogram exported to Grafana. The technique measures per-request latency inside a real server keyed by the request object with no app changes; you attach to the binary inside the container via the worker's pid and root, and the symbols must be present.
Figure 45.1: Per-request latency from inside nginx, keyed by the request object
Download .excalidraw source
·
Edit on excalidraw.com
One HTTP request to a Java or Python service is seen by an eBPF socket probe that times recv to send and captures the process comm. The loader mints one trace_id and emits three correlated signals: a span to Tempo (http.server.request), a log to Loki carrying the trace_id, and a RED metric to Prometheus with an exemplar. All three share the trace_id, so in Grafana you can click from metric to trace to logs. We mint the trace_id in the loader, while OBI propagates real W3C context across services.
Figure 46.1: One request, one trace_id, three correlated signals
Download .excalidraw source
·
Edit on excalidraw.com
OBI architecture across two layers. In kernel space, kprobes on sockets (TCP recv/send) and uprobes on TLS/libssl and language runtimes capture events. In user space, the OBI agent maps those raw events to OpenTelemetry semantic conventions (RED metrics and spans) and feeds the OpenTelemetry Collector, which exports over OTLP to traces in Tempo, metrics in Prometheus, and logs in Loki. OBI is zero-code auto-instrumentation that turns eBPF probes into OTel signals with no app changes, and it is language-agnostic because it reads the wire, not your symbols.
Figure 46.2: OBI, the production shape of what this chapter sketched
Download .excalidraw source
·
Edit on excalidraw.com
Clients send SQL to postgres, which runs as one binary with many backend processes (backend pid A, backend pid B). A uprobe on exec_simple_query captures per-query duration and the SQL text; a uprobe on ProcSleep captures lock-wait time. Both are keyed by the backend pid and exported to Grafana as query latency with SQL text and time waiting on locks. One uprobe on the postgres binary covers every backend process, and the backend pid separates connections.
Figure 47.1: One uprobe covers every backend; the pid separates connections
Download .excalidraw source
·
Edit on excalidraw.com
A loader loads a tracepoint program, an exec-count map, and a link (attachment), then pins all three to /sys/fs/bpf (bpffs), where the pins hold references, and the loader exits. Because the pins hold references, the program, map, and link outlive the loader until the pin is removed. Any reader process can open the pinned map to read results; removing the pin (rm) drops the reference and detaches.
Figure 48.1: Pins in bpffs hold references, so objects outlive the loader
Download .excalidraw source
·
Edit on excalidraw.com
Two ways to create BPF objects. The usual way: user space (libbpf or aya) issues many bpf() syscalls (map create, prog load) to build maps and programs in the kernel. The loader-program way: user space runs a syscall program once via BPF_PROG_RUN, and that program calls bpf_sys_bpf N times in the kernel to create the same maps and programs. Running once replays the load sequence in-kernel, which is the basis of light skeletons and signed loading.
Figure 49.1. A loader program issues the bpf() commands itself, in-kernel
Download .excalidraw source
·
Edit on excalidraw.com
User space is the producer: it reserves and submits samples into a user ring buffer (BPF_MAP_TYPE_USER_RINGBUF), the channel running user-to-BPF. A BPF program is the consumer: whenever it runs, it calls bpf_user_ringbuf_drain with a callback, which receives each pending sample and updates an aggregate map (count and sum). The program drains pending samples whenever it runs, and each sample arrives as a dynptr, covered in the dynptr chapter later in this part.
Figure 50.1: The ring buffer that runs backwards: user space produces, BPF consumes
Download .excalidraw source
·
Edit on excalidraw.com
The same eBPF bytecode (a portable ISA) runs two ways. Loaded via bpf() into the kernel runtime: verifier plus JIT, kernel hooks, privileged and system-wide. Or embedded in a user-space VM (rbpf, uBPF, bpftime) running in your app, with no root, portable. rbpf is a Rust VM you embed; bpftime runs uprobes and USDT in user space and can share maps with the kernel.
Figure 51.1. eBPF is an ISA: the same bytecode runs in the kernel or in a user-space VM
Download .excalidraw source
·
Edit on excalidraw.com
Two ways to call into the kernel from BPF. BPF helpers: a frozen, numbered UAPI list of about 210, with a stable ABI and scalar and memory arguments; adding one is a permanent ABI commitment. kfuncs: kernel functions registered via BTF, taking typed kernel pointers, with per-function flags and no ABI stability; subsystems export their own and churn is expected. The acquire/release discipline, verifier-enforced: bpf_task_from_pid (KF_ACQUIRE | KF_RET_NULL) goes through a forced null-check, then must reach bpf_task_release (KF_RELEASE). Drop the release on any path and the program will not load: kfuncs let the verifier enforce reference safety.
Figure 52.1: Helpers are a frozen UAPI; kfuncs are BTF-registered functions the verifier reasons about
Download .excalidraw source
·
Edit on excalidraw.com
Delegating BPF into a container without init-namespace privilege. A privileged runtime in the init user namespace mounts a bpffs with delegate_cmds, delegate_maps, delegate_progs, and delegate_attachs options. Inside a container user namespace with no init-namespace CAP_BPF, an unprivileged app opens that bpffs and calls BPF_TOKEN_CREATE to derive a token fd from it. The app then makes bpf() calls like PROG_LOAD and MAP_CREATE passing the token_fd, and the kernel checks them against the token, not init-namespace capabilities. The four axes (cmds, maps, progs, attachs) are the policy; the token grants only what was delegated: trust, not unconditional access.
Figure 53.1: A delegated bpffs mints a token; the kernel checks the token, not init-ns caps
Download .excalidraw source
·
Edit on excalidraw.com
An event (tracepoint) drives a BPF program that runs to completion and arms a timer. The timer lives in a map value alongside a count and rate, as a struct bpf_timer. The program calls init and start. Later the timer callback fires in softirq, atomic context: it sets rate = count and re-arms itself. Alternatively a workqueue callback runs in process, sleepable context for slow-path or I/O work; the program can schedule sleepable work there. The takeaway: timer is softirq (atomic, periodic, self-rescheduling); workqueue is process context (sleepable, fast-path/slow-path).
Figure 54.1: A timer or workqueue callback fires after the program returns, doing deferred work
Download .excalidraw source
·
Edit on excalidraw.com
struct_ops: BPF implements a kernel interface (a vtable), and the kernel calls in. On the left, BPF programs in sections struct_ops/ssthresh, struct_ops/cong_avoid, and struct_ops/undo_cwnd fill the slots of a STRUCT_OPS map holding a struct tcp_congestion_ops, which is registered via a link. On the right, the TCP stack's call sites invoke them: on ACK it calls cong_avoid, on loss it calls ssthresh, and the algorithm is selected via sysctl or setsockopt. The kernel calls your BPF. The same mechanism powers sched_ext (Part 6), HID-BPF, bpf Qdisc, and FUSE: BPF as a pluggable kernel module.
Figure 55.1: BPF fills a kernel-defined vtable; the kernel calls into it at the interface's call sites
Download .excalidraw source
·
Edit on excalidraw.com
One safe handle for variable-length memory, whatever backs it. On the left, backing stores: local memory, a ringbuf reservation, an skb or xdp packet, and a user-ringbuf sample. They are wrapped by a bpf_dynptr in the middle: a handle, not a raw pointer. On the right, bpf_dynptr_data(offset, len) returns a bounds-checked slice and the verifier enforces no out-of-bounds access. skb and xdp use bpf_dynptr_slice because data may be non-contiguous, and the slice is invalidated when the dynptr is.
Figure 56.1: A dynptr is a verifier-tracked handle; data access returns a bounds-checked slice
Download .excalidraw source
·
Edit on excalidraw.com
BPF arena: a shared heap where BPF builds real pointer data structures. On the left a BPF program calls bpf_arena_alloc_pages, uses __arena pointers, and builds a list, tree, or hash. In the center is the BPF arena, a sparse shared region up to 4 GB. On the right, user space mmaps the same region and reads the structures directly with no per-access syscall; the mmap link is zero-copy and bidirectional. Before arena, developers faked pointers with array-map indices; now lists, trees, and graphs use normal pointers, shared zero-copy.
Figure 56.2: An arena is a shared region where BPF builds pointer-based structures user space mmaps
Download .excalidraw source
·
Edit on excalidraw.com
Iterators flip the model: the kernel calls your program for every element of a set. On the left, a kernel set: all tasks, all TCP sockets, all map elements. The kernel drives one call per element into the BPF iterator program in the middle, which runs once per element and calls BPF_SEQ_PRINTF. On the right, the seq_file output is read by cat /sys/fs/bpf/task_iter or by read() on the link fd. Open-coded iterators (bpf_for or KF_ITER kfuncs) put bounded loops inside any BPF program.
Figure 57.1: The kernel drives the loop; your program is the per-element body, emitting to a seq_file
Download .excalidraw source
·
Edit on excalidraw.com
Compile once against generic types; relocate to the target kernel at load. In the development phase, eBPF source that reads task->pid plus a vmlinux.h generated from BTF go through the compiler (preserve_access_index), which emits a .o with BTF relocations describing 'field pid in task_struct' by name, not offset. At target runtime, you ship that one .o; the loader (aya or libbpf) reads the target kernel BTF at /sys/kernel/btf/vmlinux and patches offsets by name, producing a program loaded and running with the correct offsets for this kernel. Found by name and type, not offset, it survives fields moving, nesting, or differing across versions on kernels 5.8 and newer with BTF.
Figure 58.1. Relocations name the fields at compile time; the loader patches offsets from the target's BTF
Download .excalidraw source
·
Edit on excalidraw.com
Operating eBPF: outlive the process, swap without a gap, keep the state. Three pillars. One, pinning for lifetime: pin program, link, and map to bpffs so they outlive the loader process and a new loader re-acquires them by path. Two, link update for zero-downtime: BPF_LINK_UPDATE swaps the program under a live link with no gap, no dropped packets or events. Three, pinned maps for state: reuse the same map across versions so counters and connection state survive the upgrade. By hand, a systemd unit pins and a deploy script updates the link; at fleet scale, L3AF (LF Networking) and bpfman (CNCF) productize exactly these three pillars.
Figure 59.1: The three pillars of operating eBPF, and the orchestrators built on them
Download .excalidraw source
·
Edit on excalidraw.com
Offload: run the program somewhere other than the host CPU. Packets from the wire arrive at a NIC or DPU where offloaded eBPF runs (off the host CPU), dropping or redirecting before the host; only some packets continue to the host CPU kernel, where native or generic XDP runs and sees only what the NIC passes. Where 'somewhere' can be: a SmartNIC flow processor that JITs eBPF into NIC machine code (Netronome/Corigine NFP); a DPU running ordinary eBPF on its ARM Linux, where Aya runs unchanged; FPGA synthesis via hXDP or eHDL (research); or GPU and Tensor cores doing ML inference on telemetry (NVIDIA Morpheus). True hardware offload is narrow (NFP); the practical 2026 answer is eBPF on a DPU's Linux; FPGA and GPU are the frontier.
Figure 60.1: Offload targets, from the established SmartNIC path to the DPU answer to the research frontier
Download .excalidraw source
·
Edit on excalidraw.com
Attribute hardware energy to workloads: measure shares with eBPF, divide RAPL. On the left, RAPL via powercap provides energy_uj per domain (package, core, uncore, dram) at socket level, not per-process; and eBPF on sched_switch provides per-workload on-CPU time or cycles via perf counters. These feed an attribution step in the centre: watts times workload_time divided by total_time gives per-workload watts, exported to Grafana as ebpf_estimated_watts per workload. Limits: it ignores DVFS frequency and C-states, so it is comparative, not absolute. The control frontier is cpufreq_ext, which writes frequency policy in eBPF via struct_ops.
Figure 61.1: RAPL gives total socket energy; eBPF gives the per-workload weights to divide it by
Download .excalidraw source
·
Edit on excalidraw.com
Every signal carries the trace_id: Grafana turns four stores into one investigation. Sources on the left (Quarkus in Podman, FastAPI in Podman, and eBPF/Aya) all send OTLP to the OTel Collector on ports 4317 and 4318. The collector fans out to Prometheus for metrics (Mimir in production), Tempo for traces and spans, and Loki for logs plus Pyroscope for profiles. At the bottom, Grafana links every signal by trace_id: exemplars take you from a metric to a trace, tracesToLogs from a span to logs, derivedFields from a log back to a trace, and traces to profiles. The lab's otel-lgtm uses Prometheus; Mimir is the Prometheus-compatible production swap with the same PromQL and the same correlation.
Figure 62.1: Four backends, one trace_id, the correlation web Grafana stitches together
Download .excalidraw source
·
Edit on excalidraw.com
The final project: one request, every layer, one trace_id. A curl or Postman call with a traceparent hits FastAPI /checkout in Podman, which calls Quarkus /inventory in Podman, propagating the traceparent. Both apps send OTLP to the OTel Collector. An eBPF/Aya socket and L7 observer watches the sockets, extracts the traceparent, and emits ebpf_* metrics per request with the trace_id. The collector fans out to Tempo (spans from both services), Prometheus (app plus ebpf metrics), and Loki (trace-stamped logs); the eBPF metrics with their trace_id also go to Prometheus. At the bottom Grafana correlates everything on one trace_id: app spans, the eBPF view, metrics, and logs. App SDKs supply the trace_id; the eBPF layer extracts it from L7 or correlates by time, pid, and service: kernel to span in one view.
Figure 63.1: One request, observed from the HTTP span down to the kernel, joined on a single trace_id
Download .excalidraw source
·
Edit on excalidraw.com
Drive bpftrace from Python: one-liners become repeatable, parseable tools. A Python tool using subprocess and json.loads on NDJSON runs bpftrace with -e PROG and -f json. bpftrace compiles the DSL to eBPF via LLVM, attaches, and aggregates in in-kernel maps; the kernel's probes fire and maps aggregate, sending events back. bpftrace writes NDJSON on stdout, which the Python tool dispatches by type (attached_probes, printf, map, hist or lhist, value) into a table, an alert, or an OTel metric. bpftrace is for fast exploration and validation with no compile or deploy; Aya is for production: typed, embeddable, one binary.
Figure 64.1: bpftrace compiles and runs the probe; Python parses its JSON stream into a tool
Download .excalidraw source
·
Edit on excalidraw.com
bpftrace tools mapped to the kernel layer each observes. Around the stack (applications, system libraries, system call interface, VFS/sockets/scheduler, file systems/TCP-UDP/virtual memory, block/net devices, device drivers) sit bpftrace tools: vfscount and vfsstat and opensnoop and statsnoop and syncsnoop at VFS; writeback and xfsdist at file systems; mdflush at the volume manager; biosnoop and biolatency and bitesize at the block device; bashreadline at applications; gethostlatency at system libraries; syscount and killsnoop and execsnoop and pidpersec at the syscall interface; cpuwalk and runqlat and runqlen and offcputime at the scheduler; oomkill at virtual memory; tcpconnect and tcpaccept and tcpretrans and tcpdrop at TCP/UDP; and capable as a general security tool.
Figure 64.2: bpftrace's own tools, mapped to where each attaches (bpftrace project)
Download .excalidraw source
·
Edit on excalidraw.com
Drive bpftool from Python: inventory, inspect, and audit the BPF on a host. A Python tool using subprocess and json.loads issues a subcommand to bpftool -j (prog/map/link show, map dump, feature probe, net show), which queries the kernel's loaded programs, maps, links, and BTF and returns a JSON inventory. The tool parses it into progs, top by run_time, maps, dump, links, net, features, and audit tables. The swiss-army knife we cross-checked with all book, now scriptable; the run_time top needs sysctl kernel.bpf_stats_enabled=1.
Figure 65.1: bpftool returns a JSON inventory of loaded BPF; Python turns it into tools
Download .excalidraw source
·
Edit on excalidraw.com
Drive the ready-made BCC tools from Python: the validation suite, summarized. A Python wrapper spawns a BCC tool (execsnoop, biolatency, runqlat, tcpconnect, either classic Python plus C or libbpf CO-RE), which attaches to the kernel (compiling first if classic) where probes and maps run; the kernel returns events. The tool prints columnar text on stdout, which the wrapper parses into a top-N summary, counts, or a captured histogram. Classic BCC compiles inline C at runtime and needs clang plus kernel headers; libbpf-tools are precompiled CO-RE from Chapter 58. BCC is for depth, bpftrace for quick questions, Aya for production.
Figure 66.1: A BCC tool gathers; the Python wrapper resolves, runs, and summarizes it
Download .excalidraw source
·
Edit on excalidraw.com
A curated subset of the bcc tools mapped to the kernel layer each observes. Around the stack (applications, system libraries, system call interface, VFS/sockets/scheduler, file systems/TCP-UDP/virtual memory, block/net devices, device drivers) sit tools: filetop and vfsstat and cachestat and opensnoop and statsnoop at VFS; ext4slower and xfsslower at file systems; btrfsslower and nfsslower at the volume manager; biolatency and biosnoop and biotop and bitesize at the block device; bashreadline at applications; mysqld_qslower and dbstat at applications; execsnoop and opensnoop and syscount at the syscall interface; gethostlatency and sslsniff and memleak at system libraries; syscount and killsnoop and statsnoop at the syscall interface; runqlat and cpudist and runqlen and profile and offcputime at the scheduler; oomkill and memleak and slabratetop at virtual memory; tcpconnect and tcpaccept and tcplife and tcpretrans at TCP/UDP; and capable, funccount, funclatency, trace, argdist, and stackcount as general tools.
Figure 66.2: a curated subset of the bcc tools, mapped to where each attaches (iovisor/bcc)
Download .excalidraw source
·
Edit on excalidraw.com
From a kprobe counting unlink to operating a fleet, and the road ahead. The arc runs through six phases: Foundations (Part 0); Tracing and probing (Parts 1-2); Performance, networking, and security (Parts 3-5); Schedulers through advanced kernel surface (Parts 6-8); Operating eBPF (Part 9); and the Field guide (Part 10). It points to the frontier: all-Rust kernel side, sched_ext, struct_ops, cpufreq_ext, OBI, bpfman and L3AF, and DPU offload. The loop never changed: pick an event, write the handler, attach, observe, using Rust to ship and bpftrace, bcc, and bpftool to explore.
Figure 67.1. The arc of the book, and where it points next
Download .excalidraw source
·
Edit on excalidraw.com
Observe a privacy-preserving workload: time the operations, never the data. On the left, an HE workload built on TFHE-rs in Rust exposes boundary functions (he_keygen, he_encrypt which produces ciphertext, he_add and he_compute which perform homomorphic addition and multiplication on ciphertext, and he_decrypt), and its operands stay encrypted. An eBPF/Aya observer attaches a uprobe and uretprobe to each he_* boundary by symbol, measuring entry-to-return duration. That feeds a metric, ebpf_he_op_latency_seconds tagged by op (keygen, encrypt, add, compute, decrypt), exported to Grafana. It extends the Chapter 63 final project with the same uprobe and OTel machinery, on a workload whose data you never read: eBPF measures duration and stacks, not values.
Figure 68.1: timing each homomorphic operation by symbol, without ever reading its (encrypted) operands
Download .excalidraw source
·
Edit on excalidraw.com
Performance Co-Pilot architecture and its eBPF intersection. On the left, pluggable agents called PMDAs feed a collector daemon, pmcd: pmdalinux (kernel, /proc, cgroups); pmdabpf (eBPF CO-RE ELF modules); pmdabpftrace (bpftrace scripts); and pmdaopenmetrics (scrapes an Aya loader's Prometheus /metrics endpoint). pmdabpf and pmdabpftrace are highlighted as the eBPF intersection, and pmdaopenmetrics bridges the book's Aya loaders. On the right, consumers read from pmcd: pminfo, pmrep, pmstat, and pmchart for live query and reporting; pmlogger to record archives for later replay; pmie, the inference engine, for alerts; and pmproxy with pmseries for a REST API and time series stored in Redis. Below that, grafana-pcp brings PCP metrics into the same Grafana dashboards as the OTel stack. The model is pull-and-record (archives and alerts), which complements the book's push-based OTLP stream; both land in the same Grafana.
Figure 69.1: PCP collects from PMDAs into pmcd; pmdabpf and pmdabpftrace are the eBPF on-ramp
Download .excalidraw source
·
Edit on excalidraw.com