Cilium BPF and XDP Reference Guide描述了如何通过ip
和tc
命令将BPF程序加载到网络设备。如何以相同的方式将BPF程序附加到内核函数/用户空间函数?
答案 0 :(得分:2)
TL; DR 您可以使用传统的kprobe API跟踪功能,然后使用perf_event_open
+ ioctl
附加BPF程序。
这是在内核中的the load_and_attach
function文件load_bpf.c
以及bcc中文件libbpf.c
的{{3}}和the bpf_attach_kprobe
中实现的。
在跟踪bpf_attach_tracing_event
function时,您可以看到这一点:
$ strace -s 100 python examples/hello_world.py
[...]
bpf(BPF_PROG_LOAD, {prog_type=BPF_PROG_TYPE_KPROBE, insn_cnt=15, insns=0x7f35716217d0, license="GPL", log_level=0, log_size=0, log_buf=0, kern_version=265728}, 72) = 3
openat(AT_FDCWD, "/sys/bus/event_source/devices/kprobe/type", O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/sys/bus/event_source/devices/kprobe/format/retprobe", O_RDONLY) = -1 ENOENT (No such file or directory)
openat(AT_FDCWD, "/sys/kernel/debug/tracing/kprobe_events", O_WRONLY|O_APPEND) = 4
getpid() = 8121
write(4, "p:kprobes/p_sys_clone_bcc_8121 sys_clone", 40) = 40
close(4) = 0
openat(AT_FDCWD, "/sys/kernel/debug/tracing/events/kprobes/p_sys_clone_bcc_8121/id", O_RDONLY) = 4
read(4, "1846\n", 4096) = 5
close(4) = 0
perf_event_open({type=PERF_TYPE_TRACEPOINT, size=0 /* PERF_ATTR_SIZE_??? */, config=1846, ...}, -1, 0, -1, PERF_FLAG_FD_CLOEXEC) = 4
mmap(NULL, 36864, PROT_READ|PROT_WRITE, MAP_SHARED, 4, 0) = 0x7f356c58b000
ioctl(4, PERF_EVENT_IOC_SET_BPF, 0x3) = 0
ioctl(4, PERF_EVENT_IOC_ENABLE, 0) = 0
openat(AT_FDCWD, "/sys/kernel/debug/tracing/trace_pipe", O_RDONLY) = 5
fstat(5, {st_mode=S_IFREG|0444, st_size=0, ...}) = 0
fstat(5, {st_mode=S_IFREG|0444, st_size=0, ...}) = 0
read(5,
bpf
)在内核中加载BPF程序。sys_clone
中写p:kprobes/p_sys_clone_bcc_8121 sys_clone
来跟踪p:kprobes/p_sys_clone_bcc_8121 sys_clone
。p:kprobes/p_sys_clone_bcc_8121 sys_clone
中检索要在perf_event_open
中使用的ID。perf_event_open
PERF_TYPE_TRACEPOINT
0x3
引用)附加到该perf_event,并带有PERF_EVENT_IOC_SET_BPF
ioctl。