In this lesson, you will learn how to transition BPF objects from ephemeral memory into persistent entities using the BPF filesystem, ensuring your programs and maps survive even after the loading user-space process terminates.
The Problem: Ephemeral Lifecycles
By default, when you load a BPF program or create a map, they exist only as long as the user-space process that loaded them keeps a file descriptor (FD) open. If the process crashes or finishes, the kernel automatically cleans up the objects. While this prevents resource leaks, it is inconvenient for persistent services like firewalls or traffic monitors that need to remain active regardless of the management tool's state.
The Solution: Pinning
To make an object persist, we use BPF pinning. This mechanism attaches a BPF program or map to a virtual file within a specialized mount point, typically located at /sys/fs/bpf/. Once an object is "pinned" to a path in this directory, the kernel increments its reference count, effectively keeping it alive even if the original user-space application closes.
Consider this workflow using the bpftool utility, which is the standard way to manage this lifecycle:
-
Mount the BPF filesystem:
mount -t bpf bpf /sys/fs/bpf/ -
Pin an object: If you have a map ID, you can pin it to a path:
bpftool map pin id 1024 /sys/fs/bpf/my_persistent_map
Once pinned, other processes can "discover" or retrieve the object by referencing that specific file path rather than searching for an ID. If your management process restarts, it simply checks if /sys/fs/bpf/my_persistent_map exists; if it does, it can re-attach to the existing map instead of creating a new, empty one, thus preserving the state of your application.
To remove the persistence, you simply delete the file in the BPF filesystem. Once the last reference (the file system pin) is removed, the kernel will garbage collect the object if no other processes are using it.
Key Takeaway: Pinning BPF objects to the /sys/fs/bpf/ filesystem detaches their lifecycle from the loading process, allowing for persistent network infrastructure that survives application restarts.