BPF struct_ops Example with Custom Kernel Module
This example demonstrates BPF struct_ops functionality using a custom kernel module that defines struct_ops operations triggered via a proc file write.
Overview
struct_ops allows BPF programs to implement kernel subsystem operations dynamically. This example includes:
- Kernel Module (
module/hello.c) - Definesbpf_testmod_opsstruct_ops with three callbacks - BPF Program (
struct_ops.bpf.c) - Implements the struct_ops callbacks in BPF - User-space Loader (
struct_ops.c) - Loads the BPF program and triggers callbacks via/proc/bpf_testmod_trigger
Building and Running
1. Build the kernel module:
2. Load the kernel module:
3. Build the BPF program:
4. Run the example:
5. Check kernel logs:
You should see output like:
bpf_testmod loaded with struct_ops support
bpf_testmod_ops registered
Calling struct_ops callbacks:
BPF test_1 called!
test_1() returned: 42
BPF test_2 called: 10 + 20 = 30
test_2(10, 20) returned: 30
BPF test_3 called with buffer length 21
First char: H
test_3() called with buffer
6. Clean up:
How It Works
- The kernel module registers a custom struct_ops type
bpf_testmod_ops - It creates
/proc/bpf_testmod_trigger- writing to this file triggers the callbacks - The BPF program implements the three callbacks:
test_1,test_2, andtest_3 - The user-space program loads the BPF program and periodically writes to the proc file
- Each write triggers all registered callbacks, demonstrating BPF struct_ops in action
Troubleshooting
- If you get "Failed to attach struct_ops", make sure the kernel module is loaded
- Check
dmesgfor any error messages from the kernel module or BPF verifier - Ensure your kernel has CONFIG_BPF_SYSCALL=y and supports struct_ops