You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# BPF struct_ops Example with Custom Kernel Module
2
+
3
+
This example demonstrates BPF struct_ops functionality using a custom kernel module that defines struct_ops operations triggered via a proc file write.
4
+
5
+
## Overview
6
+
7
+
struct_ops allows BPF programs to implement kernel subsystem operations dynamically. This example includes:
8
+
9
+
1.**Kernel Module** (`module/hello.c`) - Defines `bpf_testmod_ops` struct_ops with three callbacks
10
+
2.**BPF Program** (`struct_ops.bpf.c`) - Implements the struct_ops callbacks in BPF
11
+
3.**User-space Loader** (`struct_ops.c`) - Loads the BPF program and triggers callbacks via `/proc/bpf_testmod_trigger`
12
+
13
+
## Building and Running
14
+
15
+
### 1. Build the kernel module:
16
+
```bash
17
+
cd module
18
+
make
19
+
cd ..
20
+
```
21
+
22
+
### 2. Load the kernel module:
23
+
```bash
24
+
sudo insmod module/hello.ko
25
+
```
26
+
27
+
### 3. Build the BPF program:
28
+
```bash
29
+
make
30
+
```
31
+
32
+
### 4. Run the example:
33
+
```bash
34
+
sudo ./struct_ops
35
+
```
36
+
37
+
### 5. Check kernel logs:
38
+
```bash
39
+
sudo dmesg -w
40
+
```
41
+
42
+
You should see output like:
43
+
```
44
+
bpf_testmod loaded with struct_ops support
45
+
bpf_testmod_ops registered
46
+
Calling struct_ops callbacks:
47
+
BPF test_1 called!
48
+
test_1() returned: 42
49
+
BPF test_2 called: 10 + 20 = 30
50
+
test_2(10, 20) returned: 30
51
+
BPF test_3 called with buffer length 21
52
+
First char: H
53
+
test_3() called with buffer
54
+
```
55
+
56
+
### 6. Clean up:
57
+
```bash
58
+
sudo rmmod hello
59
+
make clean
60
+
```
61
+
62
+
## How It Works
63
+
64
+
1. The kernel module registers a custom struct_ops type `bpf_testmod_ops`
65
+
2. It creates `/proc/bpf_testmod_trigger` - writing to this file triggers the callbacks
66
+
3. The BPF program implements the three callbacks: `test_1`, `test_2`, and `test_3`
67
+
4. The user-space program loads the BPF program and periodically writes to the proc file
68
+
5. Each write triggers all registered callbacks, demonstrating BPF struct_ops in action
69
+
70
+
## Troubleshooting
71
+
72
+
- If you get "Failed to attach struct_ops", make sure the kernel module is loaded
73
+
- Check `dmesg` for any error messages from the kernel module or BPF verifier
74
+
- Ensure your kernel has CONFIG_BPF_SYSCALL=y and supports struct_ops
0 commit comments