| 1 | //go:build linux |
| 2 | |
| 3 | // This program demonstrates attaching an eBPF program to a kernel tracepoint. |
| 4 | // The eBPF program will be attached to the page allocation tracepoint and |
| 5 | // prints out the number of times it has been reached. The tracepoint fields |
| 6 | // are printed into /sys/kernel/tracing/trace_pipe. |
| 7 | package main |
| 8 | |
| 9 | import ( |
| 10 | "log" |
| 11 | "time" |
| 12 | |
| 13 | "github.com/cilium/ebpf/link" |
| 14 | "github.com/cilium/ebpf/rlimit" |
| 15 | ) |
| 16 | |
| 17 | //go:generate go tool bpf2go -tags linux bpf tracepoint.c -- -I../headers |
| 18 | |
| 19 | const mapKey uint32 = 0 |
| 20 | |
| 21 | func main() { |
| 22 | // Allow the current process to lock memory for eBPF resources. |
| 23 | if err := rlimit.RemoveMemlock(); err != nil { |
| 24 | log.Fatal(err) |
| 25 | } |
| 26 | |
| 27 | // Load pre-compiled programs and maps into the kernel. |
| 28 | objs := bpfObjects{} |
| 29 | if err := loadBpfObjects(&objs, nil); err != nil { |
| 30 | log.Fatalf("loading objects: %v", err) |
| 31 | } |
| 32 | defer objs.Close() |
| 33 | |
| 34 | // Open a tracepoint and attach the pre-compiled program. Each time |
| 35 | // the kernel function enters, the program will increment the execution |
| 36 | // counter by 1. The read loop below polls this map value once per |
| 37 | // second. |
| 38 | // The first two arguments are taken from the following pathname: |
| 39 | // /sys/kernel/tracing/events/kmem/mm_page_alloc |
| 40 | kp, err := link.Tracepoint("kmem", "mm_page_alloc", objs.MmPageAlloc, nil) |
| 41 | if err != nil { |
| 42 | log.Fatalf("opening tracepoint: %s", err) |
| 43 | } |
| 44 | defer kp.Close() |
| 45 | |
| 46 | // Read loop reporting the total amount of times the kernel |
| 47 | // function was entered, once per second. |
| 48 | ticker := time.NewTicker(1 * time.Second) |
| 49 | defer ticker.Stop() |
| 50 | |
| 51 | log.Println("Waiting for events..") |
| 52 | for range ticker.C { |
| 53 | var value uint64 |
| 54 | if err := objs.CountingMap.Lookup(mapKey, &value); err != nil { |
| 55 | log.Fatalf("reading map: %v", err) |
| 56 | } |
| 57 | log.Printf("%v times", value) |
| 58 | } |
| 59 | } |