linux-kernelebpfbpf

How to detach ebpf program with 'bpftool prog detach'


I am trying to understand how 'bpftool prog detach' works. To experiment, I created a simple ebpf program and below is output from 'bpftool prog show name sys_exit' at runtime

81: tracing  name sys_exit  tag 4307a8383e89d281  gpl
        loaded_at 2025-06-11T10:58:58-0700  uid 0
        xlated 272B  jited 176B  memlock 4096B  map_ids 13
        btf_id 102
        pids test-project(3018)

Not sure if my command is correct but 'bpftool prog detach name sys_exit tracepoint syscalls::sys_exit' returned Error: invalid attach/detach type. Looking at bpftool source codes, it seems only programs with these types can be detached. Is this correct understanding? If so, any reasons other types are not supported for detach?

static const bool attach_types[] = {
    [BPF_SK_SKB_STREAM_PARSER] = true,
    [BPF_SK_SKB_STREAM_VERDICT] = true,
    [BPF_SK_SKB_VERDICT] = true,
    [BPF_SK_MSG_VERDICT] = true,
    [BPF_FLOW_DISSECTOR] = true,
    [__MAX_BPF_ATTACH_TYPE] = false,
};

Additionally, my understanding is 'bpftool prog detach' detaches an ebpf program from its attach point. However, this error message suggests the operation only detaches program from its map. Can someone please confirm? Thanks a lot in advance for your help.


Solution

  • Attaching programs in eBPF can be a complex topic. There is a handful of different mechanisms depending on the program type and kernel version. Nowadays we mostly use BPF links, which are then pinned to the BPF FS, so that we can detach programs by removing the link.

    Some program types like XDP/TC programs can use netlink to attach them to a network device, and you need netlink to detach them (but links are recommended).

    Before links were a thing, the BPF_PROG_ATTACH and BPF_PROG_DETACH BPF syscall commands were added to attempt an API to attach BPF programs to FD (File descriptors). It is specifically these that bpftool prog attach and bpftool prog detach wrap. But as you have noticed, only a small set of program types use these.

    Program types such as BPF_PROG_TYPE_SOCK_OPS, BPF_PROG_TYPE_SK_SKB, BPF_PROG_TYPE_SK_MSG attach to specific BPF maps containing sockets. I believe BPF_PROG_TYPE_SOCK_OPS can also be attached via links, but the SK_{SKB,MSG} program types still need to use this older style API to attach/detach.

    There is also the BPF_PROG_TYPE_FLOW_DISSECTOR program type, it attaches to a network namespace. Which can be done via the older API but it also has link support, which is superior.