I'm new to eBPF, and I know that eBPF is event-driven, which means after we register the hook point, the hook function will be executed when such an event happens. So I wonder how the program can jump to the hook function?
CodePudding user response:
There's an explicit call to the BPF program from the kernel code. For example, we can check the XDP hook in the Amazon ENA driver:
xdp_prog = READ_ONCE(rx_ring->xdp_bpf_prog);
if (!xdp_prog)
goto out;
verdict = bpf_prog_run_xdp(xdp_prog, xdp);
It first checks if a BPF program is loaded; i.e., rx_ring->xdp_bpf_prog
is not NULL. And it then runs that BPF program with the struct xdf_buff
object as argument (named xdp
here). The rest of the code handles the return code (verdict
) from the BPF program.
You can find the same sort of logic for all BPF program types.
CodePudding user response:
pchaigno's answer is good.
As a complement, there are some other eBPF program types for which you don't have pre-defined hooks and calls. For example, you do not have an explicit call for every function in the kernel where you could attach a kprobe. In such case, some different mechanisms may be at play:
When a kprobe is registered, Kprobes makes a copy of the probed instruction and replaces the first byte(s) of the probed instruction with a breakpoint instruction (e.g., int3 on i386 and x86_64).
This breakpoint is used to redirect the CPU to the probe - more details here. This is what happens as well in the case of BPF programs attached to kprobes.