|Network| My first XDP BPF code

BPF is a famous system performance tool. Specially, it is powerful for network engineers.
Recently, I attend a study group to talk about this topic.
https://hackmd.io/@yenWu/BJUR6cgWI

But, what is XDP? What is its relationship between BPF and XDP?
XDP: eXpress Data Path, exists in the network driver layer. BTW, only in RX. Therefore, with this tool, we can manage packet very early.(before traffic control)

This article is a note for setting up and testing an example.

Environment:
Ubuntu 18.04
Kernel 4.15

Install:
i. For clang、LLVM、iproute2、libelf-dev:
sudo apt install clang llvm libelf-dev iproute2

# check clang
clang -v
# check llvm
llc –version
# check iproute2
ip link

ii. for bpftool
# find kernel version, e.g. 4.15
uname -r

sudo apt-cache search linux-source
sudo apt install linux-source-4.15.0
sudo apt install libelf-dev
cd /usr/src/linux-source-4.15.0
sudo tar xjf linux-source-5.3.0.tar.bz2
cd linux-source-4.15.0/tools
make -C bpf/bpftool/
cd bpf/bpftool/
./bpftool prog/net

ref. https://github.com/nevermosby/linux-bpf-learning

Test code: xdp_drop_all.c

#include <linux/bpf.h>
/*
 * Comments from Linux Kernel:
 * Helper macro to place programs, maps, license in
 * different sections in elf_bpf file. Section names
 * are interpreted by elf_bpf loader.
 * End of comments
 * You can either use the helper header file below
 * so that you don't need to define it yourself:
 * #include <bpf/bpf_helpers.h> 
 */
#define SEC(NAME) __attribute__((section(NAME), used))
SEC("xdp")
int xdp_drop_the_world(struct xdp_md *ctx) {
    // drop everything
    return XDP_DROP;
}
char _license[] SEC("license") = "GPL";

Ref.
https://github.com/torvalds/linux/tree/master/samples/bpf
https://davidlovezoe.club/wordpress/archives/937


Compile:
sudo clang -O2 -I/usr/include/x86_64-linux-gnu -target bpf -c xdp_drop_all.c -o xdp_drop_all.o


Test:
Computer A (ip: 111.222.333.444)
#find hook point: enp0s31f6
ip a
#launch xdp
sudo ip link set dev enp0s31f6 xdp obj xdp_drop_all.o sec xdp verbose

Computer B
ping 111.222.333.444
(timeout)

Computer A (ip: 111.222.333.444)
sudo ip link set dev enp0s31f6 xdp off


Computer B
ping 111.222.333.444
(success!)

References:
https://patchwork.ozlabs.org/project/netdev/patch/151804207444.30000.12666757505388007849.stgit@firesoul/
https://www.cnblogs.com/linengier/p/11977214.html