xdp-project / xdp-tutorial

XDP tutorial
2.5k stars 580 forks source link

Why lo interface using XDP_PASS does not work anymore #300

Open dingrui37 opened 2 years ago

dingrui37 commented 2 years ago
user@dingrui-Server:~/Projects/ebpf/xdp-tutorial/basic01-xdp-pass$ sudo ./xdp_pass_user --dev lo -S
Success: Loading XDP prog name:xdp_prog_simple(id:4717) on device:lo(ifindex:1)
user@dingrui-Server:~/Projects/ebpf/xdp-tutorial/basic01-xdp-pass$ sudo bpftool net list
xdp:
lo(1) generic id 4717
veth-basic02(187) generic id 4713

tc:

flow_dissector:

user@dingrui-Server:~/Projects/ebpf/xdp-tutorial/basic01-xdp-pass$ ping 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
^C
--- 127.0.0.1 ping statistics ---
3 packets transmitted, 0 received, 100% packet loss, time 2036ms

user@dingrui-Server:~/Projects/ebpf/xdp-tutorial/basic01-xdp-pass$ sudo ip link set dev lo xdpgeneric off
user@dingrui-Server:~/Projects/ebpf/xdp-tutorial/basic01-xdp-pass$ ping 127.0.0.1
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.066 ms
^C
--- 127.0.0.1 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.066/0.066/0.066/0.000 ms
user@dingrui-Server:~/Projects/ebpf/xdp-tutorial/basic01-xdp-pass$ ping6 fc00:dead:cafe:1::1
PING fc00:dead:cafe:1::1(fc00:dead:cafe:1::1) 56 data bytes
64 bytes from fc00:dead:cafe:1::1: icmp_seq=1 ttl=64 time=0.020 ms
64 bytes from fc00:dead:cafe:1::1: icmp_seq=2 ttl=64 time=0.083 ms
^C
--- fc00:dead:cafe:1::1 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1009ms
rtt min/avg/max/mdev = 0.020/0.051/0.083/0.031 ms
user@dingrui-Server:~/Projects/ebpf/xdp-tutorial/basic01-xdp-pass$
ljluestc commented 3 months ago
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <bpf/bpf.h>
#include <bpf/libbpf.h>

static const char *pin_basedir =  "/sys/fs/bpf";

int main(int argc, char **argv) {
    int prog_fd, ifindex;
    char filename[256];

    if (argc != 3) {
        fprintf(stderr, "Usage: %s --dev <ifname>\n", argv[0]);
        return 1;
    }

    if (strcmp(argv[1], "--dev") != 0) {
        fprintf(stderr, "Usage: %s --dev <ifname>\n", argv[0]);
        return 1;
    }

    ifindex = if_nametoindex(argv[2]);
    if (!ifindex) {
        perror("if_nametoindex");
        return 1;
    }

    snprintf(filename, sizeof(filename), "%s/%s", pin_basedir, "xdp_pass_kern.o");

    prog_fd = bpf_prog_load(filename, BPF_PROG_TYPE_XDP, NULL, NULL);
    if (prog_fd < 0) {
        fprintf(stderr, "bpf_prog_load: %s\n", strerror(errno));
        return 1;
    }

    if (bpf_set_link_xdp_fd(ifindex, prog_fd, XDP_FLAGS_SKB_MODE) < 0) {
        fprintf(stderr, "link set xdp fd failed: %s\n", strerror(errno));
        return 1;
    }

    printf("Success: Loading XDP prog name:xdp_prog_simple on device:%s(ifindex:%d)\n", argv[2], ifindex);
    return 0;
}