Buffers
The maps so far hold state: a count or a table that Go reads when it wants,
as a snapshot. Many tools need the events themselves instead: one record for
each open, in the order the opens happened, delivered while they happen. A
program sends such records through a buffer, memory the kernel shares
with user space, where the program writes records and Go reads them. This
chapter covers the two buffers that carry records from programs to Go, the
ring buffer and the perf buffer, and the user ring buffer, which
carries them from Go to a program. The example attaches two programs to
sys_enter_openat that send the same record, one through each of the first
two, so their output can be compared.
Directoryexamples/tutorial/step08-buffers/
- open_events.bpf.c the two tracepoint programs
- main.go the Go program
Three buffers
Section titled “Three buffers”A ring buffer is one buffer for all CPUs, read in order; a perf buffer is one ring per CPU; a user ring buffer carries records from Go to a program.
The ring buffer
Section titled “The ring buffer”A ring buffer is a map of type BPF_MAP_TYPE_RINGBUF: one buffer of
max_entries bytes that programs on every CPU write into. The size must be a
power of 2 and a multiple of the page size, 4096 bytes on x86-64; at open,
the loader rounds a declared size up to the next such value. The kernel keeps
two positions in it: the producer position, where the next record goes,
and the consumer position, up to which Go has read. When the producer
reaches the end of the buffer, records continue at the start. The kernel
maps the buffer’s pages twice, one copy after the other, so a record that
crosses the end is still contiguous in memory, for the program and for Go.
A program writes a record in three steps:
bpf_ringbuf_reserve(&map, size, 0)takessizebytes at the producer position and returns a pointer to them, or NULL when the ring has no room. The verifier needssizeto be a constant.- The program fills the record in place, through the pointer.
bpf_ringbuf_submit(ptr, 0)hands the record to Go, orbpf_ringbuf_discard(ptr, 0)drops it.
Each record starts with an 8-byte header that the kernel writes: the
record’s length, a busy bit, set from the reserve until the submit or the
discard, and a discard bit. The record takes its length plus the header in
the ring, rounded up to 8 bytes. The verifier treats a reservation as a
reference that the program must give back on every path. Without the
bpf_ringbuf_discard call on its error path, the example’s ring_openat
fails to load on 6.18 with EINVAL, and the log ends with:
52: (95) exitUnreleased reference id=3 alloc_insn=14BPF_EXIT instruction in main prog would lead to reference leakbpf_ringbuf_output(&map, data, size, 0) is the other way to write: it
reserves, copies size bytes from data and submits, in one call. Its
size may vary at run time, at the cost of building the record somewhere
else first and copying it.
Reservations from all CPUs take a lock in turn, so records lie in the ring in the order they were reserved, and Go reads them in that order. Go stops at a record whose busy bit is set and waits for it: a program that reserves early and submits late holds back the records that other CPUs reserved after it, even submitted ones.
The perf buffer
Section titled “The perf buffer”The perf buffer is older and is built on perf events, the kernel
subsystem behind perf(1). Its map is a BPF_MAP_TYPE_PERF_EVENT_ARRAY, an
array with one slot per CPU that holds no records itself. With max_entries
left out, as in the example, the loader sizes it to the number of possible
CPUs. The Go reader, bpf.NewPerfBuffer, opens one perf event per online
CPU, of the software type PERF_COUNT_SW_BPF_OUTPUT, maps a ring of
pageCnt pages for each, plus a page that holds the ring’s positions, and
writes each event’s descriptor into its CPU’s slot.
bpf_perf_event_output(ctx, &map, BPF_F_CURRENT_CPU, data, size) copies
size bytes from the program’s memory, usually its stack, into the ring of
the CPU the program runs on. The record gets a perf header in front, 8 bytes
with its type and size, then the 4-byte size of the data, and the kernel pads
the data so the whole record is a multiple of 8 bytes. For the example’s
72-byte struct, the record takes 88 bytes, and the data Go receives is 76:
the struct and 4 bytes of padding.
Each CPU has its own ring, so records keep their order only within a CPU. Go reads the rings one after another, in the order epoll reports them, so a tool that needs one order across CPUs puts a timestamp in the record and sorts.
The program can write only into a slot that a reader filled. Before
NewPerfBuffer, or after the reader’s Close emptied the slots,
bpf_perf_event_output fails and the record is gone. A ring buffer keeps
records from the load on, reader or not. On 6.18, with both of the example’s
programs attached before either reader existed, a ring reader created after
three opens read 5 records, the 3 opens and 2 files the Go program opened
itself after the first attach, and a perf reader created at the same point
read none.
The user ring buffer
Section titled “The user ring buffer”A user ring buffer, BPF_MAP_TYPE_USER_RINGBUF, carries records the
other way: Go writes them and a BPF program reads them. The last section of
this page covers it.
Reading records in Go
Section titled “Reading records in Go”Poll, Consume and epoll
Section titled “Poll, Consume and epoll”Poll(timeoutMS) waits up to timeoutMS milliseconds, with
epoll_wait(2), until a ring has records, then reads the rings that have
them and calls the callback once per record. A negative timeout waits with no
limit, and 0 does not wait. RingBuffer.Poll returns the number of records
it read; PerfBuffer.Poll returns the number of CPU rings that had records.
Consume() reads every ring without waiting, whether epoll reported it or
not, and RingBuffer.ConsumeN(n) stops after n records. They suit a loop
that already knows records are there, or a last read of the rings before
exit. EpollFD() returns the reader’s epoll descriptor, to wait on it in an
event loop of your own, next to other descriptors.
Neither reader retries an interrupted wait, as libbpf does not: when a signal
arrives during epoll_wait, Poll returns EINTR. A Go program receives
signals it never asked for: the runtime sends SIGURG to a thread to preempt
the goroutine running on it. Treat EINTR as a poll that read nothing, as
the example does.
The callbacks
Section titled “The callbacks”A callback runs on the goroutine that called Poll or Consume, one record
at a time, so state it shares with that goroutine needs no lock.
NewRingBuffer takes a func(data []byte) int. A negative return value
stops the read: Poll returns at once with that value as the errno, and the
record that returned it counts as read, so the next Poll starts after it.
On 6.18, a callback that returned -int(unix.ECANCELED) for the second of
four records made Poll fail with:
ring_buffer__poll: operation canceledand the next Consume read the remaining 2. Positive values are ignored;
return 0.
NewPerfBuffer takes two callbacks: sample(cpu, data), called for each
record with the CPU it came from, and lost(cpu, count), called when the
kernel reports records it dropped. Either may be nil.
In both readers, data is a slice of the ring’s memory, not a copy. Once the
callback returns, the reader moves the consumer position past the record and
the kernel writes later records over those bytes. A perf record that crosses
the end of its ring is first copied into a buffer of the reader’s, which the
next such record overwrites. Either way the slice is valid only during the
call: copy what you keep, with bytes.Clone or by decoding it into a
struct, which copies.
Wakeups
Section titled “Wakeups”A wakeup is the kernel telling the reader, through epoll, that a ring has
records. Each one costs the kernel some work and wakes the thread blocked in
Poll, so both buffers avoid sending one per record where they can.
For a ring buffer, bpf_ringbuf_submit and bpf_ringbuf_discard wake the
reader only when it has caught up: when the consumer position is at the
record being submitted, which means Go has read everything before it and may
be waiting. While Go is behind, it reaches the new record without a wakeup.
The flag BPF_RB_NO_WAKEUP never wakes the reader and BPF_RB_FORCE_WAKEUP
always does. Poll reads only the rings epoll reported, so records submitted
with BPF_RB_NO_WAKEUP wait for a later wakeup or a Consume.
For a perf buffer, the reader asks the kernel for a wakeup every
PerfBufferOpts.SamplePeriod records, or every record when it is 0 or the
options are nil, the default. A larger value wakes Go less often, and the
records before the next wakeup wait in the ring, where Consume finds them.
Sizes, limits and lost records
Section titled “Sizes, limits and lost records”Ring buffer. A record and its 8-byte header, rounded up to 8 bytes, must
be smaller than the ring. In a 4096-byte ring the largest reservation is 4080
bytes: on 6.18 one of 4081 bytes returned NULL. There is no page limit: an
8192-byte record fit in a 16 KiB ring. A reservation also fails when the free
space between the consumer and the producer is too small, because Go is
behind and the ring is full. On 6.18, 100 opens into a 4096-byte ring, with
no Poll in between, stored 51 of the example’s 80-byte records, and the
other reservations returned NULL. The ring keeps no trace of a failed
reservation: what happens to that event is up to the program, and a tool
that must know counts the failures in a map or a global variable.
Perf buffer. The perf header stores the record’s size in 16 bits, so a
record, headers and padding included, must be smaller than 64 KiB, which
makes 65516 bytes the largest sample. The kernel does not refuse a larger
one: on 6.18 bpf_perf_event_output returned 0 for a 65524-byte sample, the
record’s size wrapped to 0, and the reader’s next read failed with EINVAL.
A record must also fit in its CPU’s ring of pageCnt pages. When the ring of
a CPU is full, the kernel drops the record and counts it; once there is room
again, it writes a lost record, PERF_RECORD_LOST, holding the count, before
the next sample from that CPU. The reader passes the count to lost, so the
report comes late, with the first record after the gap. On 6.18, with a ring
of one page and 100 opens before the first read, libbpf in C and gobpfgo both
read 46 samples and, after one more open, reported 54 lost and read the 47th
sample. The lost record is 24 bytes, the header, the event ID and the count;
a kernel that appends a sample ID writes 32, which the reader also accepts.
The example never fills its rings, so its lost count is 0.
Backpressure. The kernel never waits for the reader: when Go falls
behind, the program loses events, whichever buffer it uses. Size the ring for
the bursts you expect, the rate of records times the longest time between
two reads, with room to spare, and keep the callbacks short, since the next
records wait while one runs. A ring buffer’s memory is shared by all CPUs,
so one busy CPU can fill all of it; a perf buffer gives every CPU pageCnt
pages, used or not.
The user ring buffer, from Go
Section titled “The user ring buffer, from Go”In a user ring buffer, Go is the producer, through the layer’s
UserRingBuffer:
bpf.NewUserRingBuffer(m)maps the ring of the loaded mapmfor writing.Reserve(size)returns a*libbpf.UserRingBufferSamplewhoseDataissizebytes in the ring. It fails withENOSPCwhen the ring has no room now and withE2BIGfor a size that can never fit.ReserveBlocking(size, timeoutMS)waits up totimeoutMSmilliseconds for the program to free room.Submit(sample)publishes the record andDiscard(sample)gives it back unused. Every reserved sample goes to exactly one of the two.Closeunmaps the ring; the map stays with itsObject.
The program reads with bpf_user_ringbuf_drain(&map, callback, ctx, flags),
which calls callback once for each record, with the record as a
dynptr: a pointer whose size the verifier learns only at run time, read
through helpers such as bpf_dynptr_read. The callback returns 0 to go on
and 1 to stop. The drain runs only when the program runs, so the program
needs a hook that fires when records may be waiting: a tracepoint that Go
triggers, a timer, or a regular event.
// Sketch: not in examples/.struct command { __u32 pid; __u32 value;};
struct { __uint(type, BPF_MAP_TYPE_USER_RINGBUF); __uint(max_entries, 64 * 1024);} commands SEC(".maps");
struct { __uint(type, BPF_MAP_TYPE_HASH); __uint(max_entries, 1024); __type(key, __u32); __type(value, __u32);} settings SEC(".maps");
// handle_command runs once per record: 0 goes on, 1 stops the drain.static long handle_command(struct bpf_dynptr *dynptr, void *ctx) { struct command cmd;
if (bpf_dynptr_read(&cmd, sizeof(cmd), dynptr, 0, 0) < 0) return 1; // shorter than a command bpf_map_update_elem(&settings, &cmd.pid, &cmd.value, BPF_ANY); return 0;}
// The drain runs when something calls getppid(2).SEC("tracepoint/syscalls/sys_enter_getppid")int drain_commands(void *ctx) { bpf_user_ringbuf_drain(&commands, handle_command, NULL, 0); return 0;}// Sketch: not in examples/. obj is loaded and drain_commands attached.producer, err := bpf.NewUserRingBuffer(obj.Map("commands"))if err != nil { return err}defer producer.Close()
sample, err := producer.Reserve(8)if err != nil { return err // ENOSPC: full until the program drains it}binary.NativeEndian.PutUint32(sample.Data[0:], uint32(os.Getpid()))binary.NativeEndian.PutUint32(sample.Data[4:], 42)if err := producer.Submit(sample); err != nil { return err}unix.Getppid() // the program runs and drains the ringThe callback reads a fixed size with bpf_dynptr_read. For records of
varying sizes, the kfunc bpf_dynptr_size returns a record’s size; the
gobpfgo tests use it.
Kernel support
Section titled “Kernel support”- Perf buffer: every kernel gobpfgo supports, 5.10 and newer.
- Ring buffer: Linux 5.8, so every kernel gobpfgo supports has it too.
- User ring buffer: Linux 6.1. The kfunc
bpf_dynptr_sizeneeds 6.4.
The minimums for amd64 and arm64 are in Kernel support. To check a map type on the running kernel, probe it, as the production chapter shows.
Which one to use
Section titled “Which one to use”Use the ring buffer by default: one buffer for all CPUs, records in reservation order, filled in place, and every kernel gobpfgo supports has it. Use the perf buffer for programs that already write to one, or when you want each CPU’s records kept apart: the ring buffer serializes reservations with a lock, and the perf buffer has none. Use the user ring buffer to send a stream of records to a program; for one setting, a map update is simpler.
The example: one record per open, twice
Section titled “The example: one record per open, twice”The BPF program
Section titled “The BPF program”// 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 COMM_LEN 16#define NAME_LEN 32
// openat_args mirrors the record of the syscalls/sys_enter_openat// tracepoint, as in step02-tracepoint: the 8-byte common header, the// system call number, then one 8-byte slot per system call argument.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; // offset 24, a user-space pointer long flags; long mode;};
_Static_assert(__builtin_offsetof(struct openat_args, filename) == 24, "filename must be at offset 24, as in the format file");
// event is the record both programs send to user space. Every field sits// at a multiple of its size, so the struct has no padding: 72 bytes that// Go decodes field by field.struct event { __u64 ts_ns; // offset 0: bpf_ktime_get_ns __u32 pid; // offset 8: the process ID, the TGID __u32 tid; // offset 12: the thread ID __u32 uid; // offset 16 __u32 gid; // offset 20 char comm[COMM_LEN]; // offset 24 char filename[NAME_LEN]; // offset 40};
_Static_assert(sizeof(struct event) == 72, "event must be 72 bytes");
// events is a ring buffer: one buffer of max_entries bytes shared by all// CPUs. The size is a power of 2 and a multiple of the page size.struct { __uint(type, BPF_MAP_TYPE_RINGBUF); __uint(max_entries, 256 * 1024);} events SEC(".maps");
// perf_events is a perf event array: one slot per CPU, which the Go// reader fills with a perf event and its ring. With max_entries left out,// the loader sizes it to the number of possible CPUs.struct { __uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY); __uint(key_size, sizeof(__u32)); __uint(value_size, sizeof(__u32));} perf_events SEC(".maps");
// target_tgid is set by Go before the load, so both programs send only// the opens of the Go process.const volatile __u32 target_tgid = 0;
// fill_event fills e for the current task and returns 0, or a negative// error when the file name cannot be read.static __always_inline int fill_event(struct event *e, struct openat_args *ctx, __u64 pid_tgid) { __u64 uid_gid = bpf_get_current_uid_gid();
// The reserved ring memory holds old bytes; zero the whole record so // nothing past the copied strings reaches user space. __builtin_memset(e, 0, sizeof(*e)); e->ts_ns = bpf_ktime_get_ns(); e->pid = pid_tgid >> 32; e->tid = (__u32)pid_tgid; e->uid = (__u32)uid_gid; e->gid = uid_gid >> 32; bpf_get_current_comm(e->comm, sizeof(e->comm)); if (bpf_probe_read_user_str(e->filename, sizeof(e->filename), ctx->filename) < 0) return -1; return 0;}
SEC("tracepoint/syscalls/sys_enter_openat")int ring_openat(struct openat_args *ctx) { __u64 pid_tgid = bpf_get_current_pid_tgid(); struct event *e;
if ((pid_tgid >> 32) != target_tgid) return 0;
// Reserve a record in the ring. NULL means the ring has no room: // the reader is behind, and this event is dropped. e = bpf_ringbuf_reserve(&events, sizeof(*e), 0); if (!e) return 0; if (fill_event(e, ctx, pid_tgid) < 0) { // A reservation must end in a submit or a discard. bpf_ringbuf_discard(e, 0); return 0; } bpf_ringbuf_submit(e, 0); return 0;}
SEC("tracepoint/syscalls/sys_enter_openat")int perf_openat(struct openat_args *ctx) { __u64 pid_tgid = bpf_get_current_pid_tgid(); struct event rec;
if ((pid_tgid >> 32) != target_tgid) return 0;
// The record is built on the stack, then copied into the ring of the // CPU this program runs on. if (fill_event(&rec, ctx, pid_tgid) < 0) return 0; bpf_perf_event_output(ctx, &perf_events, BPF_F_CURRENT_CPU, &rec, sizeof(rec)); return 0;}
// bpf_probe_read_user_str is a GPL-only helper.char LICENSE[] SEC("license") = "GPL";The record. struct event is the record both programs send: a
timestamp from bpf_ktime_get_ns, the process and thread IDs from the two
halves of bpf_get_current_pid_tgid, the user and group IDs from the two
halves of bpf_get_current_uid_gid, the task’s 16-byte comm, and the file
name, copied from user memory with bpf_probe_read_user_str and cut to 32
bytes with its NUL. Each field sits at a multiple of its size, so the struct
has no padding, and the _Static_assert stops the build if it is ever not
72 bytes. The record has a fixed size, so the program reserves exactly
sizeof(*e), a constant the verifier accepts.
The maps. events is a 256 KiB ring buffer, room for 3276 of these
records, 80 bytes each with the header, when none is read. perf_events leaves max_entries out, so the loader gives it
one slot per possible CPU. target_tgid is a .rodata constant, as in the
maps chapter, that Go sets to its own
process ID before the load, so both programs send only the Go program’s
opens.
Filling a record. fill_event first zeroes the whole record. Reserved
ring memory holds the bytes of older records, and bpf_probe_read_user_str
writes only up to the NUL, so without the memset old bytes would follow
each file name to user space. On the stack, the zeroing also gives every byte
of rec a value before bpf_perf_event_output reads it.
ring_openat reserves a record in events and returns when the ring is
full. If the file name cannot be read, it discards the reservation;
otherwise it submits it. perf_openat builds the same record on its
stack and copies it into the perf ring of its CPU.
The Go program
Section titled “The Go program”// SPDX-License-Identifier: LGPL-2.1-only
// Command step08 attaches two tracepoint programs to sys_enter_openat that// send a record for each open made by this process: one through a ring// buffer, the other through a perf buffer. It opens three files, polls both// readers until each has delivered three records, and prints them. Run it as// root from this directory, after make in examples/.package main
import ( "bytes" "encoding/binary" "errors" "fmt" "os" "time"
"github.com/gobpfgo/gobpfgo/bpf" "golang.org/x/sys/unix")
// event mirrors struct event in open_events.bpf.c: 72 bytes, no padding.type event struct { TsNs uint64 Pid uint32 Tid uint32 UID uint32 GID uint32 Comm [16]byte Filename [32]byte}
// record is one record as a reader delivered it: the CPU it came from, -1// for the ring buffer, which does not say, and a copy of its bytes.type record struct { reader string cpu int data []byte}
// files are the paths this process opens while the programs are attached.var files = []string{"/etc/hostname", "/etc/hosts", "/etc/passwd"}
// perfPages is the size of each CPU's perf ring in pages, a power of two.const perfPages = 8
func main() { if err := run(); err != nil { fmt.Fprintln(os.Stderr, "step08:", err) os.Exit(1) }}
func run() error { obj, err := bpf.OpenFile("open_events.bpf.o", nil) if err != nil { return err } defer obj.Close()
// target_tgid is the only .rodata variable, at offset 0. Setting it // before the load limits both programs to this process. pid := binary.NativeEndian.AppendUint32(nil, uint32(os.Getpid())) if err := obj.Map(".rodata").SetInitialValue(pid); err != nil { return err } if err := obj.Load(); err != nil { return err }
// The callbacks run on the goroutine that calls Poll, this one, so the // slices need no lock. data aliases the ring: once the callback // returns, the reader hands those bytes back to the kernel for later // records, so each callback keeps a copy. var ringRecords, perfRecords []record var lost uint64
ring, err := bpf.NewRingBuffer(obj.Map("events"), func(data []byte) int { ringRecords = append(ringRecords, record{"ring", -1, bytes.Clone(data)}) return 0 // a negative value would stop Poll with that errno }) if err != nil { return err } defer ring.Close()
perf, err := bpf.NewPerfBuffer(obj.Map("perf_events"), perfPages, func(cpu int, data []byte) { perfRecords = append(perfRecords, record{"perf", cpu, bytes.Clone(data)}) }, func(cpu int, count uint64) { lost += count }, nil) if err != nil { return err } // Close removes the perf events from the map through the map's // descriptor, which the Object owns, so it must run before obj.Close. // Deferred calls run last-in first-out, so it does. defer perf.Close()
// The links are deferred last, so they are destroyed first: the // programs stop writing before the readers go away. for _, name := range []string{"ring_openat", "perf_openat"} { prog := obj.Program(name) if prog == nil { return fmt.Errorf("no program named %s in the object", name) } link, err := prog.AttachTracepoint("syscalls", "sys_enter_openat") if err != nil { return err } defer link.Destroy() }
for _, path := range files { f, err := os.Open(path) if err != nil { return err } if err := f.Close(); err != nil { return err } }
// One record per file from each program. The ring program, attached // first, also sees the second attach, which opens a tracefs file to // read the tracepoint's ID: one more open by this process. wantRing, wantPerf := len(files)+1, len(files) deadline := time.Now().Add(5 * time.Second) for len(ringRecords) < wantRing || len(perfRecords) < wantPerf { if time.Now().After(deadline) { return fmt.Errorf("got %d ring and %d perf records, want %d and %d", len(ringRecords), len(perfRecords), wantRing, wantPerf) } // Each Poll waits up to 100 ms for records and hands them to its // callback. A signal, such as the one the Go runtime sends to // preempt a goroutine, interrupts the wait with EINTR. if _, err := ring.Poll(100); err != nil && !errors.Is(err, unix.EINTR) { return err } if _, err := perf.Poll(100); err != nil && !errors.Is(err, unix.EINTR) { return err } }
return printRecords(append(ringRecords, perfRecords...), lost)}
// printRecords decodes and prints the records, with times relative to the// earliest one, and the number of records the perf buffer lost.func printRecords(records []record, lost uint64) error { events := make([]event, len(records)) for i, r := range records { // A perf record can be longer than the struct: the kernel pads it // to a multiple of 8 bytes. Decode reads the first 72 bytes. if _, err := binary.Decode(r.data, binary.NativeEndian, &events[i]); err != nil { return err } } first := events[0].TsNs for _, e := range events { first = min(first, e.TsNs) }
fmt.Printf("%-6s %3s %8s %7s %7s %4s %4s %4s %-15s %s\n", "READER", "CPU", "+TIME us", "PID", "TID", "UID", "GID", "SIZE", "COMM", "FILE") for i, e := range events { cpu := "-" if records[i].cpu >= 0 { cpu = fmt.Sprint(records[i].cpu) } comm, _, _ := bytes.Cut(e.Comm[:], []byte{0}) name, _, _ := bytes.Cut(e.Filename[:], []byte{0}) fmt.Printf("%-6s %3s %8d %7d %7d %4d %4d %4d %-15s %s\n", records[i].reader, cpu, (e.TsNs-first)/1000, e.Pid, e.Tid, e.UID, e.GID, len(records[i].data), comm, name) } fmt.Printf("perf records lost: %d\n", lost) return nil}The program opens the object, writes its process ID into target_tgid
with SetInitialValue, and loads.
The readers. It creates both readers before attaching the programs.
The perf reader must exist before perf_openat writes, or the records are
lost; the ring reader could come later, but creating both first keeps the
order simple. The callbacks append a copy of each record with bytes.Clone,
because data belongs to the ring. The perf reader uses 8 pages, 32 KiB, per
CPU, and its lost callback adds up the counts.
Order of destruction. The deferred calls run in reverse: the two links
are destroyed first, so the programs stop writing; then perf.Close removes
the perf events from the map, through the map descriptor that the object
still holds; then ring.Close, then obj.Close. A PerfBuffer must be
closed before its Object for that reason.
The poll loop. The program opens three files, then polls both readers,
100 milliseconds at most each, until each has its records or 5 seconds have
passed, treating EINTR as an empty poll. It expects 4 ring records and 3
perf records. The ring program, attached first, also sees the second attach:
AttachTracepoint reads the tracepoint’s ID from
/sys/kernel/tracing/events/syscalls/sys_enter_openat/id, an open made by
this process.
The output. printRecords decodes each record with binary.Decode into
event, whose fields mirror the C struct. For a perf record of 76 bytes,
Decode reads the first 72 and ignores the padding. Times are in
microseconds after the earliest record.
Build and run
Section titled “Build and run”-
Build the BPF objects from the
examplesdirectory:Terminal window cd examplesmake -
Run the Go program as root, from the example’s directory:
Terminal window cd tutorial/step08-bufferssudo env PATH="$PATH" go run .
On 6.18 the output is:
READER CPU +TIME us PID TID UID GID SIZE COMM FILEring - 0 1715265 1715265 0 0 72 step08-buffers /sys/kernel/tracing/events/syscring - 48 1715265 1715265 0 0 72 step08-buffers /etc/hostnamering - 60 1715265 1715265 0 0 72 step08-buffers /etc/hostsring - 68 1715265 1715265 0 0 72 step08-buffers /etc/passwdperf 8 48 1715265 1715265 0 0 76 step08-buffers /etc/hostnameperf 8 60 1715265 1715265 0 0 76 step08-buffers /etc/hostsperf 8 68 1715265 1715265 0 0 76 step08-buffers /etc/passwdperf records lost: 0The ring delivered 4 records and the perf buffer 3, as expected. The first ring record is the attach’s own read of the tracepoint ID, its path cut to 31 bytes and a NUL; the perf program was not attached yet. Both programs saw the three opens, within a microsecond of each other, and the ring records are 72 bytes where the perf records are 76, the struct and its padding. The ring record does not say which CPU wrote it; the perf reader does, and all three opens ran on CPU 8, because the goroutine stayed on one thread. That thread is the process’s main thread, so the thread ID equals the process ID. The IDs and the CPU change from run to run.
The last chapter turns to running a tool: privileges, errors, lifetimes, pinning and testing.
