Skip to content

Maps

Every program so far kept its results in a map: an array with one counter, then hash maps keyed by file name. This chapter covers what those programs used without explaining: how a map is declared, which type to pick, the flags and the global variables that become maps, and pinning. The example extends the tracepoint program with a second map, a config map that the Go program writes before the BPF program runs, so the program counts only the opens of the Go program’s own process.

  • Directoryexamples/tutorial/step05-maps/
    • open_filter.bpf.c the tracepoint program with a config map
    • main.go the Go program

A map is declared in C as a variable of an anonymous struct type, placed in the .maps section:

struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 1024);
__type(key, char[32]);
__type(value, __u64);
} counts SEC(".maps");

The struct holds no data. libbpf’s bpf_helpers.h defines __uint(name, val) as a member int (*name)[val], a pointer to an array of val integers, and __type(name, val) as a member typeof(val) *name. The numbers and types live only in the struct’s type, which clang writes into the object’s BTF. At open, the loader reads that BTF to get the map’s type, its max_entries, and the sizes of its key and value; at load, it passes them to the kernel with BPF_MAP_CREATE. The variable’s name, counts, is the map’s name, and the one Object.Map looks for.

The key and value types set the sizes, 32 and 8 bytes here, and the kernel copies keys and values as bytes of those sizes. It does not interpret them, except for a few special fields, such as a spin lock, that a value type may contain. The loader also passes the BTF IDs of the two types, so tools like bpftool map dump can print the elements with their field names. A map without types, declared with __uint(key_size, 4) and __uint(value_size, 8), works the same for the kernel.

The other members are optional. __uint(map_flags, ...) sets the creation flags, and __uint(pinning, LIBBPF_PIN_BY_NAME) asks the loader to pin the map, both covered below. A map-in-map also declares its inner map’s shape with __array(values, struct inner).

Five panels. Array: slots 0 to 3 holding 5, 0, 12 and 0, preallocated and zeroed, for counters and settings. Hash: /etc/hostname maps to 3 and /etc/hosts to 2, entries added and removed at run time, for state per name or PID. Per-CPU: key 0 has one value per CPU, which user space adds up, for busy counters. Ring buffer: records in order in one buffer for all CPUs; the program writes at one end and Go reads at the other, and the end wraps to the start; a perf event array has one buffer per CPU. Map-in-map: an outer array whose slots hold inner hash maps, so one update replaces a whole table.

Five common kinds of map, their layout and what they are for.

Array, BPF_MAP_TYPE_ARRAY, has max_entries slots indexed by a __u32 from 0 to max_entries - 1. The kernel allocates every slot when it creates the map and fills them with zeros, so a lookup of a key in range always finds a value, and elements cannot be deleted: Map.Delete on an array returns EINVAL. Use it for counters with a fixed number of slots and for settings, like the config map below.

Hash, BPF_MAP_TYPE_HASH, maps any fixed-size key to a value and holds up to max_entries elements, which exist only once they are inserted, by the program or from Go, and disappear when deleted. Use it for state per name, per process or per connection. When it is full, inserts fail. Its LRU forms, BPF_MAP_TYPE_LRU_HASH and BPF_MAP_TYPE_LRU_PERCPU_HASH, evict the least recently used element to make room instead, which suits caches and tables whose keys never stop arriving.

Per-CPU maps, BPF_MAP_TYPE_PERCPU_ARRAY and BPF_MAP_TYPE_PERCPU_HASH, keep one value per CPU for each key. A program always sees the value of the CPU it runs on, so two CPUs never write the same memory and the program needs no atomic operations. User space reads all the copies and combines them. Use them for counters that every CPU updates often.

Ring buffer, BPF_MAP_TYPE_RINGBUF, is not a key-value store. Programs write records of any size into one buffer shared by all CPUs, and user space reads them in order; max_entries is the buffer’s size in bytes. The older perf event array, BPF_MAP_TYPE_PERF_EVENT_ARRAY, keeps one buffer per CPU instead. Both stream events to user space, and the buffers chapter covers them.

Program array, BPF_MAP_TYPE_PROG_ARRAY, holds program descriptors. A program jumps to the program in one of its slots with the bpf_tail_call helper, which lets one program dispatch to others.

Map-in-map, BPF_MAP_TYPE_ARRAY_OF_MAPS and BPF_MAP_TYPE_HASH_OF_MAPS, holds other maps, which must all have the shape the declaration gives. A program looks up the inner map, then uses it like any map. From Go, one Update that stores another map’s descriptor replaces a whole inner table at once. Before the load, Map.InnerMap returns the inner map’s definition to adjust, and Map.SetInnerMapFD replaces it with an existing map as the template.

A map’s creation flags, set with __uint(map_flags, ...), change how the kernel builds it. The ones you are most likely to need:

  • BPF_F_NO_PREALLOC makes a hash map allocate each element when it is inserted, instead of all max_entries of them at creation. It saves memory for large, sparse maps, at some cost on each insert.
  • BPF_F_RDONLY_PROG and BPF_F_WRONLY_PROG stop programs from writing or reading the map; BPF_F_RDONLY and BPF_F_WRONLY do the same for user space.
  • BPF_F_MMAPABLE lets user space map an array’s memory directly. The global data maps below use it.

Element operations take their own flags. Map.Update and the bpf_map_update_elem helper take BPF_ANY to create or replace an element, BPF_NOEXIST to only create it, and BPF_EXIST to only replace it. In Go they are libbpf.BPF_ANY, libbpf.BPF_NOEXIST and libbpf.BPF_EXIST.

Global variables in a BPF program are maps too. clang places them in the .data, .bss and .rodata sections, by whether they are initialized, zero, or constant, and the loader creates one single-element array map for each section, with the section’s bytes as the value. In Go, Object.Map finds them by section name, obj.Map(".rodata"). Their map names are the object’s name, cut short, then the section name: for an object open_filter.bpf.o, the .rodata map is named open_fil.rodata, which fits the kernel’s limit of 15 characters for a map name.

A const volatile global lands in .rodata. Go can change its value after the open and before the load, with Map.SetInitialValue, and the kernel freezes the map at load, so the verifier treats the value as a constant and can drop the code it rules out. That makes .rodata the usual place for settings fixed at startup:

const volatile __u32 target_tgid = 0;

The example keeps its setting in an explicit array map instead, so that Go writes it with Map.Update after the load, the way a tool changes a setting while its program runs. Variables in .data and .bss stay writable: after the load, Map.InitialValue returns the live map memory, which Go and the program share.

A map lives as long as something holds a reference to it: a descriptor in a process, a program that uses it, or a pin, a file in the BPF file system, bpffs, usually mounted at /sys/fs/bpf. A pinned map survives the process that created it, and other processes can open it by path.

__uint(pinning, LIBBPF_PIN_BY_NAME) in the declaration makes the loader pin the map at /sys/fs/bpf/<map name>, or under the directory set in BpfObjectOpenOpts.PinRootPath. At load, if a map is already pinned at that path, the loader reuses it instead of creating a new one, provided its type, sizes and flags match; otherwise it creates the map and pins it. Two runs of the same tool then share the map’s contents. Map.Pin and Map.Unpin pin and remove a pin explicitly; removing the pin lets the kernel free the map once nothing else holds it.

The kernel creates a map at Object.Load. bpf.OpenFile only parses the definition, and until the load there is no kernel map behind the Map value: Map.FD returns -1, and an Update fails with ENOENT:

bpf_map__update_elem: no such file or directory

Settings that shape the map, such as Map.SetMaxEntries or Map.SetInitialValue, work only before the load, and element operations, Lookup, Update, Delete and NextKey, only after it.

The map’s file descriptor is a handle to the whole map, which the Object owns and closes in Object.Close. The elements are reached through it, and each call copies bytes: Lookup copies a value into your slice, a snapshot that later program runs do not change, and Update copies your bytes into the map. A BPF program works differently: its bpf_map_lookup_elem returns a pointer into the element itself, which it changes in place. Closing the descriptor does not empty the map; the kernel frees the map and its elements when the last reference is gone.

Per-CPU values from user space. A per-CPU map stores value_size bytes per CPU, and user space reads or writes all CPUs’ values at once. The buffer for Lookup or Update holds one slot per possible CPU, each value_size rounded up to a multiple of 8 bytes, so a __u32 value on a machine with 16 possible CPUs takes 16 slots of 8 bytes, 128 bytes; the value for CPU n starts at byte 8 × n. Possible CPUs are the ones the kernel could bring online, as listed in /sys/devices/system/cpu/possible, not only the online ones; libbpf.LibbpfNumPossibleCpus() returns their number. A buffer of any other size fails with EINVAL.

examples/tutorial/step05-maps/open_filter.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>
#define NAME_LEN 32
// The record of syscalls/sys_enter_openat, as in step02.
struct openat_args {
unsigned short common_type;
unsigned char common_flags;
unsigned char common_preempt_count;
int common_pid;
int syscall_nr;
long dfd;
const char *filename;
long flags;
long mode;
};
// config has one slot, written from Go: key 0 holds the process ID
// (the thread group ID, or TGID) whose opens the program counts.
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__uint(max_entries, 1);
__type(key, __u32);
__type(value, __u32);
} config SEC(".maps");
// counts maps a file name, NUL-padded to 32 bytes, to its open count.
struct {
__uint(type, BPF_MAP_TYPE_HASH);
__uint(max_entries, 1024);
__type(key, char[NAME_LEN]);
__type(value, __u64);
} counts SEC(".maps");
SEC("tracepoint/syscalls/sys_enter_openat")
int handle_openat(struct openat_args *ctx) {
char name[NAME_LEN] = {};
__u32 key = 0;
__u64 one = 1;
__u64 *count;
__u32 *tgid;
// The upper 32 bits are the TGID, the process ID getpid(2) returns;
// the lower 32 bits are the ID of the calling thread.
__u32 current = bpf_get_current_pid_tgid() >> 32;
tgid = bpf_map_lookup_elem(&config, &key);
if (!tgid || *tgid != current)
return 0;
if (bpf_probe_read_user_str(name, sizeof(name), ctx->filename) < 0)
return 0;
count = bpf_map_lookup_elem(&counts, name);
if (!count) {
if (bpf_map_update_elem(&counts, name, &one, BPF_NOEXIST) == 0)
return 0;
count = bpf_map_lookup_elem(&counts, name);
if (!count)
return 0;
}
__atomic_fetch_add(count, 1, __ATOMIC_RELAXED);
return 0;
}
// bpf_probe_read_user_str is a GPL-only helper.
char LICENSE[] SEC("license") = "GPL";

The program is the tracepoint program of step02 with one check in front. config is an array with one __u32 slot, which holds the ID of the process to count. Before Go writes it, the slot is 0, like every new array slot, and the program counts nothing, since no process that opens files has ID 0.

bpf_get_current_pid_tgid() returns two IDs in one 64-bit value. The kernel calls each thread a task, with its own ID, and groups the threads of a process under a thread group ID, or TGID, which is the ID that getpid(2) returns and user space calls the process ID. The helper returns the TGID in the upper 32 bits and the thread’s ID in the lower 32 bits, so >> 32 gives the process ID. The lower half would not work: a Go program runs its goroutines on several threads, and os.Open can make its system call from any of them, so comparing the thread ID with the process ID would miss every open made outside the main thread.

The program looks up slot 0, checks the pointer, as the verifier requires, and returns early when the opening process is not the configured one.

examples/tutorial/step05-maps/main.go
// SPDX-License-Identifier: LGPL-2.1-only
// Command step05 writes its own process ID into the config map of a
// tracepoint program that counts openat calls per file name, so the
// program counts only this process. It opens /etc/hostname three times and
// /etc/hosts twice, reads one count, lists the counts map, deletes one
// entry and lists the map again. Run it as root from this directory, after
// make in examples/.
package main
import (
"bytes"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
"os"
"github.com/gobpfgo/gobpfgo/bpf"
"github.com/gobpfgo/gobpfgo/libbpf"
"golang.org/x/sys/unix"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, "step05:", err)
os.Exit(1)
}
}
func run() error {
obj, err := bpf.OpenFile("open_filter.bpf.o", nil)
if err != nil {
return err
}
defer obj.Close()
// Load creates the maps; before it, they have no kernel side to write.
if err := obj.Load(); err != nil {
return err
}
config := obj.Map("config")
counts := obj.Map("counts")
if config == nil || counts == nil {
return errors.New("the object lacks the config or counts map")
}
// Slot 0 of config gets this process's ID. Key and value are __u32,
// so both are 4 bytes in the host's byte order.
pid := uint32(os.Getpid())
configKey := binary.NativeEndian.AppendUint32(nil, 0)
configValue := binary.NativeEndian.AppendUint32(nil, pid)
if err := config.Update(configKey, configValue, libbpf.BPF_ANY); err != nil {
return err
}
fmt.Printf("config: key % x, value % x (pid %d)\n", configKey, configValue, pid)
prog := obj.Program("handle_openat")
if prog == nil {
return errors.New("no program named handle_openat in the object")
}
link, err := prog.AttachTracepoint("syscalls", "sys_enter_openat")
if err != nil {
return err
}
defer link.Destroy()
for _, opens := range []struct {
path string
times int
}{{"/etc/hostname", 3}, {"/etc/hosts", 2}} {
for range opens.times {
f, err := os.Open(opens.path)
if err != nil {
return err
}
if err := f.Close(); err != nil {
return err
}
}
}
// A counts key is the file name followed by NUL bytes, 32 bytes in all.
value := make([]byte, counts.ValueSize())
key := nameKey(counts, "/etc/hostname")
if err := counts.Lookup(key, value, 0); err != nil {
return err
}
fmt.Printf("/etc/hostname: %d\n", binary.NativeEndian.Uint64(value))
fmt.Println("counts:")
if err := dump(counts); err != nil {
return err
}
key = nameKey(counts, "/etc/hosts")
if err := counts.Delete(key, 0); err != nil {
return err
}
fmt.Printf("deleted key:\n%s", hex.Dump(key))
fmt.Println("counts after the delete:")
return dump(counts)
}
// nameKey returns the counts key for name: KeySize bytes, NUL-padded.
func nameKey(counts *bpf.Map, name string) []byte {
key := make([]byte, counts.KeySize())
copy(key, name)
return key
}
// dump prints every element of counts, walking the keys with NextKey.
func dump(counts *bpf.Map) error {
var curKey []byte
nextKey := make([]byte, counts.KeySize())
value := make([]byte, counts.ValueSize())
for {
err := counts.NextKey(curKey, nextKey)
if errors.Is(err, unix.ENOENT) {
return nil
}
if err != nil {
return err
}
if err := counts.Lookup(nextKey, value, 0); err != nil {
return err
}
name, _, _ := bytes.Cut(nextKey, []byte{0})
fmt.Printf("%4d %s\n", binary.NativeEndian.Uint64(value), name)
curKey = append(curKey[:0], nextKey...)
}
}

The program loads the object first, since the maps exist only after the load. It then builds the config map’s key and value as byte slices of the map’s sizes, 4 bytes each, for slot 0 and the process ID. binary.NativeEndian writes each __u32 in the CPU’s byte order, the order in which the BPF program will read it. Both architectures gobpfgo runs on, x86-64 and arm64, are little-endian, so the lowest byte comes first: in the run below, PID 1693105, 0x0019d5b1, becomes the bytes b1 d5 19 00. config.Update(configKey, configValue, libbpf.BPF_ANY) stores them.

Only then does the program attach and open its files, so every open it makes is counted, and no other process’s open is.

To read one count, the program builds the key itself. nameKey makes a slice of counts.KeySize() bytes, 32, all zero, and copies the name into its start, which gives the same bytes as the C program’s zeroed name buffer after the copy. counts.Lookup with that key reads the count for /etc/hostname. dump walks the map with NextKey, as step02 did, and cuts each key at its first NUL.

counts.Delete(key, 0) removes the element for /etc/hosts. The program prints the 32 key bytes it passed with hex.Dump: the ten bytes of the name, then 22 zeros. The second walk shows the map without it. Deleting the same key again would fail with ENOENT.

  1. Build the BPF objects from the examples directory:

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

    Terminal window
    cd tutorial/step05-maps
    sudo env PATH="$PATH" go run .

On 6.18 the output is:

config: key 00 00 00 00, value b1 d5 19 00 (pid 1693105)
/etc/hostname: 3
counts:
3 /etc/hostname
2 /etc/hosts
deleted key:
00000000 2f 65 74 63 2f 68 6f 73 74 73 00 00 00 00 00 00 |/etc/hosts......|
00000010 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |................|
counts after the delete:
3 /etc/hostname

The process ID and its bytes change on every run. Unlike step02, the counts are exact, and the map holds only the two files the Go program opened, even while other processes open files: the config check drops every other process before the program touches counts.

The programs read and wrote their maps through helpers, the kernel functions a BPF program may call. The next chapter explains what they are.