Skip to content

Production

The earlier chapters each showed a hook or a map. This one is about running a tool that uses them: which privileges it needs, how to read its errors, in which order to release what it created, how to keep a map or an attached program alive across a restart, how to adapt to the kernel it runs on, and how to test it. The example is not a new hook: it counts opens with a tracepoint, as before, and shows pinning with two processes. The first pins a map and a link and exits; the second reuses the map, reads the count the first one left, opens the link, and removes everything.

  • Directoryexamples/tutorial/step09-production/
    • pinned_count.bpf.c the counter, with a pinned map
    • main.go the Go program, with a pin mode and a reuse mode

Every bpf(2) call that creates something in the kernel is privileged. Since Linux 5.8, the kernel checks narrower capabilities than root’s CAP_SYS_ADMIN:

  • CAP_BPF lets a process create maps, load BTF and load programs.
  • CAP_PERFMON, with CAP_BPF, lets it load and attach tracing programs, such as kprobes and tracepoints, which read kernel memory, and open the perf events that tracepoints and perf buffers use.
  • CAP_NET_ADMIN, with CAP_BPF, lets it load and attach networking programs, such as XDP and tc programs.
  • CAP_SYS_ADMIN is still needed for a few operations, such as listing every loaded program or map by ID, as bpftool prog list does.

Without them, the sysctl kernel.unprivileged_bpf_disabled decides what is left. At 1 or 2, as on most distributions, a process without CAP_BPF can create no map and load no program; at 2 an administrator can lower the setting again, at 1 only a reboot can. At 0, a process without privilege may create some maps and load a few networking program types, such as socket filters, which tracing tools do not use. On the 6.18 host this manual uses, it is 2.

The capabilities cover the bpf() calls, not the files a tool reads on the way. On 6.18, the buffers chapter’s program, built as a normal user’s binary and given file capabilities with setcap, ran as follows:

Capabilities Result
none bpf_map_create: operation not permitted: events, after the notice that the kernel refused the object’s BTF
cap_bpf,cap_perfmon the load worked, and the attach failed with bpf_program__attach_tracepoint: permission denied
cap_bpf,cap_perfmon,cap_dac_read_search ran, and recorded the opens under the user’s UID and GID, 1000

The attach reads the tracepoint’s ID from /sys/kernel/tracing/events/syscalls/sys_enter_openat/id, and on that host /sys/kernel/tracing has mode 0700 and belongs to root. CAP_DAC_READ_SEARCH lets the process read it anyway; an administrator can instead mount tracefs with a group the tool’s user belongs to. In the same way, pinning needs write access to the directory on bpffs, which is mounted with mode 0700 on that host: the production example below, run with the three capabilities above, failed with failed to mkdir /sys/fs/bpf/gobpfgo-tutorial/open_count: -EACCES and ran with CAP_DAC_OVERRIDE added. A directory on bpffs created by an administrator and owned by the tool’s user avoids that capability: with the three capabilities above, both modes then pinned, reused and unpinned, and only the removal of the directory itself failed, since that needs write access to /sys/fs/bpf.

Terminal window
sudo setcap cap_bpf,cap_perfmon,cap_dac_read_search+ep ./mytool
getcap ./mytool

The kernel ignores file capabilities on a file system mounted nosuid, such as /tmp on many systems, so install the binary elsewhere. A service manager can grant the same set instead, such as systemd with AmbientCapabilities=. BpfObjectOpenOpts.BpfTokenPath names a bpffs mount from which the loader derives a BPF token, the kernel’s way, since Linux 6.9, to delegate bpf() rights to a process in a user namespace; this manual does not cover tokens.

Every failure of the core, and so of the layer, is a *libbpf.Error, except bpf.ErrClosed, which the layer returns for an object already closed. Its fields are:

  • Op, the libbpf function that failed, such as bpf_prog_load or bpf_program__attach_tracepoint;
  • Errno, the kernel’s error number, a syscall.Errno;
  • Path, the file involved, when there is one, such as the object file bpf.OpenFile could not read;
  • Log, the message libbpf would have printed with the failure, and for a program the verifier rejected, the verifier’s log.

Error() joins them, and Unwrap returns Errno, so errors.Is(err, unix.EPERM) works. errors.As gives the fields:

// Sketch: not in examples/.
if err := obj.Load(); err != nil {
var lerr *libbpf.Error
if errors.As(err, &lerr) {
fmt.Printf("Op: %s, Errno: %d (%v), Path: %q\n", lerr.Op, int(lerr.Errno), lerr.Errno, lerr.Path)
fmt.Println(lerr.Log)
}
return err
}
Op: bpf_prog_load, Errno: 22 (invalid argument), Path: ""
ring_openat: 0: R1=ctx() R10=fp0
...
52: (95) exit
Unreleased reference id=3 alloc_insn=14
BPF_EXIT instruction in main prog would lead to reference leak
processed 53 insns (limit 1000000) max_states_per_insn 0 total_states 3 peak_states 3 mark_read 0

The log starts with the program’s name and holds 71 lines here. Read it from the bottom up, as Your first program shows: the summary line comes last, the reason just above it, and above that each instruction the verifier walked, with its source line and the registers’ state. The errno says what kind of failure it was: EACCES for a program the verifier proved unsafe, EINVAL for one it could not accept as written, such as this leaked reservation, and EPERM for missing privilege.

When there is a log. By default a load asks the kernel for no log, and only when it fails does the loader load again at level 1, so the error carries the log. To get the log of a successful load too, for instance to see how many instructions the verifier processed, set BpfObjectOpenOpts.KernelLogLevel, or Program.SetLogLevel before the load: 1 for the instructions the verifier walked, 2 for more detail. KernelLogBuf and Program.SetLogBuf give the kernel a buffer of yours; a buffer too small makes the load fail with ENOSPC, even for a program the verifier accepted, while the loader’s own buffer starts at 16 MiB and doubles until the log fits.

Library messages. Where libbpf would warn and carry on, gobpfgo hands the message to a print function: by default it writes messages of level LIBBPF_INFO and LIBBPF_WARN to standard error, or the levels the LIBBPF_LOG_LEVEL environment variable names, warn, info or debug. libbpf.LibbpfSetPrint replaces that function for the whole process and returns the previous one; nil silences the library. Where an operation fails, the message is in the error’s Log instead.

// Sketch: not in examples/. Send library messages to standard error with
// their level.
libbpf.LibbpfSetPrint(func(level libbpf.LibbpfPrintLevel, msg string) {
if level <= libbpf.LIBBPF_INFO {
fmt.Fprintf(os.Stderr, "[level %d] %s", level, msg)
}
})
[level 1] libbpf: Error loading .BTF into kernel: -EPERM. BTF is optional, ignoring.

Each kernel object lives as long as something holds a reference to it: a descriptor in a process, a pin on bpffs, or another kernel object. A link holds its program, and a program holds the maps it uses. Your Go values hold descriptors:

  • The Object holds the descriptors of its maps and programs. Object.Close closes them; its Program and Map values stop working.
  • A Link belongs to you, not to the object. Closing the object neither detaches it nor destroys it: the kernel keeps the program loaded and attached until you call Destroy.
  • A RingBuffer, PerfBuffer or UserRingBuffer belongs to you too. Its memory mappings keep its map alive after the object closes. A PerfBuffer’s Close removes its entries from the map through the map descriptor, so it must run while the object is open.

So release in this order: destroy the links, so the programs stop running; close the readers; close the object. With defer, which runs in reverse, register them in the opposite order: the object’s Close right after the open, the readers’ Close after they are made, each link’s Destroy after its attach. The buffers example does exactly that.

When the process exits, however it exits, the kernel closes its descriptors: an attached program whose only reference was the process’s link is detached, and maps and programs that nothing else holds are freed. A pin is the exception, and so is what a pinned object holds. bpffs lives in memory, so pins do not survive a reboot.

Go’s default action for SIGINT and SIGTERM ends the process without running deferred calls. The kernel still releases the descriptors, but the cleanup your defers do, such as removing pins, does not happen; neither does the removal of the tracefs entry that a kprobe or uprobe attached in the Legacy mode creates. A long-running tool catches the signals, for instance with signal.NotifyContext, and returns from main normally.

A pin is a file on bpffs, the BPF file system, usually mounted at /sys/fs/bpf, that holds a reference to a map, a program or a link, as the maps chapter introduced. A pinned object outlives the process that pinned it, and another process opens it by path. ls lists pins, and rm removes one; removing the pin drops its reference.

Three columns over a kernel panel. Process 1, pin mode: loads, and the loader pins open_count by name; attaches and counts 5 opens; pins the link with Link.Pin as count_link; destroys the link, closes the object and exits, which closes its descriptors. bpffs: /sys/fs/bpf/gobpfgo-tutorial/ holds open_count, a map, count_link, a link, and count_openat, a program, dashed because the example does not pin it. Process 2, reuse mode: loads with the same pin root, which reuses open_count; reads the count, 5; opens count_link with OpenLink; unpins the link and the map and removes the directory. In the kernel, the link count_link, a perf link on sys_enter_openat, holds the tracepoint program count_openat, which holds the array map open_count. After process 1 exits, no process holds a descriptor: the map pin keeps the map, the link pin keeps the link, the link keeps the program attached and the program keeps the map, so the program still runs on every openat. After process 2 unpins, the link goes without its pin and last descriptor, and the program is detached and freed; the map goes when the last descriptor to it, the Object's, closes.

Pins keep a map and a link after the first process exits; the link keeps its program attached. The second process reuses the map and opens the link, then removes both pins.

Object Pin Remove the pin Open from another process
Map Map.Pin(&path), Object.PinMaps(&dir), or LIBBPF_PIN_BY_NAME at load Map.Unpin, Object.UnpinMaps a load with the same pin path reuses it
Program Program.Pin(path), Object.PinPrograms(dir) Program.Unpin, Object.UnpinPrograms no call in this version
Link Link.Pin(path) Link.Unpin bpf.OpenLink(path)

Object.Pin(dir) pins every map and program at once, and Object.Unpin(dir) removes those pins.

A pinned map keeps its contents and a pinned program stays loaded, but neither runs anything by itself. A pinned link keeps its program attached: the program goes on running after the process exits, until the link’s pin and last descriptor are gone. A link can be pinned only if it is a BPF link, with a descriptor of its own. On 6.18 a tracepoint attach makes one, a perf link. Perf links came in Linux 5.15; before that, a tracepoint or kprobe is attached through its perf event, and the link has no BPF link descriptor to pin. This page checked pinning on 6.18 only.

The rules below were checked on 6.18:

  • The path must be on bpffs. Elsewhere the pin fails with EINVAL, and the error says specified path /tmp/... is not on BPF FS.
  • The path must not exist. Pinning over a pin fails with EEXIST.
  • One missing parent directory is created, such as the pin root of the example. A pin two missing levels down fails with ENOENT and failed to mkdir.
  • PinMaps and PinPrograms name each pin after its map or program under the directory, with dots turned into underscores: the .rodata map of open_events.bpf.o, named open_eve.rodata, is pinned as open_eve_rodata. PinMaps(nil) uses the pin path each map has stored.
  • LIBBPF_PIN_BY_NAME in a map’s declaration gives the map the pin path <pin root>/<map name> at open, where the pin root is BpfObjectOpenOpts.PinRootPath, or /sys/fs/bpf when it is nil. Map.PinPath returns that path, and Map.Unpin(nil) removes the pin there.
  • Map.IsPinned reports whether the object pinned or reused the map. It returns false after Object.Close, though the pin remains.

At load, for each map with a pin path, the loader opens what is pinned there. If nothing is, it creates the map and pins it. If a map is, it reuses that map instead of creating one, provided it matches the declaration: the same type, key and value sizes, max_entries, flags and map_extra. Otherwise the load fails. On 6.18, a copy of this chapter’s object with max_entries 2, loaded over the example’s pin, failed with:

bpf_object__reuse_map: invalid argument: couldn't reuse pinned map at '/sys/fs/bpf/gobpfgo-tutorial/open_count': parameter mismatch

So a new version of a tool that changes a pinned map’s definition must remove the old pin first, and lose its contents, or pin the new map under another name.

The example: a count that outlives its process

Section titled “The example: a count that outlives its process”
examples/tutorial/step09-production/pinned_count.bpf.c
// SPDX-License-Identifier: LGPL-2.1-only
// This constraint keeps the Go tool from treating the file as cgo
// source. clang reads it as a comment.
//go:build ignore
#include <linux/bpf.h>
#include <bpf_helpers.h>
// open_count holds one counter. LIBBPF_PIN_BY_NAME makes the loader pin
// the map at <pin root>/open_count, or reuse the map already pinned there.
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, 1);
__type(key, __u32);
__type(value, __u64);
__uint(pinning, LIBBPF_PIN_BY_NAME);
} open_count SEC(".maps");
// target_tgid is set by Go before the load, so the program counts only
// the opens of the process that attached it.
const volatile __u32 target_tgid = 0;
SEC("tracepoint/syscalls/sys_enter_openat")
int count_openat(void *ctx) {
__u32 key = 0;
__u64 *count;
if ((bpf_get_current_pid_tgid() >> 32) != target_tgid)
return 0;
count = bpf_map_lookup_elem(&open_count, &key);
if (count)
__atomic_fetch_add(count, 1, __ATOMIC_RELAXED);
return 0;
}
char LICENSE[] SEC("license") = "GPL";

open_count is an array with one __u64 counter, as in the first program, and its declaration asks for LIBBPF_PIN_BY_NAME. count_openat adds one for each openat(2) call made by the process whose ID is in target_tgid, which Go sets before the load. The filter keeps the count exact: the link will outlive the first process, and without the filter the program would go on counting every open on the machine until the second process removes it.

examples/tutorial/step09-production/main.go
// SPDX-License-Identifier: LGPL-2.1-only
// Command step09 shows pinning across two processes. "pin" loads a
// tracepoint program that counts this process's openat calls in a map the
// loader pins under /sys/fs/bpf/gobpfgo-tutorial, opens five files, pins the
// link and exits. "reuse", run next as a second process, loads the same
// object, which reuses the pinned map, reads the count the first process
// left, opens the pinned link, then removes every pin and the directory.
// Run both as root from this directory, after make in examples/.
package main
import (
"encoding/binary"
"errors"
"fmt"
"io/fs"
"os"
"strings"
"github.com/gobpfgo/gobpfgo/bpf"
"github.com/gobpfgo/gobpfgo/libbpf"
)
const (
// pinRoot is this example's directory on bpffs.
pinRoot = "/sys/fs/bpf/gobpfgo-tutorial"
// mapPin is where LIBBPF_PIN_BY_NAME puts open_count: the pin root, a
// slash and the map's name.
mapPin = pinRoot + "/open_count"
// linkPin is where the pin mode pins the tracepoint link.
linkPin = pinRoot + "/count_link"
// opens is how many files the pin mode opens.
opens = 5
)
func main() {
mode := ""
if len(os.Args) == 2 {
mode = os.Args[1]
}
var err error
switch mode {
case "pin":
err = pin()
case "reuse":
err = reuse()
default:
err = fmt.Errorf("usage: step09 pin|reuse, not %q", mode)
}
if err != nil {
fmt.Fprintln(os.Stderr, "step09:", err)
os.Exit(1)
}
}
// open opens the object with its pin root set, so the load pins open_count
// at mapPin or reuses the map already pinned there.
func open() (*bpf.Object, error) {
root := pinRoot
return bpf.OpenFile("pinned_count.bpf.o", &libbpf.BpfObjectOpenOpts{PinRootPath: &root})
}
// pin loads, attaches and counts, then pins the link and exits, leaving the
// map and the link pinned. If it fails, it removes what it pinned.
func pin() (err error) {
switch _, err := os.Stat(pinRoot); {
case err == nil:
return fmt.Errorf("%s exists: run the reuse mode, or remove it with rm -r", pinRoot)
case !errors.Is(err, fs.ErrNotExist):
return err
}
defer func() {
if err != nil {
removePins()
}
}()
obj, err := open()
if err != nil {
return err
}
defer obj.Close()
// Count only this process: target_tgid is the only .rodata variable.
tgid := binary.NativeEndian.AppendUint32(nil, uint32(os.Getpid()))
if err := obj.Map(".rodata").SetInitialValue(tgid); err != nil {
return err
}
// The load creates open_count, creates the pin root, and pins the map.
if err := obj.Load(); err != nil {
return err
}
counter := obj.Map("open_count")
prog := obj.Program("count_openat")
if counter == nil || prog == nil {
return errors.New("the object lacks open_count or count_openat")
}
// Read the kernel's IDs now: once the program is attached, every file
// this process opens, /proc included, adds to the count.
mapID, err := fdinfo(counter.FD(), "map_id")
if err != nil {
return err
}
progID, err := fdinfo(prog.FD(), "prog_id")
if err != nil {
return err
}
fmt.Printf("pin: map open_count id %s pinned at %s: %t\n", mapID, counter.PinPath(), counter.IsPinned())
fmt.Printf("pin: program count_openat id %s\n", progID)
link, err := prog.AttachTracepoint("syscalls", "sys_enter_openat")
if err != nil {
return err
}
defer link.Destroy()
if err := openFiles(opens); err != nil {
return err
}
count, err := readCount(counter)
if err != nil {
return err
}
fmt.Printf("pin: opens counted: %d\n", count)
if err := link.Pin(linkPin); err != nil {
return err
}
fmt.Printf("pin: link pinned at %s\n", link.PinPath())
// Destroy closes this process's link descriptor. The pin holds another
// reference, so the link stays and the program stays attached. Close
// closes the map and program descriptors; the map pin keeps the map.
link.Destroy()
obj.Close()
fmt.Println("pin: link destroyed and object closed; the pins remain")
return nil
}
// reuse loads the same object, which reuses the pinned map, reads the count,
// opens the pinned link, then removes the pins and the pin root. It removes
// them on failure too.
func reuse() error {
if _, err := os.Stat(pinRoot); err != nil {
return fmt.Errorf("run the pin mode first: %w", err)
}
defer removePins()
obj, err := open()
if err != nil {
return err
}
defer obj.Close()
// This process only reads the map, so the load skips the program.
prog := obj.Program("count_openat")
if prog == nil {
return errors.New("no program named count_openat in the object")
}
if err := prog.SetAutoload(false); err != nil {
return err
}
// The map pinned at mapPin has the type, sizes, flags and map_extra of
// the definition, so the load reuses it instead of creating one.
if err := obj.Load(); err != nil {
return err
}
counter := obj.Map("open_count")
if counter == nil {
return errors.New("no map named open_count in the object")
}
mapID, err := fdinfo(counter.FD(), "map_id")
if err != nil {
return err
}
fmt.Printf("reuse: map open_count id %s reused from %s: %t\n", mapID, counter.PinPath(), counter.IsPinned())
count, err := readCount(counter)
if err != nil {
return err
}
fmt.Printf("reuse: opens counted: %d\n", count)
link, err := bpf.OpenLink(linkPin)
if err != nil {
return err
}
defer link.Destroy()
linkType, err := fdinfo(link.FD(), "link_type")
if err != nil {
return err
}
progID, err := fdinfo(link.FD(), "prog_id")
if err != nil {
return err
}
fmt.Printf("reuse: link opened from %s: fd %d, type %s, program id %s\n",
link.PinPath(), link.FD(), linkType, progID)
// Remove the link's pin, then close the last reference to the link,
// which detaches the program. Then remove the map's pin and the
// directory; the map goes when the Object closes its descriptor.
if err := link.Unpin(); err != nil {
return err
}
link.Destroy()
if err := counter.Unpin(nil); err != nil {
return err
}
if err := os.Remove(pinRoot); err != nil {
return err
}
fmt.Printf("reuse: unpinned the link and the map, removed %s\n", pinRoot)
return nil
}
// openFiles opens and closes /etc/hostname n times.
func openFiles(n int) error {
for range n {
f, err := os.Open("/etc/hostname")
if err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
}
return nil
}
// readCount returns the counter in slot 0 of open_count.
func readCount(counter *bpf.Map) (uint64, error) {
key := binary.NativeEndian.AppendUint32(nil, 0)
value := make([]byte, counter.ValueSize())
if err := counter.Lookup(key, value, 0); err != nil {
return 0, err
}
return binary.NativeEndian.Uint64(value), nil
}
// fdinfo returns a field of /proc/self/fdinfo/<fd>, where the kernel
// describes a map, program or link descriptor.
func fdinfo(fd int, field string) (string, error) {
data, err := os.ReadFile(fmt.Sprintf("/proc/self/fdinfo/%d", fd))
if err != nil {
return "", err
}
for line := range strings.Lines(string(data)) {
name, value, ok := strings.Cut(line, ":")
if ok && name == field {
return strings.TrimSpace(value), nil
}
}
return "", fmt.Errorf("no %s in the fdinfo of descriptor %d", field, fd)
}
// removePins removes the pins this example makes and its pin root, where
// they exist. A pin is a file on bpffs; unlinking it is what Unpin does.
func removePins() {
for _, path := range []string{linkPin, mapPin, pinRoot} {
if err := os.Remove(path); err != nil && !errors.Is(err, fs.ErrNotExist) {
fmt.Fprintln(os.Stderr, "step09: cleanup:", err)
}
}
}

open opens the object with PinRootPath set to /sys/fs/bpf/gobpfgo-tutorial, so open_count’s pin path is /sys/fs/bpf/gobpfgo-tutorial/open_count in both modes.

The pin mode refuses to start when the pin root exists, so it never counts on top of an earlier run. It sets target_tgid, and loads: the loader creates open_count, creates the pin root and pins the map. It reads the kernel IDs of the map and the program from /proc/self/fdinfo, where the kernel describes each BPF descriptor, before attaching: once the program runs, every file the process opens counts, /proc included. Then it attaches, opens /etc/hostname five times, reads the count, and pins the link at /sys/fs/bpf/gobpfgo-tutorial/count_link. link.Destroy() closes the process’s link descriptor and obj.Close() the map and program descriptors; the pins keep the map and the link, and the link keeps the program attached. If any step fails, the deferred function removes whatever was pinned.

The reuse mode runs as a second process. It turns the program’s autoload off with SetAutoload(false), since it only reads the map, and loads: the map pinned at open_count’s pin path matches the declaration, so the loader reuses it. The map ID it prints is the first process’s, and the count is the one the first process left. bpf.OpenLink opens the pinned link; its descriptor’s fdinfo gives the link type, perf, and the ID of the program the link holds, the first process’s program. Then it removes the link’s pin with link.Unpin() and closes the descriptor with link.Destroy(), the last reference, so the kernel detaches the program and frees it. counter.Unpin(nil) removes the map’s pin, and os.Remove the directory; the map goes when the object closes its descriptor. The deferred removePins does the same with os.Remove if a step fails: a pin is a file, and unlinking it is what Unpin does.

  1. Build the BPF objects from the examples directory:

    Terminal window
    cd examples
    make
  2. Run the pin mode as root, from the example’s directory:

    Terminal window
    cd tutorial/step09-production
    sudo env PATH="$PATH" go run . pin
  3. Look at the pins, then run the reuse mode as a second process:

    Terminal window
    sudo ls -l /sys/fs/bpf/gobpfgo-tutorial
    sudo bpftool link show pinned /sys/fs/bpf/gobpfgo-tutorial/count_link
    sudo env PATH="$PATH" go run . reuse

On 6.18 the pin mode prints:

pin: map open_count id 57052 pinned at /sys/fs/bpf/gobpfgo-tutorial/open_count: true
pin: program count_openat id 56714
pin: opens counted: 5
pin: link pinned at /sys/fs/bpf/gobpfgo-tutorial/count_link
pin: link destroyed and object closed; the pins remain

With no process of the tool running, the pins are there, and bpftool, built on libbpf, shows the link still holding program 56714 on the tracepoint:

total 0
-rw------- 1 root root 0 Nov 30 03:50 count_link
-rw------- 1 root root 0 Nov 30 03:50 open_count
22602: perf_event prog 56714
tracepoint sys_enter_openat

The reuse mode prints:

reuse: map open_count id 57052 reused from /sys/fs/bpf/gobpfgo-tutorial/open_count: true
reuse: opens counted: 5
reuse: link opened from /sys/fs/bpf/gobpfgo-tutorial/count_link: fd 9, type perf, program id 56714
reuse: unpinned the link and the map, removed /sys/fs/bpf/gobpfgo-tutorial

The second process saw map 57052 and the count of 5 that the first process left, and the link it opened holds program 56714, the first process’s. Afterwards /sys/fs/bpf/gobpfgo-tutorial no longer exists, and bpftool prog show id with the old program ID fails with No such file or directory. The IDs change from run to run. Run the pin mode twice without the reuse mode in between, and the second run stops with /sys/fs/bpf/gobpfgo-tutorial exists; sudo rm -r /sys/fs/bpf/gobpfgo-tutorial removes the pins by hand, which detaches the program.

Object.Load does two things: it creates the maps and relocates the programs’ code, then loads the programs. Object.Prepare does only the first. After it, the maps exist, with descriptors, so Go can fill them, pin them or create readers on them, and no program is loaded yet. Object.Load then loads the programs whose load strategy is AUTO:

  • AUTO, the default, is loaded by Object.Load.
  • DISABLED is never loaded. Program.SetAutoload(false) sets it, as the reuse mode does, and so does a section name that starts with ?, such as SEC("?tracepoint/syscalls/sys_enter_openat").
  • MANUAL is prepared with the object and loaded only when Go calls Program.Load, after Prepare or Load. A section name that starts with ! sets it, and so does Program.SetLoadStrategy(libbpf.BPF_PROG_LOAD_STRATEGY_MANUAL) before the load.

On 6.18, with the buffers chapter’s perf_openat set to MANUAL: after Prepare, the events map had a descriptor and neither program did; after Load, ring_openat was loaded and perf_openat was not; Program.Load loaded it; and a second Program.Load failed with EBUSY and prog 'perf_openat': already loaded. A MANUAL program that the kernel refuses leaves the object as it was and can be loaded again.

Use these when one object carries programs for different kernels or features: turn off, before the load, the programs the kernel cannot take, such as an fentry program on a kernel without BPF trampolines next to a kprobe that does the same job, or load a MANUAL program only when the user asks for its feature.

gobpfgo supports Linux 5.10 and newer, and newer features need newer kernels. The loader already adapts what it can: it probes the running kernel at load, as libbpf does, and converts or drops what the kernel cannot take, such as newer BTF kinds. For the rest, a tool asks the kernel before it relies on a feature, with the core’s probes:

  • libbpf.LibbpfProbeBpfProgType(progType) loads a minimal program of that type;
  • libbpf.LibbpfProbeBpfMapType(mapType) creates a small map of that type;
  • libbpf.LibbpfProbeBpfHelper(progType, helperID) loads a program of that type that calls the helper.

Each returns whether the kernel accepted it. A probe makes the same bpf() call the real load would, so run it with the same privileges. On 6.18, as root, all four probes below returned true. As a normal user, the map and program type probes returned false, and the helper probe still returned true, because its load failed for lack of privilege, not for an unknown helper, which is the only failure it counts as unsupported.

// Sketch: not in examples/.
ring, err := libbpf.LibbpfProbeBpfMapType(libbpf.BPF_MAP_TYPE_RINGBUF)
userRing, err := libbpf.LibbpfProbeBpfMapType(libbpf.BPF_MAP_TYPE_USER_RINGBUF)
tp, err := libbpf.LibbpfProbeBpfProgType(libbpf.BPF_PROG_TYPE_TRACEPOINT)
cookie, err := libbpf.LibbpfProbeBpfHelper(libbpf.BPF_PROG_TYPE_TRACEPOINT, libbpf.BPF_FUNC_get_attach_cookie)

An unknown type returns EOPNOTSUPP, and so does a helper probe for tracing, extension, LSM and struct_ops programs, which cannot load without an attach target. Combine the probes with the load strategies: probe, then turn off the programs whose feature is missing, before Load.

The minimum kernel for each feature, on amd64 and arm64, the kernel configuration a tool needs, such as BTF and a mounted bpffs, and the kernels gobpfgo is tested on are in Kernel support. Distribution kernels often backport BPF features, which is another reason to probe rather than compare version numbers.

Kernel modules have their own BTF, under /sys/kernel/btf/<module>. The loader reads it to resolve what is not in the kernel’s own BTF, vmlinux: a CO-RE relocation against a module’s type, an fentry or LSM program attached to a module’s function, a __ksym variable or kfunc a module defines, or a module’s struct_ops type. BpfObjectOpenOpts.BtfModuleAllowlist limits which modules it reads:

  • nil, the default, allows every module;
  • an empty slice that is not nil allows none, so only vmlinux is used;
  • a list allows exactly the modules it names, matched against the full module name.

In this version, an object with CO-RE relocations makes the loader read and parse the BTF of every module the list allows, at every load. On 6.18, with 131 modules that have BTF, the median load of the CO-RE chapter’s object, over seven runs, took 18.5 ms with the default and 9.9 ms with an empty allowlist. A tool whose types and functions are all in vmlinux can pass []string{} and load faster; a tool that needs one module names that module. The list also keeps the loader from matching a name in a module the tool does not expect. BtfCustomPath, when set, replaces the CO-RE targets, modules included.

Your tool. Split its tests by what they need. Opening an object, reading its maps and programs, BTF, linking and dumps make no bpf() call, so those tests run anywhere, as a normal user and in CI. Loading, attaching and reading maps need privileges and a kernel: run those tests as root, and skip them otherwise, by checking the effective user or by skipping on EPERM. A test of a feature some kernels lack probes for it and skips with a message that names the feature, so a skip on an old kernel reads as what it is. Run the root tests with sudo and a build cache of root’s own, so root never writes files into yours:

Terminal window
sudo env PATH="$PATH" GOCACHE=/root/.cache/go-build go test ./...

gobpfgo itself is tested the same way, against libbpf:

  • Fixtures. testdata/progs/ holds C programs built with clang, one or more per feature.
  • The oracle. A C program in oracle/, linked against the pinned libbpf, runs the same fixtures through libbpf and writes what it sees, from the relocated instructions and the linked BTF bytes to the errnos of failed attaches, as JSON files in testdata/oracle/. The Go tests run the fixtures through gobpfgo and must produce the same output. The tests read the checked-in files and never build the oracle.
  • Two suites on six kernels. The unprivileged suite runs without root; the root suite loads and attaches. Both run on amd64 5.10, 6.18, 7.3.6 and 7.4-rc4 and on arm64 6.17 and 5.10, and a feature a kernel lacks skips its tests on that tier. CI builds, vets and runs the unprivileged suite on every pull request.

The examples in this manual are built and run as root on 6.18 before a page embeds them.

Choose the buffer by its costs. A ring buffer record is written once, in place, and read once; a perf buffer record is built on the stack and copied into the ring. A ring buffer shares one lock and one memory area among all CPUs; a perf buffer has a ring per CPU, pageCnt pages each, used or not. The buffers chapter covers their sizes and how each loses records.

Count per CPU on busy paths. An __atomic_fetch_add on one counter makes every CPU that runs the program write the same cache line. A per-CPU array or hash gives each CPU its own value, with no atomic operation, and Go adds them up when it reads, as the maps chapter describes.

Read maps with few system calls. Each Lookup, Update and NextKey is one bpf() call: on the README’s benchmark host, a lookup took 732 ns from Go and 611 ns from C. Walking a hash of 10000 entries is 20000 calls. Stream events through a buffer instead of polling a big map, keep maps you poll small, and read global variables through Map.InitialValue, which returns the map’s memory and needs no system call.

Poll in batches. Each wakeup costs the kernel some work and a thread switch. The ring buffer wakes Go only when it has caught up; BPF_RB_NO_WAKEUP and BPF_RB_FORCE_WAKEUP let a program choose, and PerfBufferOpts.SamplePeriod makes the perf buffer wake Go every so many records. On the Go side, the usual shape is one goroutine per reader, blocked in Poll with a timeout that bounds how long shutdown waits, and short callbacks that copy the record and hand it on. ConsumeN limits how many records one call reads, so other work is not starved.

The README’s performance section compares gobpfgo with libbpf in C, call by call.

This was the last guide chapter. The reference lists the API of both packages.