diff --git a/.github/workflows/ebpf_tcp_ping.yaml b/.github/workflows/ebpf_tcp_ping.yaml new file mode 100644 index 000000000..28c99dc0d --- /dev/null +++ b/.github/workflows/ebpf_tcp_ping.yaml @@ -0,0 +1,69 @@ +name: Test for ebpf_tcp_ping build and run + +on: + push: + branches: [ "*" ] + paths: + - 'eBPF_Supermarket/eBPF_TCP_Ping/**' + - '.github/workflows/ebpf_tcp_ping.yml' + pull_request: + branches: [ "*" ] + paths: + - 'eBPF_Supermarket/eBPF_TCP_Ping/**' + - '.github/workflows/ebpf_tcp_ping.yml' + +jobs: + run-test: + name: Build and run + runs-on: ubuntu-20.04 + + steps: + - uses: actions/checkout@v3 + + - name: Set up Go + uses: actions/setup-go@v2 + with: + go-version: 1.16 + + - name: Install build dependencies + run: | + sudo apt update + sudo apt install -y bison build-essential flex curl libedit-dev \ + libllvm12 llvm-12-dev libclang-12-dev python python3 python3-distutils zlib1g-dev libelf-dev libfl-dev \ + bpfcc-tools linux-headers-$(uname -r) libelf-dev libpcap-dev gcc-multilib build-essential + sudo ln -sf /usr/bin/llc-12 /usr/bin/llc + + - name: Cache bcc + id: cache-bcc + uses: actions/cache@v3 + with: + path: bcc + key: ${{ runner.os }}-bcc-0.24.0 + + - name: Build bcc + if: steps.cache-bcc.outputs.cache-hit != 'true' + run: | + git clone -b v0.24.0 https://github.com/iovisor/bcc.git + export LLVM_ROOT="/usr/lib/llvm-12" + mkdir bcc/build; cd bcc/build + cmake .. + make -j2 + + - name: Install bcc + run: | + cd bcc/build + sudo make install + + - name: Compile and install xdp + run: | + cd eBPF_Supermarket/eBPF_TCP_Ping + make && sudo make install + + - name: Test run ebpf ping + run: | + cd eBPF_Supermarket/eBPF_TCP_Ping + go build -o tcp_ping tcp_ping.go + # help + ./tcp_ping -h + # sudo ./telescope 127.0.0.1 + sudo timeout -s SIGINT 20 ./tcp_ping 127.0.0.1 || pwd diff --git a/eBPF_Supermarket/README.md b/eBPF_Supermarket/README.md index f20a015fc..29248d1fc 100644 --- a/eBPF_Supermarket/README.md +++ b/eBPF_Supermarket/README.md @@ -29,5 +29,5 @@ eBPF工具集散地 | | Filesystem_Subsystem | | | | | LSM_BPF | | | | | Memory_Subsystem | | | -| | +| 基于 eBPF 和 XDP 的 tcp ping |eBPF_TCP_Ping|基于 eBPF 的 tcp ping,通过 kprobe 在内核态计算 RTT。并提供 XDP 来加速回包|[@IfanTsai](https://github.com/IfanTSai)| diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/.gitignore b/eBPF_Supermarket/eBPF_TCP_Ping/.gitignore new file mode 100644 index 000000000..453a872bb --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/.gitignore @@ -0,0 +1,59 @@ +# Prerequisites +*.d + +# Object files +*.o +*.ko +*.obj +*.elf + +# Linker output +*.ilk +*.map +*.exp + +# Precompiled Headers +*.gch +*.pch + +# Libraries +*.lib +*.a +*.la +*.lo + +# Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + +# Debug files +*.dSYM/ +*.su +*.idb +*.pdb + +# Kernel Module Compile Results +*.mod* +*.cmd +.tmp_versions/ +modules.order +Module.symvers +Mkfile.old +dkms.conf +!go.mod + +*.ll +cscope* +tags + +ping diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/Makefile b/eBPF_Supermarket/eBPF_TCP_Ping/Makefile new file mode 100644 index 000000000..040339243 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/Makefile @@ -0,0 +1,29 @@ +.PHONY: all clean install uninstall + +CLANG ?= clang +LLC ?= llc +NIC ?= eth0 +XDP_OBJ := xdp_ping.o +XDP_SEC ?= xdp-ping + +INCLUDES ?= -I./include -I./lib -I./ +CLANG_FLAGS ?= -D__NR_CPUS__=4 -O2 -target bpf -nostdinc -emit-llvm +CLANF_FLAGS += -Wall -Wextra -Wshadow -Wno-address-of-packed-member -Wno-unknown-warning-option -Wno-gnu-variable-sized-type-not-at-end -Wdeclaration-after-statement +LLC_FLAGS ?= -march=bpf -mcpu=probe -mattr=dwarfris -filetype=obj + +all: $(XDP_OBJ) + +$(XDP_OBJ): %.o: %.ll + $(LLC) $(LLC_FLAGS) -o $@ $^ + +%.ll: %.c + $(CLANG) $(INCLUDES) $(CLANG_FLAGS) -c $^ -o $@ + +clean: + -rm -rf *.ll *.o + +install: $(XDP_OBJ) + sudo ip -force link set dev $(NIC) xdpgeneric obj $^ sec $(XDP_SEC) + +uninstall: + sudo ip link set dev $(NIC) xdpgeneric off diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/README.md b/eBPF_Supermarket/eBPF_TCP_Ping/README.md new file mode 100644 index 000000000..a134b7804 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/README.md @@ -0,0 +1,49 @@ +[中文](./README_CN.md) + +# eBPF-TCP-Ping + +## Introduction + +TCP ping command tool based on ebpf, using kprobe to calculate RTT in the kernel space rather than user space. In addition, we can speed up the packet return through XDP. + +- tcp_ping.go: TCP ping command tool, it can send a TCP SYN packet to other server, and use the eBPF to hook kernel tcp status function to calculate RTT. + +- xdp_ping.c: XDP program, it will be loaded to kernel or NIC. Before SYN packet enter the kernel protocol stack, it can rewrite the packet into RST and return the original way. + +## Quick Start +### load XDP program to NIC + +**The loading of XDP is optional and is only used to speed up the packet return. You can choose to use the return packet that comes with the kernel instead of XDP.** + +Please check your NIC in Makefile + +```Makefile +NIC ?= eth0 +``` + +install or uninstall XDP program +``` +make +sudo make install +sudo make uninstall +``` + +### ping other server + +help + +``` +➜ sudo go run tcp_ping.go -h +tcp_ping version: 0.0.1 +Usage: tcp_ping 172.217.194.106 [-d 500] [-c 100] [-s] + +Options: + -c Number + Number connections to keep ping (default 1) + -d duration + Ping duration ms (default 1000) + -h Show help + -s Do not show information of each ping +``` + +The tool detects port 65532, noted that port 65532 of other server needs to be opened diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/README_CN.md b/eBPF_Supermarket/eBPF_TCP_Ping/README_CN.md new file mode 100644 index 000000000..afc1977ed --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/README_CN.md @@ -0,0 +1,50 @@ +[English](./README.md) + +# eBPF-TCP-Ping + +## 介绍 + +基于 ebpf 的 tcp ping 命令行工具,通过 kprobe 来在内核态而非用户态计算 RTT。并且可使用 XDP 做回包的加速 + +- tcp_ping.go: TCP ping 命令行工具,它会发送 TCP SYN 包给指定的服务器,并且使用 eBPF 去 hook 内核 TCP 状态转换的函数来计算 RTT + +- xdp_ping.c: XDP 程序, 将会被加载到内核或网卡中。在 TCP SYN 包进入内核协议栈之前,它会原地修改数据包为 RST 后原路返回 + + +## 快速开始 + +### 加载 XDP 程序到 NIC + +**XDP 的加载是可选的,仅仅只是用于加速回包。可以选择使用 kernel 自带的回包而不是 XDP** + +请检查 Makefile 中的 NIC 变量 +```Makefile +NIC ?= eth0 +``` + +安装和卸载 XDP 程序 +``` +make +sudo make install +sudo make uninstall +``` + +### ping 其他服务器 + +帮助命令 + +``` +➜ sudo go run tcp_ping.go -h +tcp_ping version: 0.0.1 +Usage: tcp_ping 172.217.194.106 [-d 500] [-c 100] [-s] + +Options: + -c Number + Number connections to keep ping (default 1) + -d duration + Ping duration ms (default 1000) + -h Show help + -s Do not show information of each ping +``` + +该工具探测的是 65532 端口,所以务必注意被 ping 的服务器需要开放 65532 端口 diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/go.mod b/eBPF_Supermarket/eBPF_TCP_Ping/go.mod new file mode 100644 index 000000000..d7c0434f8 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/go.mod @@ -0,0 +1,5 @@ +module ping + +go 1.16 + +require github.com/iovisor/gobpf v0.2.0 diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/go.sum b/eBPF_Supermarket/eBPF_TCP_Ping/go.sum new file mode 100644 index 000000000..bddc528b3 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/go.sum @@ -0,0 +1,2 @@ +github.com/iovisor/gobpf v0.2.0 h1:34xkQxft+35GagXBk3n23eqhm0v7q0ejeVirb8sqEOQ= +github.com/iovisor/gobpf v0.2.0/go.mod h1:WSY9Jj5RhdgC3ci1QaacvbFdQ8cbrEjrpiZbLHLt2s4= diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/access.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/access.h new file mode 100644 index 000000000..0cb708df1 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/access.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_ACCESS_H_ +#define __BPF_ACCESS_H_ + +#include "compiler.h" + +#if !defined(__non_bpf_context) && defined(__bpf__) +static __always_inline __maybe_unused __u16 +map_array_get_16(const __u16 *array, __u32 index, const __u32 limit) +{ + __u16 datum = 0; + + if (__builtin_constant_p(index) || + !__builtin_constant_p(limit)) + __throw_build_bug(); + + /* LLVM tends to optimize code away that is needed for the verifier to + * understand dynamic map access. Input constraint is that index < limit + * for this util function, so we never fail here, and returned datum is + * always valid. + */ + asm volatile("%[index] <<= 1\n\t" + "if %[index] > %[limit] goto +1\n\t" + "%[array] += %[index]\n\t" + "%[datum] = *(u16 *)(%[array] + 0)\n\t" + : [datum]"=r"(datum) + : [limit]"i"(limit), [array]"r"(array), [index]"r"(index) + : /* no clobbers */ ); + + return datum; +} +#else +# define map_array_get_16(array, index, limit) __throw_build_bug() +#endif /* !__non_bpf_context && __bpf__ */ +#endif /* __BPF_ACCESS_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/api.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/api.h new file mode 100644 index 000000000..c8cc45ebb --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/api.h @@ -0,0 +1,22 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __BPF_API__ +#define __BPF_API__ + +#include +#include +#include +#include + +#include "compiler.h" +#include "section.h" +#include "helpers.h" +#include "builtins.h" +#include "tailcall.h" +#include "errno.h" +#include "loader.h" +#include "csum.h" +#include "access.h" + +#endif /* __BPF_API__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/bpf_features.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/bpf_features.h new file mode 100644 index 000000000..8acd77ace --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/bpf_features.h @@ -0,0 +1,10 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ +#ifndef BPF_FEATURES_H_ +#define BPF_FEATURES_H_ + +#define HAVE_PROG_TYPE_HELPER(prog_type, helper) \ + BPF__PROG_TYPE_ ## prog_type ## __HELPER_ ## helper +#define BPF__PROG_TYPE_sched_cls__HELPER_bpf_skb_change_tail 1 + +#endif /* BPF_FEATURES_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/builtins.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/builtins.h new file mode 100644 index 000000000..ef8509b78 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/builtins.h @@ -0,0 +1,465 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __BPF_BUILTINS__ +#define __BPF_BUILTINS__ + +#include "compiler.h" + +#ifndef __non_bpf_context + +#ifndef lock_xadd +# define lock_xadd(P, V) ((void) __sync_fetch_and_add((P), (V))) +#endif + +/* Unfortunately verifier forces aligned stack access while other memory + * do not have to be aligned (map, pkt, etc). Mark those on the /stack/ + * for objects > 8 bytes in order to force-align such memcpy candidates + * when we really need them to be aligned, this is not needed for objects + * of size <= 8 bytes and in case of > 8 bytes /only/ when 8 byte is not + * the natural object alignment (e.g. __u8 foo[12]). + */ +#define __align_stack_8 __aligned(8) + +/* Memory iterators used below. */ +#define __it_bwd(x, op) (x -= sizeof(__u##op)) +#define __it_fwd(x, op) (x += sizeof(__u##op)) + +/* Memory operators used below. */ +#define __it_set(a, op) (*(__u##op *)__it_bwd(a, op)) = 0 +#define __it_xor(a, b, r, op) r |= (*(__u##op *)__it_bwd(a, op)) ^ (*(__u##op *)__it_bwd(b, op)) +#define __it_mob(a, b, op) (*(__u##op *)__it_bwd(a, op)) = (*(__u##op *)__it_bwd(b, op)) +#define __it_mof(a, b, op) \ + do { \ + *(__u##op *)a = *(__u##op *)b; \ + __it_fwd(a, op); __it_fwd(b, op); \ + } while (0) + +static __always_inline __maybe_unused void +__bpf_memset_builtin(void *d, __u8 c, __u64 len) +{ + /* Everything non-zero or non-const (currently unsupported) as c + * gets handled here. + */ + __builtin_memset(d, c, len); +} + +static __always_inline void __bpf_memzero(void *d, __u64 len) +{ +#if __clang_major__ >= 10 + if (!__builtin_constant_p(len)) + __throw_build_bug(); + + d += len; + + switch (len) { + case 96: __it_set(d, 64); + case 88: jmp_88: __it_set(d, 64); + case 80: jmp_80: __it_set(d, 64); + case 72: jmp_72: __it_set(d, 64); + case 64: jmp_64: __it_set(d, 64); + case 56: jmp_56: __it_set(d, 64); + case 48: jmp_48: __it_set(d, 64); + case 40: jmp_40: __it_set(d, 64); + case 32: jmp_32: __it_set(d, 64); + case 24: jmp_24: __it_set(d, 64); + case 16: jmp_16: __it_set(d, 64); + case 8: jmp_8: __it_set(d, 64); + break; + + case 94: __it_set(d, 16); __it_set(d, 32); goto jmp_88; + case 86: __it_set(d, 16); __it_set(d, 32); goto jmp_80; + case 78: __it_set(d, 16); __it_set(d, 32); goto jmp_72; + case 70: __it_set(d, 16); __it_set(d, 32); goto jmp_64; + case 62: __it_set(d, 16); __it_set(d, 32); goto jmp_56; + case 54: __it_set(d, 16); __it_set(d, 32); goto jmp_48; + case 46: __it_set(d, 16); __it_set(d, 32); goto jmp_40; + case 38: __it_set(d, 16); __it_set(d, 32); goto jmp_32; + case 30: __it_set(d, 16); __it_set(d, 32); goto jmp_24; + case 22: __it_set(d, 16); __it_set(d, 32); goto jmp_16; + case 14: __it_set(d, 16); __it_set(d, 32); goto jmp_8; + case 6: __it_set(d, 16); __it_set(d, 32); + break; + + case 92: __it_set(d, 32); goto jmp_88; + case 84: __it_set(d, 32); goto jmp_80; + case 76: __it_set(d, 32); goto jmp_72; + case 68: __it_set(d, 32); goto jmp_64; + case 60: __it_set(d, 32); goto jmp_56; + case 52: __it_set(d, 32); goto jmp_48; + case 44: __it_set(d, 32); goto jmp_40; + case 36: __it_set(d, 32); goto jmp_32; + case 28: __it_set(d, 32); goto jmp_24; + case 20: __it_set(d, 32); goto jmp_16; + case 12: __it_set(d, 32); goto jmp_8; + case 4: __it_set(d, 32); + break; + + case 90: __it_set(d, 16); goto jmp_88; + case 82: __it_set(d, 16); goto jmp_80; + case 74: __it_set(d, 16); goto jmp_72; + case 66: __it_set(d, 16); goto jmp_64; + case 58: __it_set(d, 16); goto jmp_56; + case 50: __it_set(d, 16); goto jmp_48; + case 42: __it_set(d, 16); goto jmp_40; + case 34: __it_set(d, 16); goto jmp_32; + case 26: __it_set(d, 16); goto jmp_24; + case 18: __it_set(d, 16); goto jmp_16; + case 10: __it_set(d, 16); goto jmp_8; + case 2: __it_set(d, 16); + break; + + case 1: __it_set(d, 8); + break; + + default: + /* __builtin_memset() is crappy slow since it cannot + * make any assumptions about alignment & underlying + * efficient unaligned access on the target we're + * running. + */ + __throw_build_bug(); + } +#else + __bpf_memset_builtin(d, 0, len); +#endif +} + +static __always_inline __maybe_unused void +__bpf_no_builtin_memset(void *d __maybe_unused, __u8 c __maybe_unused, + __u64 len __maybe_unused) +{ + __throw_build_bug(); +} + +/* Redirect any direct use in our code to throw an error. */ +#define __builtin_memset __bpf_no_builtin_memset + +static __always_inline __nobuiltin("memset") void memset(void *d, int c, + __u64 len) +{ + if (__builtin_constant_p(len) && __builtin_constant_p(c) && c == 0) + __bpf_memzero(d, len); + else + __bpf_memset_builtin(d, c, len); +} + +static __always_inline __maybe_unused void +__bpf_memcpy_builtin(void *d, const void *s, __u64 len) +{ + /* Explicit opt-in for __builtin_memcpy(). */ + __builtin_memcpy(d, s, len); +} + +static __always_inline void __bpf_memcpy(void *d, const void *s, __u64 len) +{ +#if __clang_major__ >= 10 + if (!__builtin_constant_p(len)) + __throw_build_bug(); + + d += len; + s += len; + + switch (len) { + case 96: __it_mob(d, s, 64); + case 88: jmp_88: __it_mob(d, s, 64); + case 80: jmp_80: __it_mob(d, s, 64); + case 72: jmp_72: __it_mob(d, s, 64); + case 64: jmp_64: __it_mob(d, s, 64); + case 56: jmp_56: __it_mob(d, s, 64); + case 48: jmp_48: __it_mob(d, s, 64); + case 40: jmp_40: __it_mob(d, s, 64); + case 32: jmp_32: __it_mob(d, s, 64); + case 24: jmp_24: __it_mob(d, s, 64); + case 16: jmp_16: __it_mob(d, s, 64); + case 8: jmp_8: __it_mob(d, s, 64); + break; + + case 94: __it_mob(d, s, 16); __it_mob(d, s, 32); goto jmp_88; + case 86: __it_mob(d, s, 16); __it_mob(d, s, 32); goto jmp_80; + case 78: __it_mob(d, s, 16); __it_mob(d, s, 32); goto jmp_72; + case 70: __it_mob(d, s, 16); __it_mob(d, s, 32); goto jmp_64; + case 62: __it_mob(d, s, 16); __it_mob(d, s, 32); goto jmp_56; + case 54: __it_mob(d, s, 16); __it_mob(d, s, 32); goto jmp_48; + case 46: __it_mob(d, s, 16); __it_mob(d, s, 32); goto jmp_40; + case 38: __it_mob(d, s, 16); __it_mob(d, s, 32); goto jmp_32; + case 30: __it_mob(d, s, 16); __it_mob(d, s, 32); goto jmp_24; + case 22: __it_mob(d, s, 16); __it_mob(d, s, 32); goto jmp_16; + case 14: __it_mob(d, s, 16); __it_mob(d, s, 32); goto jmp_8; + case 6: __it_mob(d, s, 16); __it_mob(d, s, 32); + break; + + case 92: __it_mob(d, s, 32); goto jmp_88; + case 84: __it_mob(d, s, 32); goto jmp_80; + case 76: __it_mob(d, s, 32); goto jmp_72; + case 68: __it_mob(d, s, 32); goto jmp_64; + case 60: __it_mob(d, s, 32); goto jmp_56; + case 52: __it_mob(d, s, 32); goto jmp_48; + case 44: __it_mob(d, s, 32); goto jmp_40; + case 36: __it_mob(d, s, 32); goto jmp_32; + case 28: __it_mob(d, s, 32); goto jmp_24; + case 20: __it_mob(d, s, 32); goto jmp_16; + case 12: __it_mob(d, s, 32); goto jmp_8; + case 4: __it_mob(d, s, 32); + break; + + case 90: __it_mob(d, s, 16); goto jmp_88; + case 82: __it_mob(d, s, 16); goto jmp_80; + case 74: __it_mob(d, s, 16); goto jmp_72; + case 66: __it_mob(d, s, 16); goto jmp_64; + case 58: __it_mob(d, s, 16); goto jmp_56; + case 50: __it_mob(d, s, 16); goto jmp_48; + case 42: __it_mob(d, s, 16); goto jmp_40; + case 34: __it_mob(d, s, 16); goto jmp_32; + case 26: __it_mob(d, s, 16); goto jmp_24; + case 18: __it_mob(d, s, 16); goto jmp_16; + case 10: __it_mob(d, s, 16); goto jmp_8; + case 2: __it_mob(d, s, 16); + break; + + case 1: __it_mob(d, s, 8); + break; + + default: + /* __builtin_memcpy() is crappy slow since it cannot + * make any assumptions about alignment & underlying + * efficient unaligned access on the target we're + * running. + */ + __throw_build_bug(); + } +#else + __bpf_memcpy_builtin(d, s, len); +#endif +} + +static __always_inline __maybe_unused void +__bpf_no_builtin_memcpy(void *d __maybe_unused, const void *s __maybe_unused, + __u64 len __maybe_unused) +{ + __throw_build_bug(); +} + +/* Redirect any direct use in our code to throw an error. */ +#define __builtin_memcpy __bpf_no_builtin_memcpy + +static __always_inline __nobuiltin("memcpy") void memcpy(void *d, const void *s, + __u64 len) +{ + return __bpf_memcpy(d, s, len); +} + +static __always_inline __maybe_unused __u64 +__bpf_memcmp_builtin(const void *x, const void *y, __u64 len) +{ + /* Explicit opt-in for __builtin_memcmp(). We use the bcmp builtin + * here for two reasons: i) we only need to know equal or non-equal + * similar as in __bpf_memcmp(), and ii) if __bpf_memcmp() ends up + * selecting __bpf_memcmp_builtin(), clang generats a memcmp loop. + * That is, (*) -> __bpf_memcmp() -> __bpf_memcmp_builtin() -> + * __builtin_memcmp() -> memcmp() -> (*), meaning it will end up + * selecting our memcmp() from here. Remapping to __builtin_bcmp() + * breaks this loop and resolves both needs at once. + */ + return __builtin_bcmp(x, y, len); +} + +static __always_inline __u64 __bpf_memcmp(const void *x, const void *y, + __u64 len) +{ +#if __clang_major__ >= 10 + __u64 r = 0; + + if (!__builtin_constant_p(len)) + __throw_build_bug(); + + x += len; + y += len; + + switch (len) { + case 32: __it_xor(x, y, r, 64); + case 24: jmp_24: __it_xor(x, y, r, 64); + case 16: jmp_16: __it_xor(x, y, r, 64); + case 8: jmp_8: __it_xor(x, y, r, 64); + break; + + case 30: __it_xor(x, y, r, 16); __it_xor(x, y, r, 32); goto jmp_24; + case 22: __it_xor(x, y, r, 16); __it_xor(x, y, r, 32); goto jmp_16; + case 14: __it_xor(x, y, r, 16); __it_xor(x, y, r, 32); goto jmp_8; + case 6: __it_xor(x, y, r, 16); __it_xor(x, y, r, 32); + break; + + case 28: __it_xor(x, y, r, 32); goto jmp_24; + case 20: __it_xor(x, y, r, 32); goto jmp_16; + case 12: __it_xor(x, y, r, 32); goto jmp_8; + case 4: __it_xor(x, y, r, 32); + break; + + case 26: __it_xor(x, y, r, 16); goto jmp_24; + case 18: __it_xor(x, y, r, 16); goto jmp_16; + case 10: __it_xor(x, y, r, 16); goto jmp_8; + case 2: __it_xor(x, y, r, 16); + break; + + case 1: __it_xor(x, y, r, 8); + break; + + default: + __throw_build_bug(); + } + + return r; +#else + return __bpf_memcmp_builtin(x, y, len); +#endif +} + +static __always_inline __maybe_unused __u64 +__bpf_no_builtin_memcmp(const void *x __maybe_unused, + const void *y __maybe_unused, __u64 len __maybe_unused) +{ + __throw_build_bug(); + return 0; +} + +/* Redirect any direct use in our code to throw an error. */ +#define __builtin_memcmp __bpf_no_builtin_memcmp + +/* Modified for our needs in that we only return either zero (x and y + * are equal) or non-zero (x and y are non-equal). + */ +static __always_inline __nobuiltin("memcmp") __u64 memcmp(const void *x, + const void *y, + __u64 len) +{ + return __bpf_memcmp(x, y, len); +} + +static __always_inline __maybe_unused void +__bpf_memmove_builtin(void *d, const void *s, __u64 len) +{ + /* Explicit opt-in for __builtin_memmove(). */ + __builtin_memmove(d, s, len); +} + +static __always_inline void __bpf_memmove_bwd(void *d, const void *s, __u64 len) +{ + /* Our internal memcpy implementation walks backwards by default. */ + __bpf_memcpy(d, s, len); +} + +static __always_inline void __bpf_memmove_fwd(void *d, const void *s, __u64 len) +{ +#if __clang_major__ >= 10 + if (!__builtin_constant_p(len)) + __throw_build_bug(); + + switch (len) { + case 96: __it_mof(d, s, 64); + case 88: jmp_88: __it_mof(d, s, 64); + case 80: jmp_80: __it_mof(d, s, 64); + case 72: jmp_72: __it_mof(d, s, 64); + case 64: jmp_64: __it_mof(d, s, 64); + case 56: jmp_56: __it_mof(d, s, 64); + case 48: jmp_48: __it_mof(d, s, 64); + case 40: jmp_40: __it_mof(d, s, 64); + case 32: jmp_32: __it_mof(d, s, 64); + case 24: jmp_24: __it_mof(d, s, 64); + case 16: jmp_16: __it_mof(d, s, 64); + case 8: jmp_8: __it_mof(d, s, 64); + break; + + case 94: __it_mof(d, s, 16); __it_mof(d, s, 32); goto jmp_88; + case 86: __it_mof(d, s, 16); __it_mof(d, s, 32); goto jmp_80; + case 78: __it_mof(d, s, 16); __it_mof(d, s, 32); goto jmp_72; + case 70: __it_mof(d, s, 16); __it_mof(d, s, 32); goto jmp_64; + case 62: __it_mof(d, s, 16); __it_mof(d, s, 32); goto jmp_56; + case 54: __it_mof(d, s, 16); __it_mof(d, s, 32); goto jmp_48; + case 46: __it_mof(d, s, 16); __it_mof(d, s, 32); goto jmp_40; + case 38: __it_mof(d, s, 16); __it_mof(d, s, 32); goto jmp_32; + case 30: __it_mof(d, s, 16); __it_mof(d, s, 32); goto jmp_24; + case 22: __it_mof(d, s, 16); __it_mof(d, s, 32); goto jmp_16; + case 14: __it_mof(d, s, 16); __it_mof(d, s, 32); goto jmp_8; + case 6: __it_mof(d, s, 16); __it_mof(d, s, 32); + break; + + case 92: __it_mof(d, s, 32); goto jmp_88; + case 84: __it_mof(d, s, 32); goto jmp_80; + case 76: __it_mof(d, s, 32); goto jmp_72; + case 68: __it_mof(d, s, 32); goto jmp_64; + case 60: __it_mof(d, s, 32); goto jmp_56; + case 52: __it_mof(d, s, 32); goto jmp_48; + case 44: __it_mof(d, s, 32); goto jmp_40; + case 36: __it_mof(d, s, 32); goto jmp_32; + case 28: __it_mof(d, s, 32); goto jmp_24; + case 20: __it_mof(d, s, 32); goto jmp_16; + case 12: __it_mof(d, s, 32); goto jmp_8; + case 4: __it_mof(d, s, 32); + break; + + case 90: __it_mof(d, s, 16); goto jmp_88; + case 82: __it_mof(d, s, 16); goto jmp_80; + case 74: __it_mof(d, s, 16); goto jmp_72; + case 66: __it_mof(d, s, 16); goto jmp_64; + case 58: __it_mof(d, s, 16); goto jmp_56; + case 50: __it_mof(d, s, 16); goto jmp_48; + case 42: __it_mof(d, s, 16); goto jmp_40; + case 34: __it_mof(d, s, 16); goto jmp_32; + case 26: __it_mof(d, s, 16); goto jmp_24; + case 18: __it_mof(d, s, 16); goto jmp_16; + case 10: __it_mof(d, s, 16); goto jmp_8; + case 2: __it_mof(d, s, 16); + break; + + case 1: __it_mof(d, s, 8); + break; + + default: + /* __builtin_memmove() is crappy slow since it cannot + * make any assumptions about alignment & underlying + * efficient unaligned access on the target we're + * running. + */ + __throw_build_bug(); + } +#else + __bpf_memmove_builtin(d, s, len); +#endif +} + +static __always_inline __maybe_unused void +__bpf_no_builtin_memmove(void *d __maybe_unused, const void *s __maybe_unused, + __u64 len __maybe_unused) +{ + __throw_build_bug(); +} + +/* Redirect any direct use in our code to throw an error. */ +#define __builtin_memmove __bpf_no_builtin_memmove + +static __always_inline void __bpf_memmove(void *d, const void *s, __u64 len) +{ + /* Note, the forward walking memmove() might not work with on-stack data + * since we'll end up walking the memory unaligned even when __align_stack_8 + * is set. Should not matter much since we'll use memmove() mostly or only + * on pkt data. + * + * Example with d, s, len = 12 bytes: + * * __bpf_memmove_fwd() emits: mov_32 d[0],s[0]; mov_64 d[4],s[4] + * * __bpf_memmove_bwd() emits: mov_32 d[8],s[8]; mov_64 d[0],s[0] + */ + if (d <= s) + return __bpf_memmove_fwd(d, s, len); + else + return __bpf_memmove_bwd(d, s, len); +} + +static __always_inline __nobuiltin("memmove") void memmove(void *d, + const void *s, + __u64 len) +{ + return __bpf_memmove(d, s, len); +} + +#endif /* __non_bpf_context */ +#endif /* __BPF_BUILTINS__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/compiler.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/compiler.h new file mode 100644 index 000000000..2588023a5 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/compiler.h @@ -0,0 +1,124 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __BPF_COMPILER_H_ +#define __BPF_COMPILER_H_ + +#ifndef __non_bpf_context +# include "stddef.h" +#endif + +#ifndef __section +# define __section(X) __attribute__((section(X), used)) +#endif + +#ifndef __maybe_unused +# define __maybe_unused __attribute__((__unused__)) +#endif + +#ifndef offsetof +# define offsetof(T, M) __builtin_offsetof(T, M) +#endif + +#ifndef field_sizeof +# define field_sizeof(T, M) sizeof((((T *)NULL)->M)) +#endif + +#ifndef __packed +# define __packed __attribute__((packed)) +#endif + +#ifndef __nobuiltin +# if __clang_major__ >= 10 +# define __nobuiltin(X) __attribute__((no_builtin(X))) +# else +# define __nobuiltin(X) +# endif +#endif + +#ifndef likely +# define likely(X) __builtin_expect(!!(X), 1) +#endif + +#ifndef unlikely +# define unlikely(X) __builtin_expect(!!(X), 0) +#endif + +#ifndef always_succeeds /* Mainly for documentation purpose. */ +# define always_succeeds(X) likely(X) +#endif + +#undef __always_inline /* stddef.h defines its own */ +#define __always_inline inline __attribute__((always_inline)) + +#ifndef __stringify +# define __stringify(X) #X +#endif + +#ifndef __fetch +# define __fetch(X) (__u32)(__u64)(&(X)) +#endif + +#ifndef __aligned +# define __aligned(X) __attribute__((aligned(X))) +#endif + +#ifndef build_bug_on +# define build_bug_on(E) ((void)sizeof(char[1 - 2*!!(E)])) +#endif + +#ifndef __throw_build_bug +# define __throw_build_bug() __builtin_trap() +#endif + +#ifndef __printf +# define __printf(X, Y) __attribute__((__format__(printf, X, Y))) +#endif + +#ifndef barrier +# define barrier() asm volatile("": : :"memory") +#endif + +#ifndef barrier_data +# define barrier_data(ptr) asm volatile("": :"r"(ptr) :"memory") +#endif + +static __always_inline void bpf_barrier(void) +{ + /* Workaround to avoid verifier complaint: + * "dereference of modified ctx ptr R5 off=48+0, ctx+const is allowed, + * ctx+const+const is not" + */ + barrier(); +} + +#ifndef ARRAY_SIZE +# define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0])) +#endif + +#ifndef __READ_ONCE +# define __READ_ONCE(X) (*(volatile typeof(X) *)&X) +#endif + +#ifndef __WRITE_ONCE +# define __WRITE_ONCE(X, V) (*(volatile typeof(X) *)&X) = (V) +#endif + +/* {READ,WRITE}_ONCE() with verifier workaround via bpf_barrier(). */ + +#ifndef READ_ONCE +# define READ_ONCE(X) \ + ({ typeof(X) __val = __READ_ONCE(X); \ + bpf_barrier(); \ + __val; }) +#endif + +#ifndef WRITE_ONCE +# define WRITE_ONCE(X, V) \ + ({ typeof(X) __val = (V); \ + __WRITE_ONCE(X, __val); \ + bpf_barrier(); \ + __val; }) +#endif + +#endif /* __BPF_COMPILER_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/csum.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/csum.h new file mode 100644 index 000000000..d2049bef2 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/csum.h @@ -0,0 +1,49 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_CSUM_H_ +#define __BPF_CSUM_H_ + +#include "compiler.h" +#include "helpers.h" + +static __always_inline __sum16 csum_fold(__wsum csum) +{ + csum = (csum & 0xffff) + (csum >> 16); + csum = (csum & 0xffff) + (csum >> 16); + return (__sum16)~csum; +} + +static __always_inline __wsum csum_unfold(__sum16 csum) +{ + return (__wsum)csum; +} + +static __always_inline __wsum csum_add(__wsum csum, __wsum addend) +{ + csum += addend; + return csum + (csum < addend); +} + +static __always_inline __wsum csum_diff(const void *from, __u32 size_from, + const void *to, __u32 size_to, + __u32 seed) +{ + if (__builtin_constant_p(size_from) && + __builtin_constant_p(size_to)) { + /* Optimizations for frequent hot-path cases that are tiny to just + * inline into the code instead of calling more expensive helper. + */ + if (size_from == 4 && size_to == 4 && + __builtin_constant_p(seed) && seed == 0) + return csum_add(~(*(__u32 *)from), *(__u32 *)to); + if (size_from == 4 && size_to == 4) + return csum_add(seed, + csum_add(~(*(__u32 *)from), + *(__u32 *)to)); + } + + return csum_diff_external(from, size_from, to, size_to, seed); +} + +#endif /* __BPF_CSUM_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/common.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/common.h new file mode 100644 index 000000000..e85fa9d66 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/common.h @@ -0,0 +1,36 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_CTX_COMMON_H_ +#define __BPF_CTX_COMMON_H_ + +#include +#include + +#include "../compiler.h" +#include "../errno.h" + +#define __ctx_skb 1 +#define __ctx_xdp 2 + +static __always_inline void *ctx_data(const struct __ctx_buff *ctx) +{ + return (void *)(unsigned long)ctx->data; +} + +static __always_inline void *ctx_data_meta(const struct __ctx_buff *ctx) +{ + return (void *)(unsigned long)ctx->data_meta; +} + +static __always_inline void *ctx_data_end(const struct __ctx_buff *ctx) +{ + return (void *)(unsigned long)ctx->data_end; +} + +static __always_inline bool ctx_no_room(const void *needed, const void *limit) +{ + return unlikely(needed > limit); +} + +#endif /* __BPF_CTX_COMMON_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/ctx.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/ctx.h new file mode 100644 index 000000000..7c126bb3e --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/ctx.h @@ -0,0 +1,11 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_CTX_CTX_H_ +#define __BPF_CTX_CTX_H_ + +#ifndef __ctx_buff +# error "No __ctx_buff context defined. Please either include 'bpf/ctx/skb.h' or 'bpf/ctx/xdp.h'." +#endif + +#endif /* __BPF_CTX_CTX_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/nobpf.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/nobpf.h new file mode 100644 index 000000000..aafdad7d9 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/nobpf.h @@ -0,0 +1,12 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_CTX_NOBPF_H_ +#define __BPF_CTX_NOBPF_H_ + +/* Used out of a non-BPF application. */ +#define __non_bpf_context 1 + +#include "unspec.h" + +#endif /* __BPF_CTX_NOBPF_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/skb.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/skb.h new file mode 100644 index 000000000..49bdf534c --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/skb.h @@ -0,0 +1,107 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_CTX_SKB_H_ +#define __BPF_CTX_SKB_H_ + +#define __ctx_buff __sk_buff +#define __ctx_is __ctx_skb + +#include "common.h" +#include "../helpers_skb.h" + +#ifndef TC_ACT_OK +# define TC_ACT_OK 0 +#endif + +#ifndef TC_ACT_SHOT +# define TC_ACT_SHOT 2 +#endif + +#ifndef TC_ACT_REDIRECT +# define TC_ACT_REDIRECT 7 +#endif + +#define CTX_ACT_OK TC_ACT_OK +#define CTX_ACT_DROP TC_ACT_SHOT +#define CTX_ACT_TX TC_ACT_REDIRECT + +/* Discouraged since prologue will unclone full skb. */ +#define CTX_DIRECT_WRITE_OK 0 + +#define META_PIVOT field_sizeof(struct __sk_buff, cb) + +#define ctx_load_bytes skb_load_bytes +#define ctx_store_bytes skb_store_bytes + +#define ctx_adjust_hroom skb_adjust_room + +#define ctx_change_type skb_change_type +#define ctx_change_proto skb_change_proto +#define ctx_change_tail skb_change_tail + +#define ctx_pull_data skb_pull_data + +#define ctx_get_tunnel_key skb_get_tunnel_key +#define ctx_set_tunnel_key skb_set_tunnel_key + +#define ctx_event_output skb_event_output + +#define ctx_adjust_meta ({ -ENOTSUPP; }) + +/* Avoid expensive calls into the kernel flow dissector if it's not an L4 + * hash. We currently only use the hash for debugging. If needed later, we + * can map it to BPF_FUNC(get_hash_recalc) to get the L4 hash. + */ +#define get_hash(ctx) ctx->hash +#define get_hash_recalc(ctx) get_hash(ctx) + +static __always_inline __maybe_unused int +ctx_redirect(struct __sk_buff *ctx __maybe_unused, int ifindex, __u32 flags) +{ + return redirect(ifindex, flags); +} + +static __always_inline __maybe_unused int +ctx_adjust_troom(struct __sk_buff *ctx, const __s32 len_diff) +{ + return skb_change_tail(ctx, ctx->len + len_diff, 0); +} + +static __always_inline __maybe_unused __u64 +ctx_full_len(const struct __sk_buff *ctx) +{ + return ctx->len; +} + +static __always_inline __maybe_unused __u32 +ctx_wire_len(const struct __sk_buff *ctx) +{ + return ctx->wire_len; +} + +static __always_inline __maybe_unused void +ctx_store_meta(struct __sk_buff *ctx, const __u32 off, __u32 data) +{ + ctx->cb[off] = data; +} + +static __always_inline __maybe_unused __u32 +ctx_load_meta(const struct __sk_buff *ctx, const __u32 off) +{ + return ctx->cb[off]; +} + +static __always_inline __maybe_unused __u32 +ctx_get_protocol(const struct __sk_buff *ctx) +{ + return ctx->protocol; +} + +static __always_inline __maybe_unused __u32 +ctx_get_ifindex(const struct __sk_buff *ctx) +{ + return ctx->ifindex; +} + +#endif /* __BPF_CTX_SKB_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/unspec.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/unspec.h new file mode 100644 index 000000000..a4fa2f38d --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/unspec.h @@ -0,0 +1,18 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_CTX_UNSPEC_H_ +#define __BPF_CTX_UNSPEC_H_ + +/* We do not care which context we need in this case, but it must be + * something compilable, thus we reuse skb ctx here. + */ + +#ifdef __non_bpf_context +/* Do not include BPF feature header. */ +# define __BPF_FEATURES_SKB__ 1 +#endif + +#include "skb.h" + +#endif /* __BPF_CTX_UNSPEC_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/xdp.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/xdp.h new file mode 100644 index 000000000..c87d0fe63 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/ctx/xdp.h @@ -0,0 +1,325 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_CTX_XDP_H_ +#define __BPF_CTX_XDP_H_ + +#include + +#define __ctx_buff xdp_md +#define __ctx_is __ctx_xdp + +#include "common.h" +#include "../helpers_xdp.h" +#include "../builtins.h" +#include "../section.h" +#include "../loader.h" +#include "../csum.h" + +#define CTX_ACT_OK XDP_PASS +#define CTX_ACT_DROP XDP_DROP +#define CTX_ACT_TX XDP_TX /* hairpin only */ + +#define CTX_DIRECT_WRITE_OK 1 + + /* cb + RECIRC_MARKER + XFER_MARKER */ +#define META_PIVOT ((int)(field_sizeof(struct __sk_buff, cb) + \ + sizeof(__u32) * 2)) + +/* This must be a mask and all offsets guaranteed to be less than that. */ +#define __CTX_OFF_MAX 0xff + +static __always_inline __maybe_unused int +xdp_load_bytes(const struct xdp_md *ctx, __u64 off, void *to, const __u64 len) +{ + void *from; + int ret; + /* LLVM tends to generate code that verifier doesn't understand, + * so force it the way we want it in order to open up a range + * on the reg. + */ + asm volatile("r1 = *(u32 *)(%[ctx] +0)\n\t" + "r2 = *(u32 *)(%[ctx] +4)\n\t" + "%[off] &= %[offmax]\n\t" + "r1 += %[off]\n\t" + "%[from] = r1\n\t" + "r1 += %[len]\n\t" + "if r1 > r2 goto +2\n\t" + "%[ret] = 0\n\t" + "goto +1\n\t" + "%[ret] = %[errno]\n\t" + : [ret]"=r"(ret), [from]"=r"(from) + : [ctx]"r"(ctx), [off]"r"(off), [len]"ri"(len), + [offmax]"i"(__CTX_OFF_MAX), [errno]"i"(-EINVAL) + : "r1", "r2"); + if (!ret) + memcpy(to, from, len); + return ret; +} + +static __always_inline __maybe_unused int +xdp_store_bytes(const struct xdp_md *ctx, __u64 off, const void *from, + const __u64 len, __u64 flags __maybe_unused) +{ + void *to; + int ret; + /* See xdp_load_bytes(). */ + asm volatile("r1 = *(u32 *)(%[ctx] +0)\n\t" + "r2 = *(u32 *)(%[ctx] +4)\n\t" + "%[off] &= %[offmax]\n\t" + "r1 += %[off]\n\t" + "%[to] = r1\n\t" + "r1 += %[len]\n\t" + "if r1 > r2 goto +2\n\t" + "%[ret] = 0\n\t" + "goto +1\n\t" + "%[ret] = %[errno]\n\t" + : [ret]"=r"(ret), [to]"=r"(to) + : [ctx]"r"(ctx), [off]"r"(off), [len]"ri"(len), + [offmax]"i"(__CTX_OFF_MAX), [errno]"i"(-EINVAL) + : "r1", "r2"); + if (!ret) + memcpy(to, from, len); + return ret; +} + +#define ctx_load_bytes xdp_load_bytes +#define ctx_store_bytes xdp_store_bytes + +/* Fyi, remapping to stubs helps to assert that the code is not in + * use since it otherwise triggers a verifier error. + */ + +#define ctx_change_type xdp_change_type__stub +#define ctx_change_proto xdp_change_proto__stub +#define ctx_change_tail xdp_change_tail__stub + +#define ctx_pull_data(ctx, ...) do { /* Already linear. */ } while (0) + +#define ctx_get_tunnel_key xdp_get_tunnel_key__stub +#define ctx_set_tunnel_key xdp_set_tunnel_key__stub + +#define ctx_event_output xdp_event_output + +#define ctx_adjust_meta xdp_adjust_meta + +#define get_hash(ctx) ({ 0; }) +#define get_hash_recalc(ctx) get_hash(ctx) + +static __always_inline __maybe_unused void +__csum_replace_by_diff(__sum16 *sum, __wsum diff) +{ + *sum = csum_fold(csum_add(diff, ~csum_unfold(*sum))); +} + +static __always_inline __maybe_unused void +__csum_replace_by_4(__sum16 *sum, __wsum from, __wsum to) +{ + __csum_replace_by_diff(sum, csum_add(~from, to)); +} + +static __always_inline __maybe_unused int +l3_csum_replace(const struct xdp_md *ctx, __u64 off, const __u32 from, + __u32 to, + __u32 flags) +{ + __u32 size = flags & BPF_F_HDR_FIELD_MASK; + __sum16 *sum; + int ret; + + if (unlikely(flags & ~(BPF_F_HDR_FIELD_MASK))) + return -EINVAL; + if (unlikely(size != 0 && size != 2)) + return -EINVAL; + /* See xdp_load_bytes(). */ + asm volatile("r1 = *(u32 *)(%[ctx] +0)\n\t" + "r2 = *(u32 *)(%[ctx] +4)\n\t" + "%[off] &= %[offmax]\n\t" + "r1 += %[off]\n\t" + "%[sum] = r1\n\t" + "r1 += 2\n\t" + "if r1 > r2 goto +2\n\t" + "%[ret] = 0\n\t" + "goto +1\n\t" + "%[ret] = %[errno]\n\t" + : [ret]"=r"(ret), [sum]"=r"(sum) + : [ctx]"r"(ctx), [off]"r"(off), + [offmax]"i"(__CTX_OFF_MAX), [errno]"i"(-EINVAL) + : "r1", "r2"); + if (!ret) + from ? __csum_replace_by_4(sum, from, to) : + __csum_replace_by_diff(sum, to); + return ret; +} + +#define CSUM_MANGLED_0 ((__sum16)0xffff) + +static __always_inline __maybe_unused int +l4_csum_replace(const struct xdp_md *ctx, __u64 off, __u32 from, __u32 to, + __u32 flags) +{ + bool is_mmzero = flags & BPF_F_MARK_MANGLED_0; + __u32 size = flags & BPF_F_HDR_FIELD_MASK; + __sum16 *sum; + int ret; + + if (unlikely(flags & ~(BPF_F_MARK_MANGLED_0 | BPF_F_PSEUDO_HDR | + BPF_F_HDR_FIELD_MASK))) + return -EINVAL; + if (unlikely(size != 0 && size != 2)) + return -EINVAL; + /* See xdp_load_bytes(). */ + asm volatile("r1 = *(u32 *)(%[ctx] +0)\n\t" + "r2 = *(u32 *)(%[ctx] +4)\n\t" + "%[off] &= %[offmax]\n\t" + "r1 += %[off]\n\t" + "%[sum] = r1\n\t" + "r1 += 2\n\t" + "if r1 > r2 goto +2\n\t" + "%[ret] = 0\n\t" + "goto +1\n\t" + "%[ret] = %[errno]\n\t" + : [ret]"=r"(ret), [sum]"=r"(sum) + : [ctx]"r"(ctx), [off]"r"(off), + [offmax]"i"(__CTX_OFF_MAX), [errno]"i"(-EINVAL) + : "r1", "r2"); + if (!ret) { + if (is_mmzero && !*sum) + return 0; + from ? __csum_replace_by_4(sum, from, to) : + __csum_replace_by_diff(sum, to); + if (is_mmzero && !*sum) + *sum = CSUM_MANGLED_0; + } + return ret; +} + +static __always_inline __maybe_unused int +ctx_adjust_troom(struct xdp_md *ctx, const __s32 len_diff) +{ + return xdp_adjust_tail(ctx, len_diff); +} + +static __always_inline __maybe_unused int +ctx_adjust_hroom(struct xdp_md *ctx, const __s32 len_diff, const __u32 mode, + const __u64 flags __maybe_unused) +{ + const __u32 move_len_v4 = 14 + 20; + const __u32 move_len_v6 = 14 + 40; + void *data, *data_end; + int ret; + + build_bug_on(len_diff <= 0 || len_diff >= 64); + build_bug_on(mode != BPF_ADJ_ROOM_NET); + + ret = xdp_adjust_head(ctx, -len_diff); + + /* XXX: Note, this hack is currently tailored to NodePort DSR + * requirements and not a generic helper. If needed elsewhere, + * this must be made more generic. + */ + if (!ret) { + data_end = ctx_data_end(ctx); + data = ctx_data(ctx); + switch (len_diff) { + case 28: /* struct {iphdr + icmphdr} */ + break; + case 20: /* struct iphdr */ + case 8: /* __u32 opt[2] */ + if (data + move_len_v4 + len_diff <= data_end) + __bpf_memmove_fwd(data, data + len_diff, + move_len_v4); + else + ret = -EFAULT; + break; + case 48: /* struct {ipv6hdr + icmp6hdr} */ + break; + case 40: /* struct ipv6hdr */ + case 24: /* struct dsr_opt_v6 */ + if (data + move_len_v6 + len_diff <= data_end) + __bpf_memmove_fwd(data, data + len_diff, + move_len_v6); + else + ret = -EFAULT; + break; + default: + __throw_build_bug(); + } + } + return ret; +} + +#define redirect redirect__stub +#define redirect_peer redirect + +static __always_inline __maybe_unused int +ctx_redirect(const struct xdp_md *ctx, int ifindex, const __u32 flags) +{ + if (unlikely(flags)) + return -ENOTSUPP; + if ((__u32)ifindex != ctx->ingress_ifindex) + return -ENOTSUPP; + return XDP_TX; +} + +static __always_inline __maybe_unused __u64 +ctx_full_len(const struct xdp_md *ctx) +{ + /* No non-linear section in XDP. */ + return ctx_data_end(ctx) - ctx_data(ctx); +} + +static __always_inline __maybe_unused __u32 +ctx_wire_len(const struct xdp_md *ctx) +{ + return ctx_full_len(ctx); +} + +struct bpf_elf_map __section_maps cilium_xdp_scratch = { + .type = BPF_MAP_TYPE_PERCPU_ARRAY, + .size_key = sizeof(int), + .size_value = META_PIVOT, + .pinning = PIN_GLOBAL_NS, + .max_elem = 1, +}; + +static __always_inline __maybe_unused void +ctx_store_meta(struct xdp_md *ctx __maybe_unused, const __u64 off, __u32 datum) +{ + __u32 zero = 0, *data_meta = map_lookup_elem(&cilium_xdp_scratch, &zero); + + if (always_succeeds(data_meta)) + data_meta[off] = datum; + build_bug_on((off + 1) * sizeof(__u32) > META_PIVOT); +} + +static __always_inline __maybe_unused __u32 +ctx_load_meta(const struct xdp_md *ctx __maybe_unused, const __u64 off) +{ + __u32 zero = 0, *data_meta = map_lookup_elem(&cilium_xdp_scratch, &zero); + + if (always_succeeds(data_meta)) + return data_meta[off]; + build_bug_on((off + 1) * sizeof(__u32) > META_PIVOT); + return 0; +} + +static __always_inline __maybe_unused __u32 +ctx_get_protocol(const struct xdp_md *ctx) +{ + void *data_end = ctx_data_end(ctx); + struct ethhdr *eth = ctx_data(ctx); + + if (ctx_no_room(eth + 1, data_end)) + return 0; + + return eth->h_proto; +} + +static __always_inline __maybe_unused __u32 +ctx_get_ifindex(const struct xdp_md *ctx) +{ + return ctx->ingress_ifindex; +} + +#endif /* __BPF_CTX_XDP_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/errno.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/errno.h new file mode 100644 index 000000000..c7d09afe4 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/errno.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __BPF_ERRNO__ +#define __BPF_ERRNO__ + +/* Few basic errno codes as we don't want to include errno.h. */ + +#ifndef EPERM +# define EPERM 1 +#endif +#ifndef ENOENT +# define ENOENT 2 +#endif +#ifndef ENXIO +# define ENXIO 6 +#endif +#ifndef ENOMEM +# define ENOMEM 12 +#endif +#ifndef EFAULT +# define EFAULT 14 +#endif +#ifndef EINVAL +# define EINVAL 22 +#endif +#ifndef ENOTSUP +# define ENOTSUP 95 +#endif +#ifndef EADDRINUSE +# define EADDRINUSE 98 +#endif +#ifndef ENOTSUPP +# define ENOTSUPP 524 +#endif + +#endif /* __BPF_ERRNO__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/features.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/features.h new file mode 100644 index 000000000..0956a487b --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/features.h @@ -0,0 +1,39 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef ____BPF_FEATURES____ +#define ____BPF_FEATURES____ + +#include "bpf_features.h" + +/* Neither skb nor xdp related features. */ + +/* Testing both here since both were added to the same kernel release + * and we need to ensure both are enabled. + */ +#if HAVE_PROG_TYPE_HELPER(cgroup_sock_addr, bpf_get_netns_cookie) && \ + HAVE_PROG_TYPE_HELPER(cgroup_sock, bpf_get_netns_cookie) +# define BPF_HAVE_NETNS_COOKIE 1 +#endif + +#if HAVE_PROG_TYPE_HELPER(cgroup_sock_addr, bpf_get_socket_cookie) +# define BPF_HAVE_SOCKET_COOKIE 1 +#endif + +#if HAVE_PROG_TYPE_HELPER(cgroup_sock_addr, bpf_jiffies64) && \ + HAVE_PROG_TYPE_HELPER(cgroup_sock, bpf_jiffies64) && \ + HAVE_PROG_TYPE_HELPER(sched_cls, bpf_jiffies64) && \ + HAVE_PROG_TYPE_HELPER(xdp, bpf_jiffies64) +# define BPF_HAVE_JIFFIES 1 +#endif + +#if HAVE_PROG_TYPE_HELPER(sched_cls, bpf_csum_level) +# define BPF_HAVE_CSUM_LEVEL 1 +#endif + +#if HAVE_PROG_TYPE_HELPER(cgroup_sock_addr, bpf_sk_lookup_tcp) && \ + HAVE_PROG_TYPE_HELPER(cgroup_sock_addr, bpf_sk_lookup_udp) +# define BPF_HAVE_SOCKET_LOOKUP 1 +#endif + +#endif /* ____BPF_FEATURES____ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/features_skb.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/features_skb.h new file mode 100644 index 000000000..1125f3854 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/features_skb.h @@ -0,0 +1,19 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_FEATURES_SKB__ +#define __BPF_FEATURES_SKB__ + +#include "features.h" + +/* Only skb related features. */ + +#if HAVE_PROG_TYPE_HELPER(sched_cls, bpf_skb_change_tail) +# define BPF_HAVE_CHANGE_TAIL 1 +#endif + +#if HAVE_PROG_TYPE_HELPER(sched_cls, bpf_fib_lookup) +# define BPF_HAVE_FIB_LOOKUP 1 +#endif + +#endif /* __BPF_FEATURES_SKB__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/features_xdp.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/features_xdp.h new file mode 100644 index 000000000..6ead5f6da --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/features_xdp.h @@ -0,0 +1,15 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_FEATURES_XDP__ +#define __BPF_FEATURES_XDP__ + +#include "features.h" + +/* Only xdp related features. */ + +#if HAVE_PROG_TYPE_HELPER(xdp, bpf_fib_lookup) +# define BPF_HAVE_FIB_LOOKUP 1 +#endif + +#endif /* __BPF_FEATURES_XDP__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/helpers.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/helpers.h new file mode 100644 index 000000000..dde7ee788 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/helpers.h @@ -0,0 +1,104 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __BPF_HELPERS__ +#define __BPF_HELPERS__ + +#include + +#include "ctx/ctx.h" +#include "compiler.h" + +#ifndef BPF_FUNC +# define BPF_FUNC(NAME, ...) \ + (* NAME)(__VA_ARGS__) __maybe_unused = (void *)BPF_FUNC_##NAME +#endif + +#ifndef BPF_STUB +# define BPF_STUB(NAME, ...) \ + (* NAME##__stub)(__VA_ARGS__) __maybe_unused = (void *)((__u32)-1) +#endif + +#ifndef BPF_FUNC_REMAP +# define BPF_FUNC_REMAP(NAME, ...) \ + (* NAME)(__VA_ARGS__) __maybe_unused +#endif + +#if __ctx_is == __ctx_skb +# include "helpers_skb.h" +#else +# include "helpers_xdp.h" +#endif + +/* Map access/manipulation */ +static void *BPF_FUNC(map_lookup_elem, const void *map, const void *key); +static int BPF_FUNC(map_update_elem, const void *map, const void *key, + const void *value, __u32 flags); +static int BPF_FUNC(map_delete_elem, const void *map, const void *key); + +/* Time access */ +static __u64 BPF_FUNC(ktime_get_ns); +static __u64 BPF_FUNC(ktime_get_boot_ns); +static __u64 BPF_FUNC(jiffies64); +#define jiffies jiffies64() + +/* We have cookies! ;-) */ +static __sock_cookie BPF_FUNC(get_socket_cookie, void *ctx); +static __net_cookie BPF_FUNC(get_netns_cookie, void *ctx); + +/* Debugging */ +static __printf(1, 3) void +BPF_FUNC(trace_printk, const char *fmt, int fmt_size, ...); + +/* Random numbers */ +static __u32 BPF_FUNC(get_prandom_u32); + +/* Checksumming */ +static int BPF_FUNC_REMAP(csum_diff_external, const void *from, __u32 size_from, + const void *to, __u32 size_to, __u32 seed) = + (void *)BPF_FUNC_csum_diff; + +/* Tail calls */ +static void BPF_FUNC(tail_call, void *ctx, const void *map, __u32 index); + +/* System helpers */ +static __u32 BPF_FUNC(get_smp_processor_id); + +/* Padded struct so the dmac at the end can be passed to another helper + * e.g. as a map value buffer. Otherwise verifier will trip over it with + * 'invalid indirect read from stack off'. + */ +struct bpf_fib_lookup_padded { + struct bpf_fib_lookup l; + __u8 pad[2]; +}; + +/* Routing helpers */ +static int BPF_FUNC(fib_lookup, void *ctx, struct bpf_fib_lookup *params, + __u32 plen, __u32 flags); + +/* Sockops and SK_MSG helpers */ +static int BPF_FUNC(sock_map_update, struct bpf_sock_ops *skops, void *map, + __u32 key, __u64 flags); +static int BPF_FUNC(sock_hash_update, struct bpf_sock_ops *skops, void *map, + void *key, __u64 flags); +static int BPF_FUNC(msg_redirect_hash, struct sk_msg_md *md, void *map, + void *key, __u64 flags); + +/* Socket lookup helpers */ +static struct bpf_sock *BPF_FUNC(sk_lookup_tcp, void *ctx, + struct bpf_sock_tuple *tuple, __u32 tuple_size, + __u64 netns, __u64 flags); +static struct bpf_sock *BPF_FUNC(sk_lookup_udp, void *ctx, + struct bpf_sock_tuple *tuple, __u32 tuple_size, + __u64 netns, __u64 flags); + +/* Socket helpers, misc */ +/* Remapped name to avoid clash with getsockopt(2) when included from + * regular applications. + */ +static int BPF_FUNC_REMAP(get_socket_opt, void *ctx, int level, int optname, + void *optval, int optlen) = + (void *)BPF_FUNC_getsockopt; + +#endif /* __BPF_HELPERS__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/helpers_skb.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/helpers_skb.h new file mode 100644 index 000000000..f3815ae08 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/helpers_skb.h @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __BPF_HELPERS_SKB__ +#define __BPF_HELPERS_SKB__ + +#include + +#include "compiler.h" +#include "helpers.h" +#include "features_skb.h" + +/* Only used helpers in Cilium go below. */ + +/* Packet redirection */ +static int BPF_FUNC(redirect, int ifindex, __u32 flags); +static int BPF_FUNC(redirect_neigh, int ifindex, struct bpf_redir_neigh *params, + int plen, __u32 flags); +static int BPF_FUNC(redirect_peer, int ifindex, __u32 flags); + +/* Packet manipulation */ +static int BPF_FUNC(skb_load_bytes, struct __sk_buff *skb, __u32 off, + void *to, __u32 len); +static int BPF_FUNC(skb_store_bytes, struct __sk_buff *skb, __u32 off, + const void *from, __u32 len, __u32 flags); + +static int BPF_FUNC(l3_csum_replace, struct __sk_buff *skb, __u32 off, + __u32 from, __u32 to, __u32 flags); +static int BPF_FUNC(l4_csum_replace, struct __sk_buff *skb, __u32 off, + __u32 from, __u32 to, __u32 flags); + +static int BPF_FUNC(skb_adjust_room, struct __sk_buff *skb, __s32 len_diff, + __u32 mode, __u64 flags); + +static int BPF_FUNC(skb_change_type, struct __sk_buff *skb, __u32 type); +static int BPF_FUNC(skb_change_proto, struct __sk_buff *skb, __u32 proto, + __u32 flags); +static int BPF_FUNC(skb_change_tail, struct __sk_buff *skb, __u32 nlen, + __u32 flags); +static int BPF_FUNC(skb_change_head, struct __sk_buff *skb, __u32 head_room, + __u64 flags); + +static int BPF_FUNC(skb_pull_data, struct __sk_buff *skb, __u32 len); + +/* Packet tunnel encap/decap */ +static int BPF_FUNC(skb_get_tunnel_key, struct __sk_buff *skb, + struct bpf_tunnel_key *to, __u32 size, __u32 flags); +static int BPF_FUNC(skb_set_tunnel_key, struct __sk_buff *skb, + const struct bpf_tunnel_key *from, __u32 size, + __u32 flags); + +/* Events for user space */ +static int BPF_FUNC_REMAP(skb_event_output, struct __sk_buff *skb, void *map, + __u64 index, const void *data, __u32 size) = + (void *)BPF_FUNC_perf_event_output; + +/* Socket lookup, assign, release */ +static struct bpf_sock *BPF_FUNC(skc_lookup_tcp, struct __sk_buff *skb, + struct bpf_sock_tuple *tuple, __u32 tuple_size, + __u64 netns, __u64 flags); +static int BPF_FUNC(sk_release, struct bpf_sock *sk); +static int BPF_FUNC(sk_assign, struct __sk_buff *skb, struct bpf_sock *sk, + __u64 flags); + +#endif /* __BPF_HELPERS_SKB__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/helpers_xdp.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/helpers_xdp.h new file mode 100644 index 000000000..b0638c833 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/helpers_xdp.h @@ -0,0 +1,55 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __BPF_HELPERS_XDP__ +#define __BPF_HELPERS_XDP__ + +#include + +#include "compiler.h" +#include "helpers.h" +#include "features_xdp.h" + +/* Only used helpers in Cilium go below. */ + +/* Packet misc meta data & encapsulation helper */ +static int BPF_FUNC(xdp_adjust_meta, struct xdp_md *xdp, int delta); +static int BPF_FUNC(xdp_adjust_head, struct xdp_md *xdp, int delta); +static int BPF_FUNC(xdp_adjust_tail, struct xdp_md *xdp, int delta); + +/* Packet redirection */ +static int BPF_STUB(redirect, int ifindex, __u32 flags); + +/* Packet manipulation */ +static int BPF_STUB(xdp_load_bytes, struct xdp_md *xdp, __u32 off, + void *to, __u32 len); +static int BPF_STUB(xdp_store_bytes, struct xdp_md *xdp, __u32 off, + const void *from, __u32 len, __u32 flags); + +static int BPF_STUB(l3_csum_replace, struct xdp_md *xdp, __u32 off, + __u32 from, __u32 to, __u32 flags); +static int BPF_STUB(l4_csum_replace, struct xdp_md *xdp, __u32 off, + __u32 from, __u32 to, __u32 flags); + +static int BPF_STUB(xdp_adjust_room, struct xdp_md *xdp, __s32 len_diff, + __u32 mode, __u64 flags); + +static int BPF_STUB(xdp_change_type, struct xdp_md *xdp, __u32 type); +static int BPF_STUB(xdp_change_proto, struct xdp_md *xdp, __u32 proto, + __u32 flags); +static int BPF_STUB(xdp_change_tail, struct xdp_md *xdp, __u32 nlen, + __u32 flags); + +/* Packet tunnel encap/decap */ +static int BPF_STUB(xdp_get_tunnel_key, struct xdp_md *xdp, + struct bpf_tunnel_key *to, __u32 size, __u32 flags); +static int BPF_STUB(xdp_set_tunnel_key, struct xdp_md *xdp, + const struct bpf_tunnel_key *from, __u32 size, + __u32 flags); + +/* Events for user space */ +static int BPF_FUNC_REMAP(xdp_event_output, struct xdp_md *xdp, void *map, + __u64 index, const void *data, __u32 size) = + (void *)BPF_FUNC_perf_event_output; + +#endif /* __BPF_HELPERS_XDP__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/loader.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/loader.h new file mode 100644 index 000000000..197e25d65 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/loader.h @@ -0,0 +1,27 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __BPF_LOADER__ +#define __BPF_LOADER__ + +#include + +#define PIN_NONE 0 +#define PIN_OBJECT_NS 1 +#define PIN_GLOBAL_NS 2 + +struct bpf_elf_map { + __u32 type; + __u32 size_key; + __u32 size_value; + __u32 max_elem; + __u32 flags; + __u32 id; + __u32 pinning; + __u32 inner_id; + __u32 inner_idx; +}; + +#define NO_PREPOPULATE -1 + +#endif /* __BPF_LOADER__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/section.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/section.h new file mode 100644 index 000000000..5fe09e0d0 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/section.h @@ -0,0 +1,26 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __BPF_SECTION__ +#define __BPF_SECTION__ + +#include "compiler.h" + +#ifndef __section_tail +# define __section_tail(ID, KEY) __section(__stringify(ID) "/" __stringify(KEY)) +#endif + +#ifndef __section_license +# define __section_license __section("license") +#endif + +#ifndef __section_maps +# define __section_maps __section("maps") +#endif + +#ifndef BPF_LICENSE +# define BPF_LICENSE(NAME) \ + char ____license[] __section_license = NAME +#endif + +#endif /* __BPF_SECTION__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/stddef.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/stddef.h new file mode 100644 index 000000000..7d1b196d7 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/stddef.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_STDDEF_H_ +#define __BPF_STDDEF_H_ + +#define NULL ((void *)0) + +#define bool _Bool + +enum { + false = 0, + true = 1, +}; + +#endif /* __BPF_STDDEF_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/tailcall.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/tailcall.h new file mode 100644 index 000000000..76002e6f1 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/tailcall.h @@ -0,0 +1,54 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_TAILCALL_H_ +#define __BPF_TAILCALL_H_ + +#include "compiler.h" + +#if !defined(__non_bpf_context) && defined(__bpf__) +static __always_inline __maybe_unused void +tail_call_static(const struct __ctx_buff *ctx, const void *map, + const __u32 slot) +{ + if (!__builtin_constant_p(slot)) + __throw_build_bug(); + + /* Don't gamble, but _guarantee_ that LLVM won't optimize setting + * r2 and r3 from different paths ending up at the same call insn as + * otherwise we won't be able to use the jmpq/nopl retpoline-free + * patching by the x86-64 JIT in the kernel. + * + * Note on clobber list: we need to stay in-line with BPF calling + * convention, so even if we don't end up using r0, r4, r5, we need + * to mark them as clobber so that LLVM doesn't end up using them + * before / after the call. + */ + asm volatile("r1 = %[ctx]\n\t" + "r2 = %[map]\n\t" + "r3 = %[slot]\n\t" + "call 12\n\t" + :: [ctx]"r"(ctx), [map]"r"(map), [slot]"i"(slot) + : "r0", "r1", "r2", "r3", "r4", "r5"); +} + +static __always_inline __maybe_unused void +tail_call_dynamic(struct __ctx_buff *ctx, const void *map, __u32 slot) +{ + if (__builtin_constant_p(slot)) + __throw_build_bug(); + + /* Only for the case where slot is not known at compilation time, + * we give LLVM a free pass to optimize since we cannot do much + * here anyway as x86-64 JIT will emit a retpoline for this case. + */ + tail_call(ctx, map, slot); +} +#else +/* BPF unit tests compile some BPF code under their native arch. Tail calls + * won't work in this context. Only compile above under __bpf__ target. + */ +# define tail_call_static(ctx, map, slot) __throw_build_bug() +# define tail_call_dynamic(ctx, map, slot) __throw_build_bug() +#endif /* !__non_bpf_context && __bpf__ */ +#endif /* __BPF_TAILCALL_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/types_mapper.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/types_mapper.h new file mode 100644 index 000000000..613a894da --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/types_mapper.h @@ -0,0 +1,36 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __BPF_TYPES_MAPPER__ +#define __BPF_TYPES_MAPPER__ + +typedef __signed__ char __s8; +typedef unsigned char __u8; + +typedef __signed__ short __s16; +typedef unsigned short __u16; + +typedef __signed__ int __s32; +typedef unsigned int __u32; + +typedef __signed__ long long __s64; +typedef unsigned long long __u64; + +typedef __u16 __le16; +typedef __u16 __be16; + +typedef __u32 __le32; +typedef __u32 __be32; + +typedef __u64 __le64; +typedef __u64 __be64; + +typedef __u16 __sum16; +typedef __u32 __wsum; + +typedef __u64 __aligned_u64; + +typedef __u64 __net_cookie; +typedef __u64 __sock_cookie; + +#endif /* __BPF_TYPES_MAPPER__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/verifier.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/verifier.h new file mode 100644 index 000000000..6d387f31e --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/bpf/verifier.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __BPF_VERIFIER__ +#define __BPF_VERIFIER__ + +#include "compiler.h" + +/* relax_verifier is a dummy helper call to introduce a pruning checkpoint + * to help relax the verifier to avoid reaching complexity limits on older + * kernels. + */ +static __always_inline void relax_verifier(void) +{ +#ifndef HAVE_LARGE_INSN_LIMIT + volatile int __maybe_unused id = get_smp_processor_id(); +#endif +} + +#endif /* __BPF_VERIFIER__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/elf/elf.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/elf/elf.h new file mode 100644 index 000000000..9e59b3275 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/elf/elf.h @@ -0,0 +1,3749 @@ +/* This file defines standard ELF types, structures, and macros. + Copyright (C) 1995-2016 Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, see + . */ + +#ifndef _ELF_H +#define _ELF_H 1 + +#include + +__BEGIN_DECLS + +/* Standard ELF types. */ + +#include + +/* Type for a 16-bit quantity. */ +typedef uint16_t Elf32_Half; +typedef uint16_t Elf64_Half; + +/* Types for signed and unsigned 32-bit quantities. */ +typedef uint32_t Elf32_Word; +typedef int32_t Elf32_Sword; +typedef uint32_t Elf64_Word; +typedef int32_t Elf64_Sword; + +/* Types for signed and unsigned 64-bit quantities. */ +typedef uint64_t Elf32_Xword; +typedef int64_t Elf32_Sxword; +typedef uint64_t Elf64_Xword; +typedef int64_t Elf64_Sxword; + +/* Type of addresses. */ +typedef uint32_t Elf32_Addr; +typedef uint64_t Elf64_Addr; + +/* Type of file offsets. */ +typedef uint32_t Elf32_Off; +typedef uint64_t Elf64_Off; + +/* Type for section indices, which are 16-bit quantities. */ +typedef uint16_t Elf32_Section; +typedef uint16_t Elf64_Section; + +/* Type for version symbol information. */ +typedef Elf32_Half Elf32_Versym; +typedef Elf64_Half Elf64_Versym; + + +/* The ELF file header. This appears at the start of every ELF file. */ + +#define EI_NIDENT (16) + +typedef struct +{ + unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */ + Elf32_Half e_type; /* Object file type */ + Elf32_Half e_machine; /* Architecture */ + Elf32_Word e_version; /* Object file version */ + Elf32_Addr e_entry; /* Entry point virtual address */ + Elf32_Off e_phoff; /* Program header table file offset */ + Elf32_Off e_shoff; /* Section header table file offset */ + Elf32_Word e_flags; /* Processor-specific flags */ + Elf32_Half e_ehsize; /* ELF header size in bytes */ + Elf32_Half e_phentsize; /* Program header table entry size */ + Elf32_Half e_phnum; /* Program header table entry count */ + Elf32_Half e_shentsize; /* Section header table entry size */ + Elf32_Half e_shnum; /* Section header table entry count */ + Elf32_Half e_shstrndx; /* Section header string table index */ +} Elf32_Ehdr; + +typedef struct +{ + unsigned char e_ident[EI_NIDENT]; /* Magic number and other info */ + Elf64_Half e_type; /* Object file type */ + Elf64_Half e_machine; /* Architecture */ + Elf64_Word e_version; /* Object file version */ + Elf64_Addr e_entry; /* Entry point virtual address */ + Elf64_Off e_phoff; /* Program header table file offset */ + Elf64_Off e_shoff; /* Section header table file offset */ + Elf64_Word e_flags; /* Processor-specific flags */ + Elf64_Half e_ehsize; /* ELF header size in bytes */ + Elf64_Half e_phentsize; /* Program header table entry size */ + Elf64_Half e_phnum; /* Program header table entry count */ + Elf64_Half e_shentsize; /* Section header table entry size */ + Elf64_Half e_shnum; /* Section header table entry count */ + Elf64_Half e_shstrndx; /* Section header string table index */ +} Elf64_Ehdr; + +/* Fields in the e_ident array. The EI_* macros are indices into the + array. The macros under each EI_* macro are the values the byte + may have. */ + +#define EI_MAG0 0 /* File identification byte 0 index */ +#define ELFMAG0 0x7f /* Magic number byte 0 */ + +#define EI_MAG1 1 /* File identification byte 1 index */ +#define ELFMAG1 'E' /* Magic number byte 1 */ + +#define EI_MAG2 2 /* File identification byte 2 index */ +#define ELFMAG2 'L' /* Magic number byte 2 */ + +#define EI_MAG3 3 /* File identification byte 3 index */ +#define ELFMAG3 'F' /* Magic number byte 3 */ + +/* Conglomeration of the identification bytes, for easy testing as a word. */ +#define ELFMAG "\177ELF" +#define SELFMAG 4 + +#define EI_CLASS 4 /* File class byte index */ +#define ELFCLASSNONE 0 /* Invalid class */ +#define ELFCLASS32 1 /* 32-bit objects */ +#define ELFCLASS64 2 /* 64-bit objects */ +#define ELFCLASSNUM 3 + +#define EI_DATA 5 /* Data encoding byte index */ +#define ELFDATANONE 0 /* Invalid data encoding */ +#define ELFDATA2LSB 1 /* 2's complement, little endian */ +#define ELFDATA2MSB 2 /* 2's complement, big endian */ +#define ELFDATANUM 3 + +#define EI_VERSION 6 /* File version byte index */ + /* Value must be EV_CURRENT */ + +#define EI_OSABI 7 /* OS ABI identification */ +#define ELFOSABI_NONE 0 /* UNIX System V ABI */ +#define ELFOSABI_SYSV 0 /* Alias. */ +#define ELFOSABI_HPUX 1 /* HP-UX */ +#define ELFOSABI_NETBSD 2 /* NetBSD. */ +#define ELFOSABI_GNU 3 /* Object uses GNU ELF extensions. */ +#define ELFOSABI_LINUX ELFOSABI_GNU /* Compatibility alias. */ +#define ELFOSABI_SOLARIS 6 /* Sun Solaris. */ +#define ELFOSABI_AIX 7 /* IBM AIX. */ +#define ELFOSABI_IRIX 8 /* SGI Irix. */ +#define ELFOSABI_FREEBSD 9 /* FreeBSD. */ +#define ELFOSABI_TRU64 10 /* Compaq TRU64 UNIX. */ +#define ELFOSABI_MODESTO 11 /* Novell Modesto. */ +#define ELFOSABI_OPENBSD 12 /* OpenBSD. */ +#define ELFOSABI_ARM_AEABI 64 /* ARM EABI */ +#define ELFOSABI_ARM 97 /* ARM */ +#define ELFOSABI_STANDALONE 255 /* Standalone (embedded) application */ + +#define EI_ABIVERSION 8 /* ABI version */ + +#define EI_PAD 9 /* Byte index of padding bytes */ + +/* Legal values for e_type (object file type). */ + +#define ET_NONE 0 /* No file type */ +#define ET_REL 1 /* Relocatable file */ +#define ET_EXEC 2 /* Executable file */ +#define ET_DYN 3 /* Shared object file */ +#define ET_CORE 4 /* Core file */ +#define ET_NUM 5 /* Number of defined types */ +#define ET_LOOS 0xfe00 /* OS-specific range start */ +#define ET_HIOS 0xfeff /* OS-specific range end */ +#define ET_LOPROC 0xff00 /* Processor-specific range start */ +#define ET_HIPROC 0xffff /* Processor-specific range end */ + +/* Legal values for e_machine (architecture). */ + +#define EM_NONE 0 /* No machine */ +#define EM_M32 1 /* AT&T WE 32100 */ +#define EM_SPARC 2 /* SUN SPARC */ +#define EM_386 3 /* Intel 80386 */ +#define EM_68K 4 /* Motorola m68k family */ +#define EM_88K 5 /* Motorola m88k family */ +#define EM_IAMCU 6 /* Intel MCU */ +#define EM_860 7 /* Intel 80860 */ +#define EM_MIPS 8 /* MIPS R3000 big-endian */ +#define EM_S370 9 /* IBM System/370 */ +#define EM_MIPS_RS3_LE 10 /* MIPS R3000 little-endian */ + /* reserved 11-14 */ +#define EM_PARISC 15 /* HPPA */ + /* reserved 16 */ +#define EM_VPP500 17 /* Fujitsu VPP500 */ +#define EM_SPARC32PLUS 18 /* Sun's "v8plus" */ +#define EM_960 19 /* Intel 80960 */ +#define EM_PPC 20 /* PowerPC */ +#define EM_PPC64 21 /* PowerPC 64-bit */ +#define EM_S390 22 /* IBM S390 */ +#define EM_SPU 23 /* IBM SPU/SPC */ + /* reserved 24-35 */ +#define EM_V800 36 /* NEC V800 series */ +#define EM_FR20 37 /* Fujitsu FR20 */ +#define EM_RH32 38 /* TRW RH-32 */ +#define EM_RCE 39 /* Motorola RCE */ +#define EM_ARM 40 /* ARM */ +#define EM_FAKE_ALPHA 41 /* Digital Alpha */ +#define EM_SH 42 /* Hitachi SH */ +#define EM_SPARCV9 43 /* SPARC v9 64-bit */ +#define EM_TRICORE 44 /* Siemens Tricore */ +#define EM_ARC 45 /* Argonaut RISC Core */ +#define EM_H8_300 46 /* Hitachi H8/300 */ +#define EM_H8_300H 47 /* Hitachi H8/300H */ +#define EM_H8S 48 /* Hitachi H8S */ +#define EM_H8_500 49 /* Hitachi H8/500 */ +#define EM_IA_64 50 /* Intel Merced */ +#define EM_MIPS_X 51 /* Stanford MIPS-X */ +#define EM_COLDFIRE 52 /* Motorola Coldfire */ +#define EM_68HC12 53 /* Motorola M68HC12 */ +#define EM_MMA 54 /* Fujitsu MMA Multimedia Accelerator */ +#define EM_PCP 55 /* Siemens PCP */ +#define EM_NCPU 56 /* Sony nCPU embeeded RISC */ +#define EM_NDR1 57 /* Denso NDR1 microprocessor */ +#define EM_STARCORE 58 /* Motorola Start*Core processor */ +#define EM_ME16 59 /* Toyota ME16 processor */ +#define EM_ST100 60 /* STMicroelectronic ST100 processor */ +#define EM_TINYJ 61 /* Advanced Logic Corp. Tinyj emb.fam */ +#define EM_X86_64 62 /* AMD x86-64 architecture */ +#define EM_PDSP 63 /* Sony DSP Processor */ +#define EM_PDP10 64 /* Digital PDP-10 */ +#define EM_PDP11 65 /* Digital PDP-11 */ +#define EM_FX66 66 /* Siemens FX66 microcontroller */ +#define EM_ST9PLUS 67 /* STMicroelectronics ST9+ 8/16 mc */ +#define EM_ST7 68 /* STmicroelectronics ST7 8 bit mc */ +#define EM_68HC16 69 /* Motorola MC68HC16 microcontroller */ +#define EM_68HC11 70 /* Motorola MC68HC11 microcontroller */ +#define EM_68HC08 71 /* Motorola MC68HC08 microcontroller */ +#define EM_68HC05 72 /* Motorola MC68HC05 microcontroller */ +#define EM_SVX 73 /* Silicon Graphics SVx */ +#define EM_ST19 74 /* STMicroelectronics ST19 8 bit mc */ +#define EM_VAX 75 /* Digital VAX */ +#define EM_CRIS 76 /* Axis Communications 32-bit emb.proc */ +#define EM_JAVELIN 77 /* Infineon Technologies 32-bit emb.proc */ +#define EM_FIREPATH 78 /* Element 14 64-bit DSP Processor */ +#define EM_ZSP 79 /* LSI Logic 16-bit DSP Processor */ +#define EM_MMIX 80 /* Donald Knuth's educational 64-bit proc */ +#define EM_HUANY 81 /* Harvard University machine-independent object files */ +#define EM_PRISM 82 /* SiTera Prism */ +#define EM_AVR 83 /* Atmel AVR 8-bit microcontroller */ +#define EM_FR30 84 /* Fujitsu FR30 */ +#define EM_D10V 85 /* Mitsubishi D10V */ +#define EM_D30V 86 /* Mitsubishi D30V */ +#define EM_V850 87 /* NEC v850 */ +#define EM_M32R 88 /* Mitsubishi M32R */ +#define EM_MN10300 89 /* Matsushita MN10300 */ +#define EM_MN10200 90 /* Matsushita MN10200 */ +#define EM_PJ 91 /* picoJava */ +#define EM_OPENRISC 92 /* OpenRISC 32-bit embedded processor */ +#define EM_ARC_COMPACT 93 /* ARC International ARCompact */ +#define EM_XTENSA 94 /* Tensilica Xtensa Architecture */ +#define EM_VIDEOCORE 95 /* Alphamosaic VideoCore */ +#define EM_TMM_GPP 96 /* Thompson Multimedia General Purpose Proc */ +#define EM_NS32K 97 /* National Semi. 32000 */ +#define EM_TPC 98 /* Tenor Network TPC */ +#define EM_SNP1K 99 /* Trebia SNP 1000 */ +#define EM_ST200 100 /* STMicroelectronics ST200 */ +#define EM_IP2K 101 /* Ubicom IP2xxx */ +#define EM_MAX 102 /* MAX processor */ +#define EM_CR 103 /* National Semi. CompactRISC */ +#define EM_F2MC16 104 /* Fujitsu F2MC16 */ +#define EM_MSP430 105 /* Texas Instruments msp430 */ +#define EM_BLACKFIN 106 /* Analog Devices Blackfin DSP */ +#define EM_SE_C33 107 /* Seiko Epson S1C33 family */ +#define EM_SEP 108 /* Sharp embedded microprocessor */ +#define EM_ARCA 109 /* Arca RISC */ +#define EM_UNICORE 110 /* PKU-Unity & MPRC Peking Uni. mc series */ +#define EM_EXCESS 111 /* eXcess configurable cpu */ +#define EM_DXP 112 /* Icera Semi. Deep Execution Processor */ +#define EM_ALTERA_NIOS2 113 /* Altera Nios II */ +#define EM_CRX 114 /* National Semi. CompactRISC CRX */ +#define EM_XGATE 115 /* Motorola XGATE */ +#define EM_C166 116 /* Infineon C16x/XC16x */ +#define EM_M16C 117 /* Renesas M16C */ +#define EM_DSPIC30F 118 /* Microchip Technology dsPIC30F */ +#define EM_CE 119 /* Freescale Communication Engine RISC */ +#define EM_M32C 120 /* Renesas M32C */ + /* reserved 121-130 */ +#define EM_TSK3000 131 /* Altium TSK3000 */ +#define EM_RS08 132 /* Freescale RS08 */ +#define EM_SHARC 133 /* Analog Devices SHARC family */ +#define EM_ECOG2 134 /* Cyan Technology eCOG2 */ +#define EM_SCORE7 135 /* Sunplus S+core7 RISC */ +#define EM_DSP24 136 /* New Japan Radio (NJR) 24-bit DSP */ +#define EM_VIDEOCORE3 137 /* Broadcom VideoCore III */ +#define EM_LATTICEMICO32 138 /* RISC for Lattice FPGA */ +#define EM_SE_C17 139 /* Seiko Epson C17 */ +#define EM_TI_C6000 140 /* Texas Instruments TMS320C6000 DSP */ +#define EM_TI_C2000 141 /* Texas Instruments TMS320C2000 DSP */ +#define EM_TI_C5500 142 /* Texas Instruments TMS320C55x DSP */ +#define EM_TI_ARP32 143 /* Texas Instruments App. Specific RISC */ +#define EM_TI_PRU 144 /* Texas Instruments Prog. Realtime Unit */ + /* reserved 145-159 */ +#define EM_MMDSP_PLUS 160 /* STMicroelectronics 64bit VLIW DSP */ +#define EM_CYPRESS_M8C 161 /* Cypress M8C */ +#define EM_R32C 162 /* Renesas R32C */ +#define EM_TRIMEDIA 163 /* NXP Semi. TriMedia */ +#define EM_QDSP6 164 /* QUALCOMM DSP6 */ +#define EM_8051 165 /* Intel 8051 and variants */ +#define EM_STXP7X 166 /* STMicroelectronics STxP7x */ +#define EM_NDS32 167 /* Andes Tech. compact code emb. RISC */ +#define EM_ECOG1X 168 /* Cyan Technology eCOG1X */ +#define EM_MAXQ30 169 /* Dallas Semi. MAXQ30 mc */ +#define EM_XIMO16 170 /* New Japan Radio (NJR) 16-bit DSP */ +#define EM_MANIK 171 /* M2000 Reconfigurable RISC */ +#define EM_CRAYNV2 172 /* Cray NV2 vector architecture */ +#define EM_RX 173 /* Renesas RX */ +#define EM_METAG 174 /* Imagination Tech. META */ +#define EM_MCST_ELBRUS 175 /* MCST Elbrus */ +#define EM_ECOG16 176 /* Cyan Technology eCOG16 */ +#define EM_CR16 177 /* National Semi. CompactRISC CR16 */ +#define EM_ETPU 178 /* Freescale Extended Time Processing Unit */ +#define EM_SLE9X 179 /* Infineon Tech. SLE9X */ +#define EM_L10M 180 /* Intel L10M */ +#define EM_K10M 181 /* Intel K10M */ + /* reserved 182 */ +#define EM_AARCH64 183 /* ARM AARCH64 */ + /* reserved 184 */ +#define EM_AVR32 185 /* Amtel 32-bit microprocessor */ +#define EM_STM8 186 /* STMicroelectronics STM8 */ +#define EM_TILE64 187 /* Tileta TILE64 */ +#define EM_TILEPRO 188 /* Tilera TILEPro */ +#define EM_MICROBLAZE 189 /* Xilinx MicroBlaze */ +#define EM_CUDA 190 /* NVIDIA CUDA */ +#define EM_TILEGX 191 /* Tilera TILE-Gx */ +#define EM_CLOUDSHIELD 192 /* CloudShield */ +#define EM_COREA_1ST 193 /* KIPO-KAIST Core-A 1st gen. */ +#define EM_COREA_2ND 194 /* KIPO-KAIST Core-A 2nd gen. */ +#define EM_ARC_COMPACT2 195 /* Synopsys ARCompact V2 */ +#define EM_OPEN8 196 /* Open8 RISC */ +#define EM_RL78 197 /* Renesas RL78 */ +#define EM_VIDEOCORE5 198 /* Broadcom VideoCore V */ +#define EM_78KOR 199 /* Renesas 78KOR */ +#define EM_56800EX 200 /* Freescale 56800EX DSC */ +#define EM_BA1 201 /* Beyond BA1 */ +#define EM_BA2 202 /* Beyond BA2 */ +#define EM_XCORE 203 /* XMOS xCORE */ +#define EM_MCHP_PIC 204 /* Microchip 8-bit PIC(r) */ + /* reserved 205-209 */ +#define EM_KM32 210 /* KM211 KM32 */ +#define EM_KMX32 211 /* KM211 KMX32 */ +#define EM_EMX16 212 /* KM211 KMX16 */ +#define EM_EMX8 213 /* KM211 KMX8 */ +#define EM_KVARC 214 /* KM211 KVARC */ +#define EM_CDP 215 /* Paneve CDP */ +#define EM_COGE 216 /* Cognitive Smart Memory Processor */ +#define EM_COOL 217 /* Bluechip CoolEngine */ +#define EM_NORC 218 /* Nanoradio Optimized RISC */ +#define EM_CSR_KALIMBA 219 /* CSR Kalimba */ +#define EM_Z80 220 /* Zilog Z80 */ +#define EM_VISIUM 221 /* Controls and Data Services VISIUMcore */ +#define EM_FT32 222 /* FTDI Chip FT32 */ +#define EM_MOXIE 223 /* Moxie processor */ +#define EM_AMDGPU 224 /* AMD GPU */ + /* reserved 225-242 */ +#define EM_RISCV 243 /* RISC-V */ + +#define EM_BPF 247 /* Linux BPF -- in-kernel virtual machine */ + +#define EM_NUM 248 + +/* Old spellings/synonyms. */ + +#define EM_ARC_A5 EM_ARC_COMPACT + +/* If it is necessary to assign new unofficial EM_* values, please + pick large random numbers (0x8523, 0xa7f2, etc.) to minimize the + chances of collision with official or non-GNU unofficial values. */ + +#define EM_ALPHA 0x9026 + +/* Legal values for e_version (version). */ + +#define EV_NONE 0 /* Invalid ELF version */ +#define EV_CURRENT 1 /* Current version */ +#define EV_NUM 2 + +/* Section header. */ + +typedef struct +{ + Elf32_Word sh_name; /* Section name (string tbl index) */ + Elf32_Word sh_type; /* Section type */ + Elf32_Word sh_flags; /* Section flags */ + Elf32_Addr sh_addr; /* Section virtual addr at execution */ + Elf32_Off sh_offset; /* Section file offset */ + Elf32_Word sh_size; /* Section size in bytes */ + Elf32_Word sh_link; /* Link to another section */ + Elf32_Word sh_info; /* Additional section information */ + Elf32_Word sh_addralign; /* Section alignment */ + Elf32_Word sh_entsize; /* Entry size if section holds table */ +} Elf32_Shdr; + +typedef struct +{ + Elf64_Word sh_name; /* Section name (string tbl index) */ + Elf64_Word sh_type; /* Section type */ + Elf64_Xword sh_flags; /* Section flags */ + Elf64_Addr sh_addr; /* Section virtual addr at execution */ + Elf64_Off sh_offset; /* Section file offset */ + Elf64_Xword sh_size; /* Section size in bytes */ + Elf64_Word sh_link; /* Link to another section */ + Elf64_Word sh_info; /* Additional section information */ + Elf64_Xword sh_addralign; /* Section alignment */ + Elf64_Xword sh_entsize; /* Entry size if section holds table */ +} Elf64_Shdr; + +/* Special section indices. */ + +#define SHN_UNDEF 0 /* Undefined section */ +#define SHN_LORESERVE 0xff00 /* Start of reserved indices */ +#define SHN_LOPROC 0xff00 /* Start of processor-specific */ +#define SHN_BEFORE 0xff00 /* Order section before all others + (Solaris). */ +#define SHN_AFTER 0xff01 /* Order section after all others + (Solaris). */ +#define SHN_HIPROC 0xff1f /* End of processor-specific */ +#define SHN_LOOS 0xff20 /* Start of OS-specific */ +#define SHN_HIOS 0xff3f /* End of OS-specific */ +#define SHN_ABS 0xfff1 /* Associated symbol is absolute */ +#define SHN_COMMON 0xfff2 /* Associated symbol is common */ +#define SHN_XINDEX 0xffff /* Index is in extra table. */ +#define SHN_HIRESERVE 0xffff /* End of reserved indices */ + +/* Legal values for sh_type (section type). */ + +#define SHT_NULL 0 /* Section header table entry unused */ +#define SHT_PROGBITS 1 /* Program data */ +#define SHT_SYMTAB 2 /* Symbol table */ +#define SHT_STRTAB 3 /* String table */ +#define SHT_RELA 4 /* Relocation entries with addends */ +#define SHT_HASH 5 /* Symbol hash table */ +#define SHT_DYNAMIC 6 /* Dynamic linking information */ +#define SHT_NOTE 7 /* Notes */ +#define SHT_NOBITS 8 /* Program space with no data (bss) */ +#define SHT_REL 9 /* Relocation entries, no addends */ +#define SHT_SHLIB 10 /* Reserved */ +#define SHT_DYNSYM 11 /* Dynamic linker symbol table */ +#define SHT_INIT_ARRAY 14 /* Array of constructors */ +#define SHT_FINI_ARRAY 15 /* Array of destructors */ +#define SHT_PREINIT_ARRAY 16 /* Array of pre-constructors */ +#define SHT_GROUP 17 /* Section group */ +#define SHT_SYMTAB_SHNDX 18 /* Extended section indeces */ +#define SHT_NUM 19 /* Number of defined types. */ +#define SHT_LOOS 0x60000000 /* Start OS-specific. */ +#define SHT_GNU_ATTRIBUTES 0x6ffffff5 /* Object attributes. */ +#define SHT_GNU_HASH 0x6ffffff6 /* GNU-style hash table. */ +#define SHT_GNU_LIBLIST 0x6ffffff7 /* Prelink library list */ +#define SHT_CHECKSUM 0x6ffffff8 /* Checksum for DSO content. */ +#define SHT_LOSUNW 0x6ffffffa /* Sun-specific low bound. */ +#define SHT_SUNW_move 0x6ffffffa +#define SHT_SUNW_COMDAT 0x6ffffffb +#define SHT_SUNW_syminfo 0x6ffffffc +#define SHT_GNU_verdef 0x6ffffffd /* Version definition section. */ +#define SHT_GNU_verneed 0x6ffffffe /* Version needs section. */ +#define SHT_GNU_versym 0x6fffffff /* Version symbol table. */ +#define SHT_HISUNW 0x6fffffff /* Sun-specific high bound. */ +#define SHT_HIOS 0x6fffffff /* End OS-specific type */ +#define SHT_LOPROC 0x70000000 /* Start of processor-specific */ +#define SHT_HIPROC 0x7fffffff /* End of processor-specific */ +#define SHT_LOUSER 0x80000000 /* Start of application-specific */ +#define SHT_HIUSER 0x8fffffff /* End of application-specific */ + +/* Legal values for sh_flags (section flags). */ + +#define SHF_WRITE (1 << 0) /* Writable */ +#define SHF_ALLOC (1 << 1) /* Occupies memory during execution */ +#define SHF_EXECINSTR (1 << 2) /* Executable */ +#define SHF_MERGE (1 << 4) /* Might be merged */ +#define SHF_STRINGS (1 << 5) /* Contains nul-terminated strings */ +#define SHF_INFO_LINK (1 << 6) /* `sh_info' contains SHT index */ +#define SHF_LINK_ORDER (1 << 7) /* Preserve order after combining */ +#define SHF_OS_NONCONFORMING (1 << 8) /* Non-standard OS specific handling + required */ +#define SHF_GROUP (1 << 9) /* Section is member of a group. */ +#define SHF_TLS (1 << 10) /* Section hold thread-local data. */ +#define SHF_COMPRESSED (1 << 11) /* Section with compressed data. */ +#define SHF_MASKOS 0x0ff00000 /* OS-specific. */ +#define SHF_MASKPROC 0xf0000000 /* Processor-specific */ +#define SHF_ORDERED (1 << 30) /* Special ordering requirement + (Solaris). */ +#define SHF_EXCLUDE (1U << 31) /* Section is excluded unless + referenced or allocated (Solaris).*/ + +/* Section compression header. Used when SHF_COMPRESSED is set. */ + +typedef struct +{ + Elf32_Word ch_type; /* Compression format. */ + Elf32_Word ch_size; /* Uncompressed data size. */ + Elf32_Word ch_addralign; /* Uncompressed data alignment. */ +} Elf32_Chdr; + +typedef struct +{ + Elf64_Word ch_type; /* Compression format. */ + Elf64_Word ch_reserved; + Elf64_Xword ch_size; /* Uncompressed data size. */ + Elf64_Xword ch_addralign; /* Uncompressed data alignment. */ +} Elf64_Chdr; + +/* Legal values for ch_type (compression algorithm). */ +#define ELFCOMPRESS_ZLIB 1 /* ZLIB/DEFLATE algorithm. */ +#define ELFCOMPRESS_LOOS 0x60000000 /* Start of OS-specific. */ +#define ELFCOMPRESS_HIOS 0x6fffffff /* End of OS-specific. */ +#define ELFCOMPRESS_LOPROC 0x70000000 /* Start of processor-specific. */ +#define ELFCOMPRESS_HIPROC 0x7fffffff /* End of processor-specific. */ + +/* Section group handling. */ +#define GRP_COMDAT 0x1 /* Mark group as COMDAT. */ + +/* Symbol table entry. */ + +typedef struct +{ + Elf32_Word st_name; /* Symbol name (string tbl index) */ + Elf32_Addr st_value; /* Symbol value */ + Elf32_Word st_size; /* Symbol size */ + unsigned char st_info; /* Symbol type and binding */ + unsigned char st_other; /* Symbol visibility */ + Elf32_Section st_shndx; /* Section index */ +} Elf32_Sym; + +typedef struct +{ + Elf64_Word st_name; /* Symbol name (string tbl index) */ + unsigned char st_info; /* Symbol type and binding */ + unsigned char st_other; /* Symbol visibility */ + Elf64_Section st_shndx; /* Section index */ + Elf64_Addr st_value; /* Symbol value */ + Elf64_Xword st_size; /* Symbol size */ +} Elf64_Sym; + +/* The syminfo section if available contains additional information about + every dynamic symbol. */ + +typedef struct +{ + Elf32_Half si_boundto; /* Direct bindings, symbol bound to */ + Elf32_Half si_flags; /* Per symbol flags */ +} Elf32_Syminfo; + +typedef struct +{ + Elf64_Half si_boundto; /* Direct bindings, symbol bound to */ + Elf64_Half si_flags; /* Per symbol flags */ +} Elf64_Syminfo; + +/* Possible values for si_boundto. */ +#define SYMINFO_BT_SELF 0xffff /* Symbol bound to self */ +#define SYMINFO_BT_PARENT 0xfffe /* Symbol bound to parent */ +#define SYMINFO_BT_LOWRESERVE 0xff00 /* Beginning of reserved entries */ + +/* Possible bitmasks for si_flags. */ +#define SYMINFO_FLG_DIRECT 0x0001 /* Direct bound symbol */ +#define SYMINFO_FLG_PASSTHRU 0x0002 /* Pass-thru symbol for translator */ +#define SYMINFO_FLG_COPY 0x0004 /* Symbol is a copy-reloc */ +#define SYMINFO_FLG_LAZYLOAD 0x0008 /* Symbol bound to object to be lazy + loaded */ +/* Syminfo version values. */ +#define SYMINFO_NONE 0 +#define SYMINFO_CURRENT 1 +#define SYMINFO_NUM 2 + + +/* How to extract and insert information held in the st_info field. */ + +#define ELF32_ST_BIND(val) (((unsigned char) (val)) >> 4) +#define ELF32_ST_TYPE(val) ((val) & 0xf) +#define ELF32_ST_INFO(bind, type) (((bind) << 4) + ((type) & 0xf)) + +/* Both Elf32_Sym and Elf64_Sym use the same one-byte st_info field. */ +#define ELF64_ST_BIND(val) ELF32_ST_BIND (val) +#define ELF64_ST_TYPE(val) ELF32_ST_TYPE (val) +#define ELF64_ST_INFO(bind, type) ELF32_ST_INFO ((bind), (type)) + +/* Legal values for ST_BIND subfield of st_info (symbol binding). */ + +#define STB_LOCAL 0 /* Local symbol */ +#define STB_GLOBAL 1 /* Global symbol */ +#define STB_WEAK 2 /* Weak symbol */ +#define STB_NUM 3 /* Number of defined types. */ +#define STB_LOOS 10 /* Start of OS-specific */ +#define STB_GNU_UNIQUE 10 /* Unique symbol. */ +#define STB_HIOS 12 /* End of OS-specific */ +#define STB_LOPROC 13 /* Start of processor-specific */ +#define STB_HIPROC 15 /* End of processor-specific */ + +/* Legal values for ST_TYPE subfield of st_info (symbol type). */ + +#define STT_NOTYPE 0 /* Symbol type is unspecified */ +#define STT_OBJECT 1 /* Symbol is a data object */ +#define STT_FUNC 2 /* Symbol is a code object */ +#define STT_SECTION 3 /* Symbol associated with a section */ +#define STT_FILE 4 /* Symbol's name is file name */ +#define STT_COMMON 5 /* Symbol is a common data object */ +#define STT_TLS 6 /* Symbol is thread-local data object*/ +#define STT_NUM 7 /* Number of defined types. */ +#define STT_LOOS 10 /* Start of OS-specific */ +#define STT_GNU_IFUNC 10 /* Symbol is indirect code object */ +#define STT_HIOS 12 /* End of OS-specific */ +#define STT_LOPROC 13 /* Start of processor-specific */ +#define STT_HIPROC 15 /* End of processor-specific */ + + +/* Symbol table indices are found in the hash buckets and chain table + of a symbol hash table section. This special index value indicates + the end of a chain, meaning no further symbols are found in that bucket. */ + +#define STN_UNDEF 0 /* End of a chain. */ + + +/* How to extract and insert information held in the st_other field. */ + +#define ELF32_ST_VISIBILITY(o) ((o) & 0x03) + +/* For ELF64 the definitions are the same. */ +#define ELF64_ST_VISIBILITY(o) ELF32_ST_VISIBILITY (o) + +/* Symbol visibility specification encoded in the st_other field. */ +#define STV_DEFAULT 0 /* Default symbol visibility rules */ +#define STV_INTERNAL 1 /* Processor specific hidden class */ +#define STV_HIDDEN 2 /* Sym unavailable in other modules */ +#define STV_PROTECTED 3 /* Not preemptible, not exported */ + + +/* Relocation table entry without addend (in section of type SHT_REL). */ + +typedef struct +{ + Elf32_Addr r_offset; /* Address */ + Elf32_Word r_info; /* Relocation type and symbol index */ +} Elf32_Rel; + +/* I have seen two different definitions of the Elf64_Rel and + Elf64_Rela structures, so we'll leave them out until Novell (or + whoever) gets their act together. */ +/* The following, at least, is used on Sparc v9, MIPS, and Alpha. */ + +typedef struct +{ + Elf64_Addr r_offset; /* Address */ + Elf64_Xword r_info; /* Relocation type and symbol index */ +} Elf64_Rel; + +/* Relocation table entry with addend (in section of type SHT_RELA). */ + +typedef struct +{ + Elf32_Addr r_offset; /* Address */ + Elf32_Word r_info; /* Relocation type and symbol index */ + Elf32_Sword r_addend; /* Addend */ +} Elf32_Rela; + +typedef struct +{ + Elf64_Addr r_offset; /* Address */ + Elf64_Xword r_info; /* Relocation type and symbol index */ + Elf64_Sxword r_addend; /* Addend */ +} Elf64_Rela; + +/* How to extract and insert information held in the r_info field. */ + +#define ELF32_R_SYM(val) ((val) >> 8) +#define ELF32_R_TYPE(val) ((val) & 0xff) +#define ELF32_R_INFO(sym, type) (((sym) << 8) + ((type) & 0xff)) + +#define ELF64_R_SYM(i) ((i) >> 32) +#define ELF64_R_TYPE(i) ((i) & 0xffffffff) +#define ELF64_R_INFO(sym,type) ((((Elf64_Xword) (sym)) << 32) + (type)) + +/* Program segment header. */ + +typedef struct +{ + Elf32_Word p_type; /* Segment type */ + Elf32_Off p_offset; /* Segment file offset */ + Elf32_Addr p_vaddr; /* Segment virtual address */ + Elf32_Addr p_paddr; /* Segment physical address */ + Elf32_Word p_filesz; /* Segment size in file */ + Elf32_Word p_memsz; /* Segment size in memory */ + Elf32_Word p_flags; /* Segment flags */ + Elf32_Word p_align; /* Segment alignment */ +} Elf32_Phdr; + +typedef struct +{ + Elf64_Word p_type; /* Segment type */ + Elf64_Word p_flags; /* Segment flags */ + Elf64_Off p_offset; /* Segment file offset */ + Elf64_Addr p_vaddr; /* Segment virtual address */ + Elf64_Addr p_paddr; /* Segment physical address */ + Elf64_Xword p_filesz; /* Segment size in file */ + Elf64_Xword p_memsz; /* Segment size in memory */ + Elf64_Xword p_align; /* Segment alignment */ +} Elf64_Phdr; + +/* Special value for e_phnum. This indicates that the real number of + program headers is too large to fit into e_phnum. Instead the real + value is in the field sh_info of section 0. */ + +#define PN_XNUM 0xffff + +/* Legal values for p_type (segment type). */ + +#define PT_NULL 0 /* Program header table entry unused */ +#define PT_LOAD 1 /* Loadable program segment */ +#define PT_DYNAMIC 2 /* Dynamic linking information */ +#define PT_INTERP 3 /* Program interpreter */ +#define PT_NOTE 4 /* Auxiliary information */ +#define PT_SHLIB 5 /* Reserved */ +#define PT_PHDR 6 /* Entry for header table itself */ +#define PT_TLS 7 /* Thread-local storage segment */ +#define PT_NUM 8 /* Number of defined types */ +#define PT_LOOS 0x60000000 /* Start of OS-specific */ +#define PT_GNU_EH_FRAME 0x6474e550 /* GCC .eh_frame_hdr segment */ +#define PT_GNU_STACK 0x6474e551 /* Indicates stack executability */ +#define PT_GNU_RELRO 0x6474e552 /* Read-only after relocation */ +#define PT_LOSUNW 0x6ffffffa +#define PT_SUNWBSS 0x6ffffffa /* Sun Specific segment */ +#define PT_SUNWSTACK 0x6ffffffb /* Stack segment */ +#define PT_HISUNW 0x6fffffff +#define PT_HIOS 0x6fffffff /* End of OS-specific */ +#define PT_LOPROC 0x70000000 /* Start of processor-specific */ +#define PT_HIPROC 0x7fffffff /* End of processor-specific */ + +/* Legal values for p_flags (segment flags). */ + +#define PF_X (1 << 0) /* Segment is executable */ +#define PF_W (1 << 1) /* Segment is writable */ +#define PF_R (1 << 2) /* Segment is readable */ +#define PF_MASKOS 0x0ff00000 /* OS-specific */ +#define PF_MASKPROC 0xf0000000 /* Processor-specific */ + +/* Legal values for note segment descriptor types for core files. */ + +#define NT_PRSTATUS 1 /* Contains copy of prstatus struct */ +#define NT_FPREGSET 2 /* Contains copy of fpregset struct */ +#define NT_PRPSINFO 3 /* Contains copy of prpsinfo struct */ +#define NT_PRXREG 4 /* Contains copy of prxregset struct */ +#define NT_TASKSTRUCT 4 /* Contains copy of task structure */ +#define NT_PLATFORM 5 /* String from sysinfo(SI_PLATFORM) */ +#define NT_AUXV 6 /* Contains copy of auxv array */ +#define NT_GWINDOWS 7 /* Contains copy of gwindows struct */ +#define NT_ASRS 8 /* Contains copy of asrset struct */ +#define NT_PSTATUS 10 /* Contains copy of pstatus struct */ +#define NT_PSINFO 13 /* Contains copy of psinfo struct */ +#define NT_PRCRED 14 /* Contains copy of prcred struct */ +#define NT_UTSNAME 15 /* Contains copy of utsname struct */ +#define NT_LWPSTATUS 16 /* Contains copy of lwpstatus struct */ +#define NT_LWPSINFO 17 /* Contains copy of lwpinfo struct */ +#define NT_PRFPXREG 20 /* Contains copy of fprxregset struct */ +#define NT_SIGINFO 0x53494749 /* Contains copy of siginfo_t, + size might increase */ +#define NT_FILE 0x46494c45 /* Contains information about mapped + files */ +#define NT_PRXFPREG 0x46e62b7f /* Contains copy of user_fxsr_struct */ +#define NT_PPC_VMX 0x100 /* PowerPC Altivec/VMX registers */ +#define NT_PPC_SPE 0x101 /* PowerPC SPE/EVR registers */ +#define NT_PPC_VSX 0x102 /* PowerPC VSX registers */ +#define NT_386_TLS 0x200 /* i386 TLS slots (struct user_desc) */ +#define NT_386_IOPERM 0x201 /* x86 io permission bitmap (1=deny) */ +#define NT_X86_XSTATE 0x202 /* x86 extended state using xsave */ +#define NT_S390_HIGH_GPRS 0x300 /* s390 upper register halves */ +#define NT_S390_TIMER 0x301 /* s390 timer register */ +#define NT_S390_TODCMP 0x302 /* s390 TOD clock comparator register */ +#define NT_S390_TODPREG 0x303 /* s390 TOD programmable register */ +#define NT_S390_CTRS 0x304 /* s390 control registers */ +#define NT_S390_PREFIX 0x305 /* s390 prefix register */ +#define NT_S390_LAST_BREAK 0x306 /* s390 breaking event address */ +#define NT_S390_SYSTEM_CALL 0x307 /* s390 system call restart data */ +#define NT_S390_TDB 0x308 /* s390 transaction diagnostic block */ +#define NT_ARM_VFP 0x400 /* ARM VFP/NEON registers */ +#define NT_ARM_TLS 0x401 /* ARM TLS register */ +#define NT_ARM_HW_BREAK 0x402 /* ARM hardware breakpoint registers */ +#define NT_ARM_HW_WATCH 0x403 /* ARM hardware watchpoint registers */ +#define NT_ARM_SYSTEM_CALL 0x404 /* ARM system call number */ + +/* Legal values for the note segment descriptor types for object files. */ + +#define NT_VERSION 1 /* Contains a version string. */ + + +/* Dynamic section entry. */ + +typedef struct +{ + Elf32_Sword d_tag; /* Dynamic entry type */ + union + { + Elf32_Word d_val; /* Integer value */ + Elf32_Addr d_ptr; /* Address value */ + } d_un; +} Elf32_Dyn; + +typedef struct +{ + Elf64_Sxword d_tag; /* Dynamic entry type */ + union + { + Elf64_Xword d_val; /* Integer value */ + Elf64_Addr d_ptr; /* Address value */ + } d_un; +} Elf64_Dyn; + +/* Legal values for d_tag (dynamic entry type). */ + +#define DT_NULL 0 /* Marks end of dynamic section */ +#define DT_NEEDED 1 /* Name of needed library */ +#define DT_PLTRELSZ 2 /* Size in bytes of PLT relocs */ +#define DT_PLTGOT 3 /* Processor defined value */ +#define DT_HASH 4 /* Address of symbol hash table */ +#define DT_STRTAB 5 /* Address of string table */ +#define DT_SYMTAB 6 /* Address of symbol table */ +#define DT_RELA 7 /* Address of Rela relocs */ +#define DT_RELASZ 8 /* Total size of Rela relocs */ +#define DT_RELAENT 9 /* Size of one Rela reloc */ +#define DT_STRSZ 10 /* Size of string table */ +#define DT_SYMENT 11 /* Size of one symbol table entry */ +#define DT_INIT 12 /* Address of init function */ +#define DT_FINI 13 /* Address of termination function */ +#define DT_SONAME 14 /* Name of shared object */ +#define DT_RPATH 15 /* Library search path (deprecated) */ +#define DT_SYMBOLIC 16 /* Start symbol search here */ +#define DT_REL 17 /* Address of Rel relocs */ +#define DT_RELSZ 18 /* Total size of Rel relocs */ +#define DT_RELENT 19 /* Size of one Rel reloc */ +#define DT_PLTREL 20 /* Type of reloc in PLT */ +#define DT_DEBUG 21 /* For debugging; unspecified */ +#define DT_TEXTREL 22 /* Reloc might modify .text */ +#define DT_JMPREL 23 /* Address of PLT relocs */ +#define DT_BIND_NOW 24 /* Process relocations of object */ +#define DT_INIT_ARRAY 25 /* Array with addresses of init fct */ +#define DT_FINI_ARRAY 26 /* Array with addresses of fini fct */ +#define DT_INIT_ARRAYSZ 27 /* Size in bytes of DT_INIT_ARRAY */ +#define DT_FINI_ARRAYSZ 28 /* Size in bytes of DT_FINI_ARRAY */ +#define DT_RUNPATH 29 /* Library search path */ +#define DT_FLAGS 30 /* Flags for the object being loaded */ +#define DT_ENCODING 32 /* Start of encoded range */ +#define DT_PREINIT_ARRAY 32 /* Array with addresses of preinit fct*/ +#define DT_PREINIT_ARRAYSZ 33 /* size in bytes of DT_PREINIT_ARRAY */ +#define DT_NUM 34 /* Number used */ +#define DT_LOOS 0x6000000d /* Start of OS-specific */ +#define DT_HIOS 0x6ffff000 /* End of OS-specific */ +#define DT_LOPROC 0x70000000 /* Start of processor-specific */ +#define DT_HIPROC 0x7fffffff /* End of processor-specific */ +#define DT_PROCNUM DT_MIPS_NUM /* Most used by any processor */ + +/* DT_* entries which fall between DT_VALRNGHI & DT_VALRNGLO use the + Dyn.d_un.d_val field of the Elf*_Dyn structure. This follows Sun's + approach. */ +#define DT_VALRNGLO 0x6ffffd00 +#define DT_GNU_PRELINKED 0x6ffffdf5 /* Prelinking timestamp */ +#define DT_GNU_CONFLICTSZ 0x6ffffdf6 /* Size of conflict section */ +#define DT_GNU_LIBLISTSZ 0x6ffffdf7 /* Size of library list */ +#define DT_CHECKSUM 0x6ffffdf8 +#define DT_PLTPADSZ 0x6ffffdf9 +#define DT_MOVEENT 0x6ffffdfa +#define DT_MOVESZ 0x6ffffdfb +#define DT_FEATURE_1 0x6ffffdfc /* Feature selection (DTF_*). */ +#define DT_POSFLAG_1 0x6ffffdfd /* Flags for DT_* entries, effecting + the following DT_* entry. */ +#define DT_SYMINSZ 0x6ffffdfe /* Size of syminfo table (in bytes) */ +#define DT_SYMINENT 0x6ffffdff /* Entry size of syminfo */ +#define DT_VALRNGHI 0x6ffffdff +#define DT_VALTAGIDX(tag) (DT_VALRNGHI - (tag)) /* Reverse order! */ +#define DT_VALNUM 12 + +/* DT_* entries which fall between DT_ADDRRNGHI & DT_ADDRRNGLO use the + Dyn.d_un.d_ptr field of the Elf*_Dyn structure. + + If any adjustment is made to the ELF object after it has been + built these entries will need to be adjusted. */ +#define DT_ADDRRNGLO 0x6ffffe00 +#define DT_GNU_HASH 0x6ffffef5 /* GNU-style hash table. */ +#define DT_TLSDESC_PLT 0x6ffffef6 +#define DT_TLSDESC_GOT 0x6ffffef7 +#define DT_GNU_CONFLICT 0x6ffffef8 /* Start of conflict section */ +#define DT_GNU_LIBLIST 0x6ffffef9 /* Library list */ +#define DT_CONFIG 0x6ffffefa /* Configuration information. */ +#define DT_DEPAUDIT 0x6ffffefb /* Dependency auditing. */ +#define DT_AUDIT 0x6ffffefc /* Object auditing. */ +#define DT_PLTPAD 0x6ffffefd /* PLT padding. */ +#define DT_MOVETAB 0x6ffffefe /* Move table. */ +#define DT_SYMINFO 0x6ffffeff /* Syminfo table. */ +#define DT_ADDRRNGHI 0x6ffffeff +#define DT_ADDRTAGIDX(tag) (DT_ADDRRNGHI - (tag)) /* Reverse order! */ +#define DT_ADDRNUM 11 + +/* The versioning entry types. The next are defined as part of the + GNU extension. */ +#define DT_VERSYM 0x6ffffff0 + +#define DT_RELACOUNT 0x6ffffff9 +#define DT_RELCOUNT 0x6ffffffa + +/* These were chosen by Sun. */ +#define DT_FLAGS_1 0x6ffffffb /* State flags, see DF_1_* below. */ +#define DT_VERDEF 0x6ffffffc /* Address of version definition + table */ +#define DT_VERDEFNUM 0x6ffffffd /* Number of version definitions */ +#define DT_VERNEED 0x6ffffffe /* Address of table with needed + versions */ +#define DT_VERNEEDNUM 0x6fffffff /* Number of needed versions */ +#define DT_VERSIONTAGIDX(tag) (DT_VERNEEDNUM - (tag)) /* Reverse order! */ +#define DT_VERSIONTAGNUM 16 + +/* Sun added these machine-independent extensions in the "processor-specific" + range. Be compatible. */ +#define DT_AUXILIARY 0x7ffffffd /* Shared object to load before self */ +#define DT_FILTER 0x7fffffff /* Shared object to get values from */ +#define DT_EXTRATAGIDX(tag) ((Elf32_Word)-((Elf32_Sword) (tag) <<1>>1)-1) +#define DT_EXTRANUM 3 + +/* Values of `d_un.d_val' in the DT_FLAGS entry. */ +#define DF_ORIGIN 0x00000001 /* Object may use DF_ORIGIN */ +#define DF_SYMBOLIC 0x00000002 /* Symbol resolutions starts here */ +#define DF_TEXTREL 0x00000004 /* Object contains text relocations */ +#define DF_BIND_NOW 0x00000008 /* No lazy binding for this object */ +#define DF_STATIC_TLS 0x00000010 /* Module uses the static TLS model */ + +/* State flags selectable in the `d_un.d_val' element of the DT_FLAGS_1 + entry in the dynamic section. */ +#define DF_1_NOW 0x00000001 /* Set RTLD_NOW for this object. */ +#define DF_1_GLOBAL 0x00000002 /* Set RTLD_GLOBAL for this object. */ +#define DF_1_GROUP 0x00000004 /* Set RTLD_GROUP for this object. */ +#define DF_1_NODELETE 0x00000008 /* Set RTLD_NODELETE for this object.*/ +#define DF_1_LOADFLTR 0x00000010 /* Trigger filtee loading at runtime.*/ +#define DF_1_INITFIRST 0x00000020 /* Set RTLD_INITFIRST for this object*/ +#define DF_1_NOOPEN 0x00000040 /* Set RTLD_NOOPEN for this object. */ +#define DF_1_ORIGIN 0x00000080 /* $ORIGIN must be handled. */ +#define DF_1_DIRECT 0x00000100 /* Direct binding enabled. */ +#define DF_1_TRANS 0x00000200 +#define DF_1_INTERPOSE 0x00000400 /* Object is used to interpose. */ +#define DF_1_NODEFLIB 0x00000800 /* Ignore default lib search path. */ +#define DF_1_NODUMP 0x00001000 /* Object can't be dldump'ed. */ +#define DF_1_CONFALT 0x00002000 /* Configuration alternative created.*/ +#define DF_1_ENDFILTEE 0x00004000 /* Filtee terminates filters search. */ +#define DF_1_DISPRELDNE 0x00008000 /* Disp reloc applied at build time. */ +#define DF_1_DISPRELPND 0x00010000 /* Disp reloc applied at run-time. */ +#define DF_1_NODIRECT 0x00020000 /* Object has no-direct binding. */ +#define DF_1_IGNMULDEF 0x00040000 +#define DF_1_NOKSYMS 0x00080000 +#define DF_1_NOHDR 0x00100000 +#define DF_1_EDITED 0x00200000 /* Object is modified after built. */ +#define DF_1_NORELOC 0x00400000 +#define DF_1_SYMINTPOSE 0x00800000 /* Object has individual interposers. */ +#define DF_1_GLOBAUDIT 0x01000000 /* Global auditing required. */ +#define DF_1_SINGLETON 0x02000000 /* Singleton symbols are used. */ + +/* Flags for the feature selection in DT_FEATURE_1. */ +#define DTF_1_PARINIT 0x00000001 +#define DTF_1_CONFEXP 0x00000002 + +/* Flags in the DT_POSFLAG_1 entry effecting only the next DT_* entry. */ +#define DF_P1_LAZYLOAD 0x00000001 /* Lazyload following object. */ +#define DF_P1_GROUPPERM 0x00000002 /* Symbols from next object are not + generally available. */ + +/* Version definition sections. */ + +typedef struct +{ + Elf32_Half vd_version; /* Version revision */ + Elf32_Half vd_flags; /* Version information */ + Elf32_Half vd_ndx; /* Version Index */ + Elf32_Half vd_cnt; /* Number of associated aux entries */ + Elf32_Word vd_hash; /* Version name hash value */ + Elf32_Word vd_aux; /* Offset in bytes to verdaux array */ + Elf32_Word vd_next; /* Offset in bytes to next verdef + entry */ +} Elf32_Verdef; + +typedef struct +{ + Elf64_Half vd_version; /* Version revision */ + Elf64_Half vd_flags; /* Version information */ + Elf64_Half vd_ndx; /* Version Index */ + Elf64_Half vd_cnt; /* Number of associated aux entries */ + Elf64_Word vd_hash; /* Version name hash value */ + Elf64_Word vd_aux; /* Offset in bytes to verdaux array */ + Elf64_Word vd_next; /* Offset in bytes to next verdef + entry */ +} Elf64_Verdef; + + +/* Legal values for vd_version (version revision). */ +#define VER_DEF_NONE 0 /* No version */ +#define VER_DEF_CURRENT 1 /* Current version */ +#define VER_DEF_NUM 2 /* Given version number */ + +/* Legal values for vd_flags (version information flags). */ +#define VER_FLG_BASE 0x1 /* Version definition of file itself */ +#define VER_FLG_WEAK 0x2 /* Weak version identifier */ + +/* Versym symbol index values. */ +#define VER_NDX_LOCAL 0 /* Symbol is local. */ +#define VER_NDX_GLOBAL 1 /* Symbol is global. */ +#define VER_NDX_LORESERVE 0xff00 /* Beginning of reserved entries. */ +#define VER_NDX_ELIMINATE 0xff01 /* Symbol is to be eliminated. */ + +/* Auxialiary version information. */ + +typedef struct +{ + Elf32_Word vda_name; /* Version or dependency names */ + Elf32_Word vda_next; /* Offset in bytes to next verdaux + entry */ +} Elf32_Verdaux; + +typedef struct +{ + Elf64_Word vda_name; /* Version or dependency names */ + Elf64_Word vda_next; /* Offset in bytes to next verdaux + entry */ +} Elf64_Verdaux; + + +/* Version dependency section. */ + +typedef struct +{ + Elf32_Half vn_version; /* Version of structure */ + Elf32_Half vn_cnt; /* Number of associated aux entries */ + Elf32_Word vn_file; /* Offset of filename for this + dependency */ + Elf32_Word vn_aux; /* Offset in bytes to vernaux array */ + Elf32_Word vn_next; /* Offset in bytes to next verneed + entry */ +} Elf32_Verneed; + +typedef struct +{ + Elf64_Half vn_version; /* Version of structure */ + Elf64_Half vn_cnt; /* Number of associated aux entries */ + Elf64_Word vn_file; /* Offset of filename for this + dependency */ + Elf64_Word vn_aux; /* Offset in bytes to vernaux array */ + Elf64_Word vn_next; /* Offset in bytes to next verneed + entry */ +} Elf64_Verneed; + + +/* Legal values for vn_version (version revision). */ +#define VER_NEED_NONE 0 /* No version */ +#define VER_NEED_CURRENT 1 /* Current version */ +#define VER_NEED_NUM 2 /* Given version number */ + +/* Auxiliary needed version information. */ + +typedef struct +{ + Elf32_Word vna_hash; /* Hash value of dependency name */ + Elf32_Half vna_flags; /* Dependency specific information */ + Elf32_Half vna_other; /* Unused */ + Elf32_Word vna_name; /* Dependency name string offset */ + Elf32_Word vna_next; /* Offset in bytes to next vernaux + entry */ +} Elf32_Vernaux; + +typedef struct +{ + Elf64_Word vna_hash; /* Hash value of dependency name */ + Elf64_Half vna_flags; /* Dependency specific information */ + Elf64_Half vna_other; /* Unused */ + Elf64_Word vna_name; /* Dependency name string offset */ + Elf64_Word vna_next; /* Offset in bytes to next vernaux + entry */ +} Elf64_Vernaux; + + +/* Legal values for vna_flags. */ +#define VER_FLG_WEAK 0x2 /* Weak version identifier */ + + +/* Auxiliary vector. */ + +/* This vector is normally only used by the program interpreter. The + usual definition in an ABI supplement uses the name auxv_t. The + vector is not usually defined in a standard file, but it + can't hurt. We rename it to avoid conflicts. The sizes of these + types are an arrangement between the exec server and the program + interpreter, so we don't fully specify them here. */ + +typedef struct +{ + uint32_t a_type; /* Entry type */ + union + { + uint32_t a_val; /* Integer value */ + /* We use to have pointer elements added here. We cannot do that, + though, since it does not work when using 32-bit definitions + on 64-bit platforms and vice versa. */ + } a_un; +} Elf32_auxv_t; + +typedef struct +{ + uint64_t a_type; /* Entry type */ + union + { + uint64_t a_val; /* Integer value */ + /* We use to have pointer elements added here. We cannot do that, + though, since it does not work when using 32-bit definitions + on 64-bit platforms and vice versa. */ + } a_un; +} Elf64_auxv_t; + +/* Legal values for a_type (entry type). */ + +#define AT_NULL 0 /* End of vector */ +#define AT_IGNORE 1 /* Entry should be ignored */ +#define AT_EXECFD 2 /* File descriptor of program */ +#define AT_PHDR 3 /* Program headers for program */ +#define AT_PHENT 4 /* Size of program header entry */ +#define AT_PHNUM 5 /* Number of program headers */ +#define AT_PAGESZ 6 /* System page size */ +#define AT_BASE 7 /* Base address of interpreter */ +#define AT_FLAGS 8 /* Flags */ +#define AT_ENTRY 9 /* Entry point of program */ +#define AT_NOTELF 10 /* Program is not ELF */ +#define AT_UID 11 /* Real uid */ +#define AT_EUID 12 /* Effective uid */ +#define AT_GID 13 /* Real gid */ +#define AT_EGID 14 /* Effective gid */ +#define AT_CLKTCK 17 /* Frequency of times() */ + +/* Some more special a_type values describing the hardware. */ +#define AT_PLATFORM 15 /* String identifying platform. */ +#define AT_HWCAP 16 /* Machine-dependent hints about + processor capabilities. */ + +/* This entry gives some information about the FPU initialization + performed by the kernel. */ +#define AT_FPUCW 18 /* Used FPU control word. */ + +/* Cache block sizes. */ +#define AT_DCACHEBSIZE 19 /* Data cache block size. */ +#define AT_ICACHEBSIZE 20 /* Instruction cache block size. */ +#define AT_UCACHEBSIZE 21 /* Unified cache block size. */ + +/* A special ignored value for PPC, used by the kernel to control the + interpretation of the AUXV. Must be > 16. */ +#define AT_IGNOREPPC 22 /* Entry should be ignored. */ + +#define AT_SECURE 23 /* Boolean, was exec setuid-like? */ + +#define AT_BASE_PLATFORM 24 /* String identifying real platforms.*/ + +#define AT_RANDOM 25 /* Address of 16 random bytes. */ + +#define AT_HWCAP2 26 /* More machine-dependent hints about + processor capabilities. */ + +#define AT_EXECFN 31 /* Filename of executable. */ + +/* Pointer to the global system page used for system calls and other + nice things. */ +#define AT_SYSINFO 32 +#define AT_SYSINFO_EHDR 33 + +/* Shapes of the caches. Bits 0-3 contains associativity; bits 4-7 contains + log2 of line size; mask those to get cache size. */ +#define AT_L1I_CACHESHAPE 34 +#define AT_L1D_CACHESHAPE 35 +#define AT_L2_CACHESHAPE 36 +#define AT_L3_CACHESHAPE 37 + +/* Note section contents. Each entry in the note section begins with + a header of a fixed form. */ + +typedef struct +{ + Elf32_Word n_namesz; /* Length of the note's name. */ + Elf32_Word n_descsz; /* Length of the note's descriptor. */ + Elf32_Word n_type; /* Type of the note. */ +} Elf32_Nhdr; + +typedef struct +{ + Elf64_Word n_namesz; /* Length of the note's name. */ + Elf64_Word n_descsz; /* Length of the note's descriptor. */ + Elf64_Word n_type; /* Type of the note. */ +} Elf64_Nhdr; + +/* Known names of notes. */ + +/* Solaris entries in the note section have this name. */ +#define ELF_NOTE_SOLARIS "SUNW Solaris" + +/* Note entries for GNU systems have this name. */ +#define ELF_NOTE_GNU "GNU" + + +/* Defined types of notes for Solaris. */ + +/* Value of descriptor (one word) is desired pagesize for the binary. */ +#define ELF_NOTE_PAGESIZE_HINT 1 + + +/* Defined note types for GNU systems. */ + +/* ABI information. The descriptor consists of words: + word 0: OS descriptor + word 1: major version of the ABI + word 2: minor version of the ABI + word 3: subminor version of the ABI +*/ +#define NT_GNU_ABI_TAG 1 +#define ELF_NOTE_ABI NT_GNU_ABI_TAG /* Old name. */ + +/* Known OSes. These values can appear in word 0 of an + NT_GNU_ABI_TAG note section entry. */ +#define ELF_NOTE_OS_LINUX 0 +#define ELF_NOTE_OS_GNU 1 +#define ELF_NOTE_OS_SOLARIS2 2 +#define ELF_NOTE_OS_FREEBSD 3 + +/* Synthetic hwcap information. The descriptor begins with two words: + word 0: number of entries + word 1: bitmask of enabled entries + Then follow variable-length entries, one byte followed by a + '\0'-terminated hwcap name string. The byte gives the bit + number to test if enabled, (1U << bit) & bitmask. */ +#define NT_GNU_HWCAP 2 + +/* Build ID bits as generated by ld --build-id. + The descriptor consists of any nonzero number of bytes. */ +#define NT_GNU_BUILD_ID 3 + +/* Version note generated by GNU gold containing a version string. */ +#define NT_GNU_GOLD_VERSION 4 + + +/* Move records. */ +typedef struct +{ + Elf32_Xword m_value; /* Symbol value. */ + Elf32_Word m_info; /* Size and index. */ + Elf32_Word m_poffset; /* Symbol offset. */ + Elf32_Half m_repeat; /* Repeat count. */ + Elf32_Half m_stride; /* Stride info. */ +} Elf32_Move; + +typedef struct +{ + Elf64_Xword m_value; /* Symbol value. */ + Elf64_Xword m_info; /* Size and index. */ + Elf64_Xword m_poffset; /* Symbol offset. */ + Elf64_Half m_repeat; /* Repeat count. */ + Elf64_Half m_stride; /* Stride info. */ +} Elf64_Move; + +/* Macro to construct move records. */ +#define ELF32_M_SYM(info) ((info) >> 8) +#define ELF32_M_SIZE(info) ((unsigned char) (info)) +#define ELF32_M_INFO(sym, size) (((sym) << 8) + (unsigned char) (size)) + +#define ELF64_M_SYM(info) ELF32_M_SYM (info) +#define ELF64_M_SIZE(info) ELF32_M_SIZE (info) +#define ELF64_M_INFO(sym, size) ELF32_M_INFO (sym, size) + + +/* Motorola 68k specific definitions. */ + +/* Values for Elf32_Ehdr.e_flags. */ +#define EF_CPU32 0x00810000 + +/* m68k relocs. */ + +#define R_68K_NONE 0 /* No reloc */ +#define R_68K_32 1 /* Direct 32 bit */ +#define R_68K_16 2 /* Direct 16 bit */ +#define R_68K_8 3 /* Direct 8 bit */ +#define R_68K_PC32 4 /* PC relative 32 bit */ +#define R_68K_PC16 5 /* PC relative 16 bit */ +#define R_68K_PC8 6 /* PC relative 8 bit */ +#define R_68K_GOT32 7 /* 32 bit PC relative GOT entry */ +#define R_68K_GOT16 8 /* 16 bit PC relative GOT entry */ +#define R_68K_GOT8 9 /* 8 bit PC relative GOT entry */ +#define R_68K_GOT32O 10 /* 32 bit GOT offset */ +#define R_68K_GOT16O 11 /* 16 bit GOT offset */ +#define R_68K_GOT8O 12 /* 8 bit GOT offset */ +#define R_68K_PLT32 13 /* 32 bit PC relative PLT address */ +#define R_68K_PLT16 14 /* 16 bit PC relative PLT address */ +#define R_68K_PLT8 15 /* 8 bit PC relative PLT address */ +#define R_68K_PLT32O 16 /* 32 bit PLT offset */ +#define R_68K_PLT16O 17 /* 16 bit PLT offset */ +#define R_68K_PLT8O 18 /* 8 bit PLT offset */ +#define R_68K_COPY 19 /* Copy symbol at runtime */ +#define R_68K_GLOB_DAT 20 /* Create GOT entry */ +#define R_68K_JMP_SLOT 21 /* Create PLT entry */ +#define R_68K_RELATIVE 22 /* Adjust by program base */ +#define R_68K_TLS_GD32 25 /* 32 bit GOT offset for GD */ +#define R_68K_TLS_GD16 26 /* 16 bit GOT offset for GD */ +#define R_68K_TLS_GD8 27 /* 8 bit GOT offset for GD */ +#define R_68K_TLS_LDM32 28 /* 32 bit GOT offset for LDM */ +#define R_68K_TLS_LDM16 29 /* 16 bit GOT offset for LDM */ +#define R_68K_TLS_LDM8 30 /* 8 bit GOT offset for LDM */ +#define R_68K_TLS_LDO32 31 /* 32 bit module-relative offset */ +#define R_68K_TLS_LDO16 32 /* 16 bit module-relative offset */ +#define R_68K_TLS_LDO8 33 /* 8 bit module-relative offset */ +#define R_68K_TLS_IE32 34 /* 32 bit GOT offset for IE */ +#define R_68K_TLS_IE16 35 /* 16 bit GOT offset for IE */ +#define R_68K_TLS_IE8 36 /* 8 bit GOT offset for IE */ +#define R_68K_TLS_LE32 37 /* 32 bit offset relative to + static TLS block */ +#define R_68K_TLS_LE16 38 /* 16 bit offset relative to + static TLS block */ +#define R_68K_TLS_LE8 39 /* 8 bit offset relative to + static TLS block */ +#define R_68K_TLS_DTPMOD32 40 /* 32 bit module number */ +#define R_68K_TLS_DTPREL32 41 /* 32 bit module-relative offset */ +#define R_68K_TLS_TPREL32 42 /* 32 bit TP-relative offset */ +/* Keep this the last entry. */ +#define R_68K_NUM 43 + +/* Intel 80386 specific definitions. */ + +/* i386 relocs. */ + +#define R_386_NONE 0 /* No reloc */ +#define R_386_32 1 /* Direct 32 bit */ +#define R_386_PC32 2 /* PC relative 32 bit */ +#define R_386_GOT32 3 /* 32 bit GOT entry */ +#define R_386_PLT32 4 /* 32 bit PLT address */ +#define R_386_COPY 5 /* Copy symbol at runtime */ +#define R_386_GLOB_DAT 6 /* Create GOT entry */ +#define R_386_JMP_SLOT 7 /* Create PLT entry */ +#define R_386_RELATIVE 8 /* Adjust by program base */ +#define R_386_GOTOFF 9 /* 32 bit offset to GOT */ +#define R_386_GOTPC 10 /* 32 bit PC relative offset to GOT */ +#define R_386_32PLT 11 +#define R_386_TLS_TPOFF 14 /* Offset in static TLS block */ +#define R_386_TLS_IE 15 /* Address of GOT entry for static TLS + block offset */ +#define R_386_TLS_GOTIE 16 /* GOT entry for static TLS block + offset */ +#define R_386_TLS_LE 17 /* Offset relative to static TLS + block */ +#define R_386_TLS_GD 18 /* Direct 32 bit for GNU version of + general dynamic thread local data */ +#define R_386_TLS_LDM 19 /* Direct 32 bit for GNU version of + local dynamic thread local data + in LE code */ +#define R_386_16 20 +#define R_386_PC16 21 +#define R_386_8 22 +#define R_386_PC8 23 +#define R_386_TLS_GD_32 24 /* Direct 32 bit for general dynamic + thread local data */ +#define R_386_TLS_GD_PUSH 25 /* Tag for pushl in GD TLS code */ +#define R_386_TLS_GD_CALL 26 /* Relocation for call to + __tls_get_addr() */ +#define R_386_TLS_GD_POP 27 /* Tag for popl in GD TLS code */ +#define R_386_TLS_LDM_32 28 /* Direct 32 bit for local dynamic + thread local data in LE code */ +#define R_386_TLS_LDM_PUSH 29 /* Tag for pushl in LDM TLS code */ +#define R_386_TLS_LDM_CALL 30 /* Relocation for call to + __tls_get_addr() in LDM code */ +#define R_386_TLS_LDM_POP 31 /* Tag for popl in LDM TLS code */ +#define R_386_TLS_LDO_32 32 /* Offset relative to TLS block */ +#define R_386_TLS_IE_32 33 /* GOT entry for negated static TLS + block offset */ +#define R_386_TLS_LE_32 34 /* Negated offset relative to static + TLS block */ +#define R_386_TLS_DTPMOD32 35 /* ID of module containing symbol */ +#define R_386_TLS_DTPOFF32 36 /* Offset in TLS block */ +#define R_386_TLS_TPOFF32 37 /* Negated offset in static TLS block */ +#define R_386_SIZE32 38 /* 32-bit symbol size */ +#define R_386_TLS_GOTDESC 39 /* GOT offset for TLS descriptor. */ +#define R_386_TLS_DESC_CALL 40 /* Marker of call through TLS + descriptor for + relaxation. */ +#define R_386_TLS_DESC 41 /* TLS descriptor containing + pointer to code and to + argument, returning the TLS + offset for the symbol. */ +#define R_386_IRELATIVE 42 /* Adjust indirectly by program base */ +#define R_386_GOT32X 43 /* Load from 32 bit GOT entry, + relaxable. */ +/* Keep this the last entry. */ +#define R_386_NUM 44 + +/* SUN SPARC specific definitions. */ + +/* Legal values for ST_TYPE subfield of st_info (symbol type). */ + +#define STT_SPARC_REGISTER 13 /* Global register reserved to app. */ + +/* Values for Elf64_Ehdr.e_flags. */ + +#define EF_SPARCV9_MM 3 +#define EF_SPARCV9_TSO 0 +#define EF_SPARCV9_PSO 1 +#define EF_SPARCV9_RMO 2 +#define EF_SPARC_LEDATA 0x800000 /* little endian data */ +#define EF_SPARC_EXT_MASK 0xFFFF00 +#define EF_SPARC_32PLUS 0x000100 /* generic V8+ features */ +#define EF_SPARC_SUN_US1 0x000200 /* Sun UltraSPARC1 extensions */ +#define EF_SPARC_HAL_R1 0x000400 /* HAL R1 extensions */ +#define EF_SPARC_SUN_US3 0x000800 /* Sun UltraSPARCIII extensions */ + +/* SPARC relocs. */ + +#define R_SPARC_NONE 0 /* No reloc */ +#define R_SPARC_8 1 /* Direct 8 bit */ +#define R_SPARC_16 2 /* Direct 16 bit */ +#define R_SPARC_32 3 /* Direct 32 bit */ +#define R_SPARC_DISP8 4 /* PC relative 8 bit */ +#define R_SPARC_DISP16 5 /* PC relative 16 bit */ +#define R_SPARC_DISP32 6 /* PC relative 32 bit */ +#define R_SPARC_WDISP30 7 /* PC relative 30 bit shifted */ +#define R_SPARC_WDISP22 8 /* PC relative 22 bit shifted */ +#define R_SPARC_HI22 9 /* High 22 bit */ +#define R_SPARC_22 10 /* Direct 22 bit */ +#define R_SPARC_13 11 /* Direct 13 bit */ +#define R_SPARC_LO10 12 /* Truncated 10 bit */ +#define R_SPARC_GOT10 13 /* Truncated 10 bit GOT entry */ +#define R_SPARC_GOT13 14 /* 13 bit GOT entry */ +#define R_SPARC_GOT22 15 /* 22 bit GOT entry shifted */ +#define R_SPARC_PC10 16 /* PC relative 10 bit truncated */ +#define R_SPARC_PC22 17 /* PC relative 22 bit shifted */ +#define R_SPARC_WPLT30 18 /* 30 bit PC relative PLT address */ +#define R_SPARC_COPY 19 /* Copy symbol at runtime */ +#define R_SPARC_GLOB_DAT 20 /* Create GOT entry */ +#define R_SPARC_JMP_SLOT 21 /* Create PLT entry */ +#define R_SPARC_RELATIVE 22 /* Adjust by program base */ +#define R_SPARC_UA32 23 /* Direct 32 bit unaligned */ + +/* Additional Sparc64 relocs. */ + +#define R_SPARC_PLT32 24 /* Direct 32 bit ref to PLT entry */ +#define R_SPARC_HIPLT22 25 /* High 22 bit PLT entry */ +#define R_SPARC_LOPLT10 26 /* Truncated 10 bit PLT entry */ +#define R_SPARC_PCPLT32 27 /* PC rel 32 bit ref to PLT entry */ +#define R_SPARC_PCPLT22 28 /* PC rel high 22 bit PLT entry */ +#define R_SPARC_PCPLT10 29 /* PC rel trunc 10 bit PLT entry */ +#define R_SPARC_10 30 /* Direct 10 bit */ +#define R_SPARC_11 31 /* Direct 11 bit */ +#define R_SPARC_64 32 /* Direct 64 bit */ +#define R_SPARC_OLO10 33 /* 10bit with secondary 13bit addend */ +#define R_SPARC_HH22 34 /* Top 22 bits of direct 64 bit */ +#define R_SPARC_HM10 35 /* High middle 10 bits of ... */ +#define R_SPARC_LM22 36 /* Low middle 22 bits of ... */ +#define R_SPARC_PC_HH22 37 /* Top 22 bits of pc rel 64 bit */ +#define R_SPARC_PC_HM10 38 /* High middle 10 bit of ... */ +#define R_SPARC_PC_LM22 39 /* Low miggle 22 bits of ... */ +#define R_SPARC_WDISP16 40 /* PC relative 16 bit shifted */ +#define R_SPARC_WDISP19 41 /* PC relative 19 bit shifted */ +#define R_SPARC_GLOB_JMP 42 /* was part of v9 ABI but was removed */ +#define R_SPARC_7 43 /* Direct 7 bit */ +#define R_SPARC_5 44 /* Direct 5 bit */ +#define R_SPARC_6 45 /* Direct 6 bit */ +#define R_SPARC_DISP64 46 /* PC relative 64 bit */ +#define R_SPARC_PLT64 47 /* Direct 64 bit ref to PLT entry */ +#define R_SPARC_HIX22 48 /* High 22 bit complemented */ +#define R_SPARC_LOX10 49 /* Truncated 11 bit complemented */ +#define R_SPARC_H44 50 /* Direct high 12 of 44 bit */ +#define R_SPARC_M44 51 /* Direct mid 22 of 44 bit */ +#define R_SPARC_L44 52 /* Direct low 10 of 44 bit */ +#define R_SPARC_REGISTER 53 /* Global register usage */ +#define R_SPARC_UA64 54 /* Direct 64 bit unaligned */ +#define R_SPARC_UA16 55 /* Direct 16 bit unaligned */ +#define R_SPARC_TLS_GD_HI22 56 +#define R_SPARC_TLS_GD_LO10 57 +#define R_SPARC_TLS_GD_ADD 58 +#define R_SPARC_TLS_GD_CALL 59 +#define R_SPARC_TLS_LDM_HI22 60 +#define R_SPARC_TLS_LDM_LO10 61 +#define R_SPARC_TLS_LDM_ADD 62 +#define R_SPARC_TLS_LDM_CALL 63 +#define R_SPARC_TLS_LDO_HIX22 64 +#define R_SPARC_TLS_LDO_LOX10 65 +#define R_SPARC_TLS_LDO_ADD 66 +#define R_SPARC_TLS_IE_HI22 67 +#define R_SPARC_TLS_IE_LO10 68 +#define R_SPARC_TLS_IE_LD 69 +#define R_SPARC_TLS_IE_LDX 70 +#define R_SPARC_TLS_IE_ADD 71 +#define R_SPARC_TLS_LE_HIX22 72 +#define R_SPARC_TLS_LE_LOX10 73 +#define R_SPARC_TLS_DTPMOD32 74 +#define R_SPARC_TLS_DTPMOD64 75 +#define R_SPARC_TLS_DTPOFF32 76 +#define R_SPARC_TLS_DTPOFF64 77 +#define R_SPARC_TLS_TPOFF32 78 +#define R_SPARC_TLS_TPOFF64 79 +#define R_SPARC_GOTDATA_HIX22 80 +#define R_SPARC_GOTDATA_LOX10 81 +#define R_SPARC_GOTDATA_OP_HIX22 82 +#define R_SPARC_GOTDATA_OP_LOX10 83 +#define R_SPARC_GOTDATA_OP 84 +#define R_SPARC_H34 85 +#define R_SPARC_SIZE32 86 +#define R_SPARC_SIZE64 87 +#define R_SPARC_WDISP10 88 +#define R_SPARC_JMP_IREL 248 +#define R_SPARC_IRELATIVE 249 +#define R_SPARC_GNU_VTINHERIT 250 +#define R_SPARC_GNU_VTENTRY 251 +#define R_SPARC_REV32 252 +/* Keep this the last entry. */ +#define R_SPARC_NUM 253 + +/* For Sparc64, legal values for d_tag of Elf64_Dyn. */ + +#define DT_SPARC_REGISTER 0x70000001 +#define DT_SPARC_NUM 2 + +/* MIPS R3000 specific definitions. */ + +/* Legal values for e_flags field of Elf32_Ehdr. */ + +#define EF_MIPS_NOREORDER 1 /* A .noreorder directive was used. */ +#define EF_MIPS_PIC 2 /* Contains PIC code. */ +#define EF_MIPS_CPIC 4 /* Uses PIC calling sequence. */ +#define EF_MIPS_XGOT 8 +#define EF_MIPS_64BIT_WHIRL 16 +#define EF_MIPS_ABI2 32 +#define EF_MIPS_ABI_ON32 64 +#define EF_MIPS_FP64 512 /* Uses FP64 (12 callee-saved). */ +#define EF_MIPS_NAN2008 1024 /* Uses IEEE 754-2008 NaN encoding. */ +#define EF_MIPS_ARCH 0xf0000000 /* MIPS architecture level. */ + +/* Legal values for MIPS architecture level. */ + +#define EF_MIPS_ARCH_1 0x00000000 /* -mips1 code. */ +#define EF_MIPS_ARCH_2 0x10000000 /* -mips2 code. */ +#define EF_MIPS_ARCH_3 0x20000000 /* -mips3 code. */ +#define EF_MIPS_ARCH_4 0x30000000 /* -mips4 code. */ +#define EF_MIPS_ARCH_5 0x40000000 /* -mips5 code. */ +#define EF_MIPS_ARCH_32 0x50000000 /* MIPS32 code. */ +#define EF_MIPS_ARCH_64 0x60000000 /* MIPS64 code. */ +#define EF_MIPS_ARCH_32R2 0x70000000 /* MIPS32r2 code. */ +#define EF_MIPS_ARCH_64R2 0x80000000 /* MIPS64r2 code. */ + +/* The following are unofficial names and should not be used. */ + +#define E_MIPS_ARCH_1 EF_MIPS_ARCH_1 +#define E_MIPS_ARCH_2 EF_MIPS_ARCH_2 +#define E_MIPS_ARCH_3 EF_MIPS_ARCH_3 +#define E_MIPS_ARCH_4 EF_MIPS_ARCH_4 +#define E_MIPS_ARCH_5 EF_MIPS_ARCH_5 +#define E_MIPS_ARCH_32 EF_MIPS_ARCH_32 +#define E_MIPS_ARCH_64 EF_MIPS_ARCH_64 + +/* Special section indices. */ + +#define SHN_MIPS_ACOMMON 0xff00 /* Allocated common symbols. */ +#define SHN_MIPS_TEXT 0xff01 /* Allocated test symbols. */ +#define SHN_MIPS_DATA 0xff02 /* Allocated data symbols. */ +#define SHN_MIPS_SCOMMON 0xff03 /* Small common symbols. */ +#define SHN_MIPS_SUNDEFINED 0xff04 /* Small undefined symbols. */ + +/* Legal values for sh_type field of Elf32_Shdr. */ + +#define SHT_MIPS_LIBLIST 0x70000000 /* Shared objects used in link. */ +#define SHT_MIPS_MSYM 0x70000001 +#define SHT_MIPS_CONFLICT 0x70000002 /* Conflicting symbols. */ +#define SHT_MIPS_GPTAB 0x70000003 /* Global data area sizes. */ +#define SHT_MIPS_UCODE 0x70000004 /* Reserved for SGI/MIPS compilers */ +#define SHT_MIPS_DEBUG 0x70000005 /* MIPS ECOFF debugging info. */ +#define SHT_MIPS_REGINFO 0x70000006 /* Register usage information. */ +#define SHT_MIPS_PACKAGE 0x70000007 +#define SHT_MIPS_PACKSYM 0x70000008 +#define SHT_MIPS_RELD 0x70000009 +#define SHT_MIPS_IFACE 0x7000000b +#define SHT_MIPS_CONTENT 0x7000000c +#define SHT_MIPS_OPTIONS 0x7000000d /* Miscellaneous options. */ +#define SHT_MIPS_SHDR 0x70000010 +#define SHT_MIPS_FDESC 0x70000011 +#define SHT_MIPS_EXTSYM 0x70000012 +#define SHT_MIPS_DENSE 0x70000013 +#define SHT_MIPS_PDESC 0x70000014 +#define SHT_MIPS_LOCSYM 0x70000015 +#define SHT_MIPS_AUXSYM 0x70000016 +#define SHT_MIPS_OPTSYM 0x70000017 +#define SHT_MIPS_LOCSTR 0x70000018 +#define SHT_MIPS_LINE 0x70000019 +#define SHT_MIPS_RFDESC 0x7000001a +#define SHT_MIPS_DELTASYM 0x7000001b +#define SHT_MIPS_DELTAINST 0x7000001c +#define SHT_MIPS_DELTACLASS 0x7000001d +#define SHT_MIPS_DWARF 0x7000001e /* DWARF debugging information. */ +#define SHT_MIPS_DELTADECL 0x7000001f +#define SHT_MIPS_SYMBOL_LIB 0x70000020 +#define SHT_MIPS_EVENTS 0x70000021 /* Event section. */ +#define SHT_MIPS_TRANSLATE 0x70000022 +#define SHT_MIPS_PIXIE 0x70000023 +#define SHT_MIPS_XLATE 0x70000024 +#define SHT_MIPS_XLATE_DEBUG 0x70000025 +#define SHT_MIPS_WHIRL 0x70000026 +#define SHT_MIPS_EH_REGION 0x70000027 +#define SHT_MIPS_XLATE_OLD 0x70000028 +#define SHT_MIPS_PDR_EXCEPTION 0x70000029 + +/* Legal values for sh_flags field of Elf32_Shdr. */ + +#define SHF_MIPS_GPREL 0x10000000 /* Must be in global data area. */ +#define SHF_MIPS_MERGE 0x20000000 +#define SHF_MIPS_ADDR 0x40000000 +#define SHF_MIPS_STRINGS 0x80000000 +#define SHF_MIPS_NOSTRIP 0x08000000 +#define SHF_MIPS_LOCAL 0x04000000 +#define SHF_MIPS_NAMES 0x02000000 +#define SHF_MIPS_NODUPE 0x01000000 + + +/* Symbol tables. */ + +/* MIPS specific values for `st_other'. */ +#define STO_MIPS_DEFAULT 0x0 +#define STO_MIPS_INTERNAL 0x1 +#define STO_MIPS_HIDDEN 0x2 +#define STO_MIPS_PROTECTED 0x3 +#define STO_MIPS_PLT 0x8 +#define STO_MIPS_SC_ALIGN_UNUSED 0xff + +/* MIPS specific values for `st_info'. */ +#define STB_MIPS_SPLIT_COMMON 13 + +/* Entries found in sections of type SHT_MIPS_GPTAB. */ + +typedef union +{ + struct + { + Elf32_Word gt_current_g_value; /* -G value used for compilation. */ + Elf32_Word gt_unused; /* Not used. */ + } gt_header; /* First entry in section. */ + struct + { + Elf32_Word gt_g_value; /* If this value were used for -G. */ + Elf32_Word gt_bytes; /* This many bytes would be used. */ + } gt_entry; /* Subsequent entries in section. */ +} Elf32_gptab; + +/* Entry found in sections of type SHT_MIPS_REGINFO. */ + +typedef struct +{ + Elf32_Word ri_gprmask; /* General registers used. */ + Elf32_Word ri_cprmask[4]; /* Coprocessor registers used. */ + Elf32_Sword ri_gp_value; /* $gp register value. */ +} Elf32_RegInfo; + +/* Entries found in sections of type SHT_MIPS_OPTIONS. */ + +typedef struct +{ + unsigned char kind; /* Determines interpretation of the + variable part of descriptor. */ + unsigned char size; /* Size of descriptor, including header. */ + Elf32_Section section; /* Section header index of section affected, + 0 for global options. */ + Elf32_Word info; /* Kind-specific information. */ +} Elf_Options; + +/* Values for `kind' field in Elf_Options. */ + +#define ODK_NULL 0 /* Undefined. */ +#define ODK_REGINFO 1 /* Register usage information. */ +#define ODK_EXCEPTIONS 2 /* Exception processing options. */ +#define ODK_PAD 3 /* Section padding options. */ +#define ODK_HWPATCH 4 /* Hardware workarounds performed */ +#define ODK_FILL 5 /* record the fill value used by the linker. */ +#define ODK_TAGS 6 /* reserve space for desktop tools to write. */ +#define ODK_HWAND 7 /* HW workarounds. 'AND' bits when merging. */ +#define ODK_HWOR 8 /* HW workarounds. 'OR' bits when merging. */ + +/* Values for `info' in Elf_Options for ODK_EXCEPTIONS entries. */ + +#define OEX_FPU_MIN 0x1f /* FPE's which MUST be enabled. */ +#define OEX_FPU_MAX 0x1f00 /* FPE's which MAY be enabled. */ +#define OEX_PAGE0 0x10000 /* page zero must be mapped. */ +#define OEX_SMM 0x20000 /* Force sequential memory mode? */ +#define OEX_FPDBUG 0x40000 /* Force floating point debug mode? */ +#define OEX_PRECISEFP OEX_FPDBUG +#define OEX_DISMISS 0x80000 /* Dismiss invalid address faults? */ + +#define OEX_FPU_INVAL 0x10 +#define OEX_FPU_DIV0 0x08 +#define OEX_FPU_OFLO 0x04 +#define OEX_FPU_UFLO 0x02 +#define OEX_FPU_INEX 0x01 + +/* Masks for `info' in Elf_Options for an ODK_HWPATCH entry. */ + +#define OHW_R4KEOP 0x1 /* R4000 end-of-page patch. */ +#define OHW_R8KPFETCH 0x2 /* may need R8000 prefetch patch. */ +#define OHW_R5KEOP 0x4 /* R5000 end-of-page patch. */ +#define OHW_R5KCVTL 0x8 /* R5000 cvt.[ds].l bug. clean=1. */ + +#define OPAD_PREFIX 0x1 +#define OPAD_POSTFIX 0x2 +#define OPAD_SYMBOL 0x4 + +/* Entry found in `.options' section. */ + +typedef struct +{ + Elf32_Word hwp_flags1; /* Extra flags. */ + Elf32_Word hwp_flags2; /* Extra flags. */ +} Elf_Options_Hw; + +/* Masks for `info' in ElfOptions for ODK_HWAND and ODK_HWOR entries. */ + +#define OHWA0_R4KEOP_CHECKED 0x00000001 +#define OHWA1_R4KEOP_CLEAN 0x00000002 + +/* MIPS relocs. */ + +#define R_MIPS_NONE 0 /* No reloc */ +#define R_MIPS_16 1 /* Direct 16 bit */ +#define R_MIPS_32 2 /* Direct 32 bit */ +#define R_MIPS_REL32 3 /* PC relative 32 bit */ +#define R_MIPS_26 4 /* Direct 26 bit shifted */ +#define R_MIPS_HI16 5 /* High 16 bit */ +#define R_MIPS_LO16 6 /* Low 16 bit */ +#define R_MIPS_GPREL16 7 /* GP relative 16 bit */ +#define R_MIPS_LITERAL 8 /* 16 bit literal entry */ +#define R_MIPS_GOT16 9 /* 16 bit GOT entry */ +#define R_MIPS_PC16 10 /* PC relative 16 bit */ +#define R_MIPS_CALL16 11 /* 16 bit GOT entry for function */ +#define R_MIPS_GPREL32 12 /* GP relative 32 bit */ + +#define R_MIPS_SHIFT5 16 +#define R_MIPS_SHIFT6 17 +#define R_MIPS_64 18 +#define R_MIPS_GOT_DISP 19 +#define R_MIPS_GOT_PAGE 20 +#define R_MIPS_GOT_OFST 21 +#define R_MIPS_GOT_HI16 22 +#define R_MIPS_GOT_LO16 23 +#define R_MIPS_SUB 24 +#define R_MIPS_INSERT_A 25 +#define R_MIPS_INSERT_B 26 +#define R_MIPS_DELETE 27 +#define R_MIPS_HIGHER 28 +#define R_MIPS_HIGHEST 29 +#define R_MIPS_CALL_HI16 30 +#define R_MIPS_CALL_LO16 31 +#define R_MIPS_SCN_DISP 32 +#define R_MIPS_REL16 33 +#define R_MIPS_ADD_IMMEDIATE 34 +#define R_MIPS_PJUMP 35 +#define R_MIPS_RELGOT 36 +#define R_MIPS_JALR 37 +#define R_MIPS_TLS_DTPMOD32 38 /* Module number 32 bit */ +#define R_MIPS_TLS_DTPREL32 39 /* Module-relative offset 32 bit */ +#define R_MIPS_TLS_DTPMOD64 40 /* Module number 64 bit */ +#define R_MIPS_TLS_DTPREL64 41 /* Module-relative offset 64 bit */ +#define R_MIPS_TLS_GD 42 /* 16 bit GOT offset for GD */ +#define R_MIPS_TLS_LDM 43 /* 16 bit GOT offset for LDM */ +#define R_MIPS_TLS_DTPREL_HI16 44 /* Module-relative offset, high 16 bits */ +#define R_MIPS_TLS_DTPREL_LO16 45 /* Module-relative offset, low 16 bits */ +#define R_MIPS_TLS_GOTTPREL 46 /* 16 bit GOT offset for IE */ +#define R_MIPS_TLS_TPREL32 47 /* TP-relative offset, 32 bit */ +#define R_MIPS_TLS_TPREL64 48 /* TP-relative offset, 64 bit */ +#define R_MIPS_TLS_TPREL_HI16 49 /* TP-relative offset, high 16 bits */ +#define R_MIPS_TLS_TPREL_LO16 50 /* TP-relative offset, low 16 bits */ +#define R_MIPS_GLOB_DAT 51 +#define R_MIPS_COPY 126 +#define R_MIPS_JUMP_SLOT 127 +/* Keep this the last entry. */ +#define R_MIPS_NUM 128 + +/* Legal values for p_type field of Elf32_Phdr. */ + +#define PT_MIPS_REGINFO 0x70000000 /* Register usage information. */ +#define PT_MIPS_RTPROC 0x70000001 /* Runtime procedure table. */ +#define PT_MIPS_OPTIONS 0x70000002 +#define PT_MIPS_ABIFLAGS 0x70000003 /* FP mode requirement. */ + +/* Special program header types. */ + +#define PF_MIPS_LOCAL 0x10000000 + +/* Legal values for d_tag field of Elf32_Dyn. */ + +#define DT_MIPS_RLD_VERSION 0x70000001 /* Runtime linker interface version */ +#define DT_MIPS_TIME_STAMP 0x70000002 /* Timestamp */ +#define DT_MIPS_ICHECKSUM 0x70000003 /* Checksum */ +#define DT_MIPS_IVERSION 0x70000004 /* Version string (string tbl index) */ +#define DT_MIPS_FLAGS 0x70000005 /* Flags */ +#define DT_MIPS_BASE_ADDRESS 0x70000006 /* Base address */ +#define DT_MIPS_MSYM 0x70000007 +#define DT_MIPS_CONFLICT 0x70000008 /* Address of CONFLICT section */ +#define DT_MIPS_LIBLIST 0x70000009 /* Address of LIBLIST section */ +#define DT_MIPS_LOCAL_GOTNO 0x7000000a /* Number of local GOT entries */ +#define DT_MIPS_CONFLICTNO 0x7000000b /* Number of CONFLICT entries */ +#define DT_MIPS_LIBLISTNO 0x70000010 /* Number of LIBLIST entries */ +#define DT_MIPS_SYMTABNO 0x70000011 /* Number of DYNSYM entries */ +#define DT_MIPS_UNREFEXTNO 0x70000012 /* First external DYNSYM */ +#define DT_MIPS_GOTSYM 0x70000013 /* First GOT entry in DYNSYM */ +#define DT_MIPS_HIPAGENO 0x70000014 /* Number of GOT page table entries */ +#define DT_MIPS_RLD_MAP 0x70000016 /* Address of run time loader map. */ +#define DT_MIPS_DELTA_CLASS 0x70000017 /* Delta C++ class definition. */ +#define DT_MIPS_DELTA_CLASS_NO 0x70000018 /* Number of entries in + DT_MIPS_DELTA_CLASS. */ +#define DT_MIPS_DELTA_INSTANCE 0x70000019 /* Delta C++ class instances. */ +#define DT_MIPS_DELTA_INSTANCE_NO 0x7000001a /* Number of entries in + DT_MIPS_DELTA_INSTANCE. */ +#define DT_MIPS_DELTA_RELOC 0x7000001b /* Delta relocations. */ +#define DT_MIPS_DELTA_RELOC_NO 0x7000001c /* Number of entries in + DT_MIPS_DELTA_RELOC. */ +#define DT_MIPS_DELTA_SYM 0x7000001d /* Delta symbols that Delta + relocations refer to. */ +#define DT_MIPS_DELTA_SYM_NO 0x7000001e /* Number of entries in + DT_MIPS_DELTA_SYM. */ +#define DT_MIPS_DELTA_CLASSSYM 0x70000020 /* Delta symbols that hold the + class declaration. */ +#define DT_MIPS_DELTA_CLASSSYM_NO 0x70000021 /* Number of entries in + DT_MIPS_DELTA_CLASSSYM. */ +#define DT_MIPS_CXX_FLAGS 0x70000022 /* Flags indicating for C++ flavor. */ +#define DT_MIPS_PIXIE_INIT 0x70000023 +#define DT_MIPS_SYMBOL_LIB 0x70000024 +#define DT_MIPS_LOCALPAGE_GOTIDX 0x70000025 +#define DT_MIPS_LOCAL_GOTIDX 0x70000026 +#define DT_MIPS_HIDDEN_GOTIDX 0x70000027 +#define DT_MIPS_PROTECTED_GOTIDX 0x70000028 +#define DT_MIPS_OPTIONS 0x70000029 /* Address of .options. */ +#define DT_MIPS_INTERFACE 0x7000002a /* Address of .interface. */ +#define DT_MIPS_DYNSTR_ALIGN 0x7000002b +#define DT_MIPS_INTERFACE_SIZE 0x7000002c /* Size of the .interface section. */ +#define DT_MIPS_RLD_TEXT_RESOLVE_ADDR 0x7000002d /* Address of rld_text_rsolve + function stored in GOT. */ +#define DT_MIPS_PERF_SUFFIX 0x7000002e /* Default suffix of dso to be added + by rld on dlopen() calls. */ +#define DT_MIPS_COMPACT_SIZE 0x7000002f /* (O32)Size of compact rel section. */ +#define DT_MIPS_GP_VALUE 0x70000030 /* GP value for aux GOTs. */ +#define DT_MIPS_AUX_DYNAMIC 0x70000031 /* Address of aux .dynamic. */ +/* The address of .got.plt in an executable using the new non-PIC ABI. */ +#define DT_MIPS_PLTGOT 0x70000032 +/* The base of the PLT in an executable using the new non-PIC ABI if that + PLT is writable. For a non-writable PLT, this is omitted or has a zero + value. */ +#define DT_MIPS_RWPLT 0x70000034 +/* An alternative description of the classic MIPS RLD_MAP that is usable + in a PIE as it stores a relative offset from the address of the tag + rather than an absolute address. */ +#define DT_MIPS_RLD_MAP_REL 0x70000035 +#define DT_MIPS_NUM 0x36 + +/* Legal values for DT_MIPS_FLAGS Elf32_Dyn entry. */ + +#define RHF_NONE 0 /* No flags */ +#define RHF_QUICKSTART (1 << 0) /* Use quickstart */ +#define RHF_NOTPOT (1 << 1) /* Hash size not power of 2 */ +#define RHF_NO_LIBRARY_REPLACEMENT (1 << 2) /* Ignore LD_LIBRARY_PATH */ +#define RHF_NO_MOVE (1 << 3) +#define RHF_SGI_ONLY (1 << 4) +#define RHF_GUARANTEE_INIT (1 << 5) +#define RHF_DELTA_C_PLUS_PLUS (1 << 6) +#define RHF_GUARANTEE_START_INIT (1 << 7) +#define RHF_PIXIE (1 << 8) +#define RHF_DEFAULT_DELAY_LOAD (1 << 9) +#define RHF_REQUICKSTART (1 << 10) +#define RHF_REQUICKSTARTED (1 << 11) +#define RHF_CORD (1 << 12) +#define RHF_NO_UNRES_UNDEF (1 << 13) +#define RHF_RLD_ORDER_SAFE (1 << 14) + +/* Entries found in sections of type SHT_MIPS_LIBLIST. */ + +typedef struct +{ + Elf32_Word l_name; /* Name (string table index) */ + Elf32_Word l_time_stamp; /* Timestamp */ + Elf32_Word l_checksum; /* Checksum */ + Elf32_Word l_version; /* Interface version */ + Elf32_Word l_flags; /* Flags */ +} Elf32_Lib; + +typedef struct +{ + Elf64_Word l_name; /* Name (string table index) */ + Elf64_Word l_time_stamp; /* Timestamp */ + Elf64_Word l_checksum; /* Checksum */ + Elf64_Word l_version; /* Interface version */ + Elf64_Word l_flags; /* Flags */ +} Elf64_Lib; + + +/* Legal values for l_flags. */ + +#define LL_NONE 0 +#define LL_EXACT_MATCH (1 << 0) /* Require exact match */ +#define LL_IGNORE_INT_VER (1 << 1) /* Ignore interface version */ +#define LL_REQUIRE_MINOR (1 << 2) +#define LL_EXPORTS (1 << 3) +#define LL_DELAY_LOAD (1 << 4) +#define LL_DELTA (1 << 5) + +/* Entries found in sections of type SHT_MIPS_CONFLICT. */ + +typedef Elf32_Addr Elf32_Conflict; + +typedef struct +{ + /* Version of flags structure. */ + Elf32_Half version; + /* The level of the ISA: 1-5, 32, 64. */ + unsigned char isa_level; + /* The revision of ISA: 0 for MIPS V and below, 1-n otherwise. */ + unsigned char isa_rev; + /* The size of general purpose registers. */ + unsigned char gpr_size; + /* The size of co-processor 1 registers. */ + unsigned char cpr1_size; + /* The size of co-processor 2 registers. */ + unsigned char cpr2_size; + /* The floating-point ABI. */ + unsigned char fp_abi; + /* Processor-specific extension. */ + Elf32_Word isa_ext; + /* Mask of ASEs used. */ + Elf32_Word ases; + /* Mask of general flags. */ + Elf32_Word flags1; + Elf32_Word flags2; +} Elf_MIPS_ABIFlags_v0; + +/* Values for the register size bytes of an abi flags structure. */ + +#define MIPS_AFL_REG_NONE 0x00 /* No registers. */ +#define MIPS_AFL_REG_32 0x01 /* 32-bit registers. */ +#define MIPS_AFL_REG_64 0x02 /* 64-bit registers. */ +#define MIPS_AFL_REG_128 0x03 /* 128-bit registers. */ + +/* Masks for the ases word of an ABI flags structure. */ + +#define MIPS_AFL_ASE_DSP 0x00000001 /* DSP ASE. */ +#define MIPS_AFL_ASE_DSPR2 0x00000002 /* DSP R2 ASE. */ +#define MIPS_AFL_ASE_EVA 0x00000004 /* Enhanced VA Scheme. */ +#define MIPS_AFL_ASE_MCU 0x00000008 /* MCU (MicroController) ASE. */ +#define MIPS_AFL_ASE_MDMX 0x00000010 /* MDMX ASE. */ +#define MIPS_AFL_ASE_MIPS3D 0x00000020 /* MIPS-3D ASE. */ +#define MIPS_AFL_ASE_MT 0x00000040 /* MT ASE. */ +#define MIPS_AFL_ASE_SMARTMIPS 0x00000080 /* SmartMIPS ASE. */ +#define MIPS_AFL_ASE_VIRT 0x00000100 /* VZ ASE. */ +#define MIPS_AFL_ASE_MSA 0x00000200 /* MSA ASE. */ +#define MIPS_AFL_ASE_MIPS16 0x00000400 /* MIPS16 ASE. */ +#define MIPS_AFL_ASE_MICROMIPS 0x00000800 /* MICROMIPS ASE. */ +#define MIPS_AFL_ASE_XPA 0x00001000 /* XPA ASE. */ +#define MIPS_AFL_ASE_MASK 0x00001fff /* All ASEs. */ + +/* Values for the isa_ext word of an ABI flags structure. */ + +#define MIPS_AFL_EXT_XLR 1 /* RMI Xlr instruction. */ +#define MIPS_AFL_EXT_OCTEON2 2 /* Cavium Networks Octeon2. */ +#define MIPS_AFL_EXT_OCTEONP 3 /* Cavium Networks OcteonP. */ +#define MIPS_AFL_EXT_LOONGSON_3A 4 /* Loongson 3A. */ +#define MIPS_AFL_EXT_OCTEON 5 /* Cavium Networks Octeon. */ +#define MIPS_AFL_EXT_5900 6 /* MIPS R5900 instruction. */ +#define MIPS_AFL_EXT_4650 7 /* MIPS R4650 instruction. */ +#define MIPS_AFL_EXT_4010 8 /* LSI R4010 instruction. */ +#define MIPS_AFL_EXT_4100 9 /* NEC VR4100 instruction. */ +#define MIPS_AFL_EXT_3900 10 /* Toshiba R3900 instruction. */ +#define MIPS_AFL_EXT_10000 11 /* MIPS R10000 instruction. */ +#define MIPS_AFL_EXT_SB1 12 /* Broadcom SB-1 instruction. */ +#define MIPS_AFL_EXT_4111 13 /* NEC VR4111/VR4181 instruction. */ +#define MIPS_AFL_EXT_4120 14 /* NEC VR4120 instruction. */ +#define MIPS_AFL_EXT_5400 15 /* NEC VR5400 instruction. */ +#define MIPS_AFL_EXT_5500 16 /* NEC VR5500 instruction. */ +#define MIPS_AFL_EXT_LOONGSON_2E 17 /* ST Microelectronics Loongson 2E. */ +#define MIPS_AFL_EXT_LOONGSON_2F 18 /* ST Microelectronics Loongson 2F. */ + +/* Masks for the flags1 word of an ABI flags structure. */ +#define MIPS_AFL_FLAGS1_ODDSPREG 1 /* Uses odd single-precision registers. */ + +/* Object attribute values. */ +enum +{ + /* Not tagged or not using any ABIs affected by the differences. */ + Val_GNU_MIPS_ABI_FP_ANY = 0, + /* Using hard-float -mdouble-float. */ + Val_GNU_MIPS_ABI_FP_DOUBLE = 1, + /* Using hard-float -msingle-float. */ + Val_GNU_MIPS_ABI_FP_SINGLE = 2, + /* Using soft-float. */ + Val_GNU_MIPS_ABI_FP_SOFT = 3, + /* Using -mips32r2 -mfp64. */ + Val_GNU_MIPS_ABI_FP_OLD_64 = 4, + /* Using -mfpxx. */ + Val_GNU_MIPS_ABI_FP_XX = 5, + /* Using -mips32r2 -mfp64. */ + Val_GNU_MIPS_ABI_FP_64 = 6, + /* Using -mips32r2 -mfp64 -mno-odd-spreg. */ + Val_GNU_MIPS_ABI_FP_64A = 7, + /* Maximum allocated FP ABI value. */ + Val_GNU_MIPS_ABI_FP_MAX = 7 +}; + +/* HPPA specific definitions. */ + +/* Legal values for e_flags field of Elf32_Ehdr. */ + +#define EF_PARISC_TRAPNIL 0x00010000 /* Trap nil pointer dereference. */ +#define EF_PARISC_EXT 0x00020000 /* Program uses arch. extensions. */ +#define EF_PARISC_LSB 0x00040000 /* Program expects little endian. */ +#define EF_PARISC_WIDE 0x00080000 /* Program expects wide mode. */ +#define EF_PARISC_NO_KABP 0x00100000 /* No kernel assisted branch + prediction. */ +#define EF_PARISC_LAZYSWAP 0x00400000 /* Allow lazy swapping. */ +#define EF_PARISC_ARCH 0x0000ffff /* Architecture version. */ + +/* Defined values for `e_flags & EF_PARISC_ARCH' are: */ + +#define EFA_PARISC_1_0 0x020b /* PA-RISC 1.0 big-endian. */ +#define EFA_PARISC_1_1 0x0210 /* PA-RISC 1.1 big-endian. */ +#define EFA_PARISC_2_0 0x0214 /* PA-RISC 2.0 big-endian. */ + +/* Additional section indeces. */ + +#define SHN_PARISC_ANSI_COMMON 0xff00 /* Section for tenatively declared + symbols in ANSI C. */ +#define SHN_PARISC_HUGE_COMMON 0xff01 /* Common blocks in huge model. */ + +/* Legal values for sh_type field of Elf32_Shdr. */ + +#define SHT_PARISC_EXT 0x70000000 /* Contains product specific ext. */ +#define SHT_PARISC_UNWIND 0x70000001 /* Unwind information. */ +#define SHT_PARISC_DOC 0x70000002 /* Debug info for optimized code. */ + +/* Legal values for sh_flags field of Elf32_Shdr. */ + +#define SHF_PARISC_SHORT 0x20000000 /* Section with short addressing. */ +#define SHF_PARISC_HUGE 0x40000000 /* Section far from gp. */ +#define SHF_PARISC_SBP 0x80000000 /* Static branch prediction code. */ + +/* Legal values for ST_TYPE subfield of st_info (symbol type). */ + +#define STT_PARISC_MILLICODE 13 /* Millicode function entry point. */ + +#define STT_HP_OPAQUE (STT_LOOS + 0x1) +#define STT_HP_STUB (STT_LOOS + 0x2) + +/* HPPA relocs. */ + +#define R_PARISC_NONE 0 /* No reloc. */ +#define R_PARISC_DIR32 1 /* Direct 32-bit reference. */ +#define R_PARISC_DIR21L 2 /* Left 21 bits of eff. address. */ +#define R_PARISC_DIR17R 3 /* Right 17 bits of eff. address. */ +#define R_PARISC_DIR17F 4 /* 17 bits of eff. address. */ +#define R_PARISC_DIR14R 6 /* Right 14 bits of eff. address. */ +#define R_PARISC_PCREL32 9 /* 32-bit rel. address. */ +#define R_PARISC_PCREL21L 10 /* Left 21 bits of rel. address. */ +#define R_PARISC_PCREL17R 11 /* Right 17 bits of rel. address. */ +#define R_PARISC_PCREL17F 12 /* 17 bits of rel. address. */ +#define R_PARISC_PCREL14R 14 /* Right 14 bits of rel. address. */ +#define R_PARISC_DPREL21L 18 /* Left 21 bits of rel. address. */ +#define R_PARISC_DPREL14R 22 /* Right 14 bits of rel. address. */ +#define R_PARISC_GPREL21L 26 /* GP-relative, left 21 bits. */ +#define R_PARISC_GPREL14R 30 /* GP-relative, right 14 bits. */ +#define R_PARISC_LTOFF21L 34 /* LT-relative, left 21 bits. */ +#define R_PARISC_LTOFF14R 38 /* LT-relative, right 14 bits. */ +#define R_PARISC_SECREL32 41 /* 32 bits section rel. address. */ +#define R_PARISC_SEGBASE 48 /* No relocation, set segment base. */ +#define R_PARISC_SEGREL32 49 /* 32 bits segment rel. address. */ +#define R_PARISC_PLTOFF21L 50 /* PLT rel. address, left 21 bits. */ +#define R_PARISC_PLTOFF14R 54 /* PLT rel. address, right 14 bits. */ +#define R_PARISC_LTOFF_FPTR32 57 /* 32 bits LT-rel. function pointer. */ +#define R_PARISC_LTOFF_FPTR21L 58 /* LT-rel. fct ptr, left 21 bits. */ +#define R_PARISC_LTOFF_FPTR14R 62 /* LT-rel. fct ptr, right 14 bits. */ +#define R_PARISC_FPTR64 64 /* 64 bits function address. */ +#define R_PARISC_PLABEL32 65 /* 32 bits function address. */ +#define R_PARISC_PLABEL21L 66 /* Left 21 bits of fdesc address. */ +#define R_PARISC_PLABEL14R 70 /* Right 14 bits of fdesc address. */ +#define R_PARISC_PCREL64 72 /* 64 bits PC-rel. address. */ +#define R_PARISC_PCREL22F 74 /* 22 bits PC-rel. address. */ +#define R_PARISC_PCREL14WR 75 /* PC-rel. address, right 14 bits. */ +#define R_PARISC_PCREL14DR 76 /* PC rel. address, right 14 bits. */ +#define R_PARISC_PCREL16F 77 /* 16 bits PC-rel. address. */ +#define R_PARISC_PCREL16WF 78 /* 16 bits PC-rel. address. */ +#define R_PARISC_PCREL16DF 79 /* 16 bits PC-rel. address. */ +#define R_PARISC_DIR64 80 /* 64 bits of eff. address. */ +#define R_PARISC_DIR14WR 83 /* 14 bits of eff. address. */ +#define R_PARISC_DIR14DR 84 /* 14 bits of eff. address. */ +#define R_PARISC_DIR16F 85 /* 16 bits of eff. address. */ +#define R_PARISC_DIR16WF 86 /* 16 bits of eff. address. */ +#define R_PARISC_DIR16DF 87 /* 16 bits of eff. address. */ +#define R_PARISC_GPREL64 88 /* 64 bits of GP-rel. address. */ +#define R_PARISC_GPREL14WR 91 /* GP-rel. address, right 14 bits. */ +#define R_PARISC_GPREL14DR 92 /* GP-rel. address, right 14 bits. */ +#define R_PARISC_GPREL16F 93 /* 16 bits GP-rel. address. */ +#define R_PARISC_GPREL16WF 94 /* 16 bits GP-rel. address. */ +#define R_PARISC_GPREL16DF 95 /* 16 bits GP-rel. address. */ +#define R_PARISC_LTOFF64 96 /* 64 bits LT-rel. address. */ +#define R_PARISC_LTOFF14WR 99 /* LT-rel. address, right 14 bits. */ +#define R_PARISC_LTOFF14DR 100 /* LT-rel. address, right 14 bits. */ +#define R_PARISC_LTOFF16F 101 /* 16 bits LT-rel. address. */ +#define R_PARISC_LTOFF16WF 102 /* 16 bits LT-rel. address. */ +#define R_PARISC_LTOFF16DF 103 /* 16 bits LT-rel. address. */ +#define R_PARISC_SECREL64 104 /* 64 bits section rel. address. */ +#define R_PARISC_SEGREL64 112 /* 64 bits segment rel. address. */ +#define R_PARISC_PLTOFF14WR 115 /* PLT-rel. address, right 14 bits. */ +#define R_PARISC_PLTOFF14DR 116 /* PLT-rel. address, right 14 bits. */ +#define R_PARISC_PLTOFF16F 117 /* 16 bits LT-rel. address. */ +#define R_PARISC_PLTOFF16WF 118 /* 16 bits PLT-rel. address. */ +#define R_PARISC_PLTOFF16DF 119 /* 16 bits PLT-rel. address. */ +#define R_PARISC_LTOFF_FPTR64 120 /* 64 bits LT-rel. function ptr. */ +#define R_PARISC_LTOFF_FPTR14WR 123 /* LT-rel. fct. ptr., right 14 bits. */ +#define R_PARISC_LTOFF_FPTR14DR 124 /* LT-rel. fct. ptr., right 14 bits. */ +#define R_PARISC_LTOFF_FPTR16F 125 /* 16 bits LT-rel. function ptr. */ +#define R_PARISC_LTOFF_FPTR16WF 126 /* 16 bits LT-rel. function ptr. */ +#define R_PARISC_LTOFF_FPTR16DF 127 /* 16 bits LT-rel. function ptr. */ +#define R_PARISC_LORESERVE 128 +#define R_PARISC_COPY 128 /* Copy relocation. */ +#define R_PARISC_IPLT 129 /* Dynamic reloc, imported PLT */ +#define R_PARISC_EPLT 130 /* Dynamic reloc, exported PLT */ +#define R_PARISC_TPREL32 153 /* 32 bits TP-rel. address. */ +#define R_PARISC_TPREL21L 154 /* TP-rel. address, left 21 bits. */ +#define R_PARISC_TPREL14R 158 /* TP-rel. address, right 14 bits. */ +#define R_PARISC_LTOFF_TP21L 162 /* LT-TP-rel. address, left 21 bits. */ +#define R_PARISC_LTOFF_TP14R 166 /* LT-TP-rel. address, right 14 bits.*/ +#define R_PARISC_LTOFF_TP14F 167 /* 14 bits LT-TP-rel. address. */ +#define R_PARISC_TPREL64 216 /* 64 bits TP-rel. address. */ +#define R_PARISC_TPREL14WR 219 /* TP-rel. address, right 14 bits. */ +#define R_PARISC_TPREL14DR 220 /* TP-rel. address, right 14 bits. */ +#define R_PARISC_TPREL16F 221 /* 16 bits TP-rel. address. */ +#define R_PARISC_TPREL16WF 222 /* 16 bits TP-rel. address. */ +#define R_PARISC_TPREL16DF 223 /* 16 bits TP-rel. address. */ +#define R_PARISC_LTOFF_TP64 224 /* 64 bits LT-TP-rel. address. */ +#define R_PARISC_LTOFF_TP14WR 227 /* LT-TP-rel. address, right 14 bits.*/ +#define R_PARISC_LTOFF_TP14DR 228 /* LT-TP-rel. address, right 14 bits.*/ +#define R_PARISC_LTOFF_TP16F 229 /* 16 bits LT-TP-rel. address. */ +#define R_PARISC_LTOFF_TP16WF 230 /* 16 bits LT-TP-rel. address. */ +#define R_PARISC_LTOFF_TP16DF 231 /* 16 bits LT-TP-rel. address. */ +#define R_PARISC_GNU_VTENTRY 232 +#define R_PARISC_GNU_VTINHERIT 233 +#define R_PARISC_TLS_GD21L 234 /* GD 21-bit left. */ +#define R_PARISC_TLS_GD14R 235 /* GD 14-bit right. */ +#define R_PARISC_TLS_GDCALL 236 /* GD call to __t_g_a. */ +#define R_PARISC_TLS_LDM21L 237 /* LD module 21-bit left. */ +#define R_PARISC_TLS_LDM14R 238 /* LD module 14-bit right. */ +#define R_PARISC_TLS_LDMCALL 239 /* LD module call to __t_g_a. */ +#define R_PARISC_TLS_LDO21L 240 /* LD offset 21-bit left. */ +#define R_PARISC_TLS_LDO14R 241 /* LD offset 14-bit right. */ +#define R_PARISC_TLS_DTPMOD32 242 /* DTP module 32-bit. */ +#define R_PARISC_TLS_DTPMOD64 243 /* DTP module 64-bit. */ +#define R_PARISC_TLS_DTPOFF32 244 /* DTP offset 32-bit. */ +#define R_PARISC_TLS_DTPOFF64 245 /* DTP offset 32-bit. */ +#define R_PARISC_TLS_LE21L R_PARISC_TPREL21L +#define R_PARISC_TLS_LE14R R_PARISC_TPREL14R +#define R_PARISC_TLS_IE21L R_PARISC_LTOFF_TP21L +#define R_PARISC_TLS_IE14R R_PARISC_LTOFF_TP14R +#define R_PARISC_TLS_TPREL32 R_PARISC_TPREL32 +#define R_PARISC_TLS_TPREL64 R_PARISC_TPREL64 +#define R_PARISC_HIRESERVE 255 + +/* Legal values for p_type field of Elf32_Phdr/Elf64_Phdr. */ + +#define PT_HP_TLS (PT_LOOS + 0x0) +#define PT_HP_CORE_NONE (PT_LOOS + 0x1) +#define PT_HP_CORE_VERSION (PT_LOOS + 0x2) +#define PT_HP_CORE_KERNEL (PT_LOOS + 0x3) +#define PT_HP_CORE_COMM (PT_LOOS + 0x4) +#define PT_HP_CORE_PROC (PT_LOOS + 0x5) +#define PT_HP_CORE_LOADABLE (PT_LOOS + 0x6) +#define PT_HP_CORE_STACK (PT_LOOS + 0x7) +#define PT_HP_CORE_SHM (PT_LOOS + 0x8) +#define PT_HP_CORE_MMF (PT_LOOS + 0x9) +#define PT_HP_PARALLEL (PT_LOOS + 0x10) +#define PT_HP_FASTBIND (PT_LOOS + 0x11) +#define PT_HP_OPT_ANNOT (PT_LOOS + 0x12) +#define PT_HP_HSL_ANNOT (PT_LOOS + 0x13) +#define PT_HP_STACK (PT_LOOS + 0x14) + +#define PT_PARISC_ARCHEXT 0x70000000 +#define PT_PARISC_UNWIND 0x70000001 + +/* Legal values for p_flags field of Elf32_Phdr/Elf64_Phdr. */ + +#define PF_PARISC_SBP 0x08000000 + +#define PF_HP_PAGE_SIZE 0x00100000 +#define PF_HP_FAR_SHARED 0x00200000 +#define PF_HP_NEAR_SHARED 0x00400000 +#define PF_HP_CODE 0x01000000 +#define PF_HP_MODIFY 0x02000000 +#define PF_HP_LAZYSWAP 0x04000000 +#define PF_HP_SBP 0x08000000 + + +/* Alpha specific definitions. */ + +/* Legal values for e_flags field of Elf64_Ehdr. */ + +#define EF_ALPHA_32BIT 1 /* All addresses must be < 2GB. */ +#define EF_ALPHA_CANRELAX 2 /* Relocations for relaxing exist. */ + +/* Legal values for sh_type field of Elf64_Shdr. */ + +/* These two are primerily concerned with ECOFF debugging info. */ +#define SHT_ALPHA_DEBUG 0x70000001 +#define SHT_ALPHA_REGINFO 0x70000002 + +/* Legal values for sh_flags field of Elf64_Shdr. */ + +#define SHF_ALPHA_GPREL 0x10000000 + +/* Legal values for st_other field of Elf64_Sym. */ +#define STO_ALPHA_NOPV 0x80 /* No PV required. */ +#define STO_ALPHA_STD_GPLOAD 0x88 /* PV only used for initial ldgp. */ + +/* Alpha relocs. */ + +#define R_ALPHA_NONE 0 /* No reloc */ +#define R_ALPHA_REFLONG 1 /* Direct 32 bit */ +#define R_ALPHA_REFQUAD 2 /* Direct 64 bit */ +#define R_ALPHA_GPREL32 3 /* GP relative 32 bit */ +#define R_ALPHA_LITERAL 4 /* GP relative 16 bit w/optimization */ +#define R_ALPHA_LITUSE 5 /* Optimization hint for LITERAL */ +#define R_ALPHA_GPDISP 6 /* Add displacement to GP */ +#define R_ALPHA_BRADDR 7 /* PC+4 relative 23 bit shifted */ +#define R_ALPHA_HINT 8 /* PC+4 relative 16 bit shifted */ +#define R_ALPHA_SREL16 9 /* PC relative 16 bit */ +#define R_ALPHA_SREL32 10 /* PC relative 32 bit */ +#define R_ALPHA_SREL64 11 /* PC relative 64 bit */ +#define R_ALPHA_GPRELHIGH 17 /* GP relative 32 bit, high 16 bits */ +#define R_ALPHA_GPRELLOW 18 /* GP relative 32 bit, low 16 bits */ +#define R_ALPHA_GPREL16 19 /* GP relative 16 bit */ +#define R_ALPHA_COPY 24 /* Copy symbol at runtime */ +#define R_ALPHA_GLOB_DAT 25 /* Create GOT entry */ +#define R_ALPHA_JMP_SLOT 26 /* Create PLT entry */ +#define R_ALPHA_RELATIVE 27 /* Adjust by program base */ +#define R_ALPHA_TLS_GD_HI 28 +#define R_ALPHA_TLSGD 29 +#define R_ALPHA_TLS_LDM 30 +#define R_ALPHA_DTPMOD64 31 +#define R_ALPHA_GOTDTPREL 32 +#define R_ALPHA_DTPREL64 33 +#define R_ALPHA_DTPRELHI 34 +#define R_ALPHA_DTPRELLO 35 +#define R_ALPHA_DTPREL16 36 +#define R_ALPHA_GOTTPREL 37 +#define R_ALPHA_TPREL64 38 +#define R_ALPHA_TPRELHI 39 +#define R_ALPHA_TPRELLO 40 +#define R_ALPHA_TPREL16 41 +/* Keep this the last entry. */ +#define R_ALPHA_NUM 46 + +/* Magic values of the LITUSE relocation addend. */ +#define LITUSE_ALPHA_ADDR 0 +#define LITUSE_ALPHA_BASE 1 +#define LITUSE_ALPHA_BYTOFF 2 +#define LITUSE_ALPHA_JSR 3 +#define LITUSE_ALPHA_TLS_GD 4 +#define LITUSE_ALPHA_TLS_LDM 5 + +/* Legal values for d_tag of Elf64_Dyn. */ +#define DT_ALPHA_PLTRO (DT_LOPROC + 0) +#define DT_ALPHA_NUM 1 + +/* PowerPC specific declarations */ + +/* Values for Elf32/64_Ehdr.e_flags. */ +#define EF_PPC_EMB 0x80000000 /* PowerPC embedded flag */ + +/* Cygnus local bits below */ +#define EF_PPC_RELOCATABLE 0x00010000 /* PowerPC -mrelocatable flag*/ +#define EF_PPC_RELOCATABLE_LIB 0x00008000 /* PowerPC -mrelocatable-lib + flag */ + +/* PowerPC relocations defined by the ABIs */ +#define R_PPC_NONE 0 +#define R_PPC_ADDR32 1 /* 32bit absolute address */ +#define R_PPC_ADDR24 2 /* 26bit address, 2 bits ignored. */ +#define R_PPC_ADDR16 3 /* 16bit absolute address */ +#define R_PPC_ADDR16_LO 4 /* lower 16bit of absolute address */ +#define R_PPC_ADDR16_HI 5 /* high 16bit of absolute address */ +#define R_PPC_ADDR16_HA 6 /* adjusted high 16bit */ +#define R_PPC_ADDR14 7 /* 16bit address, 2 bits ignored */ +#define R_PPC_ADDR14_BRTAKEN 8 +#define R_PPC_ADDR14_BRNTAKEN 9 +#define R_PPC_REL24 10 /* PC relative 26 bit */ +#define R_PPC_REL14 11 /* PC relative 16 bit */ +#define R_PPC_REL14_BRTAKEN 12 +#define R_PPC_REL14_BRNTAKEN 13 +#define R_PPC_GOT16 14 +#define R_PPC_GOT16_LO 15 +#define R_PPC_GOT16_HI 16 +#define R_PPC_GOT16_HA 17 +#define R_PPC_PLTREL24 18 +#define R_PPC_COPY 19 +#define R_PPC_GLOB_DAT 20 +#define R_PPC_JMP_SLOT 21 +#define R_PPC_RELATIVE 22 +#define R_PPC_LOCAL24PC 23 +#define R_PPC_UADDR32 24 +#define R_PPC_UADDR16 25 +#define R_PPC_REL32 26 +#define R_PPC_PLT32 27 +#define R_PPC_PLTREL32 28 +#define R_PPC_PLT16_LO 29 +#define R_PPC_PLT16_HI 30 +#define R_PPC_PLT16_HA 31 +#define R_PPC_SDAREL16 32 +#define R_PPC_SECTOFF 33 +#define R_PPC_SECTOFF_LO 34 +#define R_PPC_SECTOFF_HI 35 +#define R_PPC_SECTOFF_HA 36 + +/* PowerPC relocations defined for the TLS access ABI. */ +#define R_PPC_TLS 67 /* none (sym+add)@tls */ +#define R_PPC_DTPMOD32 68 /* word32 (sym+add)@dtpmod */ +#define R_PPC_TPREL16 69 /* half16* (sym+add)@tprel */ +#define R_PPC_TPREL16_LO 70 /* half16 (sym+add)@tprel@l */ +#define R_PPC_TPREL16_HI 71 /* half16 (sym+add)@tprel@h */ +#define R_PPC_TPREL16_HA 72 /* half16 (sym+add)@tprel@ha */ +#define R_PPC_TPREL32 73 /* word32 (sym+add)@tprel */ +#define R_PPC_DTPREL16 74 /* half16* (sym+add)@dtprel */ +#define R_PPC_DTPREL16_LO 75 /* half16 (sym+add)@dtprel@l */ +#define R_PPC_DTPREL16_HI 76 /* half16 (sym+add)@dtprel@h */ +#define R_PPC_DTPREL16_HA 77 /* half16 (sym+add)@dtprel@ha */ +#define R_PPC_DTPREL32 78 /* word32 (sym+add)@dtprel */ +#define R_PPC_GOT_TLSGD16 79 /* half16* (sym+add)@got@tlsgd */ +#define R_PPC_GOT_TLSGD16_LO 80 /* half16 (sym+add)@got@tlsgd@l */ +#define R_PPC_GOT_TLSGD16_HI 81 /* half16 (sym+add)@got@tlsgd@h */ +#define R_PPC_GOT_TLSGD16_HA 82 /* half16 (sym+add)@got@tlsgd@ha */ +#define R_PPC_GOT_TLSLD16 83 /* half16* (sym+add)@got@tlsld */ +#define R_PPC_GOT_TLSLD16_LO 84 /* half16 (sym+add)@got@tlsld@l */ +#define R_PPC_GOT_TLSLD16_HI 85 /* half16 (sym+add)@got@tlsld@h */ +#define R_PPC_GOT_TLSLD16_HA 86 /* half16 (sym+add)@got@tlsld@ha */ +#define R_PPC_GOT_TPREL16 87 /* half16* (sym+add)@got@tprel */ +#define R_PPC_GOT_TPREL16_LO 88 /* half16 (sym+add)@got@tprel@l */ +#define R_PPC_GOT_TPREL16_HI 89 /* half16 (sym+add)@got@tprel@h */ +#define R_PPC_GOT_TPREL16_HA 90 /* half16 (sym+add)@got@tprel@ha */ +#define R_PPC_GOT_DTPREL16 91 /* half16* (sym+add)@got@dtprel */ +#define R_PPC_GOT_DTPREL16_LO 92 /* half16* (sym+add)@got@dtprel@l */ +#define R_PPC_GOT_DTPREL16_HI 93 /* half16* (sym+add)@got@dtprel@h */ +#define R_PPC_GOT_DTPREL16_HA 94 /* half16* (sym+add)@got@dtprel@ha */ +#define R_PPC_TLSGD 95 /* none (sym+add)@tlsgd */ +#define R_PPC_TLSLD 96 /* none (sym+add)@tlsld */ + +/* The remaining relocs are from the Embedded ELF ABI, and are not + in the SVR4 ELF ABI. */ +#define R_PPC_EMB_NADDR32 101 +#define R_PPC_EMB_NADDR16 102 +#define R_PPC_EMB_NADDR16_LO 103 +#define R_PPC_EMB_NADDR16_HI 104 +#define R_PPC_EMB_NADDR16_HA 105 +#define R_PPC_EMB_SDAI16 106 +#define R_PPC_EMB_SDA2I16 107 +#define R_PPC_EMB_SDA2REL 108 +#define R_PPC_EMB_SDA21 109 /* 16 bit offset in SDA */ +#define R_PPC_EMB_MRKREF 110 +#define R_PPC_EMB_RELSEC16 111 +#define R_PPC_EMB_RELST_LO 112 +#define R_PPC_EMB_RELST_HI 113 +#define R_PPC_EMB_RELST_HA 114 +#define R_PPC_EMB_BIT_FLD 115 +#define R_PPC_EMB_RELSDA 116 /* 16 bit relative offset in SDA */ + +/* Diab tool relocations. */ +#define R_PPC_DIAB_SDA21_LO 180 /* like EMB_SDA21, but lower 16 bit */ +#define R_PPC_DIAB_SDA21_HI 181 /* like EMB_SDA21, but high 16 bit */ +#define R_PPC_DIAB_SDA21_HA 182 /* like EMB_SDA21, adjusted high 16 */ +#define R_PPC_DIAB_RELSDA_LO 183 /* like EMB_RELSDA, but lower 16 bit */ +#define R_PPC_DIAB_RELSDA_HI 184 /* like EMB_RELSDA, but high 16 bit */ +#define R_PPC_DIAB_RELSDA_HA 185 /* like EMB_RELSDA, adjusted high 16 */ + +/* GNU extension to support local ifunc. */ +#define R_PPC_IRELATIVE 248 + +/* GNU relocs used in PIC code sequences. */ +#define R_PPC_REL16 249 /* half16 (sym+add-.) */ +#define R_PPC_REL16_LO 250 /* half16 (sym+add-.)@l */ +#define R_PPC_REL16_HI 251 /* half16 (sym+add-.)@h */ +#define R_PPC_REL16_HA 252 /* half16 (sym+add-.)@ha */ + +/* This is a phony reloc to handle any old fashioned TOC16 references + that may still be in object files. */ +#define R_PPC_TOC16 255 + +/* PowerPC specific values for the Dyn d_tag field. */ +#define DT_PPC_GOT (DT_LOPROC + 0) +#define DT_PPC_OPT (DT_LOPROC + 1) +#define DT_PPC_NUM 2 + +/* PowerPC specific values for the DT_PPC_OPT Dyn entry. */ +#define PPC_OPT_TLS 1 + +/* PowerPC64 relocations defined by the ABIs */ +#define R_PPC64_NONE R_PPC_NONE +#define R_PPC64_ADDR32 R_PPC_ADDR32 /* 32bit absolute address */ +#define R_PPC64_ADDR24 R_PPC_ADDR24 /* 26bit address, word aligned */ +#define R_PPC64_ADDR16 R_PPC_ADDR16 /* 16bit absolute address */ +#define R_PPC64_ADDR16_LO R_PPC_ADDR16_LO /* lower 16bits of address */ +#define R_PPC64_ADDR16_HI R_PPC_ADDR16_HI /* high 16bits of address. */ +#define R_PPC64_ADDR16_HA R_PPC_ADDR16_HA /* adjusted high 16bits. */ +#define R_PPC64_ADDR14 R_PPC_ADDR14 /* 16bit address, word aligned */ +#define R_PPC64_ADDR14_BRTAKEN R_PPC_ADDR14_BRTAKEN +#define R_PPC64_ADDR14_BRNTAKEN R_PPC_ADDR14_BRNTAKEN +#define R_PPC64_REL24 R_PPC_REL24 /* PC-rel. 26 bit, word aligned */ +#define R_PPC64_REL14 R_PPC_REL14 /* PC relative 16 bit */ +#define R_PPC64_REL14_BRTAKEN R_PPC_REL14_BRTAKEN +#define R_PPC64_REL14_BRNTAKEN R_PPC_REL14_BRNTAKEN +#define R_PPC64_GOT16 R_PPC_GOT16 +#define R_PPC64_GOT16_LO R_PPC_GOT16_LO +#define R_PPC64_GOT16_HI R_PPC_GOT16_HI +#define R_PPC64_GOT16_HA R_PPC_GOT16_HA + +#define R_PPC64_COPY R_PPC_COPY +#define R_PPC64_GLOB_DAT R_PPC_GLOB_DAT +#define R_PPC64_JMP_SLOT R_PPC_JMP_SLOT +#define R_PPC64_RELATIVE R_PPC_RELATIVE + +#define R_PPC64_UADDR32 R_PPC_UADDR32 +#define R_PPC64_UADDR16 R_PPC_UADDR16 +#define R_PPC64_REL32 R_PPC_REL32 +#define R_PPC64_PLT32 R_PPC_PLT32 +#define R_PPC64_PLTREL32 R_PPC_PLTREL32 +#define R_PPC64_PLT16_LO R_PPC_PLT16_LO +#define R_PPC64_PLT16_HI R_PPC_PLT16_HI +#define R_PPC64_PLT16_HA R_PPC_PLT16_HA + +#define R_PPC64_SECTOFF R_PPC_SECTOFF +#define R_PPC64_SECTOFF_LO R_PPC_SECTOFF_LO +#define R_PPC64_SECTOFF_HI R_PPC_SECTOFF_HI +#define R_PPC64_SECTOFF_HA R_PPC_SECTOFF_HA +#define R_PPC64_ADDR30 37 /* word30 (S + A - P) >> 2 */ +#define R_PPC64_ADDR64 38 /* doubleword64 S + A */ +#define R_PPC64_ADDR16_HIGHER 39 /* half16 #higher(S + A) */ +#define R_PPC64_ADDR16_HIGHERA 40 /* half16 #highera(S + A) */ +#define R_PPC64_ADDR16_HIGHEST 41 /* half16 #highest(S + A) */ +#define R_PPC64_ADDR16_HIGHESTA 42 /* half16 #highesta(S + A) */ +#define R_PPC64_UADDR64 43 /* doubleword64 S + A */ +#define R_PPC64_REL64 44 /* doubleword64 S + A - P */ +#define R_PPC64_PLT64 45 /* doubleword64 L + A */ +#define R_PPC64_PLTREL64 46 /* doubleword64 L + A - P */ +#define R_PPC64_TOC16 47 /* half16* S + A - .TOC */ +#define R_PPC64_TOC16_LO 48 /* half16 #lo(S + A - .TOC.) */ +#define R_PPC64_TOC16_HI 49 /* half16 #hi(S + A - .TOC.) */ +#define R_PPC64_TOC16_HA 50 /* half16 #ha(S + A - .TOC.) */ +#define R_PPC64_TOC 51 /* doubleword64 .TOC */ +#define R_PPC64_PLTGOT16 52 /* half16* M + A */ +#define R_PPC64_PLTGOT16_LO 53 /* half16 #lo(M + A) */ +#define R_PPC64_PLTGOT16_HI 54 /* half16 #hi(M + A) */ +#define R_PPC64_PLTGOT16_HA 55 /* half16 #ha(M + A) */ + +#define R_PPC64_ADDR16_DS 56 /* half16ds* (S + A) >> 2 */ +#define R_PPC64_ADDR16_LO_DS 57 /* half16ds #lo(S + A) >> 2 */ +#define R_PPC64_GOT16_DS 58 /* half16ds* (G + A) >> 2 */ +#define R_PPC64_GOT16_LO_DS 59 /* half16ds #lo(G + A) >> 2 */ +#define R_PPC64_PLT16_LO_DS 60 /* half16ds #lo(L + A) >> 2 */ +#define R_PPC64_SECTOFF_DS 61 /* half16ds* (R + A) >> 2 */ +#define R_PPC64_SECTOFF_LO_DS 62 /* half16ds #lo(R + A) >> 2 */ +#define R_PPC64_TOC16_DS 63 /* half16ds* (S + A - .TOC.) >> 2 */ +#define R_PPC64_TOC16_LO_DS 64 /* half16ds #lo(S + A - .TOC.) >> 2 */ +#define R_PPC64_PLTGOT16_DS 65 /* half16ds* (M + A) >> 2 */ +#define R_PPC64_PLTGOT16_LO_DS 66 /* half16ds #lo(M + A) >> 2 */ + +/* PowerPC64 relocations defined for the TLS access ABI. */ +#define R_PPC64_TLS 67 /* none (sym+add)@tls */ +#define R_PPC64_DTPMOD64 68 /* doubleword64 (sym+add)@dtpmod */ +#define R_PPC64_TPREL16 69 /* half16* (sym+add)@tprel */ +#define R_PPC64_TPREL16_LO 70 /* half16 (sym+add)@tprel@l */ +#define R_PPC64_TPREL16_HI 71 /* half16 (sym+add)@tprel@h */ +#define R_PPC64_TPREL16_HA 72 /* half16 (sym+add)@tprel@ha */ +#define R_PPC64_TPREL64 73 /* doubleword64 (sym+add)@tprel */ +#define R_PPC64_DTPREL16 74 /* half16* (sym+add)@dtprel */ +#define R_PPC64_DTPREL16_LO 75 /* half16 (sym+add)@dtprel@l */ +#define R_PPC64_DTPREL16_HI 76 /* half16 (sym+add)@dtprel@h */ +#define R_PPC64_DTPREL16_HA 77 /* half16 (sym+add)@dtprel@ha */ +#define R_PPC64_DTPREL64 78 /* doubleword64 (sym+add)@dtprel */ +#define R_PPC64_GOT_TLSGD16 79 /* half16* (sym+add)@got@tlsgd */ +#define R_PPC64_GOT_TLSGD16_LO 80 /* half16 (sym+add)@got@tlsgd@l */ +#define R_PPC64_GOT_TLSGD16_HI 81 /* half16 (sym+add)@got@tlsgd@h */ +#define R_PPC64_GOT_TLSGD16_HA 82 /* half16 (sym+add)@got@tlsgd@ha */ +#define R_PPC64_GOT_TLSLD16 83 /* half16* (sym+add)@got@tlsld */ +#define R_PPC64_GOT_TLSLD16_LO 84 /* half16 (sym+add)@got@tlsld@l */ +#define R_PPC64_GOT_TLSLD16_HI 85 /* half16 (sym+add)@got@tlsld@h */ +#define R_PPC64_GOT_TLSLD16_HA 86 /* half16 (sym+add)@got@tlsld@ha */ +#define R_PPC64_GOT_TPREL16_DS 87 /* half16ds* (sym+add)@got@tprel */ +#define R_PPC64_GOT_TPREL16_LO_DS 88 /* half16ds (sym+add)@got@tprel@l */ +#define R_PPC64_GOT_TPREL16_HI 89 /* half16 (sym+add)@got@tprel@h */ +#define R_PPC64_GOT_TPREL16_HA 90 /* half16 (sym+add)@got@tprel@ha */ +#define R_PPC64_GOT_DTPREL16_DS 91 /* half16ds* (sym+add)@got@dtprel */ +#define R_PPC64_GOT_DTPREL16_LO_DS 92 /* half16ds (sym+add)@got@dtprel@l */ +#define R_PPC64_GOT_DTPREL16_HI 93 /* half16 (sym+add)@got@dtprel@h */ +#define R_PPC64_GOT_DTPREL16_HA 94 /* half16 (sym+add)@got@dtprel@ha */ +#define R_PPC64_TPREL16_DS 95 /* half16ds* (sym+add)@tprel */ +#define R_PPC64_TPREL16_LO_DS 96 /* half16ds (sym+add)@tprel@l */ +#define R_PPC64_TPREL16_HIGHER 97 /* half16 (sym+add)@tprel@higher */ +#define R_PPC64_TPREL16_HIGHERA 98 /* half16 (sym+add)@tprel@highera */ +#define R_PPC64_TPREL16_HIGHEST 99 /* half16 (sym+add)@tprel@highest */ +#define R_PPC64_TPREL16_HIGHESTA 100 /* half16 (sym+add)@tprel@highesta */ +#define R_PPC64_DTPREL16_DS 101 /* half16ds* (sym+add)@dtprel */ +#define R_PPC64_DTPREL16_LO_DS 102 /* half16ds (sym+add)@dtprel@l */ +#define R_PPC64_DTPREL16_HIGHER 103 /* half16 (sym+add)@dtprel@higher */ +#define R_PPC64_DTPREL16_HIGHERA 104 /* half16 (sym+add)@dtprel@highera */ +#define R_PPC64_DTPREL16_HIGHEST 105 /* half16 (sym+add)@dtprel@highest */ +#define R_PPC64_DTPREL16_HIGHESTA 106 /* half16 (sym+add)@dtprel@highesta */ +#define R_PPC64_TLSGD 107 /* none (sym+add)@tlsgd */ +#define R_PPC64_TLSLD 108 /* none (sym+add)@tlsld */ +#define R_PPC64_TOCSAVE 109 /* none */ + +/* Added when HA and HI relocs were changed to report overflows. */ +#define R_PPC64_ADDR16_HIGH 110 +#define R_PPC64_ADDR16_HIGHA 111 +#define R_PPC64_TPREL16_HIGH 112 +#define R_PPC64_TPREL16_HIGHA 113 +#define R_PPC64_DTPREL16_HIGH 114 +#define R_PPC64_DTPREL16_HIGHA 115 + +/* GNU extension to support local ifunc. */ +#define R_PPC64_JMP_IREL 247 +#define R_PPC64_IRELATIVE 248 +#define R_PPC64_REL16 249 /* half16 (sym+add-.) */ +#define R_PPC64_REL16_LO 250 /* half16 (sym+add-.)@l */ +#define R_PPC64_REL16_HI 251 /* half16 (sym+add-.)@h */ +#define R_PPC64_REL16_HA 252 /* half16 (sym+add-.)@ha */ + +/* e_flags bits specifying ABI. + 1 for original function descriptor using ABI, + 2 for revised ABI without function descriptors, + 0 for unspecified or not using any features affected by the differences. */ +#define EF_PPC64_ABI 3 + +/* PowerPC64 specific values for the Dyn d_tag field. */ +#define DT_PPC64_GLINK (DT_LOPROC + 0) +#define DT_PPC64_OPD (DT_LOPROC + 1) +#define DT_PPC64_OPDSZ (DT_LOPROC + 2) +#define DT_PPC64_OPT (DT_LOPROC + 3) +#define DT_PPC64_NUM 4 + +/* PowerPC64 specific values for the DT_PPC64_OPT Dyn entry. */ +#define PPC64_OPT_TLS 1 +#define PPC64_OPT_MULTI_TOC 2 + +/* PowerPC64 specific values for the Elf64_Sym st_other field. */ +#define STO_PPC64_LOCAL_BIT 5 +#define STO_PPC64_LOCAL_MASK (7 << STO_PPC64_LOCAL_BIT) +#define PPC64_LOCAL_ENTRY_OFFSET(other) \ + (((1 << (((other) & STO_PPC64_LOCAL_MASK) >> STO_PPC64_LOCAL_BIT)) >> 2) << 2) + + +/* ARM specific declarations */ + +/* Processor specific flags for the ELF header e_flags field. */ +#define EF_ARM_RELEXEC 0x01 +#define EF_ARM_HASENTRY 0x02 +#define EF_ARM_INTERWORK 0x04 +#define EF_ARM_APCS_26 0x08 +#define EF_ARM_APCS_FLOAT 0x10 +#define EF_ARM_PIC 0x20 +#define EF_ARM_ALIGN8 0x40 /* 8-bit structure alignment is in use */ +#define EF_ARM_NEW_ABI 0x80 +#define EF_ARM_OLD_ABI 0x100 +#define EF_ARM_SOFT_FLOAT 0x200 +#define EF_ARM_VFP_FLOAT 0x400 +#define EF_ARM_MAVERICK_FLOAT 0x800 + +#define EF_ARM_ABI_FLOAT_SOFT 0x200 /* NB conflicts with EF_ARM_SOFT_FLOAT */ +#define EF_ARM_ABI_FLOAT_HARD 0x400 /* NB conflicts with EF_ARM_VFP_FLOAT */ + + +/* Other constants defined in the ARM ELF spec. version B-01. */ +/* NB. These conflict with values defined above. */ +#define EF_ARM_SYMSARESORTED 0x04 +#define EF_ARM_DYNSYMSUSESEGIDX 0x08 +#define EF_ARM_MAPSYMSFIRST 0x10 +#define EF_ARM_EABIMASK 0XFF000000 + +/* Constants defined in AAELF. */ +#define EF_ARM_BE8 0x00800000 +#define EF_ARM_LE8 0x00400000 + +#define EF_ARM_EABI_VERSION(flags) ((flags) & EF_ARM_EABIMASK) +#define EF_ARM_EABI_UNKNOWN 0x00000000 +#define EF_ARM_EABI_VER1 0x01000000 +#define EF_ARM_EABI_VER2 0x02000000 +#define EF_ARM_EABI_VER3 0x03000000 +#define EF_ARM_EABI_VER4 0x04000000 +#define EF_ARM_EABI_VER5 0x05000000 + +/* Additional symbol types for Thumb. */ +#define STT_ARM_TFUNC STT_LOPROC /* A Thumb function. */ +#define STT_ARM_16BIT STT_HIPROC /* A Thumb label. */ + +/* ARM-specific values for sh_flags */ +#define SHF_ARM_ENTRYSECT 0x10000000 /* Section contains an entry point */ +#define SHF_ARM_COMDEF 0x80000000 /* Section may be multiply defined + in the input to a link step. */ + +/* ARM-specific program header flags */ +#define PF_ARM_SB 0x10000000 /* Segment contains the location + addressed by the static base. */ +#define PF_ARM_PI 0x20000000 /* Position-independent segment. */ +#define PF_ARM_ABS 0x40000000 /* Absolute segment. */ + +/* Processor specific values for the Phdr p_type field. */ +#define PT_ARM_EXIDX (PT_LOPROC + 1) /* ARM unwind segment. */ + +/* Processor specific values for the Shdr sh_type field. */ +#define SHT_ARM_EXIDX (SHT_LOPROC + 1) /* ARM unwind section. */ +#define SHT_ARM_PREEMPTMAP (SHT_LOPROC + 2) /* Preemption details. */ +#define SHT_ARM_ATTRIBUTES (SHT_LOPROC + 3) /* ARM attributes section. */ + + +/* AArch64 relocs. */ + +#define R_AARCH64_NONE 0 /* No relocation. */ + +/* ILP32 AArch64 relocs. */ +#define R_AARCH64_P32_ABS32 1 /* Direct 32 bit. */ +#define R_AARCH64_P32_COPY 180 /* Copy symbol at runtime. */ +#define R_AARCH64_P32_GLOB_DAT 181 /* Create GOT entry. */ +#define R_AARCH64_P32_JUMP_SLOT 182 /* Create PLT entry. */ +#define R_AARCH64_P32_RELATIVE 183 /* Adjust by program base. */ +#define R_AARCH64_P32_TLS_DTPMOD 184 /* Module number, 32 bit. */ +#define R_AARCH64_P32_TLS_DTPREL 185 /* Module-relative offset, 32 bit. */ +#define R_AARCH64_P32_TLS_TPREL 186 /* TP-relative offset, 32 bit. */ +#define R_AARCH64_P32_TLSDESC 187 /* TLS Descriptor. */ +#define R_AARCH64_P32_IRELATIVE 188 /* STT_GNU_IFUNC relocation. */ + +/* LP64 AArch64 relocs. */ +#define R_AARCH64_ABS64 257 /* Direct 64 bit. */ +#define R_AARCH64_ABS32 258 /* Direct 32 bit. */ +#define R_AARCH64_ABS16 259 /* Direct 16-bit. */ +#define R_AARCH64_PREL64 260 /* PC-relative 64-bit. */ +#define R_AARCH64_PREL32 261 /* PC-relative 32-bit. */ +#define R_AARCH64_PREL16 262 /* PC-relative 16-bit. */ +#define R_AARCH64_MOVW_UABS_G0 263 /* Dir. MOVZ imm. from bits 15:0. */ +#define R_AARCH64_MOVW_UABS_G0_NC 264 /* Likewise for MOVK; no check. */ +#define R_AARCH64_MOVW_UABS_G1 265 /* Dir. MOVZ imm. from bits 31:16. */ +#define R_AARCH64_MOVW_UABS_G1_NC 266 /* Likewise for MOVK; no check. */ +#define R_AARCH64_MOVW_UABS_G2 267 /* Dir. MOVZ imm. from bits 47:32. */ +#define R_AARCH64_MOVW_UABS_G2_NC 268 /* Likewise for MOVK; no check. */ +#define R_AARCH64_MOVW_UABS_G3 269 /* Dir. MOV{K,Z} imm. from 63:48. */ +#define R_AARCH64_MOVW_SABS_G0 270 /* Dir. MOV{N,Z} imm. from 15:0. */ +#define R_AARCH64_MOVW_SABS_G1 271 /* Dir. MOV{N,Z} imm. from 31:16. */ +#define R_AARCH64_MOVW_SABS_G2 272 /* Dir. MOV{N,Z} imm. from 47:32. */ +#define R_AARCH64_LD_PREL_LO19 273 /* PC-rel. LD imm. from bits 20:2. */ +#define R_AARCH64_ADR_PREL_LO21 274 /* PC-rel. ADR imm. from bits 20:0. */ +#define R_AARCH64_ADR_PREL_PG_HI21 275 /* Page-rel. ADRP imm. from 32:12. */ +#define R_AARCH64_ADR_PREL_PG_HI21_NC 276 /* Likewise; no overflow check. */ +#define R_AARCH64_ADD_ABS_LO12_NC 277 /* Dir. ADD imm. from bits 11:0. */ +#define R_AARCH64_LDST8_ABS_LO12_NC 278 /* Likewise for LD/ST; no check. */ +#define R_AARCH64_TSTBR14 279 /* PC-rel. TBZ/TBNZ imm. from 15:2. */ +#define R_AARCH64_CONDBR19 280 /* PC-rel. cond. br. imm. from 20:2. */ +#define R_AARCH64_JUMP26 282 /* PC-rel. B imm. from bits 27:2. */ +#define R_AARCH64_CALL26 283 /* Likewise for CALL. */ +#define R_AARCH64_LDST16_ABS_LO12_NC 284 /* Dir. ADD imm. from bits 11:1. */ +#define R_AARCH64_LDST32_ABS_LO12_NC 285 /* Likewise for bits 11:2. */ +#define R_AARCH64_LDST64_ABS_LO12_NC 286 /* Likewise for bits 11:3. */ +#define R_AARCH64_MOVW_PREL_G0 287 /* PC-rel. MOV{N,Z} imm. from 15:0. */ +#define R_AARCH64_MOVW_PREL_G0_NC 288 /* Likewise for MOVK; no check. */ +#define R_AARCH64_MOVW_PREL_G1 289 /* PC-rel. MOV{N,Z} imm. from 31:16. */ +#define R_AARCH64_MOVW_PREL_G1_NC 290 /* Likewise for MOVK; no check. */ +#define R_AARCH64_MOVW_PREL_G2 291 /* PC-rel. MOV{N,Z} imm. from 47:32. */ +#define R_AARCH64_MOVW_PREL_G2_NC 292 /* Likewise for MOVK; no check. */ +#define R_AARCH64_MOVW_PREL_G3 293 /* PC-rel. MOV{N,Z} imm. from 63:48. */ +#define R_AARCH64_LDST128_ABS_LO12_NC 299 /* Dir. ADD imm. from bits 11:4. */ +#define R_AARCH64_MOVW_GOTOFF_G0 300 /* GOT-rel. off. MOV{N,Z} imm. 15:0. */ +#define R_AARCH64_MOVW_GOTOFF_G0_NC 301 /* Likewise for MOVK; no check. */ +#define R_AARCH64_MOVW_GOTOFF_G1 302 /* GOT-rel. o. MOV{N,Z} imm. 31:16. */ +#define R_AARCH64_MOVW_GOTOFF_G1_NC 303 /* Likewise for MOVK; no check. */ +#define R_AARCH64_MOVW_GOTOFF_G2 304 /* GOT-rel. o. MOV{N,Z} imm. 47:32. */ +#define R_AARCH64_MOVW_GOTOFF_G2_NC 305 /* Likewise for MOVK; no check. */ +#define R_AARCH64_MOVW_GOTOFF_G3 306 /* GOT-rel. o. MOV{N,Z} imm. 63:48. */ +#define R_AARCH64_GOTREL64 307 /* GOT-relative 64-bit. */ +#define R_AARCH64_GOTREL32 308 /* GOT-relative 32-bit. */ +#define R_AARCH64_GOT_LD_PREL19 309 /* PC-rel. GOT off. load imm. 20:2. */ +#define R_AARCH64_LD64_GOTOFF_LO15 310 /* GOT-rel. off. LD/ST imm. 14:3. */ +#define R_AARCH64_ADR_GOT_PAGE 311 /* P-page-rel. GOT off. ADRP 32:12. */ +#define R_AARCH64_LD64_GOT_LO12_NC 312 /* Dir. GOT off. LD/ST imm. 11:3. */ +#define R_AARCH64_LD64_GOTPAGE_LO15 313 /* GOT-page-rel. GOT off. LD/ST 14:3 */ +#define R_AARCH64_TLSGD_ADR_PREL21 512 /* PC-relative ADR imm. 20:0. */ +#define R_AARCH64_TLSGD_ADR_PAGE21 513 /* page-rel. ADRP imm. 32:12. */ +#define R_AARCH64_TLSGD_ADD_LO12_NC 514 /* direct ADD imm. from 11:0. */ +#define R_AARCH64_TLSGD_MOVW_G1 515 /* GOT-rel. MOV{N,Z} 31:16. */ +#define R_AARCH64_TLSGD_MOVW_G0_NC 516 /* GOT-rel. MOVK imm. 15:0. */ +#define R_AARCH64_TLSLD_ADR_PREL21 517 /* Like 512; local dynamic model. */ +#define R_AARCH64_TLSLD_ADR_PAGE21 518 /* Like 513; local dynamic model. */ +#define R_AARCH64_TLSLD_ADD_LO12_NC 519 /* Like 514; local dynamic model. */ +#define R_AARCH64_TLSLD_MOVW_G1 520 /* Like 515; local dynamic model. */ +#define R_AARCH64_TLSLD_MOVW_G0_NC 521 /* Like 516; local dynamic model. */ +#define R_AARCH64_TLSLD_LD_PREL19 522 /* TLS PC-rel. load imm. 20:2. */ +#define R_AARCH64_TLSLD_MOVW_DTPREL_G2 523 /* TLS DTP-rel. MOV{N,Z} 47:32. */ +#define R_AARCH64_TLSLD_MOVW_DTPREL_G1 524 /* TLS DTP-rel. MOV{N,Z} 31:16. */ +#define R_AARCH64_TLSLD_MOVW_DTPREL_G1_NC 525 /* Likewise; MOVK; no check. */ +#define R_AARCH64_TLSLD_MOVW_DTPREL_G0 526 /* TLS DTP-rel. MOV{N,Z} 15:0. */ +#define R_AARCH64_TLSLD_MOVW_DTPREL_G0_NC 527 /* Likewise; MOVK; no check. */ +#define R_AARCH64_TLSLD_ADD_DTPREL_HI12 528 /* DTP-rel. ADD imm. from 23:12. */ +#define R_AARCH64_TLSLD_ADD_DTPREL_LO12 529 /* DTP-rel. ADD imm. from 11:0. */ +#define R_AARCH64_TLSLD_ADD_DTPREL_LO12_NC 530 /* Likewise; no ovfl. check. */ +#define R_AARCH64_TLSLD_LDST8_DTPREL_LO12 531 /* DTP-rel. LD/ST imm. 11:0. */ +#define R_AARCH64_TLSLD_LDST8_DTPREL_LO12_NC 532 /* Likewise; no check. */ +#define R_AARCH64_TLSLD_LDST16_DTPREL_LO12 533 /* DTP-rel. LD/ST imm. 11:1. */ +#define R_AARCH64_TLSLD_LDST16_DTPREL_LO12_NC 534 /* Likewise; no check. */ +#define R_AARCH64_TLSLD_LDST32_DTPREL_LO12 535 /* DTP-rel. LD/ST imm. 11:2. */ +#define R_AARCH64_TLSLD_LDST32_DTPREL_LO12_NC 536 /* Likewise; no check. */ +#define R_AARCH64_TLSLD_LDST64_DTPREL_LO12 537 /* DTP-rel. LD/ST imm. 11:3. */ +#define R_AARCH64_TLSLD_LDST64_DTPREL_LO12_NC 538 /* Likewise; no check. */ +#define R_AARCH64_TLSIE_MOVW_GOTTPREL_G1 539 /* GOT-rel. MOV{N,Z} 31:16. */ +#define R_AARCH64_TLSIE_MOVW_GOTTPREL_G0_NC 540 /* GOT-rel. MOVK 15:0. */ +#define R_AARCH64_TLSIE_ADR_GOTTPREL_PAGE21 541 /* Page-rel. ADRP 32:12. */ +#define R_AARCH64_TLSIE_LD64_GOTTPREL_LO12_NC 542 /* Direct LD off. 11:3. */ +#define R_AARCH64_TLSIE_LD_GOTTPREL_PREL19 543 /* PC-rel. load imm. 20:2. */ +#define R_AARCH64_TLSLE_MOVW_TPREL_G2 544 /* TLS TP-rel. MOV{N,Z} 47:32. */ +#define R_AARCH64_TLSLE_MOVW_TPREL_G1 545 /* TLS TP-rel. MOV{N,Z} 31:16. */ +#define R_AARCH64_TLSLE_MOVW_TPREL_G1_NC 546 /* Likewise; MOVK; no check. */ +#define R_AARCH64_TLSLE_MOVW_TPREL_G0 547 /* TLS TP-rel. MOV{N,Z} 15:0. */ +#define R_AARCH64_TLSLE_MOVW_TPREL_G0_NC 548 /* Likewise; MOVK; no check. */ +#define R_AARCH64_TLSLE_ADD_TPREL_HI12 549 /* TP-rel. ADD imm. 23:12. */ +#define R_AARCH64_TLSLE_ADD_TPREL_LO12 550 /* TP-rel. ADD imm. 11:0. */ +#define R_AARCH64_TLSLE_ADD_TPREL_LO12_NC 551 /* Likewise; no ovfl. check. */ +#define R_AARCH64_TLSLE_LDST8_TPREL_LO12 552 /* TP-rel. LD/ST off. 11:0. */ +#define R_AARCH64_TLSLE_LDST8_TPREL_LO12_NC 553 /* Likewise; no ovfl. check. */ +#define R_AARCH64_TLSLE_LDST16_TPREL_LO12 554 /* TP-rel. LD/ST off. 11:1. */ +#define R_AARCH64_TLSLE_LDST16_TPREL_LO12_NC 555 /* Likewise; no check. */ +#define R_AARCH64_TLSLE_LDST32_TPREL_LO12 556 /* TP-rel. LD/ST off. 11:2. */ +#define R_AARCH64_TLSLE_LDST32_TPREL_LO12_NC 557 /* Likewise; no check. */ +#define R_AARCH64_TLSLE_LDST64_TPREL_LO12 558 /* TP-rel. LD/ST off. 11:3. */ +#define R_AARCH64_TLSLE_LDST64_TPREL_LO12_NC 559 /* Likewise; no check. */ +#define R_AARCH64_TLSDESC_LD_PREL19 560 /* PC-rel. load immediate 20:2. */ +#define R_AARCH64_TLSDESC_ADR_PREL21 561 /* PC-rel. ADR immediate 20:0. */ +#define R_AARCH64_TLSDESC_ADR_PAGE21 562 /* Page-rel. ADRP imm. 32:12. */ +#define R_AARCH64_TLSDESC_LD64_LO12 563 /* Direct LD off. from 11:3. */ +#define R_AARCH64_TLSDESC_ADD_LO12 564 /* Direct ADD imm. from 11:0. */ +#define R_AARCH64_TLSDESC_OFF_G1 565 /* GOT-rel. MOV{N,Z} imm. 31:16. */ +#define R_AARCH64_TLSDESC_OFF_G0_NC 566 /* GOT-rel. MOVK imm. 15:0; no ck. */ +#define R_AARCH64_TLSDESC_LDR 567 /* Relax LDR. */ +#define R_AARCH64_TLSDESC_ADD 568 /* Relax ADD. */ +#define R_AARCH64_TLSDESC_CALL 569 /* Relax BLR. */ +#define R_AARCH64_TLSLE_LDST128_TPREL_LO12 570 /* TP-rel. LD/ST off. 11:4. */ +#define R_AARCH64_TLSLE_LDST128_TPREL_LO12_NC 571 /* Likewise; no check. */ +#define R_AARCH64_TLSLD_LDST128_DTPREL_LO12 572 /* DTP-rel. LD/ST imm. 11:4. */ +#define R_AARCH64_TLSLD_LDST128_DTPREL_LO12_NC 573 /* Likewise; no check. */ +#define R_AARCH64_COPY 1024 /* Copy symbol at runtime. */ +#define R_AARCH64_GLOB_DAT 1025 /* Create GOT entry. */ +#define R_AARCH64_JUMP_SLOT 1026 /* Create PLT entry. */ +#define R_AARCH64_RELATIVE 1027 /* Adjust by program base. */ +#define R_AARCH64_TLS_DTPMOD 1028 /* Module number, 64 bit. */ +#define R_AARCH64_TLS_DTPREL 1029 /* Module-relative offset, 64 bit. */ +#define R_AARCH64_TLS_TPREL 1030 /* TP-relative offset, 64 bit. */ +#define R_AARCH64_TLSDESC 1031 /* TLS Descriptor. */ +#define R_AARCH64_IRELATIVE 1032 /* STT_GNU_IFUNC relocation. */ + +/* ARM relocs. */ + +#define R_ARM_NONE 0 /* No reloc */ +#define R_ARM_PC24 1 /* Deprecated PC relative 26 + bit branch. */ +#define R_ARM_ABS32 2 /* Direct 32 bit */ +#define R_ARM_REL32 3 /* PC relative 32 bit */ +#define R_ARM_PC13 4 +#define R_ARM_ABS16 5 /* Direct 16 bit */ +#define R_ARM_ABS12 6 /* Direct 12 bit */ +#define R_ARM_THM_ABS5 7 /* Direct & 0x7C (LDR, STR). */ +#define R_ARM_ABS8 8 /* Direct 8 bit */ +#define R_ARM_SBREL32 9 +#define R_ARM_THM_PC22 10 /* PC relative 24 bit (Thumb32 BL). */ +#define R_ARM_THM_PC8 11 /* PC relative & 0x3FC + (Thumb16 LDR, ADD, ADR). */ +#define R_ARM_AMP_VCALL9 12 +#define R_ARM_SWI24 13 /* Obsolete static relocation. */ +#define R_ARM_TLS_DESC 13 /* Dynamic relocation. */ +#define R_ARM_THM_SWI8 14 /* Reserved. */ +#define R_ARM_XPC25 15 /* Reserved. */ +#define R_ARM_THM_XPC22 16 /* Reserved. */ +#define R_ARM_TLS_DTPMOD32 17 /* ID of module containing symbol */ +#define R_ARM_TLS_DTPOFF32 18 /* Offset in TLS block */ +#define R_ARM_TLS_TPOFF32 19 /* Offset in static TLS block */ +#define R_ARM_COPY 20 /* Copy symbol at runtime */ +#define R_ARM_GLOB_DAT 21 /* Create GOT entry */ +#define R_ARM_JUMP_SLOT 22 /* Create PLT entry */ +#define R_ARM_RELATIVE 23 /* Adjust by program base */ +#define R_ARM_GOTOFF 24 /* 32 bit offset to GOT */ +#define R_ARM_GOTPC 25 /* 32 bit PC relative offset to GOT */ +#define R_ARM_GOT32 26 /* 32 bit GOT entry */ +#define R_ARM_PLT32 27 /* Deprecated, 32 bit PLT address. */ +#define R_ARM_CALL 28 /* PC relative 24 bit (BL, BLX). */ +#define R_ARM_JUMP24 29 /* PC relative 24 bit + (B, BL). */ +#define R_ARM_THM_JUMP24 30 /* PC relative 24 bit (Thumb32 B.W). */ +#define R_ARM_BASE_ABS 31 /* Adjust by program base. */ +#define R_ARM_ALU_PCREL_7_0 32 /* Obsolete. */ +#define R_ARM_ALU_PCREL_15_8 33 /* Obsolete. */ +#define R_ARM_ALU_PCREL_23_15 34 /* Obsolete. */ +#define R_ARM_LDR_SBREL_11_0 35 /* Deprecated, prog. base relative. */ +#define R_ARM_ALU_SBREL_19_12 36 /* Deprecated, prog. base relative. */ +#define R_ARM_ALU_SBREL_27_20 37 /* Deprecated, prog. base relative. */ +#define R_ARM_TARGET1 38 +#define R_ARM_SBREL31 39 /* Program base relative. */ +#define R_ARM_V4BX 40 +#define R_ARM_TARGET2 41 +#define R_ARM_PREL31 42 /* 32 bit PC relative. */ +#define R_ARM_MOVW_ABS_NC 43 /* Direct 16-bit (MOVW). */ +#define R_ARM_MOVT_ABS 44 /* Direct high 16-bit (MOVT). */ +#define R_ARM_MOVW_PREL_NC 45 /* PC relative 16-bit (MOVW). */ +#define R_ARM_MOVT_PREL 46 /* PC relative (MOVT). */ +#define R_ARM_THM_MOVW_ABS_NC 47 /* Direct 16 bit (Thumb32 MOVW). */ +#define R_ARM_THM_MOVT_ABS 48 /* Direct high 16 bit + (Thumb32 MOVT). */ +#define R_ARM_THM_MOVW_PREL_NC 49 /* PC relative 16 bit + (Thumb32 MOVW). */ +#define R_ARM_THM_MOVT_PREL 50 /* PC relative high 16 bit + (Thumb32 MOVT). */ +#define R_ARM_THM_JUMP19 51 /* PC relative 20 bit + (Thumb32 B.W). */ +#define R_ARM_THM_JUMP6 52 /* PC relative X & 0x7E + (Thumb16 CBZ, CBNZ). */ +#define R_ARM_THM_ALU_PREL_11_0 53 /* PC relative 12 bit + (Thumb32 ADR.W). */ +#define R_ARM_THM_PC12 54 /* PC relative 12 bit + (Thumb32 LDR{D,SB,H,SH}). */ +#define R_ARM_ABS32_NOI 55 /* Direct 32-bit. */ +#define R_ARM_REL32_NOI 56 /* PC relative 32-bit. */ +#define R_ARM_ALU_PC_G0_NC 57 /* PC relative (ADD, SUB). */ +#define R_ARM_ALU_PC_G0 58 /* PC relative (ADD, SUB). */ +#define R_ARM_ALU_PC_G1_NC 59 /* PC relative (ADD, SUB). */ +#define R_ARM_ALU_PC_G1 60 /* PC relative (ADD, SUB). */ +#define R_ARM_ALU_PC_G2 61 /* PC relative (ADD, SUB). */ +#define R_ARM_LDR_PC_G1 62 /* PC relative (LDR,STR,LDRB,STRB). */ +#define R_ARM_LDR_PC_G2 63 /* PC relative (LDR,STR,LDRB,STRB). */ +#define R_ARM_LDRS_PC_G0 64 /* PC relative (STR{D,H}, + LDR{D,SB,H,SH}). */ +#define R_ARM_LDRS_PC_G1 65 /* PC relative (STR{D,H}, + LDR{D,SB,H,SH}). */ +#define R_ARM_LDRS_PC_G2 66 /* PC relative (STR{D,H}, + LDR{D,SB,H,SH}). */ +#define R_ARM_LDC_PC_G0 67 /* PC relative (LDC, STC). */ +#define R_ARM_LDC_PC_G1 68 /* PC relative (LDC, STC). */ +#define R_ARM_LDC_PC_G2 69 /* PC relative (LDC, STC). */ +#define R_ARM_ALU_SB_G0_NC 70 /* Program base relative (ADD,SUB). */ +#define R_ARM_ALU_SB_G0 71 /* Program base relative (ADD,SUB). */ +#define R_ARM_ALU_SB_G1_NC 72 /* Program base relative (ADD,SUB). */ +#define R_ARM_ALU_SB_G1 73 /* Program base relative (ADD,SUB). */ +#define R_ARM_ALU_SB_G2 74 /* Program base relative (ADD,SUB). */ +#define R_ARM_LDR_SB_G0 75 /* Program base relative (LDR, + STR, LDRB, STRB). */ +#define R_ARM_LDR_SB_G1 76 /* Program base relative + (LDR, STR, LDRB, STRB). */ +#define R_ARM_LDR_SB_G2 77 /* Program base relative + (LDR, STR, LDRB, STRB). */ +#define R_ARM_LDRS_SB_G0 78 /* Program base relative + (LDR, STR, LDRB, STRB). */ +#define R_ARM_LDRS_SB_G1 79 /* Program base relative + (LDR, STR, LDRB, STRB). */ +#define R_ARM_LDRS_SB_G2 80 /* Program base relative + (LDR, STR, LDRB, STRB). */ +#define R_ARM_LDC_SB_G0 81 /* Program base relative (LDC,STC). */ +#define R_ARM_LDC_SB_G1 82 /* Program base relative (LDC,STC). */ +#define R_ARM_LDC_SB_G2 83 /* Program base relative (LDC,STC). */ +#define R_ARM_MOVW_BREL_NC 84 /* Program base relative 16 + bit (MOVW). */ +#define R_ARM_MOVT_BREL 85 /* Program base relative high + 16 bit (MOVT). */ +#define R_ARM_MOVW_BREL 86 /* Program base relative 16 + bit (MOVW). */ +#define R_ARM_THM_MOVW_BREL_NC 87 /* Program base relative 16 + bit (Thumb32 MOVW). */ +#define R_ARM_THM_MOVT_BREL 88 /* Program base relative high + 16 bit (Thumb32 MOVT). */ +#define R_ARM_THM_MOVW_BREL 89 /* Program base relative 16 + bit (Thumb32 MOVW). */ +#define R_ARM_TLS_GOTDESC 90 +#define R_ARM_TLS_CALL 91 +#define R_ARM_TLS_DESCSEQ 92 /* TLS relaxation. */ +#define R_ARM_THM_TLS_CALL 93 +#define R_ARM_PLT32_ABS 94 +#define R_ARM_GOT_ABS 95 /* GOT entry. */ +#define R_ARM_GOT_PREL 96 /* PC relative GOT entry. */ +#define R_ARM_GOT_BREL12 97 /* GOT entry relative to GOT + origin (LDR). */ +#define R_ARM_GOTOFF12 98 /* 12 bit, GOT entry relative + to GOT origin (LDR, STR). */ +#define R_ARM_GOTRELAX 99 +#define R_ARM_GNU_VTENTRY 100 +#define R_ARM_GNU_VTINHERIT 101 +#define R_ARM_THM_PC11 102 /* PC relative & 0xFFE (Thumb16 B). */ +#define R_ARM_THM_PC9 103 /* PC relative & 0x1FE + (Thumb16 B/B). */ +#define R_ARM_TLS_GD32 104 /* PC-rel 32 bit for global dynamic + thread local data */ +#define R_ARM_TLS_LDM32 105 /* PC-rel 32 bit for local dynamic + thread local data */ +#define R_ARM_TLS_LDO32 106 /* 32 bit offset relative to TLS + block */ +#define R_ARM_TLS_IE32 107 /* PC-rel 32 bit for GOT entry of + static TLS block offset */ +#define R_ARM_TLS_LE32 108 /* 32 bit offset relative to static + TLS block */ +#define R_ARM_TLS_LDO12 109 /* 12 bit relative to TLS + block (LDR, STR). */ +#define R_ARM_TLS_LE12 110 /* 12 bit relative to static + TLS block (LDR, STR). */ +#define R_ARM_TLS_IE12GP 111 /* 12 bit GOT entry relative + to GOT origin (LDR). */ +#define R_ARM_ME_TOO 128 /* Obsolete. */ +#define R_ARM_THM_TLS_DESCSEQ 129 +#define R_ARM_THM_TLS_DESCSEQ16 129 +#define R_ARM_THM_TLS_DESCSEQ32 130 +#define R_ARM_THM_GOT_BREL12 131 /* GOT entry relative to GOT + origin, 12 bit (Thumb32 LDR). */ +#define R_ARM_IRELATIVE 160 +#define R_ARM_RXPC25 249 +#define R_ARM_RSBREL32 250 +#define R_ARM_THM_RPC22 251 +#define R_ARM_RREL32 252 +#define R_ARM_RABS22 253 +#define R_ARM_RPC24 254 +#define R_ARM_RBASE 255 +/* Keep this the last entry. */ +#define R_ARM_NUM 256 + +/* IA-64 specific declarations. */ + +/* Processor specific flags for the Ehdr e_flags field. */ +#define EF_IA_64_MASKOS 0x0000000f /* os-specific flags */ +#define EF_IA_64_ABI64 0x00000010 /* 64-bit ABI */ +#define EF_IA_64_ARCH 0xff000000 /* arch. version mask */ + +/* Processor specific values for the Phdr p_type field. */ +#define PT_IA_64_ARCHEXT (PT_LOPROC + 0) /* arch extension bits */ +#define PT_IA_64_UNWIND (PT_LOPROC + 1) /* ia64 unwind bits */ +#define PT_IA_64_HP_OPT_ANOT (PT_LOOS + 0x12) +#define PT_IA_64_HP_HSL_ANOT (PT_LOOS + 0x13) +#define PT_IA_64_HP_STACK (PT_LOOS + 0x14) + +/* Processor specific flags for the Phdr p_flags field. */ +#define PF_IA_64_NORECOV 0x80000000 /* spec insns w/o recovery */ + +/* Processor specific values for the Shdr sh_type field. */ +#define SHT_IA_64_EXT (SHT_LOPROC + 0) /* extension bits */ +#define SHT_IA_64_UNWIND (SHT_LOPROC + 1) /* unwind bits */ + +/* Processor specific flags for the Shdr sh_flags field. */ +#define SHF_IA_64_SHORT 0x10000000 /* section near gp */ +#define SHF_IA_64_NORECOV 0x20000000 /* spec insns w/o recovery */ + +/* Processor specific values for the Dyn d_tag field. */ +#define DT_IA_64_PLT_RESERVE (DT_LOPROC + 0) +#define DT_IA_64_NUM 1 + +/* IA-64 relocations. */ +#define R_IA64_NONE 0x00 /* none */ +#define R_IA64_IMM14 0x21 /* symbol + addend, add imm14 */ +#define R_IA64_IMM22 0x22 /* symbol + addend, add imm22 */ +#define R_IA64_IMM64 0x23 /* symbol + addend, mov imm64 */ +#define R_IA64_DIR32MSB 0x24 /* symbol + addend, data4 MSB */ +#define R_IA64_DIR32LSB 0x25 /* symbol + addend, data4 LSB */ +#define R_IA64_DIR64MSB 0x26 /* symbol + addend, data8 MSB */ +#define R_IA64_DIR64LSB 0x27 /* symbol + addend, data8 LSB */ +#define R_IA64_GPREL22 0x2a /* @gprel(sym + add), add imm22 */ +#define R_IA64_GPREL64I 0x2b /* @gprel(sym + add), mov imm64 */ +#define R_IA64_GPREL32MSB 0x2c /* @gprel(sym + add), data4 MSB */ +#define R_IA64_GPREL32LSB 0x2d /* @gprel(sym + add), data4 LSB */ +#define R_IA64_GPREL64MSB 0x2e /* @gprel(sym + add), data8 MSB */ +#define R_IA64_GPREL64LSB 0x2f /* @gprel(sym + add), data8 LSB */ +#define R_IA64_LTOFF22 0x32 /* @ltoff(sym + add), add imm22 */ +#define R_IA64_LTOFF64I 0x33 /* @ltoff(sym + add), mov imm64 */ +#define R_IA64_PLTOFF22 0x3a /* @pltoff(sym + add), add imm22 */ +#define R_IA64_PLTOFF64I 0x3b /* @pltoff(sym + add), mov imm64 */ +#define R_IA64_PLTOFF64MSB 0x3e /* @pltoff(sym + add), data8 MSB */ +#define R_IA64_PLTOFF64LSB 0x3f /* @pltoff(sym + add), data8 LSB */ +#define R_IA64_FPTR64I 0x43 /* @fptr(sym + add), mov imm64 */ +#define R_IA64_FPTR32MSB 0x44 /* @fptr(sym + add), data4 MSB */ +#define R_IA64_FPTR32LSB 0x45 /* @fptr(sym + add), data4 LSB */ +#define R_IA64_FPTR64MSB 0x46 /* @fptr(sym + add), data8 MSB */ +#define R_IA64_FPTR64LSB 0x47 /* @fptr(sym + add), data8 LSB */ +#define R_IA64_PCREL60B 0x48 /* @pcrel(sym + add), brl */ +#define R_IA64_PCREL21B 0x49 /* @pcrel(sym + add), ptb, call */ +#define R_IA64_PCREL21M 0x4a /* @pcrel(sym + add), chk.s */ +#define R_IA64_PCREL21F 0x4b /* @pcrel(sym + add), fchkf */ +#define R_IA64_PCREL32MSB 0x4c /* @pcrel(sym + add), data4 MSB */ +#define R_IA64_PCREL32LSB 0x4d /* @pcrel(sym + add), data4 LSB */ +#define R_IA64_PCREL64MSB 0x4e /* @pcrel(sym + add), data8 MSB */ +#define R_IA64_PCREL64LSB 0x4f /* @pcrel(sym + add), data8 LSB */ +#define R_IA64_LTOFF_FPTR22 0x52 /* @ltoff(@fptr(s+a)), imm22 */ +#define R_IA64_LTOFF_FPTR64I 0x53 /* @ltoff(@fptr(s+a)), imm64 */ +#define R_IA64_LTOFF_FPTR32MSB 0x54 /* @ltoff(@fptr(s+a)), data4 MSB */ +#define R_IA64_LTOFF_FPTR32LSB 0x55 /* @ltoff(@fptr(s+a)), data4 LSB */ +#define R_IA64_LTOFF_FPTR64MSB 0x56 /* @ltoff(@fptr(s+a)), data8 MSB */ +#define R_IA64_LTOFF_FPTR64LSB 0x57 /* @ltoff(@fptr(s+a)), data8 LSB */ +#define R_IA64_SEGREL32MSB 0x5c /* @segrel(sym + add), data4 MSB */ +#define R_IA64_SEGREL32LSB 0x5d /* @segrel(sym + add), data4 LSB */ +#define R_IA64_SEGREL64MSB 0x5e /* @segrel(sym + add), data8 MSB */ +#define R_IA64_SEGREL64LSB 0x5f /* @segrel(sym + add), data8 LSB */ +#define R_IA64_SECREL32MSB 0x64 /* @secrel(sym + add), data4 MSB */ +#define R_IA64_SECREL32LSB 0x65 /* @secrel(sym + add), data4 LSB */ +#define R_IA64_SECREL64MSB 0x66 /* @secrel(sym + add), data8 MSB */ +#define R_IA64_SECREL64LSB 0x67 /* @secrel(sym + add), data8 LSB */ +#define R_IA64_REL32MSB 0x6c /* data 4 + REL */ +#define R_IA64_REL32LSB 0x6d /* data 4 + REL */ +#define R_IA64_REL64MSB 0x6e /* data 8 + REL */ +#define R_IA64_REL64LSB 0x6f /* data 8 + REL */ +#define R_IA64_LTV32MSB 0x74 /* symbol + addend, data4 MSB */ +#define R_IA64_LTV32LSB 0x75 /* symbol + addend, data4 LSB */ +#define R_IA64_LTV64MSB 0x76 /* symbol + addend, data8 MSB */ +#define R_IA64_LTV64LSB 0x77 /* symbol + addend, data8 LSB */ +#define R_IA64_PCREL21BI 0x79 /* @pcrel(sym + add), 21bit inst */ +#define R_IA64_PCREL22 0x7a /* @pcrel(sym + add), 22bit inst */ +#define R_IA64_PCREL64I 0x7b /* @pcrel(sym + add), 64bit inst */ +#define R_IA64_IPLTMSB 0x80 /* dynamic reloc, imported PLT, MSB */ +#define R_IA64_IPLTLSB 0x81 /* dynamic reloc, imported PLT, LSB */ +#define R_IA64_COPY 0x84 /* copy relocation */ +#define R_IA64_SUB 0x85 /* Addend and symbol difference */ +#define R_IA64_LTOFF22X 0x86 /* LTOFF22, relaxable. */ +#define R_IA64_LDXMOV 0x87 /* Use of LTOFF22X. */ +#define R_IA64_TPREL14 0x91 /* @tprel(sym + add), imm14 */ +#define R_IA64_TPREL22 0x92 /* @tprel(sym + add), imm22 */ +#define R_IA64_TPREL64I 0x93 /* @tprel(sym + add), imm64 */ +#define R_IA64_TPREL64MSB 0x96 /* @tprel(sym + add), data8 MSB */ +#define R_IA64_TPREL64LSB 0x97 /* @tprel(sym + add), data8 LSB */ +#define R_IA64_LTOFF_TPREL22 0x9a /* @ltoff(@tprel(s+a)), imm2 */ +#define R_IA64_DTPMOD64MSB 0xa6 /* @dtpmod(sym + add), data8 MSB */ +#define R_IA64_DTPMOD64LSB 0xa7 /* @dtpmod(sym + add), data8 LSB */ +#define R_IA64_LTOFF_DTPMOD22 0xaa /* @ltoff(@dtpmod(sym + add)), imm22 */ +#define R_IA64_DTPREL14 0xb1 /* @dtprel(sym + add), imm14 */ +#define R_IA64_DTPREL22 0xb2 /* @dtprel(sym + add), imm22 */ +#define R_IA64_DTPREL64I 0xb3 /* @dtprel(sym + add), imm64 */ +#define R_IA64_DTPREL32MSB 0xb4 /* @dtprel(sym + add), data4 MSB */ +#define R_IA64_DTPREL32LSB 0xb5 /* @dtprel(sym + add), data4 LSB */ +#define R_IA64_DTPREL64MSB 0xb6 /* @dtprel(sym + add), data8 MSB */ +#define R_IA64_DTPREL64LSB 0xb7 /* @dtprel(sym + add), data8 LSB */ +#define R_IA64_LTOFF_DTPREL22 0xba /* @ltoff(@dtprel(s+a)), imm22 */ + +/* SH specific declarations */ + +/* Processor specific flags for the ELF header e_flags field. */ +#define EF_SH_MACH_MASK 0x1f +#define EF_SH_UNKNOWN 0x0 +#define EF_SH1 0x1 +#define EF_SH2 0x2 +#define EF_SH3 0x3 +#define EF_SH_DSP 0x4 +#define EF_SH3_DSP 0x5 +#define EF_SH4AL_DSP 0x6 +#define EF_SH3E 0x8 +#define EF_SH4 0x9 +#define EF_SH2E 0xb +#define EF_SH4A 0xc +#define EF_SH2A 0xd +#define EF_SH4_NOFPU 0x10 +#define EF_SH4A_NOFPU 0x11 +#define EF_SH4_NOMMU_NOFPU 0x12 +#define EF_SH2A_NOFPU 0x13 +#define EF_SH3_NOMMU 0x14 +#define EF_SH2A_SH4_NOFPU 0x15 +#define EF_SH2A_SH3_NOFPU 0x16 +#define EF_SH2A_SH4 0x17 +#define EF_SH2A_SH3E 0x18 + +/* SH relocs. */ +#define R_SH_NONE 0 +#define R_SH_DIR32 1 +#define R_SH_REL32 2 +#define R_SH_DIR8WPN 3 +#define R_SH_IND12W 4 +#define R_SH_DIR8WPL 5 +#define R_SH_DIR8WPZ 6 +#define R_SH_DIR8BP 7 +#define R_SH_DIR8W 8 +#define R_SH_DIR8L 9 +#define R_SH_SWITCH16 25 +#define R_SH_SWITCH32 26 +#define R_SH_USES 27 +#define R_SH_COUNT 28 +#define R_SH_ALIGN 29 +#define R_SH_CODE 30 +#define R_SH_DATA 31 +#define R_SH_LABEL 32 +#define R_SH_SWITCH8 33 +#define R_SH_GNU_VTINHERIT 34 +#define R_SH_GNU_VTENTRY 35 +#define R_SH_TLS_GD_32 144 +#define R_SH_TLS_LD_32 145 +#define R_SH_TLS_LDO_32 146 +#define R_SH_TLS_IE_32 147 +#define R_SH_TLS_LE_32 148 +#define R_SH_TLS_DTPMOD32 149 +#define R_SH_TLS_DTPOFF32 150 +#define R_SH_TLS_TPOFF32 151 +#define R_SH_GOT32 160 +#define R_SH_PLT32 161 +#define R_SH_COPY 162 +#define R_SH_GLOB_DAT 163 +#define R_SH_JMP_SLOT 164 +#define R_SH_RELATIVE 165 +#define R_SH_GOTOFF 166 +#define R_SH_GOTPC 167 +/* Keep this the last entry. */ +#define R_SH_NUM 256 + +/* S/390 specific definitions. */ + +/* Valid values for the e_flags field. */ + +#define EF_S390_HIGH_GPRS 0x00000001 /* High GPRs kernel facility needed. */ + +/* Additional s390 relocs */ + +#define R_390_NONE 0 /* No reloc. */ +#define R_390_8 1 /* Direct 8 bit. */ +#define R_390_12 2 /* Direct 12 bit. */ +#define R_390_16 3 /* Direct 16 bit. */ +#define R_390_32 4 /* Direct 32 bit. */ +#define R_390_PC32 5 /* PC relative 32 bit. */ +#define R_390_GOT12 6 /* 12 bit GOT offset. */ +#define R_390_GOT32 7 /* 32 bit GOT offset. */ +#define R_390_PLT32 8 /* 32 bit PC relative PLT address. */ +#define R_390_COPY 9 /* Copy symbol at runtime. */ +#define R_390_GLOB_DAT 10 /* Create GOT entry. */ +#define R_390_JMP_SLOT 11 /* Create PLT entry. */ +#define R_390_RELATIVE 12 /* Adjust by program base. */ +#define R_390_GOTOFF32 13 /* 32 bit offset to GOT. */ +#define R_390_GOTPC 14 /* 32 bit PC relative offset to GOT. */ +#define R_390_GOT16 15 /* 16 bit GOT offset. */ +#define R_390_PC16 16 /* PC relative 16 bit. */ +#define R_390_PC16DBL 17 /* PC relative 16 bit shifted by 1. */ +#define R_390_PLT16DBL 18 /* 16 bit PC rel. PLT shifted by 1. */ +#define R_390_PC32DBL 19 /* PC relative 32 bit shifted by 1. */ +#define R_390_PLT32DBL 20 /* 32 bit PC rel. PLT shifted by 1. */ +#define R_390_GOTPCDBL 21 /* 32 bit PC rel. GOT shifted by 1. */ +#define R_390_64 22 /* Direct 64 bit. */ +#define R_390_PC64 23 /* PC relative 64 bit. */ +#define R_390_GOT64 24 /* 64 bit GOT offset. */ +#define R_390_PLT64 25 /* 64 bit PC relative PLT address. */ +#define R_390_GOTENT 26 /* 32 bit PC rel. to GOT entry >> 1. */ +#define R_390_GOTOFF16 27 /* 16 bit offset to GOT. */ +#define R_390_GOTOFF64 28 /* 64 bit offset to GOT. */ +#define R_390_GOTPLT12 29 /* 12 bit offset to jump slot. */ +#define R_390_GOTPLT16 30 /* 16 bit offset to jump slot. */ +#define R_390_GOTPLT32 31 /* 32 bit offset to jump slot. */ +#define R_390_GOTPLT64 32 /* 64 bit offset to jump slot. */ +#define R_390_GOTPLTENT 33 /* 32 bit rel. offset to jump slot. */ +#define R_390_PLTOFF16 34 /* 16 bit offset from GOT to PLT. */ +#define R_390_PLTOFF32 35 /* 32 bit offset from GOT to PLT. */ +#define R_390_PLTOFF64 36 /* 16 bit offset from GOT to PLT. */ +#define R_390_TLS_LOAD 37 /* Tag for load insn in TLS code. */ +#define R_390_TLS_GDCALL 38 /* Tag for function call in general + dynamic TLS code. */ +#define R_390_TLS_LDCALL 39 /* Tag for function call in local + dynamic TLS code. */ +#define R_390_TLS_GD32 40 /* Direct 32 bit for general dynamic + thread local data. */ +#define R_390_TLS_GD64 41 /* Direct 64 bit for general dynamic + thread local data. */ +#define R_390_TLS_GOTIE12 42 /* 12 bit GOT offset for static TLS + block offset. */ +#define R_390_TLS_GOTIE32 43 /* 32 bit GOT offset for static TLS + block offset. */ +#define R_390_TLS_GOTIE64 44 /* 64 bit GOT offset for static TLS + block offset. */ +#define R_390_TLS_LDM32 45 /* Direct 32 bit for local dynamic + thread local data in LE code. */ +#define R_390_TLS_LDM64 46 /* Direct 64 bit for local dynamic + thread local data in LE code. */ +#define R_390_TLS_IE32 47 /* 32 bit address of GOT entry for + negated static TLS block offset. */ +#define R_390_TLS_IE64 48 /* 64 bit address of GOT entry for + negated static TLS block offset. */ +#define R_390_TLS_IEENT 49 /* 32 bit rel. offset to GOT entry for + negated static TLS block offset. */ +#define R_390_TLS_LE32 50 /* 32 bit negated offset relative to + static TLS block. */ +#define R_390_TLS_LE64 51 /* 64 bit negated offset relative to + static TLS block. */ +#define R_390_TLS_LDO32 52 /* 32 bit offset relative to TLS + block. */ +#define R_390_TLS_LDO64 53 /* 64 bit offset relative to TLS + block. */ +#define R_390_TLS_DTPMOD 54 /* ID of module containing symbol. */ +#define R_390_TLS_DTPOFF 55 /* Offset in TLS block. */ +#define R_390_TLS_TPOFF 56 /* Negated offset in static TLS + block. */ +#define R_390_20 57 /* Direct 20 bit. */ +#define R_390_GOT20 58 /* 20 bit GOT offset. */ +#define R_390_GOTPLT20 59 /* 20 bit offset to jump slot. */ +#define R_390_TLS_GOTIE20 60 /* 20 bit GOT offset for static TLS + block offset. */ +#define R_390_IRELATIVE 61 /* STT_GNU_IFUNC relocation. */ +/* Keep this the last entry. */ +#define R_390_NUM 62 + + +/* CRIS relocations. */ +#define R_CRIS_NONE 0 +#define R_CRIS_8 1 +#define R_CRIS_16 2 +#define R_CRIS_32 3 +#define R_CRIS_8_PCREL 4 +#define R_CRIS_16_PCREL 5 +#define R_CRIS_32_PCREL 6 +#define R_CRIS_GNU_VTINHERIT 7 +#define R_CRIS_GNU_VTENTRY 8 +#define R_CRIS_COPY 9 +#define R_CRIS_GLOB_DAT 10 +#define R_CRIS_JUMP_SLOT 11 +#define R_CRIS_RELATIVE 12 +#define R_CRIS_16_GOT 13 +#define R_CRIS_32_GOT 14 +#define R_CRIS_16_GOTPLT 15 +#define R_CRIS_32_GOTPLT 16 +#define R_CRIS_32_GOTREL 17 +#define R_CRIS_32_PLT_GOTREL 18 +#define R_CRIS_32_PLT_PCREL 19 + +#define R_CRIS_NUM 20 + + +/* AMD x86-64 relocations. */ +#define R_X86_64_NONE 0 /* No reloc */ +#define R_X86_64_64 1 /* Direct 64 bit */ +#define R_X86_64_PC32 2 /* PC relative 32 bit signed */ +#define R_X86_64_GOT32 3 /* 32 bit GOT entry */ +#define R_X86_64_PLT32 4 /* 32 bit PLT address */ +#define R_X86_64_COPY 5 /* Copy symbol at runtime */ +#define R_X86_64_GLOB_DAT 6 /* Create GOT entry */ +#define R_X86_64_JUMP_SLOT 7 /* Create PLT entry */ +#define R_X86_64_RELATIVE 8 /* Adjust by program base */ +#define R_X86_64_GOTPCREL 9 /* 32 bit signed PC relative + offset to GOT */ +#define R_X86_64_32 10 /* Direct 32 bit zero extended */ +#define R_X86_64_32S 11 /* Direct 32 bit sign extended */ +#define R_X86_64_16 12 /* Direct 16 bit zero extended */ +#define R_X86_64_PC16 13 /* 16 bit sign extended pc relative */ +#define R_X86_64_8 14 /* Direct 8 bit sign extended */ +#define R_X86_64_PC8 15 /* 8 bit sign extended pc relative */ +#define R_X86_64_DTPMOD64 16 /* ID of module containing symbol */ +#define R_X86_64_DTPOFF64 17 /* Offset in module's TLS block */ +#define R_X86_64_TPOFF64 18 /* Offset in initial TLS block */ +#define R_X86_64_TLSGD 19 /* 32 bit signed PC relative offset + to two GOT entries for GD symbol */ +#define R_X86_64_TLSLD 20 /* 32 bit signed PC relative offset + to two GOT entries for LD symbol */ +#define R_X86_64_DTPOFF32 21 /* Offset in TLS block */ +#define R_X86_64_GOTTPOFF 22 /* 32 bit signed PC relative offset + to GOT entry for IE symbol */ +#define R_X86_64_TPOFF32 23 /* Offset in initial TLS block */ +#define R_X86_64_PC64 24 /* PC relative 64 bit */ +#define R_X86_64_GOTOFF64 25 /* 64 bit offset to GOT */ +#define R_X86_64_GOTPC32 26 /* 32 bit signed pc relative + offset to GOT */ +#define R_X86_64_GOT64 27 /* 64-bit GOT entry offset */ +#define R_X86_64_GOTPCREL64 28 /* 64-bit PC relative offset + to GOT entry */ +#define R_X86_64_GOTPC64 29 /* 64-bit PC relative offset to GOT */ +#define R_X86_64_GOTPLT64 30 /* like GOT64, says PLT entry needed */ +#define R_X86_64_PLTOFF64 31 /* 64-bit GOT relative offset + to PLT entry */ +#define R_X86_64_SIZE32 32 /* Size of symbol plus 32-bit addend */ +#define R_X86_64_SIZE64 33 /* Size of symbol plus 64-bit addend */ +#define R_X86_64_GOTPC32_TLSDESC 34 /* GOT offset for TLS descriptor. */ +#define R_X86_64_TLSDESC_CALL 35 /* Marker for call through TLS + descriptor. */ +#define R_X86_64_TLSDESC 36 /* TLS descriptor. */ +#define R_X86_64_IRELATIVE 37 /* Adjust indirectly by program base */ +#define R_X86_64_RELATIVE64 38 /* 64-bit adjust by program base */ + /* 39 Reserved was R_X86_64_PC32_BND */ + /* 40 Reserved was R_X86_64_PLT32_BND */ +#define R_X86_64_GOTPCRELX 41 /* Load from 32 bit signed pc relative + offset to GOT entry without REX + prefix, relaxable. */ +#define R_X86_64_REX_GOTPCRELX 42 /* Load from 32 bit signed pc relative + offset to GOT entry with REX prefix, + relaxable. */ +#define R_X86_64_NUM 43 + + +/* AM33 relocations. */ +#define R_MN10300_NONE 0 /* No reloc. */ +#define R_MN10300_32 1 /* Direct 32 bit. */ +#define R_MN10300_16 2 /* Direct 16 bit. */ +#define R_MN10300_8 3 /* Direct 8 bit. */ +#define R_MN10300_PCREL32 4 /* PC-relative 32-bit. */ +#define R_MN10300_PCREL16 5 /* PC-relative 16-bit signed. */ +#define R_MN10300_PCREL8 6 /* PC-relative 8-bit signed. */ +#define R_MN10300_GNU_VTINHERIT 7 /* Ancient C++ vtable garbage... */ +#define R_MN10300_GNU_VTENTRY 8 /* ... collection annotation. */ +#define R_MN10300_24 9 /* Direct 24 bit. */ +#define R_MN10300_GOTPC32 10 /* 32-bit PCrel offset to GOT. */ +#define R_MN10300_GOTPC16 11 /* 16-bit PCrel offset to GOT. */ +#define R_MN10300_GOTOFF32 12 /* 32-bit offset from GOT. */ +#define R_MN10300_GOTOFF24 13 /* 24-bit offset from GOT. */ +#define R_MN10300_GOTOFF16 14 /* 16-bit offset from GOT. */ +#define R_MN10300_PLT32 15 /* 32-bit PCrel to PLT entry. */ +#define R_MN10300_PLT16 16 /* 16-bit PCrel to PLT entry. */ +#define R_MN10300_GOT32 17 /* 32-bit offset to GOT entry. */ +#define R_MN10300_GOT24 18 /* 24-bit offset to GOT entry. */ +#define R_MN10300_GOT16 19 /* 16-bit offset to GOT entry. */ +#define R_MN10300_COPY 20 /* Copy symbol at runtime. */ +#define R_MN10300_GLOB_DAT 21 /* Create GOT entry. */ +#define R_MN10300_JMP_SLOT 22 /* Create PLT entry. */ +#define R_MN10300_RELATIVE 23 /* Adjust by program base. */ +#define R_MN10300_TLS_GD 24 /* 32-bit offset for global dynamic. */ +#define R_MN10300_TLS_LD 25 /* 32-bit offset for local dynamic. */ +#define R_MN10300_TLS_LDO 26 /* Module-relative offset. */ +#define R_MN10300_TLS_GOTIE 27 /* GOT offset for static TLS block + offset. */ +#define R_MN10300_TLS_IE 28 /* GOT address for static TLS block + offset. */ +#define R_MN10300_TLS_LE 29 /* Offset relative to static TLS + block. */ +#define R_MN10300_TLS_DTPMOD 30 /* ID of module containing symbol. */ +#define R_MN10300_TLS_DTPOFF 31 /* Offset in module TLS block. */ +#define R_MN10300_TLS_TPOFF 32 /* Offset in static TLS block. */ +#define R_MN10300_SYM_DIFF 33 /* Adjustment for next reloc as needed + by linker relaxation. */ +#define R_MN10300_ALIGN 34 /* Alignment requirement for linker + relaxation. */ +#define R_MN10300_NUM 35 + + +/* M32R relocs. */ +#define R_M32R_NONE 0 /* No reloc. */ +#define R_M32R_16 1 /* Direct 16 bit. */ +#define R_M32R_32 2 /* Direct 32 bit. */ +#define R_M32R_24 3 /* Direct 24 bit. */ +#define R_M32R_10_PCREL 4 /* PC relative 10 bit shifted. */ +#define R_M32R_18_PCREL 5 /* PC relative 18 bit shifted. */ +#define R_M32R_26_PCREL 6 /* PC relative 26 bit shifted. */ +#define R_M32R_HI16_ULO 7 /* High 16 bit with unsigned low. */ +#define R_M32R_HI16_SLO 8 /* High 16 bit with signed low. */ +#define R_M32R_LO16 9 /* Low 16 bit. */ +#define R_M32R_SDA16 10 /* 16 bit offset in SDA. */ +#define R_M32R_GNU_VTINHERIT 11 +#define R_M32R_GNU_VTENTRY 12 +/* M32R relocs use SHT_RELA. */ +#define R_M32R_16_RELA 33 /* Direct 16 bit. */ +#define R_M32R_32_RELA 34 /* Direct 32 bit. */ +#define R_M32R_24_RELA 35 /* Direct 24 bit. */ +#define R_M32R_10_PCREL_RELA 36 /* PC relative 10 bit shifted. */ +#define R_M32R_18_PCREL_RELA 37 /* PC relative 18 bit shifted. */ +#define R_M32R_26_PCREL_RELA 38 /* PC relative 26 bit shifted. */ +#define R_M32R_HI16_ULO_RELA 39 /* High 16 bit with unsigned low */ +#define R_M32R_HI16_SLO_RELA 40 /* High 16 bit with signed low */ +#define R_M32R_LO16_RELA 41 /* Low 16 bit */ +#define R_M32R_SDA16_RELA 42 /* 16 bit offset in SDA */ +#define R_M32R_RELA_GNU_VTINHERIT 43 +#define R_M32R_RELA_GNU_VTENTRY 44 +#define R_M32R_REL32 45 /* PC relative 32 bit. */ + +#define R_M32R_GOT24 48 /* 24 bit GOT entry */ +#define R_M32R_26_PLTREL 49 /* 26 bit PC relative to PLT shifted */ +#define R_M32R_COPY 50 /* Copy symbol at runtime */ +#define R_M32R_GLOB_DAT 51 /* Create GOT entry */ +#define R_M32R_JMP_SLOT 52 /* Create PLT entry */ +#define R_M32R_RELATIVE 53 /* Adjust by program base */ +#define R_M32R_GOTOFF 54 /* 24 bit offset to GOT */ +#define R_M32R_GOTPC24 55 /* 24 bit PC relative offset to GOT */ +#define R_M32R_GOT16_HI_ULO 56 /* High 16 bit GOT entry with unsigned + low */ +#define R_M32R_GOT16_HI_SLO 57 /* High 16 bit GOT entry with signed + low */ +#define R_M32R_GOT16_LO 58 /* Low 16 bit GOT entry */ +#define R_M32R_GOTPC_HI_ULO 59 /* High 16 bit PC relative offset to + GOT with unsigned low */ +#define R_M32R_GOTPC_HI_SLO 60 /* High 16 bit PC relative offset to + GOT with signed low */ +#define R_M32R_GOTPC_LO 61 /* Low 16 bit PC relative offset to + GOT */ +#define R_M32R_GOTOFF_HI_ULO 62 /* High 16 bit offset to GOT + with unsigned low */ +#define R_M32R_GOTOFF_HI_SLO 63 /* High 16 bit offset to GOT + with signed low */ +#define R_M32R_GOTOFF_LO 64 /* Low 16 bit offset to GOT */ +#define R_M32R_NUM 256 /* Keep this the last entry. */ + +/* MicroBlaze relocations */ +#define R_MICROBLAZE_NONE 0 /* No reloc. */ +#define R_MICROBLAZE_32 1 /* Direct 32 bit. */ +#define R_MICROBLAZE_32_PCREL 2 /* PC relative 32 bit. */ +#define R_MICROBLAZE_64_PCREL 3 /* PC relative 64 bit. */ +#define R_MICROBLAZE_32_PCREL_LO 4 /* Low 16 bits of PCREL32. */ +#define R_MICROBLAZE_64 5 /* Direct 64 bit. */ +#define R_MICROBLAZE_32_LO 6 /* Low 16 bit. */ +#define R_MICROBLAZE_SRO32 7 /* Read-only small data area. */ +#define R_MICROBLAZE_SRW32 8 /* Read-write small data area. */ +#define R_MICROBLAZE_64_NONE 9 /* No reloc. */ +#define R_MICROBLAZE_32_SYM_OP_SYM 10 /* Symbol Op Symbol relocation. */ +#define R_MICROBLAZE_GNU_VTINHERIT 11 /* GNU C++ vtable hierarchy. */ +#define R_MICROBLAZE_GNU_VTENTRY 12 /* GNU C++ vtable member usage. */ +#define R_MICROBLAZE_GOTPC_64 13 /* PC-relative GOT offset. */ +#define R_MICROBLAZE_GOT_64 14 /* GOT entry offset. */ +#define R_MICROBLAZE_PLT_64 15 /* PLT offset (PC-relative). */ +#define R_MICROBLAZE_REL 16 /* Adjust by program base. */ +#define R_MICROBLAZE_JUMP_SLOT 17 /* Create PLT entry. */ +#define R_MICROBLAZE_GLOB_DAT 18 /* Create GOT entry. */ +#define R_MICROBLAZE_GOTOFF_64 19 /* 64 bit offset to GOT. */ +#define R_MICROBLAZE_GOTOFF_32 20 /* 32 bit offset to GOT. */ +#define R_MICROBLAZE_COPY 21 /* Runtime copy. */ +#define R_MICROBLAZE_TLS 22 /* TLS Reloc. */ +#define R_MICROBLAZE_TLSGD 23 /* TLS General Dynamic. */ +#define R_MICROBLAZE_TLSLD 24 /* TLS Local Dynamic. */ +#define R_MICROBLAZE_TLSDTPMOD32 25 /* TLS Module ID. */ +#define R_MICROBLAZE_TLSDTPREL32 26 /* TLS Offset Within TLS Block. */ +#define R_MICROBLAZE_TLSDTPREL64 27 /* TLS Offset Within TLS Block. */ +#define R_MICROBLAZE_TLSGOTTPREL32 28 /* TLS Offset From Thread Pointer. */ +#define R_MICROBLAZE_TLSTPREL32 29 /* TLS Offset From Thread Pointer. */ + +/* Legal values for d_tag (dynamic entry type). */ +#define DT_NIOS2_GP 0x70000002 /* Address of _gp. */ + +/* Nios II relocations. */ +#define R_NIOS2_NONE 0 /* No reloc. */ +#define R_NIOS2_S16 1 /* Direct signed 16 bit. */ +#define R_NIOS2_U16 2 /* Direct unsigned 16 bit. */ +#define R_NIOS2_PCREL16 3 /* PC relative 16 bit. */ +#define R_NIOS2_CALL26 4 /* Direct call. */ +#define R_NIOS2_IMM5 5 /* 5 bit constant expression. */ +#define R_NIOS2_CACHE_OPX 6 /* 5 bit expression, shift 22. */ +#define R_NIOS2_IMM6 7 /* 6 bit constant expression. */ +#define R_NIOS2_IMM8 8 /* 8 bit constant expression. */ +#define R_NIOS2_HI16 9 /* High 16 bit. */ +#define R_NIOS2_LO16 10 /* Low 16 bit. */ +#define R_NIOS2_HIADJ16 11 /* High 16 bit, adjusted. */ +#define R_NIOS2_BFD_RELOC_32 12 /* 32 bit symbol value + addend. */ +#define R_NIOS2_BFD_RELOC_16 13 /* 16 bit symbol value + addend. */ +#define R_NIOS2_BFD_RELOC_8 14 /* 8 bit symbol value + addend. */ +#define R_NIOS2_GPREL 15 /* 16 bit GP pointer offset. */ +#define R_NIOS2_GNU_VTINHERIT 16 /* GNU C++ vtable hierarchy. */ +#define R_NIOS2_GNU_VTENTRY 17 /* GNU C++ vtable member usage. */ +#define R_NIOS2_UJMP 18 /* Unconditional branch. */ +#define R_NIOS2_CJMP 19 /* Conditional branch. */ +#define R_NIOS2_CALLR 20 /* Indirect call through register. */ +#define R_NIOS2_ALIGN 21 /* Alignment requirement for + linker relaxation. */ +#define R_NIOS2_GOT16 22 /* 16 bit GOT entry. */ +#define R_NIOS2_CALL16 23 /* 16 bit GOT entry for function. */ +#define R_NIOS2_GOTOFF_LO 24 /* %lo of offset to GOT pointer. */ +#define R_NIOS2_GOTOFF_HA 25 /* %hiadj of offset to GOT pointer. */ +#define R_NIOS2_PCREL_LO 26 /* %lo of PC relative offset. */ +#define R_NIOS2_PCREL_HA 27 /* %hiadj of PC relative offset. */ +#define R_NIOS2_TLS_GD16 28 /* 16 bit GOT offset for TLS GD. */ +#define R_NIOS2_TLS_LDM16 29 /* 16 bit GOT offset for TLS LDM. */ +#define R_NIOS2_TLS_LDO16 30 /* 16 bit module relative offset. */ +#define R_NIOS2_TLS_IE16 31 /* 16 bit GOT offset for TLS IE. */ +#define R_NIOS2_TLS_LE16 32 /* 16 bit LE TP-relative offset. */ +#define R_NIOS2_TLS_DTPMOD 33 /* Module number. */ +#define R_NIOS2_TLS_DTPREL 34 /* Module-relative offset. */ +#define R_NIOS2_TLS_TPREL 35 /* TP-relative offset. */ +#define R_NIOS2_COPY 36 /* Copy symbol at runtime. */ +#define R_NIOS2_GLOB_DAT 37 /* Create GOT entry. */ +#define R_NIOS2_JUMP_SLOT 38 /* Create PLT entry. */ +#define R_NIOS2_RELATIVE 39 /* Adjust by program base. */ +#define R_NIOS2_GOTOFF 40 /* 16 bit offset to GOT pointer. */ +#define R_NIOS2_CALL26_NOAT 41 /* Direct call in .noat section. */ +#define R_NIOS2_GOT_LO 42 /* %lo() of GOT entry. */ +#define R_NIOS2_GOT_HA 43 /* %hiadj() of GOT entry. */ +#define R_NIOS2_CALL_LO 44 /* %lo() of function GOT entry. */ +#define R_NIOS2_CALL_HA 45 /* %hiadj() of function GOT entry. */ + +/* TILEPro relocations. */ +#define R_TILEPRO_NONE 0 /* No reloc */ +#define R_TILEPRO_32 1 /* Direct 32 bit */ +#define R_TILEPRO_16 2 /* Direct 16 bit */ +#define R_TILEPRO_8 3 /* Direct 8 bit */ +#define R_TILEPRO_32_PCREL 4 /* PC relative 32 bit */ +#define R_TILEPRO_16_PCREL 5 /* PC relative 16 bit */ +#define R_TILEPRO_8_PCREL 6 /* PC relative 8 bit */ +#define R_TILEPRO_LO16 7 /* Low 16 bit */ +#define R_TILEPRO_HI16 8 /* High 16 bit */ +#define R_TILEPRO_HA16 9 /* High 16 bit, adjusted */ +#define R_TILEPRO_COPY 10 /* Copy relocation */ +#define R_TILEPRO_GLOB_DAT 11 /* Create GOT entry */ +#define R_TILEPRO_JMP_SLOT 12 /* Create PLT entry */ +#define R_TILEPRO_RELATIVE 13 /* Adjust by program base */ +#define R_TILEPRO_BROFF_X1 14 /* X1 pipe branch offset */ +#define R_TILEPRO_JOFFLONG_X1 15 /* X1 pipe jump offset */ +#define R_TILEPRO_JOFFLONG_X1_PLT 16 /* X1 pipe jump offset to PLT */ +#define R_TILEPRO_IMM8_X0 17 /* X0 pipe 8-bit */ +#define R_TILEPRO_IMM8_Y0 18 /* Y0 pipe 8-bit */ +#define R_TILEPRO_IMM8_X1 19 /* X1 pipe 8-bit */ +#define R_TILEPRO_IMM8_Y1 20 /* Y1 pipe 8-bit */ +#define R_TILEPRO_MT_IMM15_X1 21 /* X1 pipe mtspr */ +#define R_TILEPRO_MF_IMM15_X1 22 /* X1 pipe mfspr */ +#define R_TILEPRO_IMM16_X0 23 /* X0 pipe 16-bit */ +#define R_TILEPRO_IMM16_X1 24 /* X1 pipe 16-bit */ +#define R_TILEPRO_IMM16_X0_LO 25 /* X0 pipe low 16-bit */ +#define R_TILEPRO_IMM16_X1_LO 26 /* X1 pipe low 16-bit */ +#define R_TILEPRO_IMM16_X0_HI 27 /* X0 pipe high 16-bit */ +#define R_TILEPRO_IMM16_X1_HI 28 /* X1 pipe high 16-bit */ +#define R_TILEPRO_IMM16_X0_HA 29 /* X0 pipe high 16-bit, adjusted */ +#define R_TILEPRO_IMM16_X1_HA 30 /* X1 pipe high 16-bit, adjusted */ +#define R_TILEPRO_IMM16_X0_PCREL 31 /* X0 pipe PC relative 16 bit */ +#define R_TILEPRO_IMM16_X1_PCREL 32 /* X1 pipe PC relative 16 bit */ +#define R_TILEPRO_IMM16_X0_LO_PCREL 33 /* X0 pipe PC relative low 16 bit */ +#define R_TILEPRO_IMM16_X1_LO_PCREL 34 /* X1 pipe PC relative low 16 bit */ +#define R_TILEPRO_IMM16_X0_HI_PCREL 35 /* X0 pipe PC relative high 16 bit */ +#define R_TILEPRO_IMM16_X1_HI_PCREL 36 /* X1 pipe PC relative high 16 bit */ +#define R_TILEPRO_IMM16_X0_HA_PCREL 37 /* X0 pipe PC relative ha() 16 bit */ +#define R_TILEPRO_IMM16_X1_HA_PCREL 38 /* X1 pipe PC relative ha() 16 bit */ +#define R_TILEPRO_IMM16_X0_GOT 39 /* X0 pipe 16-bit GOT offset */ +#define R_TILEPRO_IMM16_X1_GOT 40 /* X1 pipe 16-bit GOT offset */ +#define R_TILEPRO_IMM16_X0_GOT_LO 41 /* X0 pipe low 16-bit GOT offset */ +#define R_TILEPRO_IMM16_X1_GOT_LO 42 /* X1 pipe low 16-bit GOT offset */ +#define R_TILEPRO_IMM16_X0_GOT_HI 43 /* X0 pipe high 16-bit GOT offset */ +#define R_TILEPRO_IMM16_X1_GOT_HI 44 /* X1 pipe high 16-bit GOT offset */ +#define R_TILEPRO_IMM16_X0_GOT_HA 45 /* X0 pipe ha() 16-bit GOT offset */ +#define R_TILEPRO_IMM16_X1_GOT_HA 46 /* X1 pipe ha() 16-bit GOT offset */ +#define R_TILEPRO_MMSTART_X0 47 /* X0 pipe mm "start" */ +#define R_TILEPRO_MMEND_X0 48 /* X0 pipe mm "end" */ +#define R_TILEPRO_MMSTART_X1 49 /* X1 pipe mm "start" */ +#define R_TILEPRO_MMEND_X1 50 /* X1 pipe mm "end" */ +#define R_TILEPRO_SHAMT_X0 51 /* X0 pipe shift amount */ +#define R_TILEPRO_SHAMT_X1 52 /* X1 pipe shift amount */ +#define R_TILEPRO_SHAMT_Y0 53 /* Y0 pipe shift amount */ +#define R_TILEPRO_SHAMT_Y1 54 /* Y1 pipe shift amount */ +#define R_TILEPRO_DEST_IMM8_X1 55 /* X1 pipe destination 8-bit */ +/* Relocs 56-59 are currently not defined. */ +#define R_TILEPRO_TLS_GD_CALL 60 /* "jal" for TLS GD */ +#define R_TILEPRO_IMM8_X0_TLS_GD_ADD 61 /* X0 pipe "addi" for TLS GD */ +#define R_TILEPRO_IMM8_X1_TLS_GD_ADD 62 /* X1 pipe "addi" for TLS GD */ +#define R_TILEPRO_IMM8_Y0_TLS_GD_ADD 63 /* Y0 pipe "addi" for TLS GD */ +#define R_TILEPRO_IMM8_Y1_TLS_GD_ADD 64 /* Y1 pipe "addi" for TLS GD */ +#define R_TILEPRO_TLS_IE_LOAD 65 /* "lw_tls" for TLS IE */ +#define R_TILEPRO_IMM16_X0_TLS_GD 66 /* X0 pipe 16-bit TLS GD offset */ +#define R_TILEPRO_IMM16_X1_TLS_GD 67 /* X1 pipe 16-bit TLS GD offset */ +#define R_TILEPRO_IMM16_X0_TLS_GD_LO 68 /* X0 pipe low 16-bit TLS GD offset */ +#define R_TILEPRO_IMM16_X1_TLS_GD_LO 69 /* X1 pipe low 16-bit TLS GD offset */ +#define R_TILEPRO_IMM16_X0_TLS_GD_HI 70 /* X0 pipe high 16-bit TLS GD offset */ +#define R_TILEPRO_IMM16_X1_TLS_GD_HI 71 /* X1 pipe high 16-bit TLS GD offset */ +#define R_TILEPRO_IMM16_X0_TLS_GD_HA 72 /* X0 pipe ha() 16-bit TLS GD offset */ +#define R_TILEPRO_IMM16_X1_TLS_GD_HA 73 /* X1 pipe ha() 16-bit TLS GD offset */ +#define R_TILEPRO_IMM16_X0_TLS_IE 74 /* X0 pipe 16-bit TLS IE offset */ +#define R_TILEPRO_IMM16_X1_TLS_IE 75 /* X1 pipe 16-bit TLS IE offset */ +#define R_TILEPRO_IMM16_X0_TLS_IE_LO 76 /* X0 pipe low 16-bit TLS IE offset */ +#define R_TILEPRO_IMM16_X1_TLS_IE_LO 77 /* X1 pipe low 16-bit TLS IE offset */ +#define R_TILEPRO_IMM16_X0_TLS_IE_HI 78 /* X0 pipe high 16-bit TLS IE offset */ +#define R_TILEPRO_IMM16_X1_TLS_IE_HI 79 /* X1 pipe high 16-bit TLS IE offset */ +#define R_TILEPRO_IMM16_X0_TLS_IE_HA 80 /* X0 pipe ha() 16-bit TLS IE offset */ +#define R_TILEPRO_IMM16_X1_TLS_IE_HA 81 /* X1 pipe ha() 16-bit TLS IE offset */ +#define R_TILEPRO_TLS_DTPMOD32 82 /* ID of module containing symbol */ +#define R_TILEPRO_TLS_DTPOFF32 83 /* Offset in TLS block */ +#define R_TILEPRO_TLS_TPOFF32 84 /* Offset in static TLS block */ +#define R_TILEPRO_IMM16_X0_TLS_LE 85 /* X0 pipe 16-bit TLS LE offset */ +#define R_TILEPRO_IMM16_X1_TLS_LE 86 /* X1 pipe 16-bit TLS LE offset */ +#define R_TILEPRO_IMM16_X0_TLS_LE_LO 87 /* X0 pipe low 16-bit TLS LE offset */ +#define R_TILEPRO_IMM16_X1_TLS_LE_LO 88 /* X1 pipe low 16-bit TLS LE offset */ +#define R_TILEPRO_IMM16_X0_TLS_LE_HI 89 /* X0 pipe high 16-bit TLS LE offset */ +#define R_TILEPRO_IMM16_X1_TLS_LE_HI 90 /* X1 pipe high 16-bit TLS LE offset */ +#define R_TILEPRO_IMM16_X0_TLS_LE_HA 91 /* X0 pipe ha() 16-bit TLS LE offset */ +#define R_TILEPRO_IMM16_X1_TLS_LE_HA 92 /* X1 pipe ha() 16-bit TLS LE offset */ + +#define R_TILEPRO_GNU_VTINHERIT 128 /* GNU C++ vtable hierarchy */ +#define R_TILEPRO_GNU_VTENTRY 129 /* GNU C++ vtable member usage */ + +#define R_TILEPRO_NUM 130 + + +/* TILE-Gx relocations. */ +#define R_TILEGX_NONE 0 /* No reloc */ +#define R_TILEGX_64 1 /* Direct 64 bit */ +#define R_TILEGX_32 2 /* Direct 32 bit */ +#define R_TILEGX_16 3 /* Direct 16 bit */ +#define R_TILEGX_8 4 /* Direct 8 bit */ +#define R_TILEGX_64_PCREL 5 /* PC relative 64 bit */ +#define R_TILEGX_32_PCREL 6 /* PC relative 32 bit */ +#define R_TILEGX_16_PCREL 7 /* PC relative 16 bit */ +#define R_TILEGX_8_PCREL 8 /* PC relative 8 bit */ +#define R_TILEGX_HW0 9 /* hword 0 16-bit */ +#define R_TILEGX_HW1 10 /* hword 1 16-bit */ +#define R_TILEGX_HW2 11 /* hword 2 16-bit */ +#define R_TILEGX_HW3 12 /* hword 3 16-bit */ +#define R_TILEGX_HW0_LAST 13 /* last hword 0 16-bit */ +#define R_TILEGX_HW1_LAST 14 /* last hword 1 16-bit */ +#define R_TILEGX_HW2_LAST 15 /* last hword 2 16-bit */ +#define R_TILEGX_COPY 16 /* Copy relocation */ +#define R_TILEGX_GLOB_DAT 17 /* Create GOT entry */ +#define R_TILEGX_JMP_SLOT 18 /* Create PLT entry */ +#define R_TILEGX_RELATIVE 19 /* Adjust by program base */ +#define R_TILEGX_BROFF_X1 20 /* X1 pipe branch offset */ +#define R_TILEGX_JUMPOFF_X1 21 /* X1 pipe jump offset */ +#define R_TILEGX_JUMPOFF_X1_PLT 22 /* X1 pipe jump offset to PLT */ +#define R_TILEGX_IMM8_X0 23 /* X0 pipe 8-bit */ +#define R_TILEGX_IMM8_Y0 24 /* Y0 pipe 8-bit */ +#define R_TILEGX_IMM8_X1 25 /* X1 pipe 8-bit */ +#define R_TILEGX_IMM8_Y1 26 /* Y1 pipe 8-bit */ +#define R_TILEGX_DEST_IMM8_X1 27 /* X1 pipe destination 8-bit */ +#define R_TILEGX_MT_IMM14_X1 28 /* X1 pipe mtspr */ +#define R_TILEGX_MF_IMM14_X1 29 /* X1 pipe mfspr */ +#define R_TILEGX_MMSTART_X0 30 /* X0 pipe mm "start" */ +#define R_TILEGX_MMEND_X0 31 /* X0 pipe mm "end" */ +#define R_TILEGX_SHAMT_X0 32 /* X0 pipe shift amount */ +#define R_TILEGX_SHAMT_X1 33 /* X1 pipe shift amount */ +#define R_TILEGX_SHAMT_Y0 34 /* Y0 pipe shift amount */ +#define R_TILEGX_SHAMT_Y1 35 /* Y1 pipe shift amount */ +#define R_TILEGX_IMM16_X0_HW0 36 /* X0 pipe hword 0 */ +#define R_TILEGX_IMM16_X1_HW0 37 /* X1 pipe hword 0 */ +#define R_TILEGX_IMM16_X0_HW1 38 /* X0 pipe hword 1 */ +#define R_TILEGX_IMM16_X1_HW1 39 /* X1 pipe hword 1 */ +#define R_TILEGX_IMM16_X0_HW2 40 /* X0 pipe hword 2 */ +#define R_TILEGX_IMM16_X1_HW2 41 /* X1 pipe hword 2 */ +#define R_TILEGX_IMM16_X0_HW3 42 /* X0 pipe hword 3 */ +#define R_TILEGX_IMM16_X1_HW3 43 /* X1 pipe hword 3 */ +#define R_TILEGX_IMM16_X0_HW0_LAST 44 /* X0 pipe last hword 0 */ +#define R_TILEGX_IMM16_X1_HW0_LAST 45 /* X1 pipe last hword 0 */ +#define R_TILEGX_IMM16_X0_HW1_LAST 46 /* X0 pipe last hword 1 */ +#define R_TILEGX_IMM16_X1_HW1_LAST 47 /* X1 pipe last hword 1 */ +#define R_TILEGX_IMM16_X0_HW2_LAST 48 /* X0 pipe last hword 2 */ +#define R_TILEGX_IMM16_X1_HW2_LAST 49 /* X1 pipe last hword 2 */ +#define R_TILEGX_IMM16_X0_HW0_PCREL 50 /* X0 pipe PC relative hword 0 */ +#define R_TILEGX_IMM16_X1_HW0_PCREL 51 /* X1 pipe PC relative hword 0 */ +#define R_TILEGX_IMM16_X0_HW1_PCREL 52 /* X0 pipe PC relative hword 1 */ +#define R_TILEGX_IMM16_X1_HW1_PCREL 53 /* X1 pipe PC relative hword 1 */ +#define R_TILEGX_IMM16_X0_HW2_PCREL 54 /* X0 pipe PC relative hword 2 */ +#define R_TILEGX_IMM16_X1_HW2_PCREL 55 /* X1 pipe PC relative hword 2 */ +#define R_TILEGX_IMM16_X0_HW3_PCREL 56 /* X0 pipe PC relative hword 3 */ +#define R_TILEGX_IMM16_X1_HW3_PCREL 57 /* X1 pipe PC relative hword 3 */ +#define R_TILEGX_IMM16_X0_HW0_LAST_PCREL 58 /* X0 pipe PC-rel last hword 0 */ +#define R_TILEGX_IMM16_X1_HW0_LAST_PCREL 59 /* X1 pipe PC-rel last hword 0 */ +#define R_TILEGX_IMM16_X0_HW1_LAST_PCREL 60 /* X0 pipe PC-rel last hword 1 */ +#define R_TILEGX_IMM16_X1_HW1_LAST_PCREL 61 /* X1 pipe PC-rel last hword 1 */ +#define R_TILEGX_IMM16_X0_HW2_LAST_PCREL 62 /* X0 pipe PC-rel last hword 2 */ +#define R_TILEGX_IMM16_X1_HW2_LAST_PCREL 63 /* X1 pipe PC-rel last hword 2 */ +#define R_TILEGX_IMM16_X0_HW0_GOT 64 /* X0 pipe hword 0 GOT offset */ +#define R_TILEGX_IMM16_X1_HW0_GOT 65 /* X1 pipe hword 0 GOT offset */ +#define R_TILEGX_IMM16_X0_HW0_PLT_PCREL 66 /* X0 pipe PC-rel PLT hword 0 */ +#define R_TILEGX_IMM16_X1_HW0_PLT_PCREL 67 /* X1 pipe PC-rel PLT hword 0 */ +#define R_TILEGX_IMM16_X0_HW1_PLT_PCREL 68 /* X0 pipe PC-rel PLT hword 1 */ +#define R_TILEGX_IMM16_X1_HW1_PLT_PCREL 69 /* X1 pipe PC-rel PLT hword 1 */ +#define R_TILEGX_IMM16_X0_HW2_PLT_PCREL 70 /* X0 pipe PC-rel PLT hword 2 */ +#define R_TILEGX_IMM16_X1_HW2_PLT_PCREL 71 /* X1 pipe PC-rel PLT hword 2 */ +#define R_TILEGX_IMM16_X0_HW0_LAST_GOT 72 /* X0 pipe last hword 0 GOT offset */ +#define R_TILEGX_IMM16_X1_HW0_LAST_GOT 73 /* X1 pipe last hword 0 GOT offset */ +#define R_TILEGX_IMM16_X0_HW1_LAST_GOT 74 /* X0 pipe last hword 1 GOT offset */ +#define R_TILEGX_IMM16_X1_HW1_LAST_GOT 75 /* X1 pipe last hword 1 GOT offset */ +#define R_TILEGX_IMM16_X0_HW3_PLT_PCREL 76 /* X0 pipe PC-rel PLT hword 3 */ +#define R_TILEGX_IMM16_X1_HW3_PLT_PCREL 77 /* X1 pipe PC-rel PLT hword 3 */ +#define R_TILEGX_IMM16_X0_HW0_TLS_GD 78 /* X0 pipe hword 0 TLS GD offset */ +#define R_TILEGX_IMM16_X1_HW0_TLS_GD 79 /* X1 pipe hword 0 TLS GD offset */ +#define R_TILEGX_IMM16_X0_HW0_TLS_LE 80 /* X0 pipe hword 0 TLS LE offset */ +#define R_TILEGX_IMM16_X1_HW0_TLS_LE 81 /* X1 pipe hword 0 TLS LE offset */ +#define R_TILEGX_IMM16_X0_HW0_LAST_TLS_LE 82 /* X0 pipe last hword 0 LE off */ +#define R_TILEGX_IMM16_X1_HW0_LAST_TLS_LE 83 /* X1 pipe last hword 0 LE off */ +#define R_TILEGX_IMM16_X0_HW1_LAST_TLS_LE 84 /* X0 pipe last hword 1 LE off */ +#define R_TILEGX_IMM16_X1_HW1_LAST_TLS_LE 85 /* X1 pipe last hword 1 LE off */ +#define R_TILEGX_IMM16_X0_HW0_LAST_TLS_GD 86 /* X0 pipe last hword 0 GD off */ +#define R_TILEGX_IMM16_X1_HW0_LAST_TLS_GD 87 /* X1 pipe last hword 0 GD off */ +#define R_TILEGX_IMM16_X0_HW1_LAST_TLS_GD 88 /* X0 pipe last hword 1 GD off */ +#define R_TILEGX_IMM16_X1_HW1_LAST_TLS_GD 89 /* X1 pipe last hword 1 GD off */ +/* Relocs 90-91 are currently not defined. */ +#define R_TILEGX_IMM16_X0_HW0_TLS_IE 92 /* X0 pipe hword 0 TLS IE offset */ +#define R_TILEGX_IMM16_X1_HW0_TLS_IE 93 /* X1 pipe hword 0 TLS IE offset */ +#define R_TILEGX_IMM16_X0_HW0_LAST_PLT_PCREL 94 /* X0 pipe PC-rel PLT last hword 0 */ +#define R_TILEGX_IMM16_X1_HW0_LAST_PLT_PCREL 95 /* X1 pipe PC-rel PLT last hword 0 */ +#define R_TILEGX_IMM16_X0_HW1_LAST_PLT_PCREL 96 /* X0 pipe PC-rel PLT last hword 1 */ +#define R_TILEGX_IMM16_X1_HW1_LAST_PLT_PCREL 97 /* X1 pipe PC-rel PLT last hword 1 */ +#define R_TILEGX_IMM16_X0_HW2_LAST_PLT_PCREL 98 /* X0 pipe PC-rel PLT last hword 2 */ +#define R_TILEGX_IMM16_X1_HW2_LAST_PLT_PCREL 99 /* X1 pipe PC-rel PLT last hword 2 */ +#define R_TILEGX_IMM16_X0_HW0_LAST_TLS_IE 100 /* X0 pipe last hword 0 IE off */ +#define R_TILEGX_IMM16_X1_HW0_LAST_TLS_IE 101 /* X1 pipe last hword 0 IE off */ +#define R_TILEGX_IMM16_X0_HW1_LAST_TLS_IE 102 /* X0 pipe last hword 1 IE off */ +#define R_TILEGX_IMM16_X1_HW1_LAST_TLS_IE 103 /* X1 pipe last hword 1 IE off */ +/* Relocs 104-105 are currently not defined. */ +#define R_TILEGX_TLS_DTPMOD64 106 /* 64-bit ID of symbol's module */ +#define R_TILEGX_TLS_DTPOFF64 107 /* 64-bit offset in TLS block */ +#define R_TILEGX_TLS_TPOFF64 108 /* 64-bit offset in static TLS block */ +#define R_TILEGX_TLS_DTPMOD32 109 /* 32-bit ID of symbol's module */ +#define R_TILEGX_TLS_DTPOFF32 110 /* 32-bit offset in TLS block */ +#define R_TILEGX_TLS_TPOFF32 111 /* 32-bit offset in static TLS block */ +#define R_TILEGX_TLS_GD_CALL 112 /* "jal" for TLS GD */ +#define R_TILEGX_IMM8_X0_TLS_GD_ADD 113 /* X0 pipe "addi" for TLS GD */ +#define R_TILEGX_IMM8_X1_TLS_GD_ADD 114 /* X1 pipe "addi" for TLS GD */ +#define R_TILEGX_IMM8_Y0_TLS_GD_ADD 115 /* Y0 pipe "addi" for TLS GD */ +#define R_TILEGX_IMM8_Y1_TLS_GD_ADD 116 /* Y1 pipe "addi" for TLS GD */ +#define R_TILEGX_TLS_IE_LOAD 117 /* "ld_tls" for TLS IE */ +#define R_TILEGX_IMM8_X0_TLS_ADD 118 /* X0 pipe "addi" for TLS GD/IE */ +#define R_TILEGX_IMM8_X1_TLS_ADD 119 /* X1 pipe "addi" for TLS GD/IE */ +#define R_TILEGX_IMM8_Y0_TLS_ADD 120 /* Y0 pipe "addi" for TLS GD/IE */ +#define R_TILEGX_IMM8_Y1_TLS_ADD 121 /* Y1 pipe "addi" for TLS GD/IE */ + +#define R_TILEGX_GNU_VTINHERIT 128 /* GNU C++ vtable hierarchy */ +#define R_TILEGX_GNU_VTENTRY 129 /* GNU C++ vtable member usage */ + +#define R_TILEGX_NUM 130 + +/* BPF specific declarations. */ + +#define R_BPF_NONE 0 /* No reloc */ +#define R_BPF_MAP_FD 1 /* Map fd to pointer */ + +/* Imagination Meta specific relocations. */ + +#define R_METAG_HIADDR16 0 +#define R_METAG_LOADDR16 1 +#define R_METAG_ADDR32 2 /* 32bit absolute address */ +#define R_METAG_NONE 3 /* No reloc */ +#define R_METAG_RELBRANCH 4 +#define R_METAG_GETSETOFF 5 + +/* Backward compatability */ +#define R_METAG_REG32OP1 6 +#define R_METAG_REG32OP2 7 +#define R_METAG_REG32OP3 8 +#define R_METAG_REG16OP1 9 +#define R_METAG_REG16OP2 10 +#define R_METAG_REG16OP3 11 +#define R_METAG_REG32OP4 12 + +#define R_METAG_HIOG 13 +#define R_METAG_LOOG 14 + +#define R_METAG_REL8 15 +#define R_METAG_REL16 16 + +/* GNU */ +#define R_METAG_GNU_VTINHERIT 30 +#define R_METAG_GNU_VTENTRY 31 + +/* PIC relocations */ +#define R_METAG_HI16_GOTOFF 32 +#define R_METAG_LO16_GOTOFF 33 +#define R_METAG_GETSET_GOTOFF 34 +#define R_METAG_GETSET_GOT 35 +#define R_METAG_HI16_GOTPC 36 +#define R_METAG_LO16_GOTPC 37 +#define R_METAG_HI16_PLT 38 +#define R_METAG_LO16_PLT 39 +#define R_METAG_RELBRANCH_PLT 40 +#define R_METAG_GOTOFF 41 +#define R_METAG_PLT 42 +#define R_METAG_COPY 43 +#define R_METAG_JMP_SLOT 44 +#define R_METAG_RELATIVE 45 +#define R_METAG_GLOB_DAT 46 + +/* TLS relocations */ +#define R_METAG_TLS_GD 47 +#define R_METAG_TLS_LDM 48 +#define R_METAG_TLS_LDO_HI16 49 +#define R_METAG_TLS_LDO_LO16 50 +#define R_METAG_TLS_LDO 51 +#define R_METAG_TLS_IE 52 +#define R_METAG_TLS_IENONPIC 53 +#define R_METAG_TLS_IENONPIC_HI16 54 +#define R_METAG_TLS_IENONPIC_LO16 55 +#define R_METAG_TLS_TPOFF 56 +#define R_METAG_TLS_DTPMOD 57 +#define R_METAG_TLS_DTPOFF 58 +#define R_METAG_TLS_LE 59 +#define R_METAG_TLS_LE_HI16 60 +#define R_METAG_TLS_LE_LO16 61 + +__END_DECLS + +#endif /* elf.h */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/elf/gelf.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/elf/gelf.h new file mode 100644 index 000000000..f52be29db --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/elf/gelf.h @@ -0,0 +1,341 @@ +/* This file defines generic ELF types, structures, and macros. + Copyright (C) 1999, 2000, 2001, 2002, 2004, 2005, 2007, 2015 Red Hat, Inc. + This file is part of elfutils. + + This file is free software; you can redistribute it and/or modify + it under the terms of either + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at + your option) any later version + + or + + * the GNU General Public License as published by the Free + Software Foundation; either version 2 of the License, or (at + your option) any later version + + or both in parallel, as here. + + elfutils is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see . */ + +#ifndef _GELF_H +#define _GELF_H 1 + +#include "libelf.h" + +#ifdef __cplusplus +extern "C" { +#endif + +/* Class independent type definitions. Correctly speaking this is not + true. We assume that 64-bit binaries are the largest class and + therefore all other classes can be represented without loss. */ + +/* Type for a 16-bit quantity. */ +typedef Elf64_Half GElf_Half; + +/* Types for signed and unsigned 32-bit quantities. */ +typedef Elf64_Word GElf_Word; +typedef Elf64_Sword GElf_Sword; + +/* Types for signed and unsigned 64-bit quantities. */ +typedef Elf64_Xword GElf_Xword; +typedef Elf64_Sxword GElf_Sxword; + +/* Type of addresses. */ +typedef Elf64_Addr GElf_Addr; + +/* Type of file offsets. */ +typedef Elf64_Off GElf_Off; + + +/* The ELF file header. This appears at the start of every ELF file. */ +typedef Elf64_Ehdr GElf_Ehdr; + +/* Section header. */ +typedef Elf64_Shdr GElf_Shdr; + +/* Section index. */ +/* XXX This should probably be a larger type in preparation of times when + regular section indices can be larger. */ +typedef Elf64_Section GElf_Section; + +/* Symbol table entry. */ +typedef Elf64_Sym GElf_Sym; + +/* The syminfo section if available contains additional information about + every dynamic symbol. */ +typedef Elf64_Syminfo GElf_Syminfo; + +/* Relocation table entry without addend (in section of type SHT_REL). */ +typedef Elf64_Rel GElf_Rel; + +/* Relocation table entry with addend (in section of type SHT_RELA). */ +typedef Elf64_Rela GElf_Rela; + +/* Program segment header. */ +typedef Elf64_Phdr GElf_Phdr; + +/* Header of a compressed section. */ +typedef Elf64_Chdr GElf_Chdr; + +/* Dynamic section entry. */ +typedef Elf64_Dyn GElf_Dyn; + + +/* Version definition sections. */ +typedef Elf64_Verdef GElf_Verdef; + +/* Auxialiary version information. */ +typedef Elf64_Verdaux GElf_Verdaux; + +/* Version dependency section. */ +typedef Elf64_Verneed GElf_Verneed; + +/* Auxiliary needed version information. */ +typedef Elf64_Vernaux GElf_Vernaux; + + +/* Type for version symbol information. */ +typedef Elf64_Versym GElf_Versym; + + +/* Auxiliary vector. */ +typedef Elf64_auxv_t GElf_auxv_t; + + +/* Note section contents. */ +typedef Elf64_Nhdr GElf_Nhdr; + + +/* Move structure. */ +typedef Elf64_Move GElf_Move; + + +/* Library list structure. */ +typedef Elf64_Lib GElf_Lib; + + +/* How to extract and insert information held in the st_info field. */ + +#define GELF_ST_BIND(val) ELF64_ST_BIND (val) +#define GELF_ST_TYPE(val) ELF64_ST_TYPE (val) +#define GELF_ST_INFO(bind, type) ELF64_ST_INFO (bind, type) + +/* How to extract information held in the st_other field. */ + +#define GELF_ST_VISIBILITY(val) ELF64_ST_VISIBILITY (val) + + +/* How to extract and insert information held in the r_info field. */ + +#define GELF_R_SYM(info) ELF64_R_SYM (info) +#define GELF_R_TYPE(info) ELF64_R_TYPE (info) +#define GELF_R_INFO(sym, type) ELF64_R_INFO (sym, type) + + +/* How to extract and insert information held in the m_info field. */ +#define GELF_M_SYM(info) ELF64_M_SYM (info) +#define GELF_M_SIZE(info) ELF64_M_SIZE (info) +#define GELF_M_INFO(sym, size) ELF64_M_INFO (sym, size) + + +/* Get class of the file associated with ELF. */ +extern int gelf_getclass (Elf *__elf); + + +/* Return size of array of COUNT elements of the type denoted by TYPE + in the external representation. The binary class is taken from ELF. + The result is based on version VERSION of the ELF standard. */ +extern size_t gelf_fsize (Elf *__elf, Elf_Type __type, size_t __count, + unsigned int __version); + +/* Retrieve object file header. */ +extern GElf_Ehdr *gelf_getehdr (Elf *__elf, GElf_Ehdr *__dest); + +/* Update the ELF header. */ +extern int gelf_update_ehdr (Elf *__elf, GElf_Ehdr *__src); + +/* Create new ELF header if none exists. Creates an Elf32_Ehdr if CLASS + is ELFCLASS32 or an Elf64_Ehdr if CLASS is ELFCLASS64. Returns NULL + on error. */ +extern void *gelf_newehdr (Elf *__elf, int __class); + +/* Get section at OFFSET. */ +extern Elf_Scn *gelf_offscn (Elf *__elf, GElf_Off __offset); + +/* Retrieve section header. */ +extern GElf_Shdr *gelf_getshdr (Elf_Scn *__scn, GElf_Shdr *__dst); + +/* Update section header. */ +extern int gelf_update_shdr (Elf_Scn *__scn, GElf_Shdr *__src); + +/* Retrieve program header table entry. */ +extern GElf_Phdr *gelf_getphdr (Elf *__elf, int __ndx, GElf_Phdr *__dst); + +/* Update the program header. */ +extern int gelf_update_phdr (Elf *__elf, int __ndx, GElf_Phdr *__src); + +/* Create new program header with PHNUM entries. Creates either an + Elf32_Phdr or an Elf64_Phdr depending on whether the given ELF is + ELFCLASS32 or ELFCLASS64. Returns NULL on error. */ +extern void *gelf_newphdr (Elf *__elf, size_t __phnum); + +/* Get compression header of section if any. Returns NULL and sets + elf_errno if the section isn't compressed or an error occurred. */ +extern GElf_Chdr *gelf_getchdr (Elf_Scn *__scn, GElf_Chdr *__dst); + +/* Convert data structure from the representation in the file represented + by ELF to their memory representation. */ +extern Elf_Data *gelf_xlatetom (Elf *__elf, Elf_Data *__dest, + const Elf_Data *__src, unsigned int __encode); + +/* Convert data structure from to the representation in memory + represented by ELF file representation. */ +extern Elf_Data *gelf_xlatetof (Elf *__elf, Elf_Data *__dest, + const Elf_Data *__src, unsigned int __encode); + + +/* Retrieve REL relocation info at the given index. */ +extern GElf_Rel *gelf_getrel (Elf_Data *__data, int __ndx, GElf_Rel *__dst); + +/* Retrieve RELA relocation info at the given index. */ +extern GElf_Rela *gelf_getrela (Elf_Data *__data, int __ndx, GElf_Rela *__dst); + +/* Update REL relocation information at given index. */ +extern int gelf_update_rel (Elf_Data *__dst, int __ndx, GElf_Rel *__src); + +/* Update RELA relocation information at given index. */ +extern int gelf_update_rela (Elf_Data *__dst, int __ndx, GElf_Rela *__src); + + +/* Retrieve symbol information from the symbol table at the given index. */ +extern GElf_Sym *gelf_getsym (Elf_Data *__data, int __ndx, GElf_Sym *__dst); + +/* Update symbol information in the symbol table at the given index. */ +extern int gelf_update_sym (Elf_Data *__data, int __ndx, GElf_Sym *__src); + + +/* Retrieve symbol information and separate section index from the + symbol table at the given index. */ +extern GElf_Sym *gelf_getsymshndx (Elf_Data *__symdata, Elf_Data *__shndxdata, + int __ndx, GElf_Sym *__sym, + Elf32_Word *__xshndx); + +/* Update symbol information and separate section index in the symbol + table at the given index. */ +extern int gelf_update_symshndx (Elf_Data *__symdata, Elf_Data *__shndxdata, + int __ndx, GElf_Sym *__sym, + Elf32_Word __xshndx); + + +/* Retrieve additional symbol information from the symbol table at the + given index. */ +extern GElf_Syminfo *gelf_getsyminfo (Elf_Data *__data, int __ndx, + GElf_Syminfo *__dst); + +/* Update additional symbol information in the symbol table at the + given index. */ +extern int gelf_update_syminfo (Elf_Data *__data, int __ndx, + GElf_Syminfo *__src); + + +/* Get information from dynamic table at the given index. */ +extern GElf_Dyn *gelf_getdyn (Elf_Data *__data, int __ndx, GElf_Dyn *__dst); + +/* Update information in dynamic table at the given index. */ +extern int gelf_update_dyn (Elf_Data *__dst, int __ndx, GElf_Dyn *__src); + + +/* Get move structure at the given index. */ +extern GElf_Move *gelf_getmove (Elf_Data *__data, int __ndx, GElf_Move *__dst); + +/* Update move structure at the given index. */ +extern int gelf_update_move (Elf_Data *__data, int __ndx, + GElf_Move *__src); + + +/* Get library from table at the given index. */ +extern GElf_Lib *gelf_getlib (Elf_Data *__data, int __ndx, GElf_Lib *__dst); + +/* Update library in table at the given index. */ +extern int gelf_update_lib (Elf_Data *__data, int __ndx, GElf_Lib *__src); + + + +/* Retrieve symbol version information at given index. */ +extern GElf_Versym *gelf_getversym (Elf_Data *__data, int __ndx, + GElf_Versym *__dst); + +/* Update symbol version information. */ +extern int gelf_update_versym (Elf_Data *__data, int __ndx, + GElf_Versym *__src); + + +/* Retrieve required symbol version information at given offset. */ +extern GElf_Verneed *gelf_getverneed (Elf_Data *__data, int __offset, + GElf_Verneed *__dst); + +/* Update required symbol version information. */ +extern int gelf_update_verneed (Elf_Data *__data, int __offset, + GElf_Verneed *__src); + +/* Retrieve additional required symbol version information at given offset. */ +extern GElf_Vernaux *gelf_getvernaux (Elf_Data *__data, int __offset, + GElf_Vernaux *__dst); + +/* Update additional required symbol version information. */ +extern int gelf_update_vernaux (Elf_Data *__data, int __offset, + GElf_Vernaux *__src); + + +/* Retrieve symbol version definition information at given offset. */ +extern GElf_Verdef *gelf_getverdef (Elf_Data *__data, int __offset, + GElf_Verdef *__dst); + +/* Update symbol version definition information. */ +extern int gelf_update_verdef (Elf_Data *__data, int __offset, + GElf_Verdef *__src); + +/* Retrieve additional symbol version definition information at given + offset. */ +extern GElf_Verdaux *gelf_getverdaux (Elf_Data *__data, int __offset, + GElf_Verdaux *__dst); + +/* Update additional symbol version definition information. */ +extern int gelf_update_verdaux (Elf_Data *__data, int __offset, + GElf_Verdaux *__src); + + +/* Get auxv entry at the given index. */ +extern GElf_auxv_t *gelf_getauxv (Elf_Data *__data, int __ndx, + GElf_auxv_t *__dst); + +/* Update auxv entry at the given index. */ +extern int gelf_update_auxv (Elf_Data *__data, int __ndx, GElf_auxv_t *__src); + + +/* Get note header at the given offset into the data, and the offsets of + the note's name and descriptor data. Returns the offset of the next + note header, or 0 for an invalid offset or corrupt note header. */ +extern size_t gelf_getnote (Elf_Data *__data, size_t __offset, + GElf_Nhdr *__result, + size_t *__name_offset, size_t *__desc_offset); + + +/* Compute simple checksum from permanent parts of the ELF file. */ +extern long int gelf_checksum (Elf *__elf); + +#ifdef __cplusplus +} +#endif + +#endif /* gelf.h */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/elf/libelf.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/elf/libelf.h new file mode 100644 index 000000000..171500c7c --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/elf/libelf.h @@ -0,0 +1,515 @@ +/* Interface for libelf. + Copyright (C) 1998-2010, 2015 Red Hat, Inc. + This file is part of elfutils. + + This file is free software; you can redistribute it and/or modify + it under the terms of either + + * the GNU Lesser General Public License as published by the Free + Software Foundation; either version 3 of the License, or (at + your option) any later version + + or + + * the GNU General Public License as published by the Free + Software Foundation; either version 2 of the License, or (at + your option) any later version + + or both in parallel, as here. + + elfutils is distributed in the hope that it will be useful, but + WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU + General Public License for more details. + + You should have received copies of the GNU General Public License and + the GNU Lesser General Public License along with this program. If + not, see . */ + +#ifndef _LIBELF_H +#define _LIBELF_H 1 + +#include +#include + +/* Get the ELF types. */ +#include "elf.h" + +#ifndef SHF_COMPRESSED + /* Older glibc elf.h might not yet define the ELF compression types. */ + #define SHF_COMPRESSED (1 << 11) /* Section with compressed data. */ + + /* Section compression header. Used when SHF_COMPRESSED is set. */ + + typedef struct + { + Elf32_Word ch_type; /* Compression format. */ + Elf32_Word ch_size; /* Uncompressed data size. */ + Elf32_Word ch_addralign; /* Uncompressed data alignment. */ + } Elf32_Chdr; + + typedef struct + { + Elf64_Word ch_type; /* Compression format. */ + Elf64_Word ch_reserved; + Elf64_Xword ch_size; /* Uncompressed data size. */ + Elf64_Xword ch_addralign; /* Uncompressed data alignment. */ + } Elf64_Chdr; + + /* Legal values for ch_type (compression algorithm). */ + #define ELFCOMPRESS_ZLIB 1 /* ZLIB/DEFLATE algorithm. */ + #define ELFCOMPRESS_LOOS 0x60000000 /* Start of OS-specific. */ + #define ELFCOMPRESS_HIOS 0x6fffffff /* End of OS-specific. */ + #define ELFCOMPRESS_LOPROC 0x70000000 /* Start of processor-specific. */ + #define ELFCOMPRESS_HIPROC 0x7fffffff /* End of processor-specific. */ +#endif + +#if __GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3) +# define __nonnull_attribute__(...) __attribute__ ((__nonnull__ (__VA_ARGS__))) +# define __deprecated_attribute__ __attribute__ ((__deprecated__)) +# define __pure_attribute__ __attribute__ ((__pure__)) +# define __const_attribute__ __attribute__ ((__const__)) +#else +# define __nonnull_attribute__(...) +# define __deprecated_attribute__ +# define __pure_attribute__ +# define __const_attribute__ +#endif + +#if __GNUC__ < 4 +#define __noreturn_attribute__ +#else +#define __noreturn_attribute__ __attribute__ ((noreturn)) +#endif + +#ifdef __GNUC_STDC_INLINE__ +# define __libdw_extern_inline extern __inline __attribute__ ((__gnu_inline__)) +#else +# define __libdw_extern_inline extern __inline +#endif + +/* Known translation types. */ +typedef enum +{ + ELF_T_BYTE, /* unsigned char */ + ELF_T_ADDR, /* Elf32_Addr, Elf64_Addr, ... */ + ELF_T_DYN, /* Dynamic section record. */ + ELF_T_EHDR, /* ELF header. */ + ELF_T_HALF, /* Elf32_Half, Elf64_Half, ... */ + ELF_T_OFF, /* Elf32_Off, Elf64_Off, ... */ + ELF_T_PHDR, /* Program header. */ + ELF_T_RELA, /* Relocation entry with addend. */ + ELF_T_REL, /* Relocation entry. */ + ELF_T_SHDR, /* Section header. */ + ELF_T_SWORD, /* Elf32_Sword, Elf64_Sword, ... */ + ELF_T_SYM, /* Symbol record. */ + ELF_T_WORD, /* Elf32_Word, Elf64_Word, ... */ + ELF_T_XWORD, /* Elf32_Xword, Elf64_Xword, ... */ + ELF_T_SXWORD, /* Elf32_Sxword, Elf64_Sxword, ... */ + ELF_T_VDEF, /* Elf32_Verdef, Elf64_Verdef, ... */ + ELF_T_VDAUX, /* Elf32_Verdaux, Elf64_Verdaux, ... */ + ELF_T_VNEED, /* Elf32_Verneed, Elf64_Verneed, ... */ + ELF_T_VNAUX, /* Elf32_Vernaux, Elf64_Vernaux, ... */ + ELF_T_NHDR, /* Elf32_Nhdr, Elf64_Nhdr, ... */ + ELF_T_SYMINFO, /* Elf32_Syminfo, Elf64_Syminfo, ... */ + ELF_T_MOVE, /* Elf32_Move, Elf64_Move, ... */ + ELF_T_LIB, /* Elf32_Lib, Elf64_Lib, ... */ + ELF_T_GNUHASH, /* GNU-style hash section. */ + ELF_T_AUXV, /* Elf32_auxv_t, Elf64_auxv_t, ... */ + ELF_T_CHDR, /* Compressed, Elf32_Chdr, Elf64_Chdr, ... */ + /* Keep this the last entry. */ + ELF_T_NUM +} Elf_Type; + +/* Descriptor for data to be converted to or from memory format. */ +typedef struct +{ + void *d_buf; /* Pointer to the actual data. */ + Elf_Type d_type; /* Type of this piece of data. */ + unsigned int d_version; /* ELF version. */ + size_t d_size; /* Size in bytes. */ + int64_t d_off; /* Offset into section. */ + size_t d_align; /* Alignment in section. */ +} Elf_Data; + + +/* Commands for `...'. */ +typedef enum +{ + ELF_C_NULL, /* Nothing, terminate, or compute only. */ + ELF_C_READ, /* Read .. */ + ELF_C_RDWR, /* Read and write .. */ + ELF_C_WRITE, /* Write .. */ + ELF_C_CLR, /* Clear flag. */ + ELF_C_SET, /* Set flag. */ + ELF_C_FDDONE, /* Signal that file descriptor will not be + used anymore. */ + ELF_C_FDREAD, /* Read rest of data so that file descriptor + is not used anymore. */ + /* The following are extensions. */ + ELF_C_READ_MMAP, /* Read, but mmap the file if possible. */ + ELF_C_RDWR_MMAP, /* Read and write, with mmap. */ + ELF_C_WRITE_MMAP, /* Write, with mmap. */ + ELF_C_READ_MMAP_PRIVATE, /* Read, but memory is writable, results are + not written to the file. */ + ELF_C_EMPTY, /* Copy basic file data but not the content. */ + /* Keep this the last entry. */ + ELF_C_NUM +} Elf_Cmd; + + +/* Flags for the ELF structures. */ +enum +{ + ELF_F_DIRTY = 0x1, +#define ELF_F_DIRTY ELF_F_DIRTY + ELF_F_LAYOUT = 0x4, +#define ELF_F_LAYOUT ELF_F_LAYOUT + ELF_F_PERMISSIVE = 0x8 +#define ELF_F_PERMISSIVE ELF_F_PERMISSIVE +}; + +/* Flags for elf_compress[_gnu]. */ +enum +{ + ELF_CHF_FORCE = 0x1 +#define ELF_CHF_FORCE ELF_CHF_FORCE +}; + +/* Identification values for recognized object files. */ +typedef enum +{ + ELF_K_NONE, /* Unknown. */ + ELF_K_AR, /* Archive. */ + ELF_K_COFF, /* Stupid old COFF. */ + ELF_K_ELF, /* ELF file. */ + /* Keep this the last entry. */ + ELF_K_NUM +} Elf_Kind; + + +/* Archive member header. */ +typedef struct +{ + char *ar_name; /* Name of archive member. */ + time_t ar_date; /* File date. */ + uid_t ar_uid; /* User ID. */ + gid_t ar_gid; /* Group ID. */ + mode_t ar_mode; /* File mode. */ + int64_t ar_size; /* File size. */ + char *ar_rawname; /* Original name of archive member. */ +} Elf_Arhdr; + + +/* Archive symbol table entry. */ +typedef struct +{ + char *as_name; /* Symbol name. */ + size_t as_off; /* Offset for this file in the archive. */ + unsigned long int as_hash; /* Hash value of the name. */ +} Elf_Arsym; + + +/* Descriptor for the ELF file. */ +typedef struct Elf Elf; + +/* Descriptor for ELF file section. */ +typedef struct Elf_Scn Elf_Scn; + + +#ifdef __cplusplus +extern "C" { +#endif + +/* Return descriptor for ELF file to work according to CMD. */ +extern Elf *elf_begin (int __fildes, Elf_Cmd __cmd, Elf *__ref); + +/* Create a clone of an existing ELF descriptor. */ + extern Elf *elf_clone (Elf *__elf, Elf_Cmd __cmd); + +/* Create descriptor for memory region. */ +extern Elf *elf_memory (char *__image, size_t __size); + +/* Advance archive descriptor to next element. */ +extern Elf_Cmd elf_next (Elf *__elf); + +/* Free resources allocated for ELF. */ +extern int elf_end (Elf *__elf); + +/* Update ELF descriptor and write file to disk. */ +extern int64_t elf_update (Elf *__elf, Elf_Cmd __cmd); + +/* Determine what kind of file is associated with ELF. */ +extern Elf_Kind elf_kind (Elf *__elf) __pure_attribute__; + +/* Get the base offset for an object file. */ +extern int64_t elf_getbase (Elf *__elf); + + +/* Retrieve file identification data. */ +extern char *elf_getident (Elf *__elf, size_t *__nbytes); + +/* Retrieve class-dependent object file header. */ +extern Elf32_Ehdr *elf32_getehdr (Elf *__elf); +/* Similar but this time the binary calls is ELFCLASS64. */ +extern Elf64_Ehdr *elf64_getehdr (Elf *__elf); + +/* Create ELF header if none exists. */ +extern Elf32_Ehdr *elf32_newehdr (Elf *__elf); +/* Similar but this time the binary calls is ELFCLASS64. */ +extern Elf64_Ehdr *elf64_newehdr (Elf *__elf); + +/* Get the number of program headers in the ELF file. If the file uses + more headers than can be represented in the e_phnum field of the ELF + header the information from the sh_info field in the zeroth section + header is used. */ +extern int elf_getphdrnum (Elf *__elf, size_t *__dst); + +/* Retrieve class-dependent program header table. */ +extern Elf32_Phdr *elf32_getphdr (Elf *__elf); +/* Similar but this time the binary calls is ELFCLASS64. */ +extern Elf64_Phdr *elf64_getphdr (Elf *__elf); + +/* Create ELF program header. */ +extern Elf32_Phdr *elf32_newphdr (Elf *__elf, size_t __cnt); +/* Similar but this time the binary calls is ELFCLASS64. */ +extern Elf64_Phdr *elf64_newphdr (Elf *__elf, size_t __cnt); + + +/* Get section at INDEX. */ +extern Elf_Scn *elf_getscn (Elf *__elf, size_t __index); + +/* Get section at OFFSET. */ +extern Elf_Scn *elf32_offscn (Elf *__elf, Elf32_Off __offset); +/* Similar bug this time the binary calls is ELFCLASS64. */ +extern Elf_Scn *elf64_offscn (Elf *__elf, Elf64_Off __offset); + +/* Get index of section. */ +extern size_t elf_ndxscn (Elf_Scn *__scn); + +/* Get section with next section index. */ +extern Elf_Scn *elf_nextscn (Elf *__elf, Elf_Scn *__scn); + +/* Create a new section and append it at the end of the table. */ +extern Elf_Scn *elf_newscn (Elf *__elf); + +/* Get the section index of the extended section index table for the + given symbol table. */ +extern int elf_scnshndx (Elf_Scn *__scn); + +/* Get the number of sections in the ELF file. If the file uses more + sections than can be represented in the e_shnum field of the ELF + header the information from the sh_size field in the zeroth section + header is used. */ +extern int elf_getshdrnum (Elf *__elf, size_t *__dst); +/* Sun messed up the implementation of 'elf_getshnum' in their implementation. + It was agreed to make the same functionality available under a different + name and obsolete the old name. */ +extern int elf_getshnum (Elf *__elf, size_t *__dst) + __deprecated_attribute__; + + +/* Get the section index of the section header string table in the ELF + file. If the index cannot be represented in the e_shnum field of + the ELF header the information from the sh_link field in the zeroth + section header is used. */ +extern int elf_getshdrstrndx (Elf *__elf, size_t *__dst); +/* Sun messed up the implementation of 'elf_getshnum' in their implementation. + It was agreed to make the same functionality available under a different + name and obsolete the old name. */ +extern int elf_getshstrndx (Elf *__elf, size_t *__dst) + __deprecated_attribute__; + + +/* Retrieve section header of ELFCLASS32 binary. */ +extern Elf32_Shdr *elf32_getshdr (Elf_Scn *__scn); +/* Similar for ELFCLASS64. */ +extern Elf64_Shdr *elf64_getshdr (Elf_Scn *__scn); + +/* Returns compression header for a section if section data is + compressed. Returns NULL and sets elf_errno if the section isn't + compressed or an error occurred. */ +extern Elf32_Chdr *elf32_getchdr (Elf_Scn *__scn); +extern Elf64_Chdr *elf64_getchdr (Elf_Scn *__scn); + +/* Compress or decompress the data of a section and adjust the section + header. + + elf_compress works by setting or clearing the SHF_COMPRESS flag + from the section Shdr and will encode or decode a Elf32_Chdr or + Elf64_Chdr at the start of the section data. elf_compress_gnu will + encode or decode any section, but is traditionally only used for + sections that have a name starting with ".debug" when + uncompressed or ".zdebug" when compressed and stores just the + uncompressed size. The GNU compression method is deprecated and + should only be used for legacy support. + + elf_compress takes a compression type that should be either zero to + decompress or an ELFCOMPRESS algorithm to use for compression. + Currently only ELFCOMPRESS_ZLIB is supported. elf_compress_gnu + will compress in the traditional GNU compression format when + compress is one and decompress the section data when compress is + zero. + + The FLAGS argument can be zero or ELF_CHF_FORCE. If FLAGS contains + ELF_CHF_FORCE then it will always compress the section, even if + that would not reduce the size of the data section (including the + header). Otherwise elf_compress and elf_compress_gnu will compress + the section only if the total data size is reduced. + + On successful compression or decompression the function returns + one. If (not forced) compression is requested and the data section + would not actually reduce in size, the section is not actually + compressed and zero is returned. Otherwise -1 is returned and + elf_errno is set. + + It is an error to request compression for a section that already + has SHF_COMPRESSED set, or (for elf_compress) to request + decompression for an section that doesn't have SHF_COMPRESSED set. + It is always an error to call these functions on SHT_NOBITS + sections or if the section has the SHF_ALLOC flag set. + elf_compress_gnu will not check whether the section name starts + with ".debug" or .zdebug". It is the responsibilty of the caller + to make sure the deprecated GNU compression method is only called + on correctly named sections (and to change the name of the section + when using elf_compress_gnu). + + All previous returned Shdrs and Elf_Data buffers are invalidated by + this call and should no longer be accessed. + + Note that although this changes the header and data returned it + doesn't mark the section as dirty. To keep the changes when + calling elf_update the section has to be flagged ELF_F_DIRTY. */ +extern int elf_compress (Elf_Scn *scn, int type, unsigned int flags); +extern int elf_compress_gnu (Elf_Scn *scn, int compress, unsigned int flags); + +/* Set or clear flags for ELF file. */ +extern unsigned int elf_flagelf (Elf *__elf, Elf_Cmd __cmd, + unsigned int __flags); +/* Similarly for the ELF header. */ +extern unsigned int elf_flagehdr (Elf *__elf, Elf_Cmd __cmd, + unsigned int __flags); +/* Similarly for the ELF program header. */ +extern unsigned int elf_flagphdr (Elf *__elf, Elf_Cmd __cmd, + unsigned int __flags); +/* Similarly for the given ELF section. */ +extern unsigned int elf_flagscn (Elf_Scn *__scn, Elf_Cmd __cmd, + unsigned int __flags); +/* Similarly for the given ELF data. */ +extern unsigned int elf_flagdata (Elf_Data *__data, Elf_Cmd __cmd, + unsigned int __flags); +/* Similarly for the given ELF section header. */ +extern unsigned int elf_flagshdr (Elf_Scn *__scn, Elf_Cmd __cmd, + unsigned int __flags); + + +/* Get data from section while translating from file representation to + memory representation. The Elf_Data d_type is set based on the + section type if known. Otherwise d_type is set to ELF_T_BYTE. If + the section contains compressed data then d_type is always set to + ELF_T_CHDR. */ +extern Elf_Data *elf_getdata (Elf_Scn *__scn, Elf_Data *__data); + +/* Get uninterpreted section content. */ +extern Elf_Data *elf_rawdata (Elf_Scn *__scn, Elf_Data *__data); + +/* Create new data descriptor for section SCN. */ +extern Elf_Data *elf_newdata (Elf_Scn *__scn); + +/* Get data translated from a chunk of the file contents as section data + would be for TYPE. The resulting Elf_Data pointer is valid until + elf_end (ELF) is called. */ +extern Elf_Data *elf_getdata_rawchunk (Elf *__elf, + int64_t __offset, size_t __size, + Elf_Type __type); + + +/* Return pointer to string at OFFSET in section INDEX. */ +extern char *elf_strptr (Elf *__elf, size_t __index, size_t __offset); + + +/* Return header of archive. */ +extern Elf_Arhdr *elf_getarhdr (Elf *__elf); + +/* Return offset in archive for current file ELF. */ +extern int64_t elf_getaroff (Elf *__elf); + +/* Select archive element at OFFSET. */ +extern size_t elf_rand (Elf *__elf, size_t __offset); + +/* Get symbol table of archive. */ +extern Elf_Arsym *elf_getarsym (Elf *__elf, size_t *__narsyms); + + +/* Control ELF descriptor. */ +extern int elf_cntl (Elf *__elf, Elf_Cmd __cmd); + +/* Retrieve uninterpreted file contents. */ +extern char *elf_rawfile (Elf *__elf, size_t *__nbytes); + + +/* Return size of array of COUNT elements of the type denoted by TYPE + in the external representation. The binary class is taken from ELF. + The result is based on version VERSION of the ELF standard. */ +extern size_t elf32_fsize (Elf_Type __type, size_t __count, + unsigned int __version) + __const_attribute__; +/* Similar but this time the binary calls is ELFCLASS64. */ +extern size_t elf64_fsize (Elf_Type __type, size_t __count, + unsigned int __version) + __const_attribute__; + + +/* Convert data structure from the representation in the file represented + by ELF to their memory representation. */ +extern Elf_Data *elf32_xlatetom (Elf_Data *__dest, const Elf_Data *__src, + unsigned int __encode); +/* Same for 64 bit class. */ +extern Elf_Data *elf64_xlatetom (Elf_Data *__dest, const Elf_Data *__src, + unsigned int __encode); + +/* Convert data structure from to the representation in memory + represented by ELF file representation. */ +extern Elf_Data *elf32_xlatetof (Elf_Data *__dest, const Elf_Data *__src, + unsigned int __encode); +/* Same for 64 bit class. */ +extern Elf_Data *elf64_xlatetof (Elf_Data *__dest, const Elf_Data *__src, + unsigned int __encode); + + +/* Return error code of last failing function call. This value is kept + separately for each thread. */ +extern int elf_errno (void); + +/* Return error string for ERROR. If ERROR is zero, return error string + for most recent error or NULL is none occurred. If ERROR is -1 the + behaviour is similar to the last case except that not NULL but a legal + string is returned. */ +extern const char *elf_errmsg (int __error); + + +/* Coordinate ELF library and application versions. */ +extern unsigned int elf_version (unsigned int __version); + +/* Set fill bytes used to fill holes in data structures. */ +extern void elf_fill (int __fill); + +/* Compute hash value. */ +extern unsigned long int elf_hash (const char *__string) + __pure_attribute__; + +/* Compute hash value using the GNU-specific hash function. */ +extern unsigned long int elf_gnu_hash (const char *__string) + __pure_attribute__; + + +/* Compute simple checksum from permanent parts of the ELF file. */ +extern long int elf32_checksum (Elf *__elf); +/* Similar but this time the binary calls is ELFCLASS64. */ +extern long int elf64_checksum (Elf *__elf); + +#ifdef __cplusplus +} +#endif + +#endif /* libelf.h */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/bpf.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/bpf.h new file mode 100644 index 000000000..bd28bc76d --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/bpf.h @@ -0,0 +1,5154 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +/* Copyright (c) 2011-2014 PLUMgrid, http://plumgrid.com + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of version 2 of the GNU General Public + * License as published by the Free Software Foundation. + */ +#ifndef __LINUX_BPF_H__ +#define __LINUX_BPF_H__ + +#include +#include + +/* Extended instruction set based on top of classic BPF */ + +/* instruction classes */ +#define BPF_JMP32 0x06 /* jmp mode in word width */ +#define BPF_ALU64 0x07 /* alu mode in double word width */ + +/* ld/ldx fields */ +#define BPF_DW 0x18 /* double word (64-bit) */ +#define BPF_XADD 0xc0 /* exclusive add */ + +/* alu/jmp fields */ +#define BPF_MOV 0xb0 /* mov reg to reg */ +#define BPF_ARSH 0xc0 /* sign extending arithmetic shift right */ + +/* change endianness of a register */ +#define BPF_END 0xd0 /* flags for endianness conversion: */ +#define BPF_TO_LE 0x00 /* convert to little-endian */ +#define BPF_TO_BE 0x08 /* convert to big-endian */ +#define BPF_FROM_LE BPF_TO_LE +#define BPF_FROM_BE BPF_TO_BE + +/* jmp encodings */ +#define BPF_JNE 0x50 /* jump != */ +#define BPF_JLT 0xa0 /* LT is unsigned, '<' */ +#define BPF_JLE 0xb0 /* LE is unsigned, '<=' */ +#define BPF_JSGT 0x60 /* SGT is signed '>', GT in x86 */ +#define BPF_JSGE 0x70 /* SGE is signed '>=', GE in x86 */ +#define BPF_JSLT 0xc0 /* SLT is signed, '<' */ +#define BPF_JSLE 0xd0 /* SLE is signed, '<=' */ +#define BPF_CALL 0x80 /* function call */ +#define BPF_EXIT 0x90 /* function return */ + +/* Register numbers */ +enum { + BPF_REG_0 = 0, + BPF_REG_1, + BPF_REG_2, + BPF_REG_3, + BPF_REG_4, + BPF_REG_5, + BPF_REG_6, + BPF_REG_7, + BPF_REG_8, + BPF_REG_9, + BPF_REG_10, + __MAX_BPF_REG, +}; + +/* BPF has 10 general purpose 64-bit registers and stack frame. */ +#define MAX_BPF_REG __MAX_BPF_REG + +struct bpf_insn { + __u8 code; /* opcode */ + __u8 dst_reg:4; /* dest register */ + __u8 src_reg:4; /* source register */ + __s16 off; /* signed offset */ + __s32 imm; /* signed immediate constant */ +}; + +/* Key of an a BPF_MAP_TYPE_LPM_TRIE entry */ +struct bpf_lpm_trie_key { + __u32 prefixlen; /* up to 32 for AF_INET, 128 for AF_INET6 */ + __u8 data[0]; /* Arbitrary size */ +}; + +struct bpf_cgroup_storage_key { + __u64 cgroup_inode_id; /* cgroup inode id */ + __u32 attach_type; /* program attach type */ +}; + +union bpf_iter_link_info { + struct { + __u32 map_fd; + } map; +}; + +/* BPF syscall commands, see bpf(2) man-page for details. */ +enum bpf_cmd { + BPF_MAP_CREATE, + BPF_MAP_LOOKUP_ELEM, + BPF_MAP_UPDATE_ELEM, + BPF_MAP_DELETE_ELEM, + BPF_MAP_GET_NEXT_KEY, + BPF_PROG_LOAD, + BPF_OBJ_PIN, + BPF_OBJ_GET, + BPF_PROG_ATTACH, + BPF_PROG_DETACH, + BPF_PROG_TEST_RUN, + BPF_PROG_GET_NEXT_ID, + BPF_MAP_GET_NEXT_ID, + BPF_PROG_GET_FD_BY_ID, + BPF_MAP_GET_FD_BY_ID, + BPF_OBJ_GET_INFO_BY_FD, + BPF_PROG_QUERY, + BPF_RAW_TRACEPOINT_OPEN, + BPF_BTF_LOAD, + BPF_BTF_GET_FD_BY_ID, + BPF_TASK_FD_QUERY, + BPF_MAP_LOOKUP_AND_DELETE_ELEM, + BPF_MAP_FREEZE, + BPF_BTF_GET_NEXT_ID, + BPF_MAP_LOOKUP_BATCH, + BPF_MAP_LOOKUP_AND_DELETE_BATCH, + BPF_MAP_UPDATE_BATCH, + BPF_MAP_DELETE_BATCH, + BPF_LINK_CREATE, + BPF_LINK_UPDATE, + BPF_LINK_GET_FD_BY_ID, + BPF_LINK_GET_NEXT_ID, + BPF_ENABLE_STATS, + BPF_ITER_CREATE, + BPF_LINK_DETACH, + BPF_PROG_BIND_MAP, +}; + +enum bpf_map_type { + BPF_MAP_TYPE_UNSPEC, + BPF_MAP_TYPE_HASH, + BPF_MAP_TYPE_ARRAY, + BPF_MAP_TYPE_PROG_ARRAY, + BPF_MAP_TYPE_PERF_EVENT_ARRAY, + BPF_MAP_TYPE_PERCPU_HASH, + BPF_MAP_TYPE_PERCPU_ARRAY, + BPF_MAP_TYPE_STACK_TRACE, + BPF_MAP_TYPE_CGROUP_ARRAY, + BPF_MAP_TYPE_LRU_HASH, + BPF_MAP_TYPE_LRU_PERCPU_HASH, + BPF_MAP_TYPE_LPM_TRIE, + BPF_MAP_TYPE_ARRAY_OF_MAPS, + BPF_MAP_TYPE_HASH_OF_MAPS, + BPF_MAP_TYPE_DEVMAP, + BPF_MAP_TYPE_SOCKMAP, + BPF_MAP_TYPE_CPUMAP, + BPF_MAP_TYPE_XSKMAP, + BPF_MAP_TYPE_SOCKHASH, + BPF_MAP_TYPE_CGROUP_STORAGE, + BPF_MAP_TYPE_REUSEPORT_SOCKARRAY, + BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE, + BPF_MAP_TYPE_QUEUE, + BPF_MAP_TYPE_STACK, + BPF_MAP_TYPE_SK_STORAGE, + BPF_MAP_TYPE_DEVMAP_HASH, + BPF_MAP_TYPE_STRUCT_OPS, + BPF_MAP_TYPE_RINGBUF, + BPF_MAP_TYPE_INODE_STORAGE, + BPF_MAP_TYPE_TASK_STORAGE, +}; + +/* Note that tracing related programs such as + * BPF_PROG_TYPE_{KPROBE,TRACEPOINT,PERF_EVENT,RAW_TRACEPOINT} + * are not subject to a stable API since kernel internal data + * structures can change from release to release and may + * therefore break existing tracing BPF programs. Tracing BPF + * programs correspond to /a/ specific kernel which is to be + * analyzed, and not /a/ specific kernel /and/ all future ones. + */ +enum bpf_prog_type { + BPF_PROG_TYPE_UNSPEC, + BPF_PROG_TYPE_SOCKET_FILTER, + BPF_PROG_TYPE_KPROBE, + BPF_PROG_TYPE_SCHED_CLS, + BPF_PROG_TYPE_SCHED_ACT, + BPF_PROG_TYPE_TRACEPOINT, + BPF_PROG_TYPE_XDP, + BPF_PROG_TYPE_PERF_EVENT, + BPF_PROG_TYPE_CGROUP_SKB, + BPF_PROG_TYPE_CGROUP_SOCK, + BPF_PROG_TYPE_LWT_IN, + BPF_PROG_TYPE_LWT_OUT, + BPF_PROG_TYPE_LWT_XMIT, + BPF_PROG_TYPE_SOCK_OPS, + BPF_PROG_TYPE_SK_SKB, + BPF_PROG_TYPE_CGROUP_DEVICE, + BPF_PROG_TYPE_SK_MSG, + BPF_PROG_TYPE_RAW_TRACEPOINT, + BPF_PROG_TYPE_CGROUP_SOCK_ADDR, + BPF_PROG_TYPE_LWT_SEG6LOCAL, + BPF_PROG_TYPE_LIRC_MODE2, + BPF_PROG_TYPE_SK_REUSEPORT, + BPF_PROG_TYPE_FLOW_DISSECTOR, + BPF_PROG_TYPE_CGROUP_SYSCTL, + BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE, + BPF_PROG_TYPE_CGROUP_SOCKOPT, + BPF_PROG_TYPE_TRACING, + BPF_PROG_TYPE_STRUCT_OPS, + BPF_PROG_TYPE_EXT, + BPF_PROG_TYPE_LSM, + BPF_PROG_TYPE_SK_LOOKUP, +}; + +enum bpf_attach_type { + BPF_CGROUP_INET_INGRESS, + BPF_CGROUP_INET_EGRESS, + BPF_CGROUP_INET_SOCK_CREATE, + BPF_CGROUP_SOCK_OPS, + BPF_SK_SKB_STREAM_PARSER, + BPF_SK_SKB_STREAM_VERDICT, + BPF_CGROUP_DEVICE, + BPF_SK_MSG_VERDICT, + BPF_CGROUP_INET4_BIND, + BPF_CGROUP_INET6_BIND, + BPF_CGROUP_INET4_CONNECT, + BPF_CGROUP_INET6_CONNECT, + BPF_CGROUP_INET4_POST_BIND, + BPF_CGROUP_INET6_POST_BIND, + BPF_CGROUP_UDP4_SENDMSG, + BPF_CGROUP_UDP6_SENDMSG, + BPF_LIRC_MODE2, + BPF_FLOW_DISSECTOR, + BPF_CGROUP_SYSCTL, + BPF_CGROUP_UDP4_RECVMSG, + BPF_CGROUP_UDP6_RECVMSG, + BPF_CGROUP_GETSOCKOPT, + BPF_CGROUP_SETSOCKOPT, + BPF_TRACE_RAW_TP, + BPF_TRACE_FENTRY, + BPF_TRACE_FEXIT, + BPF_MODIFY_RETURN, + BPF_LSM_MAC, + BPF_TRACE_ITER, + BPF_CGROUP_INET4_GETPEERNAME, + BPF_CGROUP_INET6_GETPEERNAME, + BPF_CGROUP_INET4_GETSOCKNAME, + BPF_CGROUP_INET6_GETSOCKNAME, + BPF_XDP_DEVMAP, + BPF_CGROUP_INET_SOCK_RELEASE, + BPF_XDP_CPUMAP, + BPF_SK_LOOKUP, + BPF_XDP, + __MAX_BPF_ATTACH_TYPE +}; + +#define MAX_BPF_ATTACH_TYPE __MAX_BPF_ATTACH_TYPE + +enum bpf_link_type { + BPF_LINK_TYPE_UNSPEC = 0, + BPF_LINK_TYPE_RAW_TRACEPOINT = 1, + BPF_LINK_TYPE_TRACING = 2, + BPF_LINK_TYPE_CGROUP = 3, + BPF_LINK_TYPE_ITER = 4, + BPF_LINK_TYPE_NETNS = 5, + BPF_LINK_TYPE_XDP = 6, + + MAX_BPF_LINK_TYPE, +}; + +/* cgroup-bpf attach flags used in BPF_PROG_ATTACH command + * + * NONE(default): No further bpf programs allowed in the subtree. + * + * BPF_F_ALLOW_OVERRIDE: If a sub-cgroup installs some bpf program, + * the program in this cgroup yields to sub-cgroup program. + * + * BPF_F_ALLOW_MULTI: If a sub-cgroup installs some bpf program, + * that cgroup program gets run in addition to the program in this cgroup. + * + * Only one program is allowed to be attached to a cgroup with + * NONE or BPF_F_ALLOW_OVERRIDE flag. + * Attaching another program on top of NONE or BPF_F_ALLOW_OVERRIDE will + * release old program and attach the new one. Attach flags has to match. + * + * Multiple programs are allowed to be attached to a cgroup with + * BPF_F_ALLOW_MULTI flag. They are executed in FIFO order + * (those that were attached first, run first) + * The programs of sub-cgroup are executed first, then programs of + * this cgroup and then programs of parent cgroup. + * When children program makes decision (like picking TCP CA or sock bind) + * parent program has a chance to override it. + * + * With BPF_F_ALLOW_MULTI a new program is added to the end of the list of + * programs for a cgroup. Though it's possible to replace an old program at + * any position by also specifying BPF_F_REPLACE flag and position itself in + * replace_bpf_fd attribute. Old program at this position will be released. + * + * A cgroup with MULTI or OVERRIDE flag allows any attach flags in sub-cgroups. + * A cgroup with NONE doesn't allow any programs in sub-cgroups. + * Ex1: + * cgrp1 (MULTI progs A, B) -> + * cgrp2 (OVERRIDE prog C) -> + * cgrp3 (MULTI prog D) -> + * cgrp4 (OVERRIDE prog E) -> + * cgrp5 (NONE prog F) + * the event in cgrp5 triggers execution of F,D,A,B in that order. + * if prog F is detached, the execution is E,D,A,B + * if prog F and D are detached, the execution is E,A,B + * if prog F, E and D are detached, the execution is C,A,B + * + * All eligible programs are executed regardless of return code from + * earlier programs. + */ +#define BPF_F_ALLOW_OVERRIDE (1U << 0) +#define BPF_F_ALLOW_MULTI (1U << 1) +#define BPF_F_REPLACE (1U << 2) + +/* If BPF_F_STRICT_ALIGNMENT is used in BPF_PROG_LOAD command, the + * verifier will perform strict alignment checking as if the kernel + * has been built with CONFIG_EFFICIENT_UNALIGNED_ACCESS not set, + * and NET_IP_ALIGN defined to 2. + */ +#define BPF_F_STRICT_ALIGNMENT (1U << 0) + +/* If BPF_F_ANY_ALIGNMENT is used in BPF_PROF_LOAD command, the + * verifier will allow any alignment whatsoever. On platforms + * with strict alignment requirements for loads ands stores (such + * as sparc and mips) the verifier validates that all loads and + * stores provably follow this requirement. This flag turns that + * checking and enforcement off. + * + * It is mostly used for testing when we want to validate the + * context and memory access aspects of the verifier, but because + * of an unaligned access the alignment check would trigger before + * the one we are interested in. + */ +#define BPF_F_ANY_ALIGNMENT (1U << 1) + +/* BPF_F_TEST_RND_HI32 is used in BPF_PROG_LOAD command for testing purpose. + * Verifier does sub-register def/use analysis and identifies instructions whose + * def only matters for low 32-bit, high 32-bit is never referenced later + * through implicit zero extension. Therefore verifier notifies JIT back-ends + * that it is safe to ignore clearing high 32-bit for these instructions. This + * saves some back-ends a lot of code-gen. However such optimization is not + * necessary on some arches, for example x86_64, arm64 etc, whose JIT back-ends + * hence hasn't used verifier's analysis result. But, we really want to have a + * way to be able to verify the correctness of the described optimization on + * x86_64 on which testsuites are frequently exercised. + * + * So, this flag is introduced. Once it is set, verifier will randomize high + * 32-bit for those instructions who has been identified as safe to ignore them. + * Then, if verifier is not doing correct analysis, such randomization will + * regress tests to expose bugs. + */ +#define BPF_F_TEST_RND_HI32 (1U << 2) + +/* The verifier internal test flag. Behavior is undefined */ +#define BPF_F_TEST_STATE_FREQ (1U << 3) + +/* If BPF_F_SLEEPABLE is used in BPF_PROG_LOAD command, the verifier will + * restrict map and helper usage for such programs. Sleepable BPF programs can + * only be attached to hooks where kernel execution context allows sleeping. + * Such programs are allowed to use helpers that may sleep like + * bpf_copy_from_user(). + */ +#define BPF_F_SLEEPABLE (1U << 4) + +/* When BPF ldimm64's insn[0].src_reg != 0 then this can have + * the following extensions: + * + * insn[0].src_reg: BPF_PSEUDO_MAP_FD + * insn[0].imm: map fd + * insn[1].imm: 0 + * insn[0].off: 0 + * insn[1].off: 0 + * ldimm64 rewrite: address of map + * verifier type: CONST_PTR_TO_MAP + */ +#define BPF_PSEUDO_MAP_FD 1 +/* insn[0].src_reg: BPF_PSEUDO_MAP_VALUE + * insn[0].imm: map fd + * insn[1].imm: offset into value + * insn[0].off: 0 + * insn[1].off: 0 + * ldimm64 rewrite: address of map[0]+offset + * verifier type: PTR_TO_MAP_VALUE + */ +#define BPF_PSEUDO_MAP_VALUE 2 +/* insn[0].src_reg: BPF_PSEUDO_BTF_ID + * insn[0].imm: kernel btd id of VAR + * insn[1].imm: 0 + * insn[0].off: 0 + * insn[1].off: 0 + * ldimm64 rewrite: address of the kernel variable + * verifier type: PTR_TO_BTF_ID or PTR_TO_MEM, depending on whether the var + * is struct/union. + */ +#define BPF_PSEUDO_BTF_ID 3 + +/* when bpf_call->src_reg == BPF_PSEUDO_CALL, bpf_call->imm == pc-relative + * offset to another bpf function + */ +#define BPF_PSEUDO_CALL 1 + +/* flags for BPF_MAP_UPDATE_ELEM command */ +enum { + BPF_ANY = 0, /* create new element or update existing */ + BPF_NOEXIST = 1, /* create new element if it didn't exist */ + BPF_EXIST = 2, /* update existing element */ + BPF_F_LOCK = 4, /* spin_lock-ed map_lookup/map_update */ +}; + +/* flags for BPF_MAP_CREATE command */ +enum { + BPF_F_NO_PREALLOC = (1U << 0), +/* Instead of having one common LRU list in the + * BPF_MAP_TYPE_LRU_[PERCPU_]HASH map, use a percpu LRU list + * which can scale and perform better. + * Note, the LRU nodes (including free nodes) cannot be moved + * across different LRU lists. + */ + BPF_F_NO_COMMON_LRU = (1U << 1), +/* Specify numa node during map creation */ + BPF_F_NUMA_NODE = (1U << 2), + +/* Flags for accessing BPF object from syscall side. */ + BPF_F_RDONLY = (1U << 3), + BPF_F_WRONLY = (1U << 4), + +/* Flag for stack_map, store build_id+offset instead of pointer */ + BPF_F_STACK_BUILD_ID = (1U << 5), + +/* Zero-initialize hash function seed. This should only be used for testing. */ + BPF_F_ZERO_SEED = (1U << 6), + +/* Flags for accessing BPF object from program side. */ + BPF_F_RDONLY_PROG = (1U << 7), + BPF_F_WRONLY_PROG = (1U << 8), + +/* Clone map from listener for newly accepted socket */ + BPF_F_CLONE = (1U << 9), + +/* Enable memory-mapping BPF map */ + BPF_F_MMAPABLE = (1U << 10), + +/* Share perf_event among processes */ + BPF_F_PRESERVE_ELEMS = (1U << 11), + +/* Create a map that is suitable to be an inner map with dynamic max entries */ + BPF_F_INNER_MAP = (1U << 12), +}; + +/* Flags for BPF_PROG_QUERY. */ + +/* Query effective (directly attached + inherited from ancestor cgroups) + * programs that will be executed for events within a cgroup. + * attach_flags with this flag are returned only for directly attached programs. + */ +#define BPF_F_QUERY_EFFECTIVE (1U << 0) + +/* Flags for BPF_PROG_TEST_RUN */ + +/* If set, run the test on the cpu specified by bpf_attr.test.cpu */ +#define BPF_F_TEST_RUN_ON_CPU (1U << 0) + +/* type for BPF_ENABLE_STATS */ +enum bpf_stats_type { + /* enabled run_time_ns and run_cnt */ + BPF_STATS_RUN_TIME = 0, +}; + +enum bpf_stack_build_id_status { + /* user space need an empty entry to identify end of a trace */ + BPF_STACK_BUILD_ID_EMPTY = 0, + /* with valid build_id and offset */ + BPF_STACK_BUILD_ID_VALID = 1, + /* couldn't get build_id, fallback to ip */ + BPF_STACK_BUILD_ID_IP = 2, +}; + +#define BPF_BUILD_ID_SIZE 20 +struct bpf_stack_build_id { + __s32 status; + unsigned char build_id[BPF_BUILD_ID_SIZE]; + union { + __u64 offset; + __u64 ip; + }; +}; + +#define BPF_OBJ_NAME_LEN 16U + +union bpf_attr { + struct { /* anonymous struct used by BPF_MAP_CREATE command */ + __u32 map_type; /* one of enum bpf_map_type */ + __u32 key_size; /* size of key in bytes */ + __u32 value_size; /* size of value in bytes */ + __u32 max_entries; /* max number of entries in a map */ + __u32 map_flags; /* BPF_MAP_CREATE related + * flags defined above. + */ + __u32 inner_map_fd; /* fd pointing to the inner map */ + __u32 numa_node; /* numa node (effective only if + * BPF_F_NUMA_NODE is set). + */ + char map_name[BPF_OBJ_NAME_LEN]; + __u32 map_ifindex; /* ifindex of netdev to create on */ + __u32 btf_fd; /* fd pointing to a BTF type data */ + __u32 btf_key_type_id; /* BTF type_id of the key */ + __u32 btf_value_type_id; /* BTF type_id of the value */ + __u32 btf_vmlinux_value_type_id;/* BTF type_id of a kernel- + * struct stored as the + * map value + */ + }; + + struct { /* anonymous struct used by BPF_MAP_*_ELEM commands */ + __u32 map_fd; + __aligned_u64 key; + union { + __aligned_u64 value; + __aligned_u64 next_key; + }; + __u64 flags; + }; + + struct { /* struct used by BPF_MAP_*_BATCH commands */ + __aligned_u64 in_batch; /* start batch, + * NULL to start from beginning + */ + __aligned_u64 out_batch; /* output: next start batch */ + __aligned_u64 keys; + __aligned_u64 values; + __u32 count; /* input/output: + * input: # of key/value + * elements + * output: # of filled elements + */ + __u32 map_fd; + __u64 elem_flags; + __u64 flags; + } batch; + + struct { /* anonymous struct used by BPF_PROG_LOAD command */ + __u32 prog_type; /* one of enum bpf_prog_type */ + __u32 insn_cnt; + __aligned_u64 insns; + __aligned_u64 license; + __u32 log_level; /* verbosity level of verifier */ + __u32 log_size; /* size of user buffer */ + __aligned_u64 log_buf; /* user supplied buffer */ + __u32 kern_version; /* not used */ + __u32 prog_flags; + char prog_name[BPF_OBJ_NAME_LEN]; + __u32 prog_ifindex; /* ifindex of netdev to prep for */ + /* For some prog types expected attach type must be known at + * load time to verify attach type specific parts of prog + * (context accesses, allowed helpers, etc). + */ + __u32 expected_attach_type; + __u32 prog_btf_fd; /* fd pointing to BTF type data */ + __u32 func_info_rec_size; /* userspace bpf_func_info size */ + __aligned_u64 func_info; /* func info */ + __u32 func_info_cnt; /* number of bpf_func_info records */ + __u32 line_info_rec_size; /* userspace bpf_line_info size */ + __aligned_u64 line_info; /* line info */ + __u32 line_info_cnt; /* number of bpf_line_info records */ + __u32 attach_btf_id; /* in-kernel BTF type id to attach to */ + union { + /* valid prog_fd to attach to bpf prog */ + __u32 attach_prog_fd; + /* or valid module BTF object fd or 0 to attach to vmlinux */ + __u32 attach_btf_obj_fd; + }; + }; + + struct { /* anonymous struct used by BPF_OBJ_* commands */ + __aligned_u64 pathname; + __u32 bpf_fd; + __u32 file_flags; + }; + + struct { /* anonymous struct used by BPF_PROG_ATTACH/DETACH commands */ + __u32 target_fd; /* container object to attach to */ + __u32 attach_bpf_fd; /* eBPF program to attach */ + __u32 attach_type; + __u32 attach_flags; + __u32 replace_bpf_fd; /* previously attached eBPF + * program to replace if + * BPF_F_REPLACE is used + */ + }; + + struct { /* anonymous struct used by BPF_PROG_TEST_RUN command */ + __u32 prog_fd; + __u32 retval; + __u32 data_size_in; /* input: len of data_in */ + __u32 data_size_out; /* input/output: len of data_out + * returns ENOSPC if data_out + * is too small. + */ + __aligned_u64 data_in; + __aligned_u64 data_out; + __u32 repeat; + __u32 duration; + __u32 ctx_size_in; /* input: len of ctx_in */ + __u32 ctx_size_out; /* input/output: len of ctx_out + * returns ENOSPC if ctx_out + * is too small. + */ + __aligned_u64 ctx_in; + __aligned_u64 ctx_out; + __u32 flags; + __u32 cpu; + } test; + + struct { /* anonymous struct used by BPF_*_GET_*_ID */ + union { + __u32 start_id; + __u32 prog_id; + __u32 map_id; + __u32 btf_id; + __u32 link_id; + }; + __u32 next_id; + __u32 open_flags; + }; + + struct { /* anonymous struct used by BPF_OBJ_GET_INFO_BY_FD */ + __u32 bpf_fd; + __u32 info_len; + __aligned_u64 info; + } info; + + struct { /* anonymous struct used by BPF_PROG_QUERY command */ + __u32 target_fd; /* container object to query */ + __u32 attach_type; + __u32 query_flags; + __u32 attach_flags; + __aligned_u64 prog_ids; + __u32 prog_cnt; + } query; + + struct { /* anonymous struct used by BPF_RAW_TRACEPOINT_OPEN command */ + __u64 name; + __u32 prog_fd; + } raw_tracepoint; + + struct { /* anonymous struct for BPF_BTF_LOAD */ + __aligned_u64 btf; + __aligned_u64 btf_log_buf; + __u32 btf_size; + __u32 btf_log_size; + __u32 btf_log_level; + }; + + struct { + __u32 pid; /* input: pid */ + __u32 fd; /* input: fd */ + __u32 flags; /* input: flags */ + __u32 buf_len; /* input/output: buf len */ + __aligned_u64 buf; /* input/output: + * tp_name for tracepoint + * symbol for kprobe + * filename for uprobe + */ + __u32 prog_id; /* output: prod_id */ + __u32 fd_type; /* output: BPF_FD_TYPE_* */ + __u64 probe_offset; /* output: probe_offset */ + __u64 probe_addr; /* output: probe_addr */ + } task_fd_query; + + struct { /* struct used by BPF_LINK_CREATE command */ + __u32 prog_fd; /* eBPF program to attach */ + union { + __u32 target_fd; /* object to attach to */ + __u32 target_ifindex; /* target ifindex */ + }; + __u32 attach_type; /* attach type */ + __u32 flags; /* extra flags */ + union { + __u32 target_btf_id; /* btf_id of target to attach to */ + struct { + __aligned_u64 iter_info; /* extra bpf_iter_link_info */ + __u32 iter_info_len; /* iter_info length */ + }; + }; + } link_create; + + struct { /* struct used by BPF_LINK_UPDATE command */ + __u32 link_fd; /* link fd */ + /* new program fd to update link with */ + __u32 new_prog_fd; + __u32 flags; /* extra flags */ + /* expected link's program fd; is specified only if + * BPF_F_REPLACE flag is set in flags */ + __u32 old_prog_fd; + } link_update; + + struct { + __u32 link_fd; + } link_detach; + + struct { /* struct used by BPF_ENABLE_STATS command */ + __u32 type; + } enable_stats; + + struct { /* struct used by BPF_ITER_CREATE command */ + __u32 link_fd; + __u32 flags; + } iter_create; + + struct { /* struct used by BPF_PROG_BIND_MAP command */ + __u32 prog_fd; + __u32 map_fd; + __u32 flags; /* extra flags */ + } prog_bind_map; + +} __attribute__((aligned(8))); + +/* The description below is an attempt at providing documentation to eBPF + * developers about the multiple available eBPF helper functions. It can be + * parsed and used to produce a manual page. The workflow is the following, + * and requires the rst2man utility: + * + * $ ./scripts/bpf_helpers_doc.py \ + * --filename include/uapi/linux/bpf.h > /tmp/bpf-helpers.rst + * $ rst2man /tmp/bpf-helpers.rst > /tmp/bpf-helpers.7 + * $ man /tmp/bpf-helpers.7 + * + * Note that in order to produce this external documentation, some RST + * formatting is used in the descriptions to get "bold" and "italics" in + * manual pages. Also note that the few trailing white spaces are + * intentional, removing them would break paragraphs for rst2man. + * + * Start of BPF helper function descriptions: + * + * void *bpf_map_lookup_elem(struct bpf_map *map, const void *key) + * Description + * Perform a lookup in *map* for an entry associated to *key*. + * Return + * Map value associated to *key*, or **NULL** if no entry was + * found. + * + * long bpf_map_update_elem(struct bpf_map *map, const void *key, const void *value, u64 flags) + * Description + * Add or update the value of the entry associated to *key* in + * *map* with *value*. *flags* is one of: + * + * **BPF_NOEXIST** + * The entry for *key* must not exist in the map. + * **BPF_EXIST** + * The entry for *key* must already exist in the map. + * **BPF_ANY** + * No condition on the existence of the entry for *key*. + * + * Flag value **BPF_NOEXIST** cannot be used for maps of types + * **BPF_MAP_TYPE_ARRAY** or **BPF_MAP_TYPE_PERCPU_ARRAY** (all + * elements always exist), the helper would return an error. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_map_delete_elem(struct bpf_map *map, const void *key) + * Description + * Delete entry with *key* from *map*. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_probe_read(void *dst, u32 size, const void *unsafe_ptr) + * Description + * For tracing programs, safely attempt to read *size* bytes from + * kernel space address *unsafe_ptr* and store the data in *dst*. + * + * Generally, use **bpf_probe_read_user**\ () or + * **bpf_probe_read_kernel**\ () instead. + * Return + * 0 on success, or a negative error in case of failure. + * + * u64 bpf_ktime_get_ns(void) + * Description + * Return the time elapsed since system boot, in nanoseconds. + * Does not include time the system was suspended. + * See: **clock_gettime**\ (**CLOCK_MONOTONIC**) + * Return + * Current *ktime*. + * + * long bpf_trace_printk(const char *fmt, u32 fmt_size, ...) + * Description + * This helper is a "printk()-like" facility for debugging. It + * prints a message defined by format *fmt* (of size *fmt_size*) + * to file *\/sys/kernel/debug/tracing/trace* from DebugFS, if + * available. It can take up to three additional **u64** + * arguments (as an eBPF helpers, the total number of arguments is + * limited to five). + * + * Each time the helper is called, it appends a line to the trace. + * Lines are discarded while *\/sys/kernel/debug/tracing/trace* is + * open, use *\/sys/kernel/debug/tracing/trace_pipe* to avoid this. + * The format of the trace is customizable, and the exact output + * one will get depends on the options set in + * *\/sys/kernel/debug/tracing/trace_options* (see also the + * *README* file under the same directory). However, it usually + * defaults to something like: + * + * :: + * + * telnet-470 [001] .N.. 419421.045894: 0x00000001: + * + * In the above: + * + * * ``telnet`` is the name of the current task. + * * ``470`` is the PID of the current task. + * * ``001`` is the CPU number on which the task is + * running. + * * In ``.N..``, each character refers to a set of + * options (whether irqs are enabled, scheduling + * options, whether hard/softirqs are running, level of + * preempt_disabled respectively). **N** means that + * **TIF_NEED_RESCHED** and **PREEMPT_NEED_RESCHED** + * are set. + * * ``419421.045894`` is a timestamp. + * * ``0x00000001`` is a fake value used by BPF for the + * instruction pointer register. + * * ```` is the message formatted with + * *fmt*. + * + * The conversion specifiers supported by *fmt* are similar, but + * more limited than for printk(). They are **%d**, **%i**, + * **%u**, **%x**, **%ld**, **%li**, **%lu**, **%lx**, **%lld**, + * **%lli**, **%llu**, **%llx**, **%p**, **%s**. No modifier (size + * of field, padding with zeroes, etc.) is available, and the + * helper will return **-EINVAL** (but print nothing) if it + * encounters an unknown specifier. + * + * Also, note that **bpf_trace_printk**\ () is slow, and should + * only be used for debugging purposes. For this reason, a notice + * block (spanning several lines) is printed to kernel logs and + * states that the helper should not be used "for production use" + * the first time this helper is used (or more precisely, when + * **trace_printk**\ () buffers are allocated). For passing values + * to user space, perf events should be preferred. + * Return + * The number of bytes written to the buffer, or a negative error + * in case of failure. + * + * u32 bpf_get_prandom_u32(void) + * Description + * Get a pseudo-random number. + * + * From a security point of view, this helper uses its own + * pseudo-random internal state, and cannot be used to infer the + * seed of other random functions in the kernel. However, it is + * essential to note that the generator used by the helper is not + * cryptographically secure. + * Return + * A random 32-bit unsigned value. + * + * u32 bpf_get_smp_processor_id(void) + * Description + * Get the SMP (symmetric multiprocessing) processor id. Note that + * all programs run with preemption disabled, which means that the + * SMP processor id is stable during all the execution of the + * program. + * Return + * The SMP id of the processor running the program. + * + * long bpf_skb_store_bytes(struct sk_buff *skb, u32 offset, const void *from, u32 len, u64 flags) + * Description + * Store *len* bytes from address *from* into the packet + * associated to *skb*, at *offset*. *flags* are a combination of + * **BPF_F_RECOMPUTE_CSUM** (automatically recompute the + * checksum for the packet after storing the bytes) and + * **BPF_F_INVALIDATE_HASH** (set *skb*\ **->hash**, *skb*\ + * **->swhash** and *skb*\ **->l4hash** to 0). + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_l3_csum_replace(struct sk_buff *skb, u32 offset, u64 from, u64 to, u64 size) + * Description + * Recompute the layer 3 (e.g. IP) checksum for the packet + * associated to *skb*. Computation is incremental, so the helper + * must know the former value of the header field that was + * modified (*from*), the new value of this field (*to*), and the + * number of bytes (2 or 4) for this field, stored in *size*. + * Alternatively, it is possible to store the difference between + * the previous and the new values of the header field in *to*, by + * setting *from* and *size* to 0. For both methods, *offset* + * indicates the location of the IP checksum within the packet. + * + * This helper works in combination with **bpf_csum_diff**\ (), + * which does not update the checksum in-place, but offers more + * flexibility and can handle sizes larger than 2 or 4 for the + * checksum to update. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_l4_csum_replace(struct sk_buff *skb, u32 offset, u64 from, u64 to, u64 flags) + * Description + * Recompute the layer 4 (e.g. TCP, UDP or ICMP) checksum for the + * packet associated to *skb*. Computation is incremental, so the + * helper must know the former value of the header field that was + * modified (*from*), the new value of this field (*to*), and the + * number of bytes (2 or 4) for this field, stored on the lowest + * four bits of *flags*. Alternatively, it is possible to store + * the difference between the previous and the new values of the + * header field in *to*, by setting *from* and the four lowest + * bits of *flags* to 0. For both methods, *offset* indicates the + * location of the IP checksum within the packet. In addition to + * the size of the field, *flags* can be added (bitwise OR) actual + * flags. With **BPF_F_MARK_MANGLED_0**, a null checksum is left + * untouched (unless **BPF_F_MARK_ENFORCE** is added as well), and + * for updates resulting in a null checksum the value is set to + * **CSUM_MANGLED_0** instead. Flag **BPF_F_PSEUDO_HDR** indicates + * the checksum is to be computed against a pseudo-header. + * + * This helper works in combination with **bpf_csum_diff**\ (), + * which does not update the checksum in-place, but offers more + * flexibility and can handle sizes larger than 2 or 4 for the + * checksum to update. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_tail_call(void *ctx, struct bpf_map *prog_array_map, u32 index) + * Description + * This special helper is used to trigger a "tail call", or in + * other words, to jump into another eBPF program. The same stack + * frame is used (but values on stack and in registers for the + * caller are not accessible to the callee). This mechanism allows + * for program chaining, either for raising the maximum number of + * available eBPF instructions, or to execute given programs in + * conditional blocks. For security reasons, there is an upper + * limit to the number of successive tail calls that can be + * performed. + * + * Upon call of this helper, the program attempts to jump into a + * program referenced at index *index* in *prog_array_map*, a + * special map of type **BPF_MAP_TYPE_PROG_ARRAY**, and passes + * *ctx*, a pointer to the context. + * + * If the call succeeds, the kernel immediately runs the first + * instruction of the new program. This is not a function call, + * and it never returns to the previous program. If the call + * fails, then the helper has no effect, and the caller continues + * to run its subsequent instructions. A call can fail if the + * destination program for the jump does not exist (i.e. *index* + * is superior to the number of entries in *prog_array_map*), or + * if the maximum number of tail calls has been reached for this + * chain of programs. This limit is defined in the kernel by the + * macro **MAX_TAIL_CALL_CNT** (not accessible to user space), + * which is currently set to 32. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_clone_redirect(struct sk_buff *skb, u32 ifindex, u64 flags) + * Description + * Clone and redirect the packet associated to *skb* to another + * net device of index *ifindex*. Both ingress and egress + * interfaces can be used for redirection. The **BPF_F_INGRESS** + * value in *flags* is used to make the distinction (ingress path + * is selected if the flag is present, egress path otherwise). + * This is the only flag supported for now. + * + * In comparison with **bpf_redirect**\ () helper, + * **bpf_clone_redirect**\ () has the associated cost of + * duplicating the packet buffer, but this can be executed out of + * the eBPF program. Conversely, **bpf_redirect**\ () is more + * efficient, but it is handled through an action code where the + * redirection happens only after the eBPF program has returned. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * u64 bpf_get_current_pid_tgid(void) + * Return + * A 64-bit integer containing the current tgid and pid, and + * created as such: + * *current_task*\ **->tgid << 32 \|** + * *current_task*\ **->pid**. + * + * u64 bpf_get_current_uid_gid(void) + * Return + * A 64-bit integer containing the current GID and UID, and + * created as such: *current_gid* **<< 32 \|** *current_uid*. + * + * long bpf_get_current_comm(void *buf, u32 size_of_buf) + * Description + * Copy the **comm** attribute of the current task into *buf* of + * *size_of_buf*. The **comm** attribute contains the name of + * the executable (excluding the path) for the current task. The + * *size_of_buf* must be strictly positive. On success, the + * helper makes sure that the *buf* is NUL-terminated. On failure, + * it is filled with zeroes. + * Return + * 0 on success, or a negative error in case of failure. + * + * u32 bpf_get_cgroup_classid(struct sk_buff *skb) + * Description + * Retrieve the classid for the current task, i.e. for the net_cls + * cgroup to which *skb* belongs. + * + * This helper can be used on TC egress path, but not on ingress. + * + * The net_cls cgroup provides an interface to tag network packets + * based on a user-provided identifier for all traffic coming from + * the tasks belonging to the related cgroup. See also the related + * kernel documentation, available from the Linux sources in file + * *Documentation/admin-guide/cgroup-v1/net_cls.rst*. + * + * The Linux kernel has two versions for cgroups: there are + * cgroups v1 and cgroups v2. Both are available to users, who can + * use a mixture of them, but note that the net_cls cgroup is for + * cgroup v1 only. This makes it incompatible with BPF programs + * run on cgroups, which is a cgroup-v2-only feature (a socket can + * only hold data for one version of cgroups at a time). + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_CGROUP_NET_CLASSID** configuration option set to + * "**y**" or to "**m**". + * Return + * The classid, or 0 for the default unconfigured classid. + * + * long bpf_skb_vlan_push(struct sk_buff *skb, __be16 vlan_proto, u16 vlan_tci) + * Description + * Push a *vlan_tci* (VLAN tag control information) of protocol + * *vlan_proto* to the packet associated to *skb*, then update + * the checksum. Note that if *vlan_proto* is different from + * **ETH_P_8021Q** and **ETH_P_8021AD**, it is considered to + * be **ETH_P_8021Q**. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_vlan_pop(struct sk_buff *skb) + * Description + * Pop a VLAN header from the packet associated to *skb*. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_get_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, u32 size, u64 flags) + * Description + * Get tunnel metadata. This helper takes a pointer *key* to an + * empty **struct bpf_tunnel_key** of **size**, that will be + * filled with tunnel metadata for the packet associated to *skb*. + * The *flags* can be set to **BPF_F_TUNINFO_IPV6**, which + * indicates that the tunnel is based on IPv6 protocol instead of + * IPv4. + * + * The **struct bpf_tunnel_key** is an object that generalizes the + * principal parameters used by various tunneling protocols into a + * single struct. This way, it can be used to easily make a + * decision based on the contents of the encapsulation header, + * "summarized" in this struct. In particular, it holds the IP + * address of the remote end (IPv4 or IPv6, depending on the case) + * in *key*\ **->remote_ipv4** or *key*\ **->remote_ipv6**. Also, + * this struct exposes the *key*\ **->tunnel_id**, which is + * generally mapped to a VNI (Virtual Network Identifier), making + * it programmable together with the **bpf_skb_set_tunnel_key**\ + * () helper. + * + * Let's imagine that the following code is part of a program + * attached to the TC ingress interface, on one end of a GRE + * tunnel, and is supposed to filter out all messages coming from + * remote ends with IPv4 address other than 10.0.0.1: + * + * :: + * + * int ret; + * struct bpf_tunnel_key key = {}; + * + * ret = bpf_skb_get_tunnel_key(skb, &key, sizeof(key), 0); + * if (ret < 0) + * return TC_ACT_SHOT; // drop packet + * + * if (key.remote_ipv4 != 0x0a000001) + * return TC_ACT_SHOT; // drop packet + * + * return TC_ACT_OK; // accept packet + * + * This interface can also be used with all encapsulation devices + * that can operate in "collect metadata" mode: instead of having + * one network device per specific configuration, the "collect + * metadata" mode only requires a single device where the + * configuration can be extracted from this helper. + * + * This can be used together with various tunnels such as VXLan, + * Geneve, GRE or IP in IP (IPIP). + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_set_tunnel_key(struct sk_buff *skb, struct bpf_tunnel_key *key, u32 size, u64 flags) + * Description + * Populate tunnel metadata for packet associated to *skb.* The + * tunnel metadata is set to the contents of *key*, of *size*. The + * *flags* can be set to a combination of the following values: + * + * **BPF_F_TUNINFO_IPV6** + * Indicate that the tunnel is based on IPv6 protocol + * instead of IPv4. + * **BPF_F_ZERO_CSUM_TX** + * For IPv4 packets, add a flag to tunnel metadata + * indicating that checksum computation should be skipped + * and checksum set to zeroes. + * **BPF_F_DONT_FRAGMENT** + * Add a flag to tunnel metadata indicating that the + * packet should not be fragmented. + * **BPF_F_SEQ_NUMBER** + * Add a flag to tunnel metadata indicating that a + * sequence number should be added to tunnel header before + * sending the packet. This flag was added for GRE + * encapsulation, but might be used with other protocols + * as well in the future. + * + * Here is a typical usage on the transmit path: + * + * :: + * + * struct bpf_tunnel_key key; + * populate key ... + * bpf_skb_set_tunnel_key(skb, &key, sizeof(key), 0); + * bpf_clone_redirect(skb, vxlan_dev_ifindex, 0); + * + * See also the description of the **bpf_skb_get_tunnel_key**\ () + * helper for additional information. + * Return + * 0 on success, or a negative error in case of failure. + * + * u64 bpf_perf_event_read(struct bpf_map *map, u64 flags) + * Description + * Read the value of a perf event counter. This helper relies on a + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. The nature of + * the perf event counter is selected when *map* is updated with + * perf event file descriptors. The *map* is an array whose size + * is the number of available CPUs, and each cell contains a value + * relative to one CPU. The value to retrieve is indicated by + * *flags*, that contains the index of the CPU to look up, masked + * with **BPF_F_INDEX_MASK**. Alternatively, *flags* can be set to + * **BPF_F_CURRENT_CPU** to indicate that the value for the + * current CPU should be retrieved. + * + * Note that before Linux 4.13, only hardware perf event can be + * retrieved. + * + * Also, be aware that the newer helper + * **bpf_perf_event_read_value**\ () is recommended over + * **bpf_perf_event_read**\ () in general. The latter has some ABI + * quirks where error and counter value are used as a return code + * (which is wrong to do since ranges may overlap). This issue is + * fixed with **bpf_perf_event_read_value**\ (), which at the same + * time provides more features over the **bpf_perf_event_read**\ + * () interface. Please refer to the description of + * **bpf_perf_event_read_value**\ () for details. + * Return + * The value of the perf event counter read from the map, or a + * negative error code in case of failure. + * + * long bpf_redirect(u32 ifindex, u64 flags) + * Description + * Redirect the packet to another net device of index *ifindex*. + * This helper is somewhat similar to **bpf_clone_redirect**\ + * (), except that the packet is not cloned, which provides + * increased performance. + * + * Except for XDP, both ingress and egress interfaces can be used + * for redirection. The **BPF_F_INGRESS** value in *flags* is used + * to make the distinction (ingress path is selected if the flag + * is present, egress path otherwise). Currently, XDP only + * supports redirection to the egress interface, and accepts no + * flag at all. + * + * The same effect can also be attained with the more generic + * **bpf_redirect_map**\ (), which uses a BPF map to store the + * redirect target instead of providing it directly to the helper. + * Return + * For XDP, the helper returns **XDP_REDIRECT** on success or + * **XDP_ABORTED** on error. For other program types, the values + * are **TC_ACT_REDIRECT** on success or **TC_ACT_SHOT** on + * error. + * + * u32 bpf_get_route_realm(struct sk_buff *skb) + * Description + * Retrieve the realm or the route, that is to say the + * **tclassid** field of the destination for the *skb*. The + * identifier retrieved is a user-provided tag, similar to the + * one used with the net_cls cgroup (see description for + * **bpf_get_cgroup_classid**\ () helper), but here this tag is + * held by a route (a destination entry), not by a task. + * + * Retrieving this identifier works with the clsact TC egress hook + * (see also **tc-bpf(8)**), or alternatively on conventional + * classful egress qdiscs, but not on TC ingress path. In case of + * clsact TC egress hook, this has the advantage that, internally, + * the destination entry has not been dropped yet in the transmit + * path. Therefore, the destination entry does not need to be + * artificially held via **netif_keep_dst**\ () for a classful + * qdisc until the *skb* is freed. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_IP_ROUTE_CLASSID** configuration option. + * Return + * The realm of the route for the packet associated to *skb*, or 0 + * if none was found. + * + * long bpf_perf_event_output(void *ctx, struct bpf_map *map, u64 flags, void *data, u64 size) + * Description + * Write raw *data* blob into a special BPF perf event held by + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf + * event must have the following attributes: **PERF_SAMPLE_RAW** + * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and + * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. + * + * The *flags* are used to indicate the index in *map* for which + * the value must be put, masked with **BPF_F_INDEX_MASK**. + * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** + * to indicate that the index of the current CPU core should be + * used. + * + * The value to write, of *size*, is passed through eBPF stack and + * pointed by *data*. + * + * The context of the program *ctx* needs also be passed to the + * helper. + * + * On user space, a program willing to read the values needs to + * call **perf_event_open**\ () on the perf event (either for + * one or for all CPUs) and to store the file descriptor into the + * *map*. This must be done before the eBPF program can send data + * into it. An example is available in file + * *samples/bpf/trace_output_user.c* in the Linux kernel source + * tree (the eBPF program counterpart is in + * *samples/bpf/trace_output_kern.c*). + * + * **bpf_perf_event_output**\ () achieves better performance + * than **bpf_trace_printk**\ () for sharing data with user + * space, and is much better suitable for streaming data from eBPF + * programs. + * + * Note that this helper is not restricted to tracing use cases + * and can be used with programs attached to TC or XDP as well, + * where it allows for passing data to user space listeners. Data + * can be: + * + * * Only custom structs, + * * Only the packet payload, or + * * A combination of both. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_load_bytes(const void *skb, u32 offset, void *to, u32 len) + * Description + * This helper was provided as an easy way to load data from a + * packet. It can be used to load *len* bytes from *offset* from + * the packet associated to *skb*, into the buffer pointed by + * *to*. + * + * Since Linux 4.7, usage of this helper has mostly been replaced + * by "direct packet access", enabling packet data to be + * manipulated with *skb*\ **->data** and *skb*\ **->data_end** + * pointing respectively to the first byte of packet data and to + * the byte after the last byte of packet data. However, it + * remains useful if one wishes to read large quantities of data + * at once from a packet into the eBPF stack. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_get_stackid(void *ctx, struct bpf_map *map, u64 flags) + * Description + * Walk a user or a kernel stack and return its id. To achieve + * this, the helper needs *ctx*, which is a pointer to the context + * on which the tracing program is executed, and a pointer to a + * *map* of type **BPF_MAP_TYPE_STACK_TRACE**. + * + * The last argument, *flags*, holds the number of stack frames to + * skip (from 0 to 255), masked with + * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set + * a combination of the following flags: + * + * **BPF_F_USER_STACK** + * Collect a user space stack instead of a kernel stack. + * **BPF_F_FAST_STACK_CMP** + * Compare stacks by hash only. + * **BPF_F_REUSE_STACKID** + * If two different stacks hash into the same *stackid*, + * discard the old one. + * + * The stack id retrieved is a 32 bit long integer handle which + * can be further combined with other data (including other stack + * ids) and used as a key into maps. This can be useful for + * generating a variety of graphs (such as flame graphs or off-cpu + * graphs). + * + * For walking a stack, this helper is an improvement over + * **bpf_probe_read**\ (), which can be used with unrolled loops + * but is not efficient and consumes a lot of eBPF instructions. + * Instead, **bpf_get_stackid**\ () can collect up to + * **PERF_MAX_STACK_DEPTH** both kernel and user frames. Note that + * this limit can be controlled with the **sysctl** program, and + * that it should be manually increased in order to profile long + * user stacks (such as stacks for Java programs). To do so, use: + * + * :: + * + * # sysctl kernel.perf_event_max_stack= + * Return + * The positive or null stack id on success, or a negative error + * in case of failure. + * + * s64 bpf_csum_diff(__be32 *from, u32 from_size, __be32 *to, u32 to_size, __wsum seed) + * Description + * Compute a checksum difference, from the raw buffer pointed by + * *from*, of length *from_size* (that must be a multiple of 4), + * towards the raw buffer pointed by *to*, of size *to_size* + * (same remark). An optional *seed* can be added to the value + * (this can be cascaded, the seed may come from a previous call + * to the helper). + * + * This is flexible enough to be used in several ways: + * + * * With *from_size* == 0, *to_size* > 0 and *seed* set to + * checksum, it can be used when pushing new data. + * * With *from_size* > 0, *to_size* == 0 and *seed* set to + * checksum, it can be used when removing data from a packet. + * * With *from_size* > 0, *to_size* > 0 and *seed* set to 0, it + * can be used to compute a diff. Note that *from_size* and + * *to_size* do not need to be equal. + * + * This helper can be used in combination with + * **bpf_l3_csum_replace**\ () and **bpf_l4_csum_replace**\ (), to + * which one can feed in the difference computed with + * **bpf_csum_diff**\ (). + * Return + * The checksum result, or a negative error code in case of + * failure. + * + * long bpf_skb_get_tunnel_opt(struct sk_buff *skb, void *opt, u32 size) + * Description + * Retrieve tunnel options metadata for the packet associated to + * *skb*, and store the raw tunnel option data to the buffer *opt* + * of *size*. + * + * This helper can be used with encapsulation devices that can + * operate in "collect metadata" mode (please refer to the related + * note in the description of **bpf_skb_get_tunnel_key**\ () for + * more details). A particular example where this can be used is + * in combination with the Geneve encapsulation protocol, where it + * allows for pushing (with **bpf_skb_get_tunnel_opt**\ () helper) + * and retrieving arbitrary TLVs (Type-Length-Value headers) from + * the eBPF program. This allows for full customization of these + * headers. + * Return + * The size of the option data retrieved. + * + * long bpf_skb_set_tunnel_opt(struct sk_buff *skb, void *opt, u32 size) + * Description + * Set tunnel options metadata for the packet associated to *skb* + * to the option data contained in the raw buffer *opt* of *size*. + * + * See also the description of the **bpf_skb_get_tunnel_opt**\ () + * helper for additional information. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_change_proto(struct sk_buff *skb, __be16 proto, u64 flags) + * Description + * Change the protocol of the *skb* to *proto*. Currently + * supported are transition from IPv4 to IPv6, and from IPv6 to + * IPv4. The helper takes care of the groundwork for the + * transition, including resizing the socket buffer. The eBPF + * program is expected to fill the new headers, if any, via + * **skb_store_bytes**\ () and to recompute the checksums with + * **bpf_l3_csum_replace**\ () and **bpf_l4_csum_replace**\ + * (). The main case for this helper is to perform NAT64 + * operations out of an eBPF program. + * + * Internally, the GSO type is marked as dodgy so that headers are + * checked and segments are recalculated by the GSO/GRO engine. + * The size for GSO target is adapted as well. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_change_type(struct sk_buff *skb, u32 type) + * Description + * Change the packet type for the packet associated to *skb*. This + * comes down to setting *skb*\ **->pkt_type** to *type*, except + * the eBPF program does not have a write access to *skb*\ + * **->pkt_type** beside this helper. Using a helper here allows + * for graceful handling of errors. + * + * The major use case is to change incoming *skb*s to + * **PACKET_HOST** in a programmatic way instead of having to + * recirculate via **redirect**\ (..., **BPF_F_INGRESS**), for + * example. + * + * Note that *type* only allows certain values. At this time, they + * are: + * + * **PACKET_HOST** + * Packet is for us. + * **PACKET_BROADCAST** + * Send packet to all. + * **PACKET_MULTICAST** + * Send packet to group. + * **PACKET_OTHERHOST** + * Send packet to someone else. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_under_cgroup(struct sk_buff *skb, struct bpf_map *map, u32 index) + * Description + * Check whether *skb* is a descendant of the cgroup2 held by + * *map* of type **BPF_MAP_TYPE_CGROUP_ARRAY**, at *index*. + * Return + * The return value depends on the result of the test, and can be: + * + * * 0, if the *skb* failed the cgroup2 descendant test. + * * 1, if the *skb* succeeded the cgroup2 descendant test. + * * A negative error code, if an error occurred. + * + * u32 bpf_get_hash_recalc(struct sk_buff *skb) + * Description + * Retrieve the hash of the packet, *skb*\ **->hash**. If it is + * not set, in particular if the hash was cleared due to mangling, + * recompute this hash. Later accesses to the hash can be done + * directly with *skb*\ **->hash**. + * + * Calling **bpf_set_hash_invalid**\ (), changing a packet + * prototype with **bpf_skb_change_proto**\ (), or calling + * **bpf_skb_store_bytes**\ () with the + * **BPF_F_INVALIDATE_HASH** are actions susceptible to clear + * the hash and to trigger a new computation for the next call to + * **bpf_get_hash_recalc**\ (). + * Return + * The 32-bit hash. + * + * u64 bpf_get_current_task(void) + * Return + * A pointer to the current task struct. + * + * long bpf_probe_write_user(void *dst, const void *src, u32 len) + * Description + * Attempt in a safe way to write *len* bytes from the buffer + * *src* to *dst* in memory. It only works for threads that are in + * user context, and *dst* must be a valid user space address. + * + * This helper should not be used to implement any kind of + * security mechanism because of TOC-TOU attacks, but rather to + * debug, divert, and manipulate execution of semi-cooperative + * processes. + * + * Keep in mind that this feature is meant for experiments, and it + * has a risk of crashing the system and running programs. + * Therefore, when an eBPF program using this helper is attached, + * a warning including PID and process name is printed to kernel + * logs. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_current_task_under_cgroup(struct bpf_map *map, u32 index) + * Description + * Check whether the probe is being run is the context of a given + * subset of the cgroup2 hierarchy. The cgroup2 to test is held by + * *map* of type **BPF_MAP_TYPE_CGROUP_ARRAY**, at *index*. + * Return + * The return value depends on the result of the test, and can be: + * + * * 0, if current task belongs to the cgroup2. + * * 1, if current task does not belong to the cgroup2. + * * A negative error code, if an error occurred. + * + * long bpf_skb_change_tail(struct sk_buff *skb, u32 len, u64 flags) + * Description + * Resize (trim or grow) the packet associated to *skb* to the + * new *len*. The *flags* are reserved for future usage, and must + * be left at zero. + * + * The basic idea is that the helper performs the needed work to + * change the size of the packet, then the eBPF program rewrites + * the rest via helpers like **bpf_skb_store_bytes**\ (), + * **bpf_l3_csum_replace**\ (), **bpf_l3_csum_replace**\ () + * and others. This helper is a slow path utility intended for + * replies with control messages. And because it is targeted for + * slow path, the helper itself can afford to be slow: it + * implicitly linearizes, unclones and drops offloads from the + * *skb*. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_pull_data(struct sk_buff *skb, u32 len) + * Description + * Pull in non-linear data in case the *skb* is non-linear and not + * all of *len* are part of the linear section. Make *len* bytes + * from *skb* readable and writable. If a zero value is passed for + * *len*, then the whole length of the *skb* is pulled. + * + * This helper is only needed for reading and writing with direct + * packet access. + * + * For direct packet access, testing that offsets to access + * are within packet boundaries (test on *skb*\ **->data_end**) is + * susceptible to fail if offsets are invalid, or if the requested + * data is in non-linear parts of the *skb*. On failure the + * program can just bail out, or in the case of a non-linear + * buffer, use a helper to make the data available. The + * **bpf_skb_load_bytes**\ () helper is a first solution to access + * the data. Another one consists in using **bpf_skb_pull_data** + * to pull in once the non-linear parts, then retesting and + * eventually access the data. + * + * At the same time, this also makes sure the *skb* is uncloned, + * which is a necessary condition for direct write. As this needs + * to be an invariant for the write part only, the verifier + * detects writes and adds a prologue that is calling + * **bpf_skb_pull_data()** to effectively unclone the *skb* from + * the very beginning in case it is indeed cloned. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * s64 bpf_csum_update(struct sk_buff *skb, __wsum csum) + * Description + * Add the checksum *csum* into *skb*\ **->csum** in case the + * driver has supplied a checksum for the entire packet into that + * field. Return an error otherwise. This helper is intended to be + * used in combination with **bpf_csum_diff**\ (), in particular + * when the checksum needs to be updated after data has been + * written into the packet through direct packet access. + * Return + * The checksum on success, or a negative error code in case of + * failure. + * + * void bpf_set_hash_invalid(struct sk_buff *skb) + * Description + * Invalidate the current *skb*\ **->hash**. It can be used after + * mangling on headers through direct packet access, in order to + * indicate that the hash is outdated and to trigger a + * recalculation the next time the kernel tries to access this + * hash or when the **bpf_get_hash_recalc**\ () helper is called. + * + * long bpf_get_numa_node_id(void) + * Description + * Return the id of the current NUMA node. The primary use case + * for this helper is the selection of sockets for the local NUMA + * node, when the program is attached to sockets using the + * **SO_ATTACH_REUSEPORT_EBPF** option (see also **socket(7)**), + * but the helper is also available to other eBPF program types, + * similarly to **bpf_get_smp_processor_id**\ (). + * Return + * The id of current NUMA node. + * + * long bpf_skb_change_head(struct sk_buff *skb, u32 len, u64 flags) + * Description + * Grows headroom of packet associated to *skb* and adjusts the + * offset of the MAC header accordingly, adding *len* bytes of + * space. It automatically extends and reallocates memory as + * required. + * + * This helper can be used on a layer 3 *skb* to push a MAC header + * for redirection into a layer 2 device. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_xdp_adjust_head(struct xdp_buff *xdp_md, int delta) + * Description + * Adjust (move) *xdp_md*\ **->data** by *delta* bytes. Note that + * it is possible to use a negative value for *delta*. This helper + * can be used to prepare the packet for pushing or popping + * headers. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_probe_read_str(void *dst, u32 size, const void *unsafe_ptr) + * Description + * Copy a NUL terminated string from an unsafe kernel address + * *unsafe_ptr* to *dst*. See **bpf_probe_read_kernel_str**\ () for + * more details. + * + * Generally, use **bpf_probe_read_user_str**\ () or + * **bpf_probe_read_kernel_str**\ () instead. + * Return + * On success, the strictly positive length of the string, + * including the trailing NUL character. On error, a negative + * value. + * + * u64 bpf_get_socket_cookie(struct sk_buff *skb) + * Description + * If the **struct sk_buff** pointed by *skb* has a known socket, + * retrieve the cookie (generated by the kernel) of this socket. + * If no cookie has been set yet, generate a new cookie. Once + * generated, the socket cookie remains stable for the life of the + * socket. This helper can be useful for monitoring per socket + * networking traffic statistics as it provides a global socket + * identifier that can be assumed unique. + * Return + * A 8-byte long non-decreasing number on success, or 0 if the + * socket field is missing inside *skb*. + * + * u64 bpf_get_socket_cookie(struct bpf_sock_addr *ctx) + * Description + * Equivalent to bpf_get_socket_cookie() helper that accepts + * *skb*, but gets socket from **struct bpf_sock_addr** context. + * Return + * A 8-byte long non-decreasing number. + * + * u64 bpf_get_socket_cookie(struct bpf_sock_ops *ctx) + * Description + * Equivalent to **bpf_get_socket_cookie**\ () helper that accepts + * *skb*, but gets socket from **struct bpf_sock_ops** context. + * Return + * A 8-byte long non-decreasing number. + * + * u32 bpf_get_socket_uid(struct sk_buff *skb) + * Return + * The owner UID of the socket associated to *skb*. If the socket + * is **NULL**, or if it is not a full socket (i.e. if it is a + * time-wait or a request socket instead), **overflowuid** value + * is returned (note that **overflowuid** might also be the actual + * UID value for the socket). + * + * long bpf_set_hash(struct sk_buff *skb, u32 hash) + * Description + * Set the full hash for *skb* (set the field *skb*\ **->hash**) + * to value *hash*. + * Return + * 0 + * + * long bpf_setsockopt(void *bpf_socket, int level, int optname, void *optval, int optlen) + * Description + * Emulate a call to **setsockopt()** on the socket associated to + * *bpf_socket*, which must be a full socket. The *level* at + * which the option resides and the name *optname* of the option + * must be specified, see **setsockopt(2)** for more information. + * The option value of length *optlen* is pointed by *optval*. + * + * *bpf_socket* should be one of the following: + * + * * **struct bpf_sock_ops** for **BPF_PROG_TYPE_SOCK_OPS**. + * * **struct bpf_sock_addr** for **BPF_CGROUP_INET4_CONNECT** + * and **BPF_CGROUP_INET6_CONNECT**. + * + * This helper actually implements a subset of **setsockopt()**. + * It supports the following *level*\ s: + * + * * **SOL_SOCKET**, which supports the following *optname*\ s: + * **SO_RCVBUF**, **SO_SNDBUF**, **SO_MAX_PACING_RATE**, + * **SO_PRIORITY**, **SO_RCVLOWAT**, **SO_MARK**, + * **SO_BINDTODEVICE**, **SO_KEEPALIVE**. + * * **IPPROTO_TCP**, which supports the following *optname*\ s: + * **TCP_CONGESTION**, **TCP_BPF_IW**, + * **TCP_BPF_SNDCWND_CLAMP**, **TCP_SAVE_SYN**, + * **TCP_KEEPIDLE**, **TCP_KEEPINTVL**, **TCP_KEEPCNT**, + * **TCP_SYNCNT**, **TCP_USER_TIMEOUT**, **TCP_NOTSENT_LOWAT**. + * * **IPPROTO_IP**, which supports *optname* **IP_TOS**. + * * **IPPROTO_IPV6**, which supports *optname* **IPV6_TCLASS**. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_adjust_room(struct sk_buff *skb, s32 len_diff, u32 mode, u64 flags) + * Description + * Grow or shrink the room for data in the packet associated to + * *skb* by *len_diff*, and according to the selected *mode*. + * + * By default, the helper will reset any offloaded checksum + * indicator of the skb to CHECKSUM_NONE. This can be avoided + * by the following flag: + * + * * **BPF_F_ADJ_ROOM_NO_CSUM_RESET**: Do not reset offloaded + * checksum data of the skb to CHECKSUM_NONE. + * + * There are two supported modes at this time: + * + * * **BPF_ADJ_ROOM_MAC**: Adjust room at the mac layer + * (room space is added or removed below the layer 2 header). + * + * * **BPF_ADJ_ROOM_NET**: Adjust room at the network layer + * (room space is added or removed below the layer 3 header). + * + * The following flags are supported at this time: + * + * * **BPF_F_ADJ_ROOM_FIXED_GSO**: Do not adjust gso_size. + * Adjusting mss in this way is not allowed for datagrams. + * + * * **BPF_F_ADJ_ROOM_ENCAP_L3_IPV4**, + * **BPF_F_ADJ_ROOM_ENCAP_L3_IPV6**: + * Any new space is reserved to hold a tunnel header. + * Configure skb offsets and other fields accordingly. + * + * * **BPF_F_ADJ_ROOM_ENCAP_L4_GRE**, + * **BPF_F_ADJ_ROOM_ENCAP_L4_UDP**: + * Use with ENCAP_L3 flags to further specify the tunnel type. + * + * * **BPF_F_ADJ_ROOM_ENCAP_L2**\ (*len*): + * Use with ENCAP_L3/L4 flags to further specify the tunnel + * type; *len* is the length of the inner MAC header. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_redirect_map(struct bpf_map *map, u32 key, u64 flags) + * Description + * Redirect the packet to the endpoint referenced by *map* at + * index *key*. Depending on its type, this *map* can contain + * references to net devices (for forwarding packets through other + * ports), or to CPUs (for redirecting XDP frames to another CPU; + * but this is only implemented for native XDP (with driver + * support) as of this writing). + * + * The lower two bits of *flags* are used as the return code if + * the map lookup fails. This is so that the return value can be + * one of the XDP program return codes up to **XDP_TX**, as chosen + * by the caller. Any higher bits in the *flags* argument must be + * unset. + * + * See also **bpf_redirect**\ (), which only supports redirecting + * to an ifindex, but doesn't require a map to do so. + * Return + * **XDP_REDIRECT** on success, or the value of the two lower bits + * of the *flags* argument on error. + * + * long bpf_sk_redirect_map(struct sk_buff *skb, struct bpf_map *map, u32 key, u64 flags) + * Description + * Redirect the packet to the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKMAP**) at index *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress path otherwise). This is the only flag supported for now. + * Return + * **SK_PASS** on success, or **SK_DROP** on error. + * + * long bpf_sock_map_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags) + * Description + * Add an entry to, or update a *map* referencing sockets. The + * *skops* is used as a new value for the entry associated to + * *key*. *flags* is one of: + * + * **BPF_NOEXIST** + * The entry for *key* must not exist in the map. + * **BPF_EXIST** + * The entry for *key* must already exist in the map. + * **BPF_ANY** + * No condition on the existence of the entry for *key*. + * + * If the *map* has eBPF programs (parser and verdict), those will + * be inherited by the socket being added. If the socket is + * already attached to eBPF programs, this results in an error. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_xdp_adjust_meta(struct xdp_buff *xdp_md, int delta) + * Description + * Adjust the address pointed by *xdp_md*\ **->data_meta** by + * *delta* (which can be positive or negative). Note that this + * operation modifies the address stored in *xdp_md*\ **->data**, + * so the latter must be loaded only after the helper has been + * called. + * + * The use of *xdp_md*\ **->data_meta** is optional and programs + * are not required to use it. The rationale is that when the + * packet is processed with XDP (e.g. as DoS filter), it is + * possible to push further meta data along with it before passing + * to the stack, and to give the guarantee that an ingress eBPF + * program attached as a TC classifier on the same device can pick + * this up for further post-processing. Since TC works with socket + * buffers, it remains possible to set from XDP the **mark** or + * **priority** pointers, or other pointers for the socket buffer. + * Having this scratch space generic and programmable allows for + * more flexibility as the user is free to store whatever meta + * data they need. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_perf_event_read_value(struct bpf_map *map, u64 flags, struct bpf_perf_event_value *buf, u32 buf_size) + * Description + * Read the value of a perf event counter, and store it into *buf* + * of size *buf_size*. This helper relies on a *map* of type + * **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. The nature of the perf event + * counter is selected when *map* is updated with perf event file + * descriptors. The *map* is an array whose size is the number of + * available CPUs, and each cell contains a value relative to one + * CPU. The value to retrieve is indicated by *flags*, that + * contains the index of the CPU to look up, masked with + * **BPF_F_INDEX_MASK**. Alternatively, *flags* can be set to + * **BPF_F_CURRENT_CPU** to indicate that the value for the + * current CPU should be retrieved. + * + * This helper behaves in a way close to + * **bpf_perf_event_read**\ () helper, save that instead of + * just returning the value observed, it fills the *buf* + * structure. This allows for additional data to be retrieved: in + * particular, the enabled and running times (in *buf*\ + * **->enabled** and *buf*\ **->running**, respectively) are + * copied. In general, **bpf_perf_event_read_value**\ () is + * recommended over **bpf_perf_event_read**\ (), which has some + * ABI issues and provides fewer functionalities. + * + * These values are interesting, because hardware PMU (Performance + * Monitoring Unit) counters are limited resources. When there are + * more PMU based perf events opened than available counters, + * kernel will multiplex these events so each event gets certain + * percentage (but not all) of the PMU time. In case that + * multiplexing happens, the number of samples or counter value + * will not reflect the case compared to when no multiplexing + * occurs. This makes comparison between different runs difficult. + * Typically, the counter value should be normalized before + * comparing to other experiments. The usual normalization is done + * as follows. + * + * :: + * + * normalized_counter = counter * t_enabled / t_running + * + * Where t_enabled is the time enabled for event and t_running is + * the time running for event since last normalization. The + * enabled and running times are accumulated since the perf event + * open. To achieve scaling factor between two invocations of an + * eBPF program, users can use CPU id as the key (which is + * typical for perf array usage model) to remember the previous + * value and do the calculation inside the eBPF program. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_perf_prog_read_value(struct bpf_perf_event_data *ctx, struct bpf_perf_event_value *buf, u32 buf_size) + * Description + * For en eBPF program attached to a perf event, retrieve the + * value of the event counter associated to *ctx* and store it in + * the structure pointed by *buf* and of size *buf_size*. Enabled + * and running times are also stored in the structure (see + * description of helper **bpf_perf_event_read_value**\ () for + * more details). + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_getsockopt(void *bpf_socket, int level, int optname, void *optval, int optlen) + * Description + * Emulate a call to **getsockopt()** on the socket associated to + * *bpf_socket*, which must be a full socket. The *level* at + * which the option resides and the name *optname* of the option + * must be specified, see **getsockopt(2)** for more information. + * The retrieved value is stored in the structure pointed by + * *opval* and of length *optlen*. + * + * *bpf_socket* should be one of the following: + * + * * **struct bpf_sock_ops** for **BPF_PROG_TYPE_SOCK_OPS**. + * * **struct bpf_sock_addr** for **BPF_CGROUP_INET4_CONNECT** + * and **BPF_CGROUP_INET6_CONNECT**. + * + * This helper actually implements a subset of **getsockopt()**. + * It supports the following *level*\ s: + * + * * **IPPROTO_TCP**, which supports *optname* + * **TCP_CONGESTION**. + * * **IPPROTO_IP**, which supports *optname* **IP_TOS**. + * * **IPPROTO_IPV6**, which supports *optname* **IPV6_TCLASS**. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_override_return(struct pt_regs *regs, u64 rc) + * Description + * Used for error injection, this helper uses kprobes to override + * the return value of the probed function, and to set it to *rc*. + * The first argument is the context *regs* on which the kprobe + * works. + * + * This helper works by setting the PC (program counter) + * to an override function which is run in place of the original + * probed function. This means the probed function is not run at + * all. The replacement function just returns with the required + * value. + * + * This helper has security implications, and thus is subject to + * restrictions. It is only available if the kernel was compiled + * with the **CONFIG_BPF_KPROBE_OVERRIDE** configuration + * option, and in this case it only works on functions tagged with + * **ALLOW_ERROR_INJECTION** in the kernel code. + * + * Also, the helper is only available for the architectures having + * the CONFIG_FUNCTION_ERROR_INJECTION option. As of this writing, + * x86 architecture is the only one to support this feature. + * Return + * 0 + * + * long bpf_sock_ops_cb_flags_set(struct bpf_sock_ops *bpf_sock, int argval) + * Description + * Attempt to set the value of the **bpf_sock_ops_cb_flags** field + * for the full TCP socket associated to *bpf_sock_ops* to + * *argval*. + * + * The primary use of this field is to determine if there should + * be calls to eBPF programs of type + * **BPF_PROG_TYPE_SOCK_OPS** at various points in the TCP + * code. A program of the same type can change its value, per + * connection and as necessary, when the connection is + * established. This field is directly accessible for reading, but + * this helper must be used for updates in order to return an + * error if an eBPF program tries to set a callback that is not + * supported in the current kernel. + * + * *argval* is a flag array which can combine these flags: + * + * * **BPF_SOCK_OPS_RTO_CB_FLAG** (retransmission time out) + * * **BPF_SOCK_OPS_RETRANS_CB_FLAG** (retransmission) + * * **BPF_SOCK_OPS_STATE_CB_FLAG** (TCP state change) + * * **BPF_SOCK_OPS_RTT_CB_FLAG** (every RTT) + * + * Therefore, this function can be used to clear a callback flag by + * setting the appropriate bit to zero. e.g. to disable the RTO + * callback: + * + * **bpf_sock_ops_cb_flags_set(bpf_sock,** + * **bpf_sock->bpf_sock_ops_cb_flags & ~BPF_SOCK_OPS_RTO_CB_FLAG)** + * + * Here are some examples of where one could call such eBPF + * program: + * + * * When RTO fires. + * * When a packet is retransmitted. + * * When the connection terminates. + * * When a packet is sent. + * * When a packet is received. + * Return + * Code **-EINVAL** if the socket is not a full TCP socket; + * otherwise, a positive number containing the bits that could not + * be set is returned (which comes down to 0 if all bits were set + * as required). + * + * long bpf_msg_redirect_map(struct sk_msg_buff *msg, struct bpf_map *map, u32 key, u64 flags) + * Description + * This helper is used in programs implementing policies at the + * socket level. If the message *msg* is allowed to pass (i.e. if + * the verdict eBPF program returns **SK_PASS**), redirect it to + * the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKMAP**) at index *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress path otherwise). This is the only flag supported for now. + * Return + * **SK_PASS** on success, or **SK_DROP** on error. + * + * long bpf_msg_apply_bytes(struct sk_msg_buff *msg, u32 bytes) + * Description + * For socket policies, apply the verdict of the eBPF program to + * the next *bytes* (number of bytes) of message *msg*. + * + * For example, this helper can be used in the following cases: + * + * * A single **sendmsg**\ () or **sendfile**\ () system call + * contains multiple logical messages that the eBPF program is + * supposed to read and for which it should apply a verdict. + * * An eBPF program only cares to read the first *bytes* of a + * *msg*. If the message has a large payload, then setting up + * and calling the eBPF program repeatedly for all bytes, even + * though the verdict is already known, would create unnecessary + * overhead. + * + * When called from within an eBPF program, the helper sets a + * counter internal to the BPF infrastructure, that is used to + * apply the last verdict to the next *bytes*. If *bytes* is + * smaller than the current data being processed from a + * **sendmsg**\ () or **sendfile**\ () system call, the first + * *bytes* will be sent and the eBPF program will be re-run with + * the pointer for start of data pointing to byte number *bytes* + * **+ 1**. If *bytes* is larger than the current data being + * processed, then the eBPF verdict will be applied to multiple + * **sendmsg**\ () or **sendfile**\ () calls until *bytes* are + * consumed. + * + * Note that if a socket closes with the internal counter holding + * a non-zero value, this is not a problem because data is not + * being buffered for *bytes* and is sent as it is received. + * Return + * 0 + * + * long bpf_msg_cork_bytes(struct sk_msg_buff *msg, u32 bytes) + * Description + * For socket policies, prevent the execution of the verdict eBPF + * program for message *msg* until *bytes* (byte number) have been + * accumulated. + * + * This can be used when one needs a specific number of bytes + * before a verdict can be assigned, even if the data spans + * multiple **sendmsg**\ () or **sendfile**\ () calls. The extreme + * case would be a user calling **sendmsg**\ () repeatedly with + * 1-byte long message segments. Obviously, this is bad for + * performance, but it is still valid. If the eBPF program needs + * *bytes* bytes to validate a header, this helper can be used to + * prevent the eBPF program to be called again until *bytes* have + * been accumulated. + * Return + * 0 + * + * long bpf_msg_pull_data(struct sk_msg_buff *msg, u32 start, u32 end, u64 flags) + * Description + * For socket policies, pull in non-linear data from user space + * for *msg* and set pointers *msg*\ **->data** and *msg*\ + * **->data_end** to *start* and *end* bytes offsets into *msg*, + * respectively. + * + * If a program of type **BPF_PROG_TYPE_SK_MSG** is run on a + * *msg* it can only parse data that the (**data**, **data_end**) + * pointers have already consumed. For **sendmsg**\ () hooks this + * is likely the first scatterlist element. But for calls relying + * on the **sendpage** handler (e.g. **sendfile**\ ()) this will + * be the range (**0**, **0**) because the data is shared with + * user space and by default the objective is to avoid allowing + * user space to modify data while (or after) eBPF verdict is + * being decided. This helper can be used to pull in data and to + * set the start and end pointer to given values. Data will be + * copied if necessary (i.e. if data was not linear and if start + * and end pointers do not point to the same chunk). + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_bind(struct bpf_sock_addr *ctx, struct sockaddr *addr, int addr_len) + * Description + * Bind the socket associated to *ctx* to the address pointed by + * *addr*, of length *addr_len*. This allows for making outgoing + * connection from the desired IP address, which can be useful for + * example when all processes inside a cgroup should use one + * single IP address on a host that has multiple IP configured. + * + * This helper works for IPv4 and IPv6, TCP and UDP sockets. The + * domain (*addr*\ **->sa_family**) must be **AF_INET** (or + * **AF_INET6**). It's advised to pass zero port (**sin_port** + * or **sin6_port**) which triggers IP_BIND_ADDRESS_NO_PORT-like + * behavior and lets the kernel efficiently pick up an unused + * port as long as 4-tuple is unique. Passing non-zero port might + * lead to degraded performance. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_xdp_adjust_tail(struct xdp_buff *xdp_md, int delta) + * Description + * Adjust (move) *xdp_md*\ **->data_end** by *delta* bytes. It is + * possible to both shrink and grow the packet tail. + * Shrink done via *delta* being a negative integer. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_skb_get_xfrm_state(struct sk_buff *skb, u32 index, struct bpf_xfrm_state *xfrm_state, u32 size, u64 flags) + * Description + * Retrieve the XFRM state (IP transform framework, see also + * **ip-xfrm(8)**) at *index* in XFRM "security path" for *skb*. + * + * The retrieved value is stored in the **struct bpf_xfrm_state** + * pointed by *xfrm_state* and of length *size*. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_XFRM** configuration option. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_get_stack(void *ctx, void *buf, u32 size, u64 flags) + * Description + * Return a user or a kernel stack in bpf program provided buffer. + * To achieve this, the helper needs *ctx*, which is a pointer + * to the context on which the tracing program is executed. + * To store the stacktrace, the bpf program provides *buf* with + * a nonnegative *size*. + * + * The last argument, *flags*, holds the number of stack frames to + * skip (from 0 to 255), masked with + * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set + * the following flags: + * + * **BPF_F_USER_STACK** + * Collect a user space stack instead of a kernel stack. + * **BPF_F_USER_BUILD_ID** + * Collect buildid+offset instead of ips for user stack, + * only valid if **BPF_F_USER_STACK** is also specified. + * + * **bpf_get_stack**\ () can collect up to + * **PERF_MAX_STACK_DEPTH** both kernel and user frames, subject + * to sufficient large buffer size. Note that + * this limit can be controlled with the **sysctl** program, and + * that it should be manually increased in order to profile long + * user stacks (such as stacks for Java programs). To do so, use: + * + * :: + * + * # sysctl kernel.perf_event_max_stack= + * Return + * A non-negative value equal to or less than *size* on success, + * or a negative error in case of failure. + * + * long bpf_skb_load_bytes_relative(const void *skb, u32 offset, void *to, u32 len, u32 start_header) + * Description + * This helper is similar to **bpf_skb_load_bytes**\ () in that + * it provides an easy way to load *len* bytes from *offset* + * from the packet associated to *skb*, into the buffer pointed + * by *to*. The difference to **bpf_skb_load_bytes**\ () is that + * a fifth argument *start_header* exists in order to select a + * base offset to start from. *start_header* can be one of: + * + * **BPF_HDR_START_MAC** + * Base offset to load data from is *skb*'s mac header. + * **BPF_HDR_START_NET** + * Base offset to load data from is *skb*'s network header. + * + * In general, "direct packet access" is the preferred method to + * access packet data, however, this helper is in particular useful + * in socket filters where *skb*\ **->data** does not always point + * to the start of the mac header and where "direct packet access" + * is not available. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_fib_lookup(void *ctx, struct bpf_fib_lookup *params, int plen, u32 flags) + * Description + * Do FIB lookup in kernel tables using parameters in *params*. + * If lookup is successful and result shows packet is to be + * forwarded, the neighbor tables are searched for the nexthop. + * If successful (ie., FIB lookup shows forwarding and nexthop + * is resolved), the nexthop address is returned in ipv4_dst + * or ipv6_dst based on family, smac is set to mac address of + * egress device, dmac is set to nexthop mac address, rt_metric + * is set to metric from route (IPv4/IPv6 only), and ifindex + * is set to the device index of the nexthop from the FIB lookup. + * + * *plen* argument is the size of the passed in struct. + * *flags* argument can be a combination of one or more of the + * following values: + * + * **BPF_FIB_LOOKUP_DIRECT** + * Do a direct table lookup vs full lookup using FIB + * rules. + * **BPF_FIB_LOOKUP_OUTPUT** + * Perform lookup from an egress perspective (default is + * ingress). + * + * *ctx* is either **struct xdp_md** for XDP programs or + * **struct sk_buff** tc cls_act programs. + * Return + * * < 0 if any input argument is invalid + * * 0 on success (packet is forwarded, nexthop neighbor exists) + * * > 0 one of **BPF_FIB_LKUP_RET_** codes explaining why the + * packet is not forwarded or needs assist from full stack + * + * long bpf_sock_hash_update(struct bpf_sock_ops *skops, struct bpf_map *map, void *key, u64 flags) + * Description + * Add an entry to, or update a sockhash *map* referencing sockets. + * The *skops* is used as a new value for the entry associated to + * *key*. *flags* is one of: + * + * **BPF_NOEXIST** + * The entry for *key* must not exist in the map. + * **BPF_EXIST** + * The entry for *key* must already exist in the map. + * **BPF_ANY** + * No condition on the existence of the entry for *key*. + * + * If the *map* has eBPF programs (parser and verdict), those will + * be inherited by the socket being added. If the socket is + * already attached to eBPF programs, this results in an error. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_msg_redirect_hash(struct sk_msg_buff *msg, struct bpf_map *map, void *key, u64 flags) + * Description + * This helper is used in programs implementing policies at the + * socket level. If the message *msg* is allowed to pass (i.e. if + * the verdict eBPF program returns **SK_PASS**), redirect it to + * the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKHASH**) using hash *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress path otherwise). This is the only flag supported for now. + * Return + * **SK_PASS** on success, or **SK_DROP** on error. + * + * long bpf_sk_redirect_hash(struct sk_buff *skb, struct bpf_map *map, void *key, u64 flags) + * Description + * This helper is used in programs implementing policies at the + * skb socket level. If the sk_buff *skb* is allowed to pass (i.e. + * if the verdict eBPF program returns **SK_PASS**), redirect it + * to the socket referenced by *map* (of type + * **BPF_MAP_TYPE_SOCKHASH**) using hash *key*. Both ingress and + * egress interfaces can be used for redirection. The + * **BPF_F_INGRESS** value in *flags* is used to make the + * distinction (ingress path is selected if the flag is present, + * egress otherwise). This is the only flag supported for now. + * Return + * **SK_PASS** on success, or **SK_DROP** on error. + * + * long bpf_lwt_push_encap(struct sk_buff *skb, u32 type, void *hdr, u32 len) + * Description + * Encapsulate the packet associated to *skb* within a Layer 3 + * protocol header. This header is provided in the buffer at + * address *hdr*, with *len* its size in bytes. *type* indicates + * the protocol of the header and can be one of: + * + * **BPF_LWT_ENCAP_SEG6** + * IPv6 encapsulation with Segment Routing Header + * (**struct ipv6_sr_hdr**). *hdr* only contains the SRH, + * the IPv6 header is computed by the kernel. + * **BPF_LWT_ENCAP_SEG6_INLINE** + * Only works if *skb* contains an IPv6 packet. Insert a + * Segment Routing Header (**struct ipv6_sr_hdr**) inside + * the IPv6 header. + * **BPF_LWT_ENCAP_IP** + * IP encapsulation (GRE/GUE/IPIP/etc). The outer header + * must be IPv4 or IPv6, followed by zero or more + * additional headers, up to **LWT_BPF_MAX_HEADROOM** + * total bytes in all prepended headers. Please note that + * if **skb_is_gso**\ (*skb*) is true, no more than two + * headers can be prepended, and the inner header, if + * present, should be either GRE or UDP/GUE. + * + * **BPF_LWT_ENCAP_SEG6**\ \* types can be called by BPF programs + * of type **BPF_PROG_TYPE_LWT_IN**; **BPF_LWT_ENCAP_IP** type can + * be called by bpf programs of types **BPF_PROG_TYPE_LWT_IN** and + * **BPF_PROG_TYPE_LWT_XMIT**. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_lwt_seg6_store_bytes(struct sk_buff *skb, u32 offset, const void *from, u32 len) + * Description + * Store *len* bytes from address *from* into the packet + * associated to *skb*, at *offset*. Only the flags, tag and TLVs + * inside the outermost IPv6 Segment Routing Header can be + * modified through this helper. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_lwt_seg6_adjust_srh(struct sk_buff *skb, u32 offset, s32 delta) + * Description + * Adjust the size allocated to TLVs in the outermost IPv6 + * Segment Routing Header contained in the packet associated to + * *skb*, at position *offset* by *delta* bytes. Only offsets + * after the segments are accepted. *delta* can be as well + * positive (growing) as negative (shrinking). + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_lwt_seg6_action(struct sk_buff *skb, u32 action, void *param, u32 param_len) + * Description + * Apply an IPv6 Segment Routing action of type *action* to the + * packet associated to *skb*. Each action takes a parameter + * contained at address *param*, and of length *param_len* bytes. + * *action* can be one of: + * + * **SEG6_LOCAL_ACTION_END_X** + * End.X action: Endpoint with Layer-3 cross-connect. + * Type of *param*: **struct in6_addr**. + * **SEG6_LOCAL_ACTION_END_T** + * End.T action: Endpoint with specific IPv6 table lookup. + * Type of *param*: **int**. + * **SEG6_LOCAL_ACTION_END_B6** + * End.B6 action: Endpoint bound to an SRv6 policy. + * Type of *param*: **struct ipv6_sr_hdr**. + * **SEG6_LOCAL_ACTION_END_B6_ENCAP** + * End.B6.Encap action: Endpoint bound to an SRv6 + * encapsulation policy. + * Type of *param*: **struct ipv6_sr_hdr**. + * + * A call to this helper is susceptible to change the underlying + * packet buffer. Therefore, at load time, all checks on pointers + * previously done by the verifier are invalidated and must be + * performed again, if the helper is used in combination with + * direct packet access. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_rc_repeat(void *ctx) + * Description + * This helper is used in programs implementing IR decoding, to + * report a successfully decoded repeat key message. This delays + * the generation of a key up event for previously generated + * key down event. + * + * Some IR protocols like NEC have a special IR message for + * repeating last button, for when a button is held down. + * + * The *ctx* should point to the lirc sample as passed into + * the program. + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_BPF_LIRC_MODE2** configuration option set to + * "**y**". + * Return + * 0 + * + * long bpf_rc_keydown(void *ctx, u32 protocol, u64 scancode, u32 toggle) + * Description + * This helper is used in programs implementing IR decoding, to + * report a successfully decoded key press with *scancode*, + * *toggle* value in the given *protocol*. The scancode will be + * translated to a keycode using the rc keymap, and reported as + * an input key down event. After a period a key up event is + * generated. This period can be extended by calling either + * **bpf_rc_keydown**\ () again with the same values, or calling + * **bpf_rc_repeat**\ (). + * + * Some protocols include a toggle bit, in case the button was + * released and pressed again between consecutive scancodes. + * + * The *ctx* should point to the lirc sample as passed into + * the program. + * + * The *protocol* is the decoded protocol number (see + * **enum rc_proto** for some predefined values). + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_BPF_LIRC_MODE2** configuration option set to + * "**y**". + * Return + * 0 + * + * u64 bpf_skb_cgroup_id(struct sk_buff *skb) + * Description + * Return the cgroup v2 id of the socket associated with the *skb*. + * This is roughly similar to the **bpf_get_cgroup_classid**\ () + * helper for cgroup v1 by providing a tag resp. identifier that + * can be matched on or used for map lookups e.g. to implement + * policy. The cgroup v2 id of a given path in the hierarchy is + * exposed in user space through the f_handle API in order to get + * to the same 64-bit id. + * + * This helper can be used on TC egress path, but not on ingress, + * and is available only if the kernel was compiled with the + * **CONFIG_SOCK_CGROUP_DATA** configuration option. + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * u64 bpf_get_current_cgroup_id(void) + * Return + * A 64-bit integer containing the current cgroup id based + * on the cgroup within which the current task is running. + * + * void *bpf_get_local_storage(void *map, u64 flags) + * Description + * Get the pointer to the local storage area. + * The type and the size of the local storage is defined + * by the *map* argument. + * The *flags* meaning is specific for each map type, + * and has to be 0 for cgroup local storage. + * + * Depending on the BPF program type, a local storage area + * can be shared between multiple instances of the BPF program, + * running simultaneously. + * + * A user should care about the synchronization by himself. + * For example, by using the **BPF_STX_XADD** instruction to alter + * the shared data. + * Return + * A pointer to the local storage area. + * + * long bpf_sk_select_reuseport(struct sk_reuseport_md *reuse, struct bpf_map *map, void *key, u64 flags) + * Description + * Select a **SO_REUSEPORT** socket from a + * **BPF_MAP_TYPE_REUSEPORT_ARRAY** *map*. + * It checks the selected socket is matching the incoming + * request in the socket buffer. + * Return + * 0 on success, or a negative error in case of failure. + * + * u64 bpf_skb_ancestor_cgroup_id(struct sk_buff *skb, int ancestor_level) + * Description + * Return id of cgroup v2 that is ancestor of cgroup associated + * with the *skb* at the *ancestor_level*. The root cgroup is at + * *ancestor_level* zero and each step down the hierarchy + * increments the level. If *ancestor_level* == level of cgroup + * associated with *skb*, then return value will be same as that + * of **bpf_skb_cgroup_id**\ (). + * + * The helper is useful to implement policies based on cgroups + * that are upper in hierarchy than immediate cgroup associated + * with *skb*. + * + * The format of returned id and helper limitations are same as in + * **bpf_skb_cgroup_id**\ (). + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * struct bpf_sock *bpf_sk_lookup_tcp(void *ctx, struct bpf_sock_tuple *tuple, u32 tuple_size, u64 netns, u64 flags) + * Description + * Look for TCP socket matching *tuple*, optionally in a child + * network namespace *netns*. The return value must be checked, + * and if non-**NULL**, released via **bpf_sk_release**\ (). + * + * The *ctx* should point to the context of the program, such as + * the skb or socket (depending on the hook in use). This is used + * to determine the base network namespace for the lookup. + * + * *tuple_size* must be one of: + * + * **sizeof**\ (*tuple*\ **->ipv4**) + * Look for an IPv4 socket. + * **sizeof**\ (*tuple*\ **->ipv6**) + * Look for an IPv6 socket. + * + * If the *netns* is a negative signed 32-bit integer, then the + * socket lookup table in the netns associated with the *ctx* + * will be used. For the TC hooks, this is the netns of the device + * in the skb. For socket hooks, this is the netns of the socket. + * If *netns* is any other signed 32-bit value greater than or + * equal to zero then it specifies the ID of the netns relative to + * the netns associated with the *ctx*. *netns* values beyond the + * range of 32-bit integers are reserved for future use. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_NET** configuration option. + * Return + * Pointer to **struct bpf_sock**, or **NULL** in case of failure. + * For sockets with reuseport option, the **struct bpf_sock** + * result is from *reuse*\ **->socks**\ [] using the hash of the + * tuple. + * + * struct bpf_sock *bpf_sk_lookup_udp(void *ctx, struct bpf_sock_tuple *tuple, u32 tuple_size, u64 netns, u64 flags) + * Description + * Look for UDP socket matching *tuple*, optionally in a child + * network namespace *netns*. The return value must be checked, + * and if non-**NULL**, released via **bpf_sk_release**\ (). + * + * The *ctx* should point to the context of the program, such as + * the skb or socket (depending on the hook in use). This is used + * to determine the base network namespace for the lookup. + * + * *tuple_size* must be one of: + * + * **sizeof**\ (*tuple*\ **->ipv4**) + * Look for an IPv4 socket. + * **sizeof**\ (*tuple*\ **->ipv6**) + * Look for an IPv6 socket. + * + * If the *netns* is a negative signed 32-bit integer, then the + * socket lookup table in the netns associated with the *ctx* + * will be used. For the TC hooks, this is the netns of the device + * in the skb. For socket hooks, this is the netns of the socket. + * If *netns* is any other signed 32-bit value greater than or + * equal to zero then it specifies the ID of the netns relative to + * the netns associated with the *ctx*. *netns* values beyond the + * range of 32-bit integers are reserved for future use. + * + * All values for *flags* are reserved for future usage, and must + * be left at zero. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_NET** configuration option. + * Return + * Pointer to **struct bpf_sock**, or **NULL** in case of failure. + * For sockets with reuseport option, the **struct bpf_sock** + * result is from *reuse*\ **->socks**\ [] using the hash of the + * tuple. + * + * long bpf_sk_release(void *sock) + * Description + * Release the reference held by *sock*. *sock* must be a + * non-**NULL** pointer that was returned from + * **bpf_sk_lookup_xxx**\ (). + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_map_push_elem(struct bpf_map *map, const void *value, u64 flags) + * Description + * Push an element *value* in *map*. *flags* is one of: + * + * **BPF_EXIST** + * If the queue/stack is full, the oldest element is + * removed to make room for this. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_map_pop_elem(struct bpf_map *map, void *value) + * Description + * Pop an element from *map*. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_map_peek_elem(struct bpf_map *map, void *value) + * Description + * Get an element from *map* without removing it. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_msg_push_data(struct sk_msg_buff *msg, u32 start, u32 len, u64 flags) + * Description + * For socket policies, insert *len* bytes into *msg* at offset + * *start*. + * + * If a program of type **BPF_PROG_TYPE_SK_MSG** is run on a + * *msg* it may want to insert metadata or options into the *msg*. + * This can later be read and used by any of the lower layer BPF + * hooks. + * + * This helper may fail if under memory pressure (a malloc + * fails) in these cases BPF programs will get an appropriate + * error and BPF programs will need to handle them. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_msg_pop_data(struct sk_msg_buff *msg, u32 start, u32 len, u64 flags) + * Description + * Will remove *len* bytes from a *msg* starting at byte *start*. + * This may result in **ENOMEM** errors under certain situations if + * an allocation and copy are required due to a full ring buffer. + * However, the helper will try to avoid doing the allocation + * if possible. Other errors can occur if input parameters are + * invalid either due to *start* byte not being valid part of *msg* + * payload and/or *pop* value being to large. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_rc_pointer_rel(void *ctx, s32 rel_x, s32 rel_y) + * Description + * This helper is used in programs implementing IR decoding, to + * report a successfully decoded pointer movement. + * + * The *ctx* should point to the lirc sample as passed into + * the program. + * + * This helper is only available is the kernel was compiled with + * the **CONFIG_BPF_LIRC_MODE2** configuration option set to + * "**y**". + * Return + * 0 + * + * long bpf_spin_lock(struct bpf_spin_lock *lock) + * Description + * Acquire a spinlock represented by the pointer *lock*, which is + * stored as part of a value of a map. Taking the lock allows to + * safely update the rest of the fields in that value. The + * spinlock can (and must) later be released with a call to + * **bpf_spin_unlock**\ (\ *lock*\ ). + * + * Spinlocks in BPF programs come with a number of restrictions + * and constraints: + * + * * **bpf_spin_lock** objects are only allowed inside maps of + * types **BPF_MAP_TYPE_HASH** and **BPF_MAP_TYPE_ARRAY** (this + * list could be extended in the future). + * * BTF description of the map is mandatory. + * * The BPF program can take ONE lock at a time, since taking two + * or more could cause dead locks. + * * Only one **struct bpf_spin_lock** is allowed per map element. + * * When the lock is taken, calls (either BPF to BPF or helpers) + * are not allowed. + * * The **BPF_LD_ABS** and **BPF_LD_IND** instructions are not + * allowed inside a spinlock-ed region. + * * The BPF program MUST call **bpf_spin_unlock**\ () to release + * the lock, on all execution paths, before it returns. + * * The BPF program can access **struct bpf_spin_lock** only via + * the **bpf_spin_lock**\ () and **bpf_spin_unlock**\ () + * helpers. Loading or storing data into the **struct + * bpf_spin_lock** *lock*\ **;** field of a map is not allowed. + * * To use the **bpf_spin_lock**\ () helper, the BTF description + * of the map value must be a struct and have **struct + * bpf_spin_lock** *anyname*\ **;** field at the top level. + * Nested lock inside another struct is not allowed. + * * The **struct bpf_spin_lock** *lock* field in a map value must + * be aligned on a multiple of 4 bytes in that value. + * * Syscall with command **BPF_MAP_LOOKUP_ELEM** does not copy + * the **bpf_spin_lock** field to user space. + * * Syscall with command **BPF_MAP_UPDATE_ELEM**, or update from + * a BPF program, do not update the **bpf_spin_lock** field. + * * **bpf_spin_lock** cannot be on the stack or inside a + * networking packet (it can only be inside of a map values). + * * **bpf_spin_lock** is available to root only. + * * Tracing programs and socket filter programs cannot use + * **bpf_spin_lock**\ () due to insufficient preemption checks + * (but this may change in the future). + * * **bpf_spin_lock** is not allowed in inner maps of map-in-map. + * Return + * 0 + * + * long bpf_spin_unlock(struct bpf_spin_lock *lock) + * Description + * Release the *lock* previously locked by a call to + * **bpf_spin_lock**\ (\ *lock*\ ). + * Return + * 0 + * + * struct bpf_sock *bpf_sk_fullsock(struct bpf_sock *sk) + * Description + * This helper gets a **struct bpf_sock** pointer such + * that all the fields in this **bpf_sock** can be accessed. + * Return + * A **struct bpf_sock** pointer on success, or **NULL** in + * case of failure. + * + * struct bpf_tcp_sock *bpf_tcp_sock(struct bpf_sock *sk) + * Description + * This helper gets a **struct bpf_tcp_sock** pointer from a + * **struct bpf_sock** pointer. + * Return + * A **struct bpf_tcp_sock** pointer on success, or **NULL** in + * case of failure. + * + * long bpf_skb_ecn_set_ce(struct sk_buff *skb) + * Description + * Set ECN (Explicit Congestion Notification) field of IP header + * to **CE** (Congestion Encountered) if current value is **ECT** + * (ECN Capable Transport). Otherwise, do nothing. Works with IPv6 + * and IPv4. + * Return + * 1 if the **CE** flag is set (either by the current helper call + * or because it was already present), 0 if it is not set. + * + * struct bpf_sock *bpf_get_listener_sock(struct bpf_sock *sk) + * Description + * Return a **struct bpf_sock** pointer in **TCP_LISTEN** state. + * **bpf_sk_release**\ () is unnecessary and not allowed. + * Return + * A **struct bpf_sock** pointer on success, or **NULL** in + * case of failure. + * + * struct bpf_sock *bpf_skc_lookup_tcp(void *ctx, struct bpf_sock_tuple *tuple, u32 tuple_size, u64 netns, u64 flags) + * Description + * Look for TCP socket matching *tuple*, optionally in a child + * network namespace *netns*. The return value must be checked, + * and if non-**NULL**, released via **bpf_sk_release**\ (). + * + * This function is identical to **bpf_sk_lookup_tcp**\ (), except + * that it also returns timewait or request sockets. Use + * **bpf_sk_fullsock**\ () or **bpf_tcp_sock**\ () to access the + * full structure. + * + * This helper is available only if the kernel was compiled with + * **CONFIG_NET** configuration option. + * Return + * Pointer to **struct bpf_sock**, or **NULL** in case of failure. + * For sockets with reuseport option, the **struct bpf_sock** + * result is from *reuse*\ **->socks**\ [] using the hash of the + * tuple. + * + * long bpf_tcp_check_syncookie(void *sk, void *iph, u32 iph_len, struct tcphdr *th, u32 th_len) + * Description + * Check whether *iph* and *th* contain a valid SYN cookie ACK for + * the listening socket in *sk*. + * + * *iph* points to the start of the IPv4 or IPv6 header, while + * *iph_len* contains **sizeof**\ (**struct iphdr**) or + * **sizeof**\ (**struct ip6hdr**). + * + * *th* points to the start of the TCP header, while *th_len* + * contains **sizeof**\ (**struct tcphdr**). + * Return + * 0 if *iph* and *th* are a valid SYN cookie ACK, or a negative + * error otherwise. + * + * long bpf_sysctl_get_name(struct bpf_sysctl *ctx, char *buf, size_t buf_len, u64 flags) + * Description + * Get name of sysctl in /proc/sys/ and copy it into provided by + * program buffer *buf* of size *buf_len*. + * + * The buffer is always NUL terminated, unless it's zero-sized. + * + * If *flags* is zero, full name (e.g. "net/ipv4/tcp_mem") is + * copied. Use **BPF_F_SYSCTL_BASE_NAME** flag to copy base name + * only (e.g. "tcp_mem"). + * Return + * Number of character copied (not including the trailing NUL). + * + * **-E2BIG** if the buffer wasn't big enough (*buf* will contain + * truncated name in this case). + * + * long bpf_sysctl_get_current_value(struct bpf_sysctl *ctx, char *buf, size_t buf_len) + * Description + * Get current value of sysctl as it is presented in /proc/sys + * (incl. newline, etc), and copy it as a string into provided + * by program buffer *buf* of size *buf_len*. + * + * The whole value is copied, no matter what file position user + * space issued e.g. sys_read at. + * + * The buffer is always NUL terminated, unless it's zero-sized. + * Return + * Number of character copied (not including the trailing NUL). + * + * **-E2BIG** if the buffer wasn't big enough (*buf* will contain + * truncated name in this case). + * + * **-EINVAL** if current value was unavailable, e.g. because + * sysctl is uninitialized and read returns -EIO for it. + * + * long bpf_sysctl_get_new_value(struct bpf_sysctl *ctx, char *buf, size_t buf_len) + * Description + * Get new value being written by user space to sysctl (before + * the actual write happens) and copy it as a string into + * provided by program buffer *buf* of size *buf_len*. + * + * User space may write new value at file position > 0. + * + * The buffer is always NUL terminated, unless it's zero-sized. + * Return + * Number of character copied (not including the trailing NUL). + * + * **-E2BIG** if the buffer wasn't big enough (*buf* will contain + * truncated name in this case). + * + * **-EINVAL** if sysctl is being read. + * + * long bpf_sysctl_set_new_value(struct bpf_sysctl *ctx, const char *buf, size_t buf_len) + * Description + * Override new value being written by user space to sysctl with + * value provided by program in buffer *buf* of size *buf_len*. + * + * *buf* should contain a string in same form as provided by user + * space on sysctl write. + * + * User space may write new value at file position > 0. To override + * the whole sysctl value file position should be set to zero. + * Return + * 0 on success. + * + * **-E2BIG** if the *buf_len* is too big. + * + * **-EINVAL** if sysctl is being read. + * + * long bpf_strtol(const char *buf, size_t buf_len, u64 flags, long *res) + * Description + * Convert the initial part of the string from buffer *buf* of + * size *buf_len* to a long integer according to the given base + * and save the result in *res*. + * + * The string may begin with an arbitrary amount of white space + * (as determined by **isspace**\ (3)) followed by a single + * optional '**-**' sign. + * + * Five least significant bits of *flags* encode base, other bits + * are currently unused. + * + * Base must be either 8, 10, 16 or 0 to detect it automatically + * similar to user space **strtol**\ (3). + * Return + * Number of characters consumed on success. Must be positive but + * no more than *buf_len*. + * + * **-EINVAL** if no valid digits were found or unsupported base + * was provided. + * + * **-ERANGE** if resulting value was out of range. + * + * long bpf_strtoul(const char *buf, size_t buf_len, u64 flags, unsigned long *res) + * Description + * Convert the initial part of the string from buffer *buf* of + * size *buf_len* to an unsigned long integer according to the + * given base and save the result in *res*. + * + * The string may begin with an arbitrary amount of white space + * (as determined by **isspace**\ (3)). + * + * Five least significant bits of *flags* encode base, other bits + * are currently unused. + * + * Base must be either 8, 10, 16 or 0 to detect it automatically + * similar to user space **strtoul**\ (3). + * Return + * Number of characters consumed on success. Must be positive but + * no more than *buf_len*. + * + * **-EINVAL** if no valid digits were found or unsupported base + * was provided. + * + * **-ERANGE** if resulting value was out of range. + * + * void *bpf_sk_storage_get(struct bpf_map *map, void *sk, void *value, u64 flags) + * Description + * Get a bpf-local-storage from a *sk*. + * + * Logically, it could be thought of getting the value from + * a *map* with *sk* as the **key**. From this + * perspective, the usage is not much different from + * **bpf_map_lookup_elem**\ (*map*, **&**\ *sk*) except this + * helper enforces the key must be a full socket and the map must + * be a **BPF_MAP_TYPE_SK_STORAGE** also. + * + * Underneath, the value is stored locally at *sk* instead of + * the *map*. The *map* is used as the bpf-local-storage + * "type". The bpf-local-storage "type" (i.e. the *map*) is + * searched against all bpf-local-storages residing at *sk*. + * + * *sk* is a kernel **struct sock** pointer for LSM program. + * *sk* is a **struct bpf_sock** pointer for other program types. + * + * An optional *flags* (**BPF_SK_STORAGE_GET_F_CREATE**) can be + * used such that a new bpf-local-storage will be + * created if one does not exist. *value* can be used + * together with **BPF_SK_STORAGE_GET_F_CREATE** to specify + * the initial value of a bpf-local-storage. If *value* is + * **NULL**, the new bpf-local-storage will be zero initialized. + * Return + * A bpf-local-storage pointer is returned on success. + * + * **NULL** if not found or there was an error in adding + * a new bpf-local-storage. + * + * long bpf_sk_storage_delete(struct bpf_map *map, void *sk) + * Description + * Delete a bpf-local-storage from a *sk*. + * Return + * 0 on success. + * + * **-ENOENT** if the bpf-local-storage cannot be found. + * **-EINVAL** if sk is not a fullsock (e.g. a request_sock). + * + * long bpf_send_signal(u32 sig) + * Description + * Send signal *sig* to the process of the current task. + * The signal may be delivered to any of this process's threads. + * Return + * 0 on success or successfully queued. + * + * **-EBUSY** if work queue under nmi is full. + * + * **-EINVAL** if *sig* is invalid. + * + * **-EPERM** if no permission to send the *sig*. + * + * **-EAGAIN** if bpf program can try again. + * + * s64 bpf_tcp_gen_syncookie(void *sk, void *iph, u32 iph_len, struct tcphdr *th, u32 th_len) + * Description + * Try to issue a SYN cookie for the packet with corresponding + * IP/TCP headers, *iph* and *th*, on the listening socket in *sk*. + * + * *iph* points to the start of the IPv4 or IPv6 header, while + * *iph_len* contains **sizeof**\ (**struct iphdr**) or + * **sizeof**\ (**struct ip6hdr**). + * + * *th* points to the start of the TCP header, while *th_len* + * contains the length of the TCP header. + * Return + * On success, lower 32 bits hold the generated SYN cookie in + * followed by 16 bits which hold the MSS value for that cookie, + * and the top 16 bits are unused. + * + * On failure, the returned value is one of the following: + * + * **-EINVAL** SYN cookie cannot be issued due to error + * + * **-ENOENT** SYN cookie should not be issued (no SYN flood) + * + * **-EOPNOTSUPP** kernel configuration does not enable SYN cookies + * + * **-EPROTONOSUPPORT** IP packet version is not 4 or 6 + * + * long bpf_skb_output(void *ctx, struct bpf_map *map, u64 flags, void *data, u64 size) + * Description + * Write raw *data* blob into a special BPF perf event held by + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf + * event must have the following attributes: **PERF_SAMPLE_RAW** + * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and + * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. + * + * The *flags* are used to indicate the index in *map* for which + * the value must be put, masked with **BPF_F_INDEX_MASK**. + * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** + * to indicate that the index of the current CPU core should be + * used. + * + * The value to write, of *size*, is passed through eBPF stack and + * pointed by *data*. + * + * *ctx* is a pointer to in-kernel struct sk_buff. + * + * This helper is similar to **bpf_perf_event_output**\ () but + * restricted to raw_tracepoint bpf programs. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_probe_read_user(void *dst, u32 size, const void *unsafe_ptr) + * Description + * Safely attempt to read *size* bytes from user space address + * *unsafe_ptr* and store the data in *dst*. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_probe_read_kernel(void *dst, u32 size, const void *unsafe_ptr) + * Description + * Safely attempt to read *size* bytes from kernel space address + * *unsafe_ptr* and store the data in *dst*. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_probe_read_user_str(void *dst, u32 size, const void *unsafe_ptr) + * Description + * Copy a NUL terminated string from an unsafe user address + * *unsafe_ptr* to *dst*. The *size* should include the + * terminating NUL byte. In case the string length is smaller than + * *size*, the target is not padded with further NUL bytes. If the + * string length is larger than *size*, just *size*-1 bytes are + * copied and the last byte is set to NUL. + * + * On success, the length of the copied string is returned. This + * makes this helper useful in tracing programs for reading + * strings, and more importantly to get its length at runtime. See + * the following snippet: + * + * :: + * + * SEC("kprobe/sys_open") + * void bpf_sys_open(struct pt_regs *ctx) + * { + * char buf[PATHLEN]; // PATHLEN is defined to 256 + * int res = bpf_probe_read_user_str(buf, sizeof(buf), + * ctx->di); + * + * // Consume buf, for example push it to + * // userspace via bpf_perf_event_output(); we + * // can use res (the string length) as event + * // size, after checking its boundaries. + * } + * + * In comparison, using **bpf_probe_read_user**\ () helper here + * instead to read the string would require to estimate the length + * at compile time, and would often result in copying more memory + * than necessary. + * + * Another useful use case is when parsing individual process + * arguments or individual environment variables navigating + * *current*\ **->mm->arg_start** and *current*\ + * **->mm->env_start**: using this helper and the return value, + * one can quickly iterate at the right offset of the memory area. + * Return + * On success, the strictly positive length of the string, + * including the trailing NUL character. On error, a negative + * value. + * + * long bpf_probe_read_kernel_str(void *dst, u32 size, const void *unsafe_ptr) + * Description + * Copy a NUL terminated string from an unsafe kernel address *unsafe_ptr* + * to *dst*. Same semantics as with **bpf_probe_read_user_str**\ () apply. + * Return + * On success, the strictly positive length of the string, including + * the trailing NUL character. On error, a negative value. + * + * long bpf_tcp_send_ack(void *tp, u32 rcv_nxt) + * Description + * Send out a tcp-ack. *tp* is the in-kernel struct **tcp_sock**. + * *rcv_nxt* is the ack_seq to be sent out. + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_send_signal_thread(u32 sig) + * Description + * Send signal *sig* to the thread corresponding to the current task. + * Return + * 0 on success or successfully queued. + * + * **-EBUSY** if work queue under nmi is full. + * + * **-EINVAL** if *sig* is invalid. + * + * **-EPERM** if no permission to send the *sig*. + * + * **-EAGAIN** if bpf program can try again. + * + * u64 bpf_jiffies64(void) + * Description + * Obtain the 64bit jiffies + * Return + * The 64 bit jiffies + * + * long bpf_read_branch_records(struct bpf_perf_event_data *ctx, void *buf, u32 size, u64 flags) + * Description + * For an eBPF program attached to a perf event, retrieve the + * branch records (**struct perf_branch_entry**) associated to *ctx* + * and store it in the buffer pointed by *buf* up to size + * *size* bytes. + * Return + * On success, number of bytes written to *buf*. On error, a + * negative value. + * + * The *flags* can be set to **BPF_F_GET_BRANCH_RECORDS_SIZE** to + * instead return the number of bytes required to store all the + * branch entries. If this flag is set, *buf* may be NULL. + * + * **-EINVAL** if arguments invalid or **size** not a multiple + * of **sizeof**\ (**struct perf_branch_entry**\ ). + * + * **-ENOENT** if architecture does not support branch records. + * + * long bpf_get_ns_current_pid_tgid(u64 dev, u64 ino, struct bpf_pidns_info *nsdata, u32 size) + * Description + * Returns 0 on success, values for *pid* and *tgid* as seen from the current + * *namespace* will be returned in *nsdata*. + * Return + * 0 on success, or one of the following in case of failure: + * + * **-EINVAL** if dev and inum supplied don't match dev_t and inode number + * with nsfs of current task, or if dev conversion to dev_t lost high bits. + * + * **-ENOENT** if pidns does not exists for the current task. + * + * long bpf_xdp_output(void *ctx, struct bpf_map *map, u64 flags, void *data, u64 size) + * Description + * Write raw *data* blob into a special BPF perf event held by + * *map* of type **BPF_MAP_TYPE_PERF_EVENT_ARRAY**. This perf + * event must have the following attributes: **PERF_SAMPLE_RAW** + * as **sample_type**, **PERF_TYPE_SOFTWARE** as **type**, and + * **PERF_COUNT_SW_BPF_OUTPUT** as **config**. + * + * The *flags* are used to indicate the index in *map* for which + * the value must be put, masked with **BPF_F_INDEX_MASK**. + * Alternatively, *flags* can be set to **BPF_F_CURRENT_CPU** + * to indicate that the index of the current CPU core should be + * used. + * + * The value to write, of *size*, is passed through eBPF stack and + * pointed by *data*. + * + * *ctx* is a pointer to in-kernel struct xdp_buff. + * + * This helper is similar to **bpf_perf_eventoutput**\ () but + * restricted to raw_tracepoint bpf programs. + * Return + * 0 on success, or a negative error in case of failure. + * + * u64 bpf_get_netns_cookie(void *ctx) + * Description + * Retrieve the cookie (generated by the kernel) of the network + * namespace the input *ctx* is associated with. The network + * namespace cookie remains stable for its lifetime and provides + * a global identifier that can be assumed unique. If *ctx* is + * NULL, then the helper returns the cookie for the initial + * network namespace. The cookie itself is very similar to that + * of **bpf_get_socket_cookie**\ () helper, but for network + * namespaces instead of sockets. + * Return + * A 8-byte long opaque number. + * + * u64 bpf_get_current_ancestor_cgroup_id(int ancestor_level) + * Description + * Return id of cgroup v2 that is ancestor of the cgroup associated + * with the current task at the *ancestor_level*. The root cgroup + * is at *ancestor_level* zero and each step down the hierarchy + * increments the level. If *ancestor_level* == level of cgroup + * associated with the current task, then return value will be the + * same as that of **bpf_get_current_cgroup_id**\ (). + * + * The helper is useful to implement policies based on cgroups + * that are upper in hierarchy than immediate cgroup associated + * with the current task. + * + * The format of returned id and helper limitations are same as in + * **bpf_get_current_cgroup_id**\ (). + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * long bpf_sk_assign(struct sk_buff *skb, void *sk, u64 flags) + * Description + * Helper is overloaded depending on BPF program type. This + * description applies to **BPF_PROG_TYPE_SCHED_CLS** and + * **BPF_PROG_TYPE_SCHED_ACT** programs. + * + * Assign the *sk* to the *skb*. When combined with appropriate + * routing configuration to receive the packet towards the socket, + * will cause *skb* to be delivered to the specified socket. + * Subsequent redirection of *skb* via **bpf_redirect**\ (), + * **bpf_clone_redirect**\ () or other methods outside of BPF may + * interfere with successful delivery to the socket. + * + * This operation is only valid from TC ingress path. + * + * The *flags* argument must be zero. + * Return + * 0 on success, or a negative error in case of failure: + * + * **-EINVAL** if specified *flags* are not supported. + * + * **-ENOENT** if the socket is unavailable for assignment. + * + * **-ENETUNREACH** if the socket is unreachable (wrong netns). + * + * **-EOPNOTSUPP** if the operation is not supported, for example + * a call from outside of TC ingress. + * + * **-ESOCKTNOSUPPORT** if the socket type is not supported + * (reuseport). + * + * long bpf_sk_assign(struct bpf_sk_lookup *ctx, struct bpf_sock *sk, u64 flags) + * Description + * Helper is overloaded depending on BPF program type. This + * description applies to **BPF_PROG_TYPE_SK_LOOKUP** programs. + * + * Select the *sk* as a result of a socket lookup. + * + * For the operation to succeed passed socket must be compatible + * with the packet description provided by the *ctx* object. + * + * L4 protocol (**IPPROTO_TCP** or **IPPROTO_UDP**) must + * be an exact match. While IP family (**AF_INET** or + * **AF_INET6**) must be compatible, that is IPv6 sockets + * that are not v6-only can be selected for IPv4 packets. + * + * Only TCP listeners and UDP unconnected sockets can be + * selected. *sk* can also be NULL to reset any previous + * selection. + * + * *flags* argument can combination of following values: + * + * * **BPF_SK_LOOKUP_F_REPLACE** to override the previous + * socket selection, potentially done by a BPF program + * that ran before us. + * + * * **BPF_SK_LOOKUP_F_NO_REUSEPORT** to skip + * load-balancing within reuseport group for the socket + * being selected. + * + * On success *ctx->sk* will point to the selected socket. + * + * Return + * 0 on success, or a negative errno in case of failure. + * + * * **-EAFNOSUPPORT** if socket family (*sk->family*) is + * not compatible with packet family (*ctx->family*). + * + * * **-EEXIST** if socket has been already selected, + * potentially by another program, and + * **BPF_SK_LOOKUP_F_REPLACE** flag was not specified. + * + * * **-EINVAL** if unsupported flags were specified. + * + * * **-EPROTOTYPE** if socket L4 protocol + * (*sk->protocol*) doesn't match packet protocol + * (*ctx->protocol*). + * + * * **-ESOCKTNOSUPPORT** if socket is not in allowed + * state (TCP listening or UDP unconnected). + * + * u64 bpf_ktime_get_boot_ns(void) + * Description + * Return the time elapsed since system boot, in nanoseconds. + * Does include the time the system was suspended. + * See: **clock_gettime**\ (**CLOCK_BOOTTIME**) + * Return + * Current *ktime*. + * + * long bpf_seq_printf(struct seq_file *m, const char *fmt, u32 fmt_size, const void *data, u32 data_len) + * Description + * **bpf_seq_printf**\ () uses seq_file **seq_printf**\ () to print + * out the format string. + * The *m* represents the seq_file. The *fmt* and *fmt_size* are for + * the format string itself. The *data* and *data_len* are format string + * arguments. The *data* are a **u64** array and corresponding format string + * values are stored in the array. For strings and pointers where pointees + * are accessed, only the pointer values are stored in the *data* array. + * The *data_len* is the size of *data* in bytes. + * + * Formats **%s**, **%p{i,I}{4,6}** requires to read kernel memory. + * Reading kernel memory may fail due to either invalid address or + * valid address but requiring a major memory fault. If reading kernel memory + * fails, the string for **%s** will be an empty string, and the ip + * address for **%p{i,I}{4,6}** will be 0. Not returning error to + * bpf program is consistent with what **bpf_trace_printk**\ () does for now. + * Return + * 0 on success, or a negative error in case of failure: + * + * **-EBUSY** if per-CPU memory copy buffer is busy, can try again + * by returning 1 from bpf program. + * + * **-EINVAL** if arguments are invalid, or if *fmt* is invalid/unsupported. + * + * **-E2BIG** if *fmt* contains too many format specifiers. + * + * **-EOVERFLOW** if an overflow happened: The same object will be tried again. + * + * long bpf_seq_write(struct seq_file *m, const void *data, u32 len) + * Description + * **bpf_seq_write**\ () uses seq_file **seq_write**\ () to write the data. + * The *m* represents the seq_file. The *data* and *len* represent the + * data to write in bytes. + * Return + * 0 on success, or a negative error in case of failure: + * + * **-EOVERFLOW** if an overflow happened: The same object will be tried again. + * + * u64 bpf_sk_cgroup_id(void *sk) + * Description + * Return the cgroup v2 id of the socket *sk*. + * + * *sk* must be a non-**NULL** pointer to a socket, e.g. one + * returned from **bpf_sk_lookup_xxx**\ (), + * **bpf_sk_fullsock**\ (), etc. The format of returned id is + * same as in **bpf_skb_cgroup_id**\ (). + * + * This helper is available only if the kernel was compiled with + * the **CONFIG_SOCK_CGROUP_DATA** configuration option. + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * u64 bpf_sk_ancestor_cgroup_id(void *sk, int ancestor_level) + * Description + * Return id of cgroup v2 that is ancestor of cgroup associated + * with the *sk* at the *ancestor_level*. The root cgroup is at + * *ancestor_level* zero and each step down the hierarchy + * increments the level. If *ancestor_level* == level of cgroup + * associated with *sk*, then return value will be same as that + * of **bpf_sk_cgroup_id**\ (). + * + * The helper is useful to implement policies based on cgroups + * that are upper in hierarchy than immediate cgroup associated + * with *sk*. + * + * The format of returned id and helper limitations are same as in + * **bpf_sk_cgroup_id**\ (). + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * long bpf_ringbuf_output(void *ringbuf, void *data, u64 size, u64 flags) + * Description + * Copy *size* bytes from *data* into a ring buffer *ringbuf*. + * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification + * of new data availability is sent. + * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification + * of new data availability is sent unconditionally. + * Return + * 0 on success, or a negative error in case of failure. + * + * void *bpf_ringbuf_reserve(void *ringbuf, u64 size, u64 flags) + * Description + * Reserve *size* bytes of payload in a ring buffer *ringbuf*. + * Return + * Valid pointer with *size* bytes of memory available; NULL, + * otherwise. + * + * void bpf_ringbuf_submit(void *data, u64 flags) + * Description + * Submit reserved ring buffer sample, pointed to by *data*. + * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification + * of new data availability is sent. + * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification + * of new data availability is sent unconditionally. + * Return + * Nothing. Always succeeds. + * + * void bpf_ringbuf_discard(void *data, u64 flags) + * Description + * Discard reserved ring buffer sample, pointed to by *data*. + * If **BPF_RB_NO_WAKEUP** is specified in *flags*, no notification + * of new data availability is sent. + * If **BPF_RB_FORCE_WAKEUP** is specified in *flags*, notification + * of new data availability is sent unconditionally. + * Return + * Nothing. Always succeeds. + * + * u64 bpf_ringbuf_query(void *ringbuf, u64 flags) + * Description + * Query various characteristics of provided ring buffer. What + * exactly is queries is determined by *flags*: + * + * * **BPF_RB_AVAIL_DATA**: Amount of data not yet consumed. + * * **BPF_RB_RING_SIZE**: The size of ring buffer. + * * **BPF_RB_CONS_POS**: Consumer position (can wrap around). + * * **BPF_RB_PROD_POS**: Producer(s) position (can wrap around). + * + * Data returned is just a momentary snapshot of actual values + * and could be inaccurate, so this facility should be used to + * power heuristics and for reporting, not to make 100% correct + * calculation. + * Return + * Requested value, or 0, if *flags* are not recognized. + * + * long bpf_csum_level(struct sk_buff *skb, u64 level) + * Description + * Change the skbs checksum level by one layer up or down, or + * reset it entirely to none in order to have the stack perform + * checksum validation. The level is applicable to the following + * protocols: TCP, UDP, GRE, SCTP, FCOE. For example, a decap of + * | ETH | IP | UDP | GUE | IP | TCP | into | ETH | IP | TCP | + * through **bpf_skb_adjust_room**\ () helper with passing in + * **BPF_F_ADJ_ROOM_NO_CSUM_RESET** flag would require one call + * to **bpf_csum_level**\ () with **BPF_CSUM_LEVEL_DEC** since + * the UDP header is removed. Similarly, an encap of the latter + * into the former could be accompanied by a helper call to + * **bpf_csum_level**\ () with **BPF_CSUM_LEVEL_INC** if the + * skb is still intended to be processed in higher layers of the + * stack instead of just egressing at tc. + * + * There are three supported level settings at this time: + * + * * **BPF_CSUM_LEVEL_INC**: Increases skb->csum_level for skbs + * with CHECKSUM_UNNECESSARY. + * * **BPF_CSUM_LEVEL_DEC**: Decreases skb->csum_level for skbs + * with CHECKSUM_UNNECESSARY. + * * **BPF_CSUM_LEVEL_RESET**: Resets skb->csum_level to 0 and + * sets CHECKSUM_NONE to force checksum validation by the stack. + * * **BPF_CSUM_LEVEL_QUERY**: No-op, returns the current + * skb->csum_level. + * Return + * 0 on success, or a negative error in case of failure. In the + * case of **BPF_CSUM_LEVEL_QUERY**, the current skb->csum_level + * is returned or the error code -EACCES in case the skb is not + * subject to CHECKSUM_UNNECESSARY. + * + * struct tcp6_sock *bpf_skc_to_tcp6_sock(void *sk) + * Description + * Dynamically cast a *sk* pointer to a *tcp6_sock* pointer. + * Return + * *sk* if casting is valid, or **NULL** otherwise. + * + * struct tcp_sock *bpf_skc_to_tcp_sock(void *sk) + * Description + * Dynamically cast a *sk* pointer to a *tcp_sock* pointer. + * Return + * *sk* if casting is valid, or **NULL** otherwise. + * + * struct tcp_timewait_sock *bpf_skc_to_tcp_timewait_sock(void *sk) + * Description + * Dynamically cast a *sk* pointer to a *tcp_timewait_sock* pointer. + * Return + * *sk* if casting is valid, or **NULL** otherwise. + * + * struct tcp_request_sock *bpf_skc_to_tcp_request_sock(void *sk) + * Description + * Dynamically cast a *sk* pointer to a *tcp_request_sock* pointer. + * Return + * *sk* if casting is valid, or **NULL** otherwise. + * + * struct udp6_sock *bpf_skc_to_udp6_sock(void *sk) + * Description + * Dynamically cast a *sk* pointer to a *udp6_sock* pointer. + * Return + * *sk* if casting is valid, or **NULL** otherwise. + * + * long bpf_get_task_stack(struct task_struct *task, void *buf, u32 size, u64 flags) + * Description + * Return a user or a kernel stack in bpf program provided buffer. + * To achieve this, the helper needs *task*, which is a valid + * pointer to **struct task_struct**. To store the stacktrace, the + * bpf program provides *buf* with a nonnegative *size*. + * + * The last argument, *flags*, holds the number of stack frames to + * skip (from 0 to 255), masked with + * **BPF_F_SKIP_FIELD_MASK**. The next bits can be used to set + * the following flags: + * + * **BPF_F_USER_STACK** + * Collect a user space stack instead of a kernel stack. + * **BPF_F_USER_BUILD_ID** + * Collect buildid+offset instead of ips for user stack, + * only valid if **BPF_F_USER_STACK** is also specified. + * + * **bpf_get_task_stack**\ () can collect up to + * **PERF_MAX_STACK_DEPTH** both kernel and user frames, subject + * to sufficient large buffer size. Note that + * this limit can be controlled with the **sysctl** program, and + * that it should be manually increased in order to profile long + * user stacks (such as stacks for Java programs). To do so, use: + * + * :: + * + * # sysctl kernel.perf_event_max_stack= + * Return + * A non-negative value equal to or less than *size* on success, + * or a negative error in case of failure. + * + * long bpf_load_hdr_opt(struct bpf_sock_ops *skops, void *searchby_res, u32 len, u64 flags) + * Description + * Load header option. Support reading a particular TCP header + * option for bpf program (**BPF_PROG_TYPE_SOCK_OPS**). + * + * If *flags* is 0, it will search the option from the + * *skops*\ **->skb_data**. The comment in **struct bpf_sock_ops** + * has details on what skb_data contains under different + * *skops*\ **->op**. + * + * The first byte of the *searchby_res* specifies the + * kind that it wants to search. + * + * If the searching kind is an experimental kind + * (i.e. 253 or 254 according to RFC6994). It also + * needs to specify the "magic" which is either + * 2 bytes or 4 bytes. It then also needs to + * specify the size of the magic by using + * the 2nd byte which is "kind-length" of a TCP + * header option and the "kind-length" also + * includes the first 2 bytes "kind" and "kind-length" + * itself as a normal TCP header option also does. + * + * For example, to search experimental kind 254 with + * 2 byte magic 0xeB9F, the searchby_res should be + * [ 254, 4, 0xeB, 0x9F, 0, 0, .... 0 ]. + * + * To search for the standard window scale option (3), + * the *searchby_res* should be [ 3, 0, 0, .... 0 ]. + * Note, kind-length must be 0 for regular option. + * + * Searching for No-Op (0) and End-of-Option-List (1) are + * not supported. + * + * *len* must be at least 2 bytes which is the minimal size + * of a header option. + * + * Supported flags: + * + * * **BPF_LOAD_HDR_OPT_TCP_SYN** to search from the + * saved_syn packet or the just-received syn packet. + * + * Return + * > 0 when found, the header option is copied to *searchby_res*. + * The return value is the total length copied. On failure, a + * negative error code is returned: + * + * **-EINVAL** if a parameter is invalid. + * + * **-ENOMSG** if the option is not found. + * + * **-ENOENT** if no syn packet is available when + * **BPF_LOAD_HDR_OPT_TCP_SYN** is used. + * + * **-ENOSPC** if there is not enough space. Only *len* number of + * bytes are copied. + * + * **-EFAULT** on failure to parse the header options in the + * packet. + * + * **-EPERM** if the helper cannot be used under the current + * *skops*\ **->op**. + * + * long bpf_store_hdr_opt(struct bpf_sock_ops *skops, const void *from, u32 len, u64 flags) + * Description + * Store header option. The data will be copied + * from buffer *from* with length *len* to the TCP header. + * + * The buffer *from* should have the whole option that + * includes the kind, kind-length, and the actual + * option data. The *len* must be at least kind-length + * long. The kind-length does not have to be 4 byte + * aligned. The kernel will take care of the padding + * and setting the 4 bytes aligned value to th->doff. + * + * This helper will check for duplicated option + * by searching the same option in the outgoing skb. + * + * This helper can only be called during + * **BPF_SOCK_OPS_WRITE_HDR_OPT_CB**. + * + * Return + * 0 on success, or negative error in case of failure: + * + * **-EINVAL** If param is invalid. + * + * **-ENOSPC** if there is not enough space in the header. + * Nothing has been written + * + * **-EEXIST** if the option already exists. + * + * **-EFAULT** on failrue to parse the existing header options. + * + * **-EPERM** if the helper cannot be used under the current + * *skops*\ **->op**. + * + * long bpf_reserve_hdr_opt(struct bpf_sock_ops *skops, u32 len, u64 flags) + * Description + * Reserve *len* bytes for the bpf header option. The + * space will be used by **bpf_store_hdr_opt**\ () later in + * **BPF_SOCK_OPS_WRITE_HDR_OPT_CB**. + * + * If **bpf_reserve_hdr_opt**\ () is called multiple times, + * the total number of bytes will be reserved. + * + * This helper can only be called during + * **BPF_SOCK_OPS_HDR_OPT_LEN_CB**. + * + * Return + * 0 on success, or negative error in case of failure: + * + * **-EINVAL** if a parameter is invalid. + * + * **-ENOSPC** if there is not enough space in the header. + * + * **-EPERM** if the helper cannot be used under the current + * *skops*\ **->op**. + * + * void *bpf_inode_storage_get(struct bpf_map *map, void *inode, void *value, u64 flags) + * Description + * Get a bpf_local_storage from an *inode*. + * + * Logically, it could be thought of as getting the value from + * a *map* with *inode* as the **key**. From this + * perspective, the usage is not much different from + * **bpf_map_lookup_elem**\ (*map*, **&**\ *inode*) except this + * helper enforces the key must be an inode and the map must also + * be a **BPF_MAP_TYPE_INODE_STORAGE**. + * + * Underneath, the value is stored locally at *inode* instead of + * the *map*. The *map* is used as the bpf-local-storage + * "type". The bpf-local-storage "type" (i.e. the *map*) is + * searched against all bpf_local_storage residing at *inode*. + * + * An optional *flags* (**BPF_LOCAL_STORAGE_GET_F_CREATE**) can be + * used such that a new bpf_local_storage will be + * created if one does not exist. *value* can be used + * together with **BPF_LOCAL_STORAGE_GET_F_CREATE** to specify + * the initial value of a bpf_local_storage. If *value* is + * **NULL**, the new bpf_local_storage will be zero initialized. + * Return + * A bpf_local_storage pointer is returned on success. + * + * **NULL** if not found or there was an error in adding + * a new bpf_local_storage. + * + * int bpf_inode_storage_delete(struct bpf_map *map, void *inode) + * Description + * Delete a bpf_local_storage from an *inode*. + * Return + * 0 on success. + * + * **-ENOENT** if the bpf_local_storage cannot be found. + * + * long bpf_d_path(struct path *path, char *buf, u32 sz) + * Description + * Return full path for given **struct path** object, which + * needs to be the kernel BTF *path* object. The path is + * returned in the provided buffer *buf* of size *sz* and + * is zero terminated. + * + * Return + * On success, the strictly positive length of the string, + * including the trailing NUL character. On error, a negative + * value. + * + * long bpf_copy_from_user(void *dst, u32 size, const void *user_ptr) + * Description + * Read *size* bytes from user space address *user_ptr* and store + * the data in *dst*. This is a wrapper of **copy_from_user**\ (). + * Return + * 0 on success, or a negative error in case of failure. + * + * long bpf_snprintf_btf(char *str, u32 str_size, struct btf_ptr *ptr, u32 btf_ptr_size, u64 flags) + * Description + * Use BTF to store a string representation of *ptr*->ptr in *str*, + * using *ptr*->type_id. This value should specify the type + * that *ptr*->ptr points to. LLVM __builtin_btf_type_id(type, 1) + * can be used to look up vmlinux BTF type ids. Traversing the + * data structure using BTF, the type information and values are + * stored in the first *str_size* - 1 bytes of *str*. Safe copy of + * the pointer data is carried out to avoid kernel crashes during + * operation. Smaller types can use string space on the stack; + * larger programs can use map data to store the string + * representation. + * + * The string can be subsequently shared with userspace via + * bpf_perf_event_output() or ring buffer interfaces. + * bpf_trace_printk() is to be avoided as it places too small + * a limit on string size to be useful. + * + * *flags* is a combination of + * + * **BTF_F_COMPACT** + * no formatting around type information + * **BTF_F_NONAME** + * no struct/union member names/types + * **BTF_F_PTR_RAW** + * show raw (unobfuscated) pointer values; + * equivalent to printk specifier %px. + * **BTF_F_ZERO** + * show zero-valued struct/union members; they + * are not displayed by default + * + * Return + * The number of bytes that were written (or would have been + * written if output had to be truncated due to string size), + * or a negative error in cases of failure. + * + * long bpf_seq_printf_btf(struct seq_file *m, struct btf_ptr *ptr, u32 ptr_size, u64 flags) + * Description + * Use BTF to write to seq_write a string representation of + * *ptr*->ptr, using *ptr*->type_id as per bpf_snprintf_btf(). + * *flags* are identical to those used for bpf_snprintf_btf. + * Return + * 0 on success or a negative error in case of failure. + * + * u64 bpf_skb_cgroup_classid(struct sk_buff *skb) + * Description + * See **bpf_get_cgroup_classid**\ () for the main description. + * This helper differs from **bpf_get_cgroup_classid**\ () in that + * the cgroup v1 net_cls class is retrieved only from the *skb*'s + * associated socket instead of the current process. + * Return + * The id is returned or 0 in case the id could not be retrieved. + * + * long bpf_redirect_neigh(u32 ifindex, struct bpf_redir_neigh *params, int plen, u64 flags) + * Description + * Redirect the packet to another net device of index *ifindex* + * and fill in L2 addresses from neighboring subsystem. This helper + * is somewhat similar to **bpf_redirect**\ (), except that it + * populates L2 addresses as well, meaning, internally, the helper + * relies on the neighbor lookup for the L2 address of the nexthop. + * + * The helper will perform a FIB lookup based on the skb's + * networking header to get the address of the next hop, unless + * this is supplied by the caller in the *params* argument. The + * *plen* argument indicates the len of *params* and should be set + * to 0 if *params* is NULL. + * + * The *flags* argument is reserved and must be 0. The helper is + * currently only supported for tc BPF program types, and enabled + * for IPv4 and IPv6 protocols. + * Return + * The helper returns **TC_ACT_REDIRECT** on success or + * **TC_ACT_SHOT** on error. + * + * void *bpf_per_cpu_ptr(const void *percpu_ptr, u32 cpu) + * Description + * Take a pointer to a percpu ksym, *percpu_ptr*, and return a + * pointer to the percpu kernel variable on *cpu*. A ksym is an + * extern variable decorated with '__ksym'. For ksym, there is a + * global var (either static or global) defined of the same name + * in the kernel. The ksym is percpu if the global var is percpu. + * The returned pointer points to the global percpu var on *cpu*. + * + * bpf_per_cpu_ptr() has the same semantic as per_cpu_ptr() in the + * kernel, except that bpf_per_cpu_ptr() may return NULL. This + * happens if *cpu* is larger than nr_cpu_ids. The caller of + * bpf_per_cpu_ptr() must check the returned value. + * Return + * A pointer pointing to the kernel percpu variable on *cpu*, or + * NULL, if *cpu* is invalid. + * + * void *bpf_this_cpu_ptr(const void *percpu_ptr) + * Description + * Take a pointer to a percpu ksym, *percpu_ptr*, and return a + * pointer to the percpu kernel variable on this cpu. See the + * description of 'ksym' in **bpf_per_cpu_ptr**\ (). + * + * bpf_this_cpu_ptr() has the same semantic as this_cpu_ptr() in + * the kernel. Different from **bpf_per_cpu_ptr**\ (), it would + * never return NULL. + * Return + * A pointer pointing to the kernel percpu variable on this cpu. + * + * long bpf_redirect_peer(u32 ifindex, u64 flags) + * Description + * Redirect the packet to another net device of index *ifindex*. + * This helper is somewhat similar to **bpf_redirect**\ (), except + * that the redirection happens to the *ifindex*' peer device and + * the netns switch takes place from ingress to ingress without + * going through the CPU's backlog queue. + * + * The *flags* argument is reserved and must be 0. The helper is + * currently only supported for tc BPF program types at the ingress + * hook and for veth device types. The peer device must reside in a + * different network namespace. + * Return + * The helper returns **TC_ACT_REDIRECT** on success or + * **TC_ACT_SHOT** on error. + * + * void *bpf_task_storage_get(struct bpf_map *map, struct task_struct *task, void *value, u64 flags) + * Description + * Get a bpf_local_storage from the *task*. + * + * Logically, it could be thought of as getting the value from + * a *map* with *task* as the **key**. From this + * perspective, the usage is not much different from + * **bpf_map_lookup_elem**\ (*map*, **&**\ *task*) except this + * helper enforces the key must be an task_struct and the map must also + * be a **BPF_MAP_TYPE_TASK_STORAGE**. + * + * Underneath, the value is stored locally at *task* instead of + * the *map*. The *map* is used as the bpf-local-storage + * "type". The bpf-local-storage "type" (i.e. the *map*) is + * searched against all bpf_local_storage residing at *task*. + * + * An optional *flags* (**BPF_LOCAL_STORAGE_GET_F_CREATE**) can be + * used such that a new bpf_local_storage will be + * created if one does not exist. *value* can be used + * together with **BPF_LOCAL_STORAGE_GET_F_CREATE** to specify + * the initial value of a bpf_local_storage. If *value* is + * **NULL**, the new bpf_local_storage will be zero initialized. + * Return + * A bpf_local_storage pointer is returned on success. + * + * **NULL** if not found or there was an error in adding + * a new bpf_local_storage. + * + * long bpf_task_storage_delete(struct bpf_map *map, struct task_struct *task) + * Description + * Delete a bpf_local_storage from a *task*. + * Return + * 0 on success. + * + * **-ENOENT** if the bpf_local_storage cannot be found. + * + * struct task_struct *bpf_get_current_task_btf(void) + * Description + * Return a BTF pointer to the "current" task. + * This pointer can also be used in helpers that accept an + * *ARG_PTR_TO_BTF_ID* of type *task_struct*. + * Return + * Pointer to the current task. + * + * long bpf_bprm_opts_set(struct linux_binprm *bprm, u64 flags) + * Description + * Set or clear certain options on *bprm*: + * + * **BPF_F_BPRM_SECUREEXEC** Set the secureexec bit + * which sets the **AT_SECURE** auxv for glibc. The bit + * is cleared if the flag is not specified. + * Return + * **-EINVAL** if invalid *flags* are passed, zero otherwise. + * + * u64 bpf_ktime_get_coarse_ns(void) + * Description + * Return a coarse-grained version of the time elapsed since + * system boot, in nanoseconds. Does not include time the system + * was suspended. + * + * See: **clock_gettime**\ (**CLOCK_MONOTONIC_COARSE**) + * Return + * Current *ktime*. + * + * long bpf_ima_inode_hash(struct inode *inode, void *dst, u32 size) + * Description + * Returns the stored IMA hash of the *inode* (if it's avaialable). + * If the hash is larger than *size*, then only *size* + * bytes will be copied to *dst* + * Return + * The **hash_algo** is returned on success, + * **-EOPNOTSUP** if IMA is disabled or **-EINVAL** if + * invalid arguments are passed. + * + * struct socket *bpf_sock_from_file(struct file *file) + * Description + * If the given file represents a socket, returns the associated + * socket. + * Return + * A pointer to a struct socket on success or NULL if the file is + * not a socket. + */ +#define __BPF_FUNC_MAPPER(FN) \ + FN(unspec), \ + FN(map_lookup_elem), \ + FN(map_update_elem), \ + FN(map_delete_elem), \ + FN(probe_read), \ + FN(ktime_get_ns), \ + FN(trace_printk), \ + FN(get_prandom_u32), \ + FN(get_smp_processor_id), \ + FN(skb_store_bytes), \ + FN(l3_csum_replace), \ + FN(l4_csum_replace), \ + FN(tail_call), \ + FN(clone_redirect), \ + FN(get_current_pid_tgid), \ + FN(get_current_uid_gid), \ + FN(get_current_comm), \ + FN(get_cgroup_classid), \ + FN(skb_vlan_push), \ + FN(skb_vlan_pop), \ + FN(skb_get_tunnel_key), \ + FN(skb_set_tunnel_key), \ + FN(perf_event_read), \ + FN(redirect), \ + FN(get_route_realm), \ + FN(perf_event_output), \ + FN(skb_load_bytes), \ + FN(get_stackid), \ + FN(csum_diff), \ + FN(skb_get_tunnel_opt), \ + FN(skb_set_tunnel_opt), \ + FN(skb_change_proto), \ + FN(skb_change_type), \ + FN(skb_under_cgroup), \ + FN(get_hash_recalc), \ + FN(get_current_task), \ + FN(probe_write_user), \ + FN(current_task_under_cgroup), \ + FN(skb_change_tail), \ + FN(skb_pull_data), \ + FN(csum_update), \ + FN(set_hash_invalid), \ + FN(get_numa_node_id), \ + FN(skb_change_head), \ + FN(xdp_adjust_head), \ + FN(probe_read_str), \ + FN(get_socket_cookie), \ + FN(get_socket_uid), \ + FN(set_hash), \ + FN(setsockopt), \ + FN(skb_adjust_room), \ + FN(redirect_map), \ + FN(sk_redirect_map), \ + FN(sock_map_update), \ + FN(xdp_adjust_meta), \ + FN(perf_event_read_value), \ + FN(perf_prog_read_value), \ + FN(getsockopt), \ + FN(override_return), \ + FN(sock_ops_cb_flags_set), \ + FN(msg_redirect_map), \ + FN(msg_apply_bytes), \ + FN(msg_cork_bytes), \ + FN(msg_pull_data), \ + FN(bind), \ + FN(xdp_adjust_tail), \ + FN(skb_get_xfrm_state), \ + FN(get_stack), \ + FN(skb_load_bytes_relative), \ + FN(fib_lookup), \ + FN(sock_hash_update), \ + FN(msg_redirect_hash), \ + FN(sk_redirect_hash), \ + FN(lwt_push_encap), \ + FN(lwt_seg6_store_bytes), \ + FN(lwt_seg6_adjust_srh), \ + FN(lwt_seg6_action), \ + FN(rc_repeat), \ + FN(rc_keydown), \ + FN(skb_cgroup_id), \ + FN(get_current_cgroup_id), \ + FN(get_local_storage), \ + FN(sk_select_reuseport), \ + FN(skb_ancestor_cgroup_id), \ + FN(sk_lookup_tcp), \ + FN(sk_lookup_udp), \ + FN(sk_release), \ + FN(map_push_elem), \ + FN(map_pop_elem), \ + FN(map_peek_elem), \ + FN(msg_push_data), \ + FN(msg_pop_data), \ + FN(rc_pointer_rel), \ + FN(spin_lock), \ + FN(spin_unlock), \ + FN(sk_fullsock), \ + FN(tcp_sock), \ + FN(skb_ecn_set_ce), \ + FN(get_listener_sock), \ + FN(skc_lookup_tcp), \ + FN(tcp_check_syncookie), \ + FN(sysctl_get_name), \ + FN(sysctl_get_current_value), \ + FN(sysctl_get_new_value), \ + FN(sysctl_set_new_value), \ + FN(strtol), \ + FN(strtoul), \ + FN(sk_storage_get), \ + FN(sk_storage_delete), \ + FN(send_signal), \ + FN(tcp_gen_syncookie), \ + FN(skb_output), \ + FN(probe_read_user), \ + FN(probe_read_kernel), \ + FN(probe_read_user_str), \ + FN(probe_read_kernel_str), \ + FN(tcp_send_ack), \ + FN(send_signal_thread), \ + FN(jiffies64), \ + FN(read_branch_records), \ + FN(get_ns_current_pid_tgid), \ + FN(xdp_output), \ + FN(get_netns_cookie), \ + FN(get_current_ancestor_cgroup_id), \ + FN(sk_assign), \ + FN(ktime_get_boot_ns), \ + FN(seq_printf), \ + FN(seq_write), \ + FN(sk_cgroup_id), \ + FN(sk_ancestor_cgroup_id), \ + FN(ringbuf_output), \ + FN(ringbuf_reserve), \ + FN(ringbuf_submit), \ + FN(ringbuf_discard), \ + FN(ringbuf_query), \ + FN(csum_level), \ + FN(skc_to_tcp6_sock), \ + FN(skc_to_tcp_sock), \ + FN(skc_to_tcp_timewait_sock), \ + FN(skc_to_tcp_request_sock), \ + FN(skc_to_udp6_sock), \ + FN(get_task_stack), \ + FN(load_hdr_opt), \ + FN(store_hdr_opt), \ + FN(reserve_hdr_opt), \ + FN(inode_storage_get), \ + FN(inode_storage_delete), \ + FN(d_path), \ + FN(copy_from_user), \ + FN(snprintf_btf), \ + FN(seq_printf_btf), \ + FN(skb_cgroup_classid), \ + FN(redirect_neigh), \ + FN(per_cpu_ptr), \ + FN(this_cpu_ptr), \ + FN(redirect_peer), \ + FN(task_storage_get), \ + FN(task_storage_delete), \ + FN(get_current_task_btf), \ + FN(bprm_opts_set), \ + FN(ktime_get_coarse_ns), \ + FN(ima_inode_hash), \ + FN(sock_from_file), \ + /* */ + +/* integer value in 'imm' field of BPF_CALL instruction selects which helper + * function eBPF program intends to call + */ +#define __BPF_ENUM_FN(x) BPF_FUNC_ ## x +enum bpf_func_id { + __BPF_FUNC_MAPPER(__BPF_ENUM_FN) + __BPF_FUNC_MAX_ID, +}; +#undef __BPF_ENUM_FN + +/* All flags used by eBPF helper functions, placed here. */ + +/* BPF_FUNC_skb_store_bytes flags. */ +enum { + BPF_F_RECOMPUTE_CSUM = (1ULL << 0), + BPF_F_INVALIDATE_HASH = (1ULL << 1), +}; + +/* BPF_FUNC_l3_csum_replace and BPF_FUNC_l4_csum_replace flags. + * First 4 bits are for passing the header field size. + */ +enum { + BPF_F_HDR_FIELD_MASK = 0xfULL, +}; + +/* BPF_FUNC_l4_csum_replace flags. */ +enum { + BPF_F_PSEUDO_HDR = (1ULL << 4), + BPF_F_MARK_MANGLED_0 = (1ULL << 5), + BPF_F_MARK_ENFORCE = (1ULL << 6), +}; + +/* BPF_FUNC_clone_redirect and BPF_FUNC_redirect flags. */ +enum { + BPF_F_INGRESS = (1ULL << 0), +}; + +/* BPF_FUNC_skb_set_tunnel_key and BPF_FUNC_skb_get_tunnel_key flags. */ +enum { + BPF_F_TUNINFO_IPV6 = (1ULL << 0), +}; + +/* flags for both BPF_FUNC_get_stackid and BPF_FUNC_get_stack. */ +enum { + BPF_F_SKIP_FIELD_MASK = 0xffULL, + BPF_F_USER_STACK = (1ULL << 8), +/* flags used by BPF_FUNC_get_stackid only. */ + BPF_F_FAST_STACK_CMP = (1ULL << 9), + BPF_F_REUSE_STACKID = (1ULL << 10), +/* flags used by BPF_FUNC_get_stack only. */ + BPF_F_USER_BUILD_ID = (1ULL << 11), +}; + +/* BPF_FUNC_skb_set_tunnel_key flags. */ +enum { + BPF_F_ZERO_CSUM_TX = (1ULL << 1), + BPF_F_DONT_FRAGMENT = (1ULL << 2), + BPF_F_SEQ_NUMBER = (1ULL << 3), +}; + +/* BPF_FUNC_perf_event_output, BPF_FUNC_perf_event_read and + * BPF_FUNC_perf_event_read_value flags. + */ +enum { + BPF_F_INDEX_MASK = 0xffffffffULL, + BPF_F_CURRENT_CPU = BPF_F_INDEX_MASK, +/* BPF_FUNC_perf_event_output for sk_buff input context. */ + BPF_F_CTXLEN_MASK = (0xfffffULL << 32), +}; + +/* Current network namespace */ +enum { + BPF_F_CURRENT_NETNS = (-1L), +}; + +/* BPF_FUNC_csum_level level values. */ +enum { + BPF_CSUM_LEVEL_QUERY, + BPF_CSUM_LEVEL_INC, + BPF_CSUM_LEVEL_DEC, + BPF_CSUM_LEVEL_RESET, +}; + +/* BPF_FUNC_skb_adjust_room flags. */ +enum { + BPF_F_ADJ_ROOM_FIXED_GSO = (1ULL << 0), + BPF_F_ADJ_ROOM_ENCAP_L3_IPV4 = (1ULL << 1), + BPF_F_ADJ_ROOM_ENCAP_L3_IPV6 = (1ULL << 2), + BPF_F_ADJ_ROOM_ENCAP_L4_GRE = (1ULL << 3), + BPF_F_ADJ_ROOM_ENCAP_L4_UDP = (1ULL << 4), + BPF_F_ADJ_ROOM_NO_CSUM_RESET = (1ULL << 5), +}; + +enum { + BPF_ADJ_ROOM_ENCAP_L2_MASK = 0xff, + BPF_ADJ_ROOM_ENCAP_L2_SHIFT = 56, +}; + +#define BPF_F_ADJ_ROOM_ENCAP_L2(len) (((__u64)len & \ + BPF_ADJ_ROOM_ENCAP_L2_MASK) \ + << BPF_ADJ_ROOM_ENCAP_L2_SHIFT) + +/* BPF_FUNC_sysctl_get_name flags. */ +enum { + BPF_F_SYSCTL_BASE_NAME = (1ULL << 0), +}; + +/* BPF_FUNC__storage_get flags */ +enum { + BPF_LOCAL_STORAGE_GET_F_CREATE = (1ULL << 0), + /* BPF_SK_STORAGE_GET_F_CREATE is only kept for backward compatibility + * and BPF_LOCAL_STORAGE_GET_F_CREATE must be used instead. + */ + BPF_SK_STORAGE_GET_F_CREATE = BPF_LOCAL_STORAGE_GET_F_CREATE, +}; + +/* BPF_FUNC_read_branch_records flags. */ +enum { + BPF_F_GET_BRANCH_RECORDS_SIZE = (1ULL << 0), +}; + +/* BPF_FUNC_bpf_ringbuf_commit, BPF_FUNC_bpf_ringbuf_discard, and + * BPF_FUNC_bpf_ringbuf_output flags. + */ +enum { + BPF_RB_NO_WAKEUP = (1ULL << 0), + BPF_RB_FORCE_WAKEUP = (1ULL << 1), +}; + +/* BPF_FUNC_bpf_ringbuf_query flags */ +enum { + BPF_RB_AVAIL_DATA = 0, + BPF_RB_RING_SIZE = 1, + BPF_RB_CONS_POS = 2, + BPF_RB_PROD_POS = 3, +}; + +/* BPF ring buffer constants */ +enum { + BPF_RINGBUF_BUSY_BIT = (1U << 31), + BPF_RINGBUF_DISCARD_BIT = (1U << 30), + BPF_RINGBUF_HDR_SZ = 8, +}; + +/* BPF_FUNC_sk_assign flags in bpf_sk_lookup context. */ +enum { + BPF_SK_LOOKUP_F_REPLACE = (1ULL << 0), + BPF_SK_LOOKUP_F_NO_REUSEPORT = (1ULL << 1), +}; + +/* Mode for BPF_FUNC_skb_adjust_room helper. */ +enum bpf_adj_room_mode { + BPF_ADJ_ROOM_NET, + BPF_ADJ_ROOM_MAC, +}; + +/* Mode for BPF_FUNC_skb_load_bytes_relative helper. */ +enum bpf_hdr_start_off { + BPF_HDR_START_MAC, + BPF_HDR_START_NET, +}; + +/* Encapsulation type for BPF_FUNC_lwt_push_encap helper. */ +enum bpf_lwt_encap_mode { + BPF_LWT_ENCAP_SEG6, + BPF_LWT_ENCAP_SEG6_INLINE, + BPF_LWT_ENCAP_IP, +}; + +/* Flags for bpf_bprm_opts_set helper */ +enum { + BPF_F_BPRM_SECUREEXEC = (1ULL << 0), +}; + +#define __bpf_md_ptr(type, name) \ +union { \ + type name; \ + __u64 :64; \ +} __attribute__((aligned(8))) + +/* user accessible mirror of in-kernel sk_buff. + * new fields can only be added to the end of this structure + */ +struct __sk_buff { + __u32 len; + __u32 pkt_type; + __u32 mark; + __u32 queue_mapping; + __u32 protocol; + __u32 vlan_present; + __u32 vlan_tci; + __u32 vlan_proto; + __u32 priority; + __u32 ingress_ifindex; + __u32 ifindex; + __u32 tc_index; + __u32 cb[5]; + __u32 hash; + __u32 tc_classid; + __u32 data; + __u32 data_end; + __u32 napi_id; + + /* Accessed by BPF_PROG_TYPE_sk_skb types from here to ... */ + __u32 family; + __u32 remote_ip4; /* Stored in network byte order */ + __u32 local_ip4; /* Stored in network byte order */ + __u32 remote_ip6[4]; /* Stored in network byte order */ + __u32 local_ip6[4]; /* Stored in network byte order */ + __u32 remote_port; /* Stored in network byte order */ + __u32 local_port; /* stored in host byte order */ + /* ... here. */ + + __u32 data_meta; + __bpf_md_ptr(struct bpf_flow_keys *, flow_keys); + __u64 tstamp; + __u32 wire_len; + __u32 gso_segs; + __bpf_md_ptr(struct bpf_sock *, sk); + __u32 gso_size; +}; + +struct bpf_tunnel_key { + __u32 tunnel_id; + union { + __u32 remote_ipv4; + __u32 remote_ipv6[4]; + }; + __u8 tunnel_tos; + __u8 tunnel_ttl; + __u16 tunnel_ext; /* Padding, future use. */ + __u32 tunnel_label; +}; + +/* user accessible mirror of in-kernel xfrm_state. + * new fields can only be added to the end of this structure + */ +struct bpf_xfrm_state { + __u32 reqid; + __u32 spi; /* Stored in network byte order */ + __u16 family; + __u16 ext; /* Padding, future use. */ + union { + __u32 remote_ipv4; /* Stored in network byte order */ + __u32 remote_ipv6[4]; /* Stored in network byte order */ + }; +}; + +/* Generic BPF return codes which all BPF program types may support. + * The values are binary compatible with their TC_ACT_* counter-part to + * provide backwards compatibility with existing SCHED_CLS and SCHED_ACT + * programs. + * + * XDP is handled seprately, see XDP_*. + */ +enum bpf_ret_code { + BPF_OK = 0, + /* 1 reserved */ + BPF_DROP = 2, + /* 3-6 reserved */ + BPF_REDIRECT = 7, + /* >127 are reserved for prog type specific return codes. + * + * BPF_LWT_REROUTE: used by BPF_PROG_TYPE_LWT_IN and + * BPF_PROG_TYPE_LWT_XMIT to indicate that skb had been + * changed and should be routed based on its new L3 header. + * (This is an L3 redirect, as opposed to L2 redirect + * represented by BPF_REDIRECT above). + */ + BPF_LWT_REROUTE = 128, +}; + +struct bpf_sock { + __u32 bound_dev_if; + __u32 family; + __u32 type; + __u32 protocol; + __u32 mark; + __u32 priority; + /* IP address also allows 1 and 2 bytes access */ + __u32 src_ip4; + __u32 src_ip6[4]; + __u32 src_port; /* host byte order */ + __u32 dst_port; /* network byte order */ + __u32 dst_ip4; + __u32 dst_ip6[4]; + __u32 state; + __s32 rx_queue_mapping; +}; + +struct bpf_tcp_sock { + __u32 snd_cwnd; /* Sending congestion window */ + __u32 srtt_us; /* smoothed round trip time << 3 in usecs */ + __u32 rtt_min; + __u32 snd_ssthresh; /* Slow start size threshold */ + __u32 rcv_nxt; /* What we want to receive next */ + __u32 snd_nxt; /* Next sequence we send */ + __u32 snd_una; /* First byte we want an ack for */ + __u32 mss_cache; /* Cached effective mss, not including SACKS */ + __u32 ecn_flags; /* ECN status bits. */ + __u32 rate_delivered; /* saved rate sample: packets delivered */ + __u32 rate_interval_us; /* saved rate sample: time elapsed */ + __u32 packets_out; /* Packets which are "in flight" */ + __u32 retrans_out; /* Retransmitted packets out */ + __u32 total_retrans; /* Total retransmits for entire connection */ + __u32 segs_in; /* RFC4898 tcpEStatsPerfSegsIn + * total number of segments in. + */ + __u32 data_segs_in; /* RFC4898 tcpEStatsPerfDataSegsIn + * total number of data segments in. + */ + __u32 segs_out; /* RFC4898 tcpEStatsPerfSegsOut + * The total number of segments sent. + */ + __u32 data_segs_out; /* RFC4898 tcpEStatsPerfDataSegsOut + * total number of data segments sent. + */ + __u32 lost_out; /* Lost packets */ + __u32 sacked_out; /* SACK'd packets */ + __u64 bytes_received; /* RFC4898 tcpEStatsAppHCThruOctetsReceived + * sum(delta(rcv_nxt)), or how many bytes + * were acked. + */ + __u64 bytes_acked; /* RFC4898 tcpEStatsAppHCThruOctetsAcked + * sum(delta(snd_una)), or how many bytes + * were acked. + */ + __u32 dsack_dups; /* RFC4898 tcpEStatsStackDSACKDups + * total number of DSACK blocks received + */ + __u32 delivered; /* Total data packets delivered incl. rexmits */ + __u32 delivered_ce; /* Like the above but only ECE marked packets */ + __u32 icsk_retransmits; /* Number of unrecovered [RTO] timeouts */ +}; + +struct bpf_sock_tuple { + union { + struct { + __be32 saddr; + __be32 daddr; + __be16 sport; + __be16 dport; + } ipv4; + struct { + __be32 saddr[4]; + __be32 daddr[4]; + __be16 sport; + __be16 dport; + } ipv6; + }; +}; + +struct bpf_xdp_sock { + __u32 queue_id; +}; + +#define XDP_PACKET_HEADROOM 256 + +/* User return codes for XDP prog type. + * A valid XDP program must return one of these defined values. All other + * return codes are reserved for future use. Unknown return codes will + * result in packet drops and a warning via bpf_warn_invalid_xdp_action(). + */ +enum xdp_action { + XDP_ABORTED = 0, + XDP_DROP, + XDP_PASS, + XDP_TX, + XDP_REDIRECT, +}; + +/* user accessible metadata for XDP packet hook + * new fields must be added to the end of this structure + */ +struct xdp_md { + __u32 data; + __u32 data_end; + __u32 data_meta; + /* Below access go through struct xdp_rxq_info */ + __u32 ingress_ifindex; /* rxq->dev->ifindex */ + __u32 rx_queue_index; /* rxq->queue_index */ + + __u32 egress_ifindex; /* txq->dev->ifindex */ +}; + +/* DEVMAP map-value layout + * + * The struct data-layout of map-value is a configuration interface. + * New members can only be added to the end of this structure. + */ +struct bpf_devmap_val { + __u32 ifindex; /* device index */ + union { + int fd; /* prog fd on map write */ + __u32 id; /* prog id on map read */ + } bpf_prog; +}; + +/* CPUMAP map-value layout + * + * The struct data-layout of map-value is a configuration interface. + * New members can only be added to the end of this structure. + */ +struct bpf_cpumap_val { + __u32 qsize; /* queue size to remote target CPU */ + union { + int fd; /* prog fd on map write */ + __u32 id; /* prog id on map read */ + } bpf_prog; +}; + +enum sk_action { + SK_DROP = 0, + SK_PASS, +}; + +/* user accessible metadata for SK_MSG packet hook, new fields must + * be added to the end of this structure + */ +struct sk_msg_md { + __bpf_md_ptr(void *, data); + __bpf_md_ptr(void *, data_end); + + __u32 family; + __u32 remote_ip4; /* Stored in network byte order */ + __u32 local_ip4; /* Stored in network byte order */ + __u32 remote_ip6[4]; /* Stored in network byte order */ + __u32 local_ip6[4]; /* Stored in network byte order */ + __u32 remote_port; /* Stored in network byte order */ + __u32 local_port; /* stored in host byte order */ + __u32 size; /* Total size of sk_msg */ + + __bpf_md_ptr(struct bpf_sock *, sk); /* current socket */ +}; + +struct sk_reuseport_md { + /* + * Start of directly accessible data. It begins from + * the tcp/udp header. + */ + __bpf_md_ptr(void *, data); + /* End of directly accessible data */ + __bpf_md_ptr(void *, data_end); + /* + * Total length of packet (starting from the tcp/udp header). + * Note that the directly accessible bytes (data_end - data) + * could be less than this "len". Those bytes could be + * indirectly read by a helper "bpf_skb_load_bytes()". + */ + __u32 len; + /* + * Eth protocol in the mac header (network byte order). e.g. + * ETH_P_IP(0x0800) and ETH_P_IPV6(0x86DD) + */ + __u32 eth_protocol; + __u32 ip_protocol; /* IP protocol. e.g. IPPROTO_TCP, IPPROTO_UDP */ + __u32 bind_inany; /* Is sock bound to an INANY address? */ + __u32 hash; /* A hash of the packet 4 tuples */ +}; + +#define BPF_TAG_SIZE 8 + +struct bpf_prog_info { + __u32 type; + __u32 id; + __u8 tag[BPF_TAG_SIZE]; + __u32 jited_prog_len; + __u32 xlated_prog_len; + __aligned_u64 jited_prog_insns; + __aligned_u64 xlated_prog_insns; + __u64 load_time; /* ns since boottime */ + __u32 created_by_uid; + __u32 nr_map_ids; + __aligned_u64 map_ids; + char name[BPF_OBJ_NAME_LEN]; + __u32 ifindex; + __u32 gpl_compatible:1; + __u32 :31; /* alignment pad */ + __u64 netns_dev; + __u64 netns_ino; + __u32 nr_jited_ksyms; + __u32 nr_jited_func_lens; + __aligned_u64 jited_ksyms; + __aligned_u64 jited_func_lens; + __u32 btf_id; + __u32 func_info_rec_size; + __aligned_u64 func_info; + __u32 nr_func_info; + __u32 nr_line_info; + __aligned_u64 line_info; + __aligned_u64 jited_line_info; + __u32 nr_jited_line_info; + __u32 line_info_rec_size; + __u32 jited_line_info_rec_size; + __u32 nr_prog_tags; + __aligned_u64 prog_tags; + __u64 run_time_ns; + __u64 run_cnt; +} __attribute__((aligned(8))); + +struct bpf_map_info { + __u32 type; + __u32 id; + __u32 key_size; + __u32 value_size; + __u32 max_entries; + __u32 map_flags; + char name[BPF_OBJ_NAME_LEN]; + __u32 ifindex; + __u32 btf_vmlinux_value_type_id; + __u64 netns_dev; + __u64 netns_ino; + __u32 btf_id; + __u32 btf_key_type_id; + __u32 btf_value_type_id; +} __attribute__((aligned(8))); + +struct bpf_btf_info { + __aligned_u64 btf; + __u32 btf_size; + __u32 id; + __aligned_u64 name; + __u32 name_len; + __u32 kernel_btf; +} __attribute__((aligned(8))); + +struct bpf_link_info { + __u32 type; + __u32 id; + __u32 prog_id; + union { + struct { + __aligned_u64 tp_name; /* in/out: tp_name buffer ptr */ + __u32 tp_name_len; /* in/out: tp_name buffer len */ + } raw_tracepoint; + struct { + __u32 attach_type; + } tracing; + struct { + __u64 cgroup_id; + __u32 attach_type; + } cgroup; + struct { + __aligned_u64 target_name; /* in/out: target_name buffer ptr */ + __u32 target_name_len; /* in/out: target_name buffer len */ + union { + struct { + __u32 map_id; + } map; + }; + } iter; + struct { + __u32 netns_ino; + __u32 attach_type; + } netns; + struct { + __u32 ifindex; + } xdp; + }; +} __attribute__((aligned(8))); + +/* User bpf_sock_addr struct to access socket fields and sockaddr struct passed + * by user and intended to be used by socket (e.g. to bind to, depends on + * attach type). + */ +struct bpf_sock_addr { + __u32 user_family; /* Allows 4-byte read, but no write. */ + __u32 user_ip4; /* Allows 1,2,4-byte read and 4-byte write. + * Stored in network byte order. + */ + __u32 user_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write. + * Stored in network byte order. + */ + __u32 user_port; /* Allows 1,2,4-byte read and 4-byte write. + * Stored in network byte order + */ + __u32 family; /* Allows 4-byte read, but no write */ + __u32 type; /* Allows 4-byte read, but no write */ + __u32 protocol; /* Allows 4-byte read, but no write */ + __u32 msg_src_ip4; /* Allows 1,2,4-byte read and 4-byte write. + * Stored in network byte order. + */ + __u32 msg_src_ip6[4]; /* Allows 1,2,4,8-byte read and 4,8-byte write. + * Stored in network byte order. + */ + __bpf_md_ptr(struct bpf_sock *, sk); +}; + +/* User bpf_sock_ops struct to access socket values and specify request ops + * and their replies. + * Some of this fields are in network (bigendian) byte order and may need + * to be converted before use (bpf_ntohl() defined in samples/bpf/bpf_endian.h). + * New fields can only be added at the end of this structure + */ +struct bpf_sock_ops { + __u32 op; + union { + __u32 args[4]; /* Optionally passed to bpf program */ + __u32 reply; /* Returned by bpf program */ + __u32 replylong[4]; /* Optionally returned by bpf prog */ + }; + __u32 family; + __u32 remote_ip4; /* Stored in network byte order */ + __u32 local_ip4; /* Stored in network byte order */ + __u32 remote_ip6[4]; /* Stored in network byte order */ + __u32 local_ip6[4]; /* Stored in network byte order */ + __u32 remote_port; /* Stored in network byte order */ + __u32 local_port; /* stored in host byte order */ + __u32 is_fullsock; /* Some TCP fields are only valid if + * there is a full socket. If not, the + * fields read as zero. + */ + __u32 snd_cwnd; + __u32 srtt_us; /* Averaged RTT << 3 in usecs */ + __u32 bpf_sock_ops_cb_flags; /* flags defined in uapi/linux/tcp.h */ + __u32 state; + __u32 rtt_min; + __u32 snd_ssthresh; + __u32 rcv_nxt; + __u32 snd_nxt; + __u32 snd_una; + __u32 mss_cache; + __u32 ecn_flags; + __u32 rate_delivered; + __u32 rate_interval_us; + __u32 packets_out; + __u32 retrans_out; + __u32 total_retrans; + __u32 segs_in; + __u32 data_segs_in; + __u32 segs_out; + __u32 data_segs_out; + __u32 lost_out; + __u32 sacked_out; + __u32 sk_txhash; + __u64 bytes_received; + __u64 bytes_acked; + __bpf_md_ptr(struct bpf_sock *, sk); + /* [skb_data, skb_data_end) covers the whole TCP header. + * + * BPF_SOCK_OPS_PARSE_HDR_OPT_CB: The packet received + * BPF_SOCK_OPS_HDR_OPT_LEN_CB: Not useful because the + * header has not been written. + * BPF_SOCK_OPS_WRITE_HDR_OPT_CB: The header and options have + * been written so far. + * BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB: The SYNACK that concludes + * the 3WHS. + * BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB: The ACK that concludes + * the 3WHS. + * + * bpf_load_hdr_opt() can also be used to read a particular option. + */ + __bpf_md_ptr(void *, skb_data); + __bpf_md_ptr(void *, skb_data_end); + __u32 skb_len; /* The total length of a packet. + * It includes the header, options, + * and payload. + */ + __u32 skb_tcp_flags; /* tcp_flags of the header. It provides + * an easy way to check for tcp_flags + * without parsing skb_data. + * + * In particular, the skb_tcp_flags + * will still be available in + * BPF_SOCK_OPS_HDR_OPT_LEN even though + * the outgoing header has not + * been written yet. + */ +}; + +/* Definitions for bpf_sock_ops_cb_flags */ +enum { + BPF_SOCK_OPS_RTO_CB_FLAG = (1<<0), + BPF_SOCK_OPS_RETRANS_CB_FLAG = (1<<1), + BPF_SOCK_OPS_STATE_CB_FLAG = (1<<2), + BPF_SOCK_OPS_RTT_CB_FLAG = (1<<3), + /* Call bpf for all received TCP headers. The bpf prog will be + * called under sock_ops->op == BPF_SOCK_OPS_PARSE_HDR_OPT_CB + * + * Please refer to the comment in BPF_SOCK_OPS_PARSE_HDR_OPT_CB + * for the header option related helpers that will be useful + * to the bpf programs. + * + * It could be used at the client/active side (i.e. connect() side) + * when the server told it that the server was in syncookie + * mode and required the active side to resend the bpf-written + * options. The active side can keep writing the bpf-options until + * it received a valid packet from the server side to confirm + * the earlier packet (and options) has been received. The later + * example patch is using it like this at the active side when the + * server is in syncookie mode. + * + * The bpf prog will usually turn this off in the common cases. + */ + BPF_SOCK_OPS_PARSE_ALL_HDR_OPT_CB_FLAG = (1<<4), + /* Call bpf when kernel has received a header option that + * the kernel cannot handle. The bpf prog will be called under + * sock_ops->op == BPF_SOCK_OPS_PARSE_HDR_OPT_CB. + * + * Please refer to the comment in BPF_SOCK_OPS_PARSE_HDR_OPT_CB + * for the header option related helpers that will be useful + * to the bpf programs. + */ + BPF_SOCK_OPS_PARSE_UNKNOWN_HDR_OPT_CB_FLAG = (1<<5), + /* Call bpf when the kernel is writing header options for the + * outgoing packet. The bpf prog will first be called + * to reserve space in a skb under + * sock_ops->op == BPF_SOCK_OPS_HDR_OPT_LEN_CB. Then + * the bpf prog will be called to write the header option(s) + * under sock_ops->op == BPF_SOCK_OPS_WRITE_HDR_OPT_CB. + * + * Please refer to the comment in BPF_SOCK_OPS_HDR_OPT_LEN_CB + * and BPF_SOCK_OPS_WRITE_HDR_OPT_CB for the header option + * related helpers that will be useful to the bpf programs. + * + * The kernel gets its chance to reserve space and write + * options first before the BPF program does. + */ + BPF_SOCK_OPS_WRITE_HDR_OPT_CB_FLAG = (1<<6), +/* Mask of all currently supported cb flags */ + BPF_SOCK_OPS_ALL_CB_FLAGS = 0x7F, +}; + +/* List of known BPF sock_ops operators. + * New entries can only be added at the end + */ +enum { + BPF_SOCK_OPS_VOID, + BPF_SOCK_OPS_TIMEOUT_INIT, /* Should return SYN-RTO value to use or + * -1 if default value should be used + */ + BPF_SOCK_OPS_RWND_INIT, /* Should return initial advertized + * window (in packets) or -1 if default + * value should be used + */ + BPF_SOCK_OPS_TCP_CONNECT_CB, /* Calls BPF program right before an + * active connection is initialized + */ + BPF_SOCK_OPS_ACTIVE_ESTABLISHED_CB, /* Calls BPF program when an + * active connection is + * established + */ + BPF_SOCK_OPS_PASSIVE_ESTABLISHED_CB, /* Calls BPF program when a + * passive connection is + * established + */ + BPF_SOCK_OPS_NEEDS_ECN, /* If connection's congestion control + * needs ECN + */ + BPF_SOCK_OPS_BASE_RTT, /* Get base RTT. The correct value is + * based on the path and may be + * dependent on the congestion control + * algorithm. In general it indicates + * a congestion threshold. RTTs above + * this indicate congestion + */ + BPF_SOCK_OPS_RTO_CB, /* Called when an RTO has triggered. + * Arg1: value of icsk_retransmits + * Arg2: value of icsk_rto + * Arg3: whether RTO has expired + */ + BPF_SOCK_OPS_RETRANS_CB, /* Called when skb is retransmitted. + * Arg1: sequence number of 1st byte + * Arg2: # segments + * Arg3: return value of + * tcp_transmit_skb (0 => success) + */ + BPF_SOCK_OPS_STATE_CB, /* Called when TCP changes state. + * Arg1: old_state + * Arg2: new_state + */ + BPF_SOCK_OPS_TCP_LISTEN_CB, /* Called on listen(2), right after + * socket transition to LISTEN state. + */ + BPF_SOCK_OPS_RTT_CB, /* Called on every RTT. + */ + BPF_SOCK_OPS_PARSE_HDR_OPT_CB, /* Parse the header option. + * It will be called to handle + * the packets received at + * an already established + * connection. + * + * sock_ops->skb_data: + * Referring to the received skb. + * It covers the TCP header only. + * + * bpf_load_hdr_opt() can also + * be used to search for a + * particular option. + */ + BPF_SOCK_OPS_HDR_OPT_LEN_CB, /* Reserve space for writing the + * header option later in + * BPF_SOCK_OPS_WRITE_HDR_OPT_CB. + * Arg1: bool want_cookie. (in + * writing SYNACK only) + * + * sock_ops->skb_data: + * Not available because no header has + * been written yet. + * + * sock_ops->skb_tcp_flags: + * The tcp_flags of the + * outgoing skb. (e.g. SYN, ACK, FIN). + * + * bpf_reserve_hdr_opt() should + * be used to reserve space. + */ + BPF_SOCK_OPS_WRITE_HDR_OPT_CB, /* Write the header options + * Arg1: bool want_cookie. (in + * writing SYNACK only) + * + * sock_ops->skb_data: + * Referring to the outgoing skb. + * It covers the TCP header + * that has already been written + * by the kernel and the + * earlier bpf-progs. + * + * sock_ops->skb_tcp_flags: + * The tcp_flags of the outgoing + * skb. (e.g. SYN, ACK, FIN). + * + * bpf_store_hdr_opt() should + * be used to write the + * option. + * + * bpf_load_hdr_opt() can also + * be used to search for a + * particular option that + * has already been written + * by the kernel or the + * earlier bpf-progs. + */ +}; + +/* List of TCP states. There is a build check in net/ipv4/tcp.c to detect + * changes between the TCP and BPF versions. Ideally this should never happen. + * If it does, we need to add code to convert them before calling + * the BPF sock_ops function. + */ +enum { + BPF_TCP_ESTABLISHED = 1, + BPF_TCP_SYN_SENT, + BPF_TCP_SYN_RECV, + BPF_TCP_FIN_WAIT1, + BPF_TCP_FIN_WAIT2, + BPF_TCP_TIME_WAIT, + BPF_TCP_CLOSE, + BPF_TCP_CLOSE_WAIT, + BPF_TCP_LAST_ACK, + BPF_TCP_LISTEN, + BPF_TCP_CLOSING, /* Now a valid state */ + BPF_TCP_NEW_SYN_RECV, + + BPF_TCP_MAX_STATES /* Leave at the end! */ +}; + +enum { + TCP_BPF_IW = 1001, /* Set TCP initial congestion window */ + TCP_BPF_SNDCWND_CLAMP = 1002, /* Set sndcwnd_clamp */ + TCP_BPF_DELACK_MAX = 1003, /* Max delay ack in usecs */ + TCP_BPF_RTO_MIN = 1004, /* Min delay ack in usecs */ + /* Copy the SYN pkt to optval + * + * BPF_PROG_TYPE_SOCK_OPS only. It is similar to the + * bpf_getsockopt(TCP_SAVED_SYN) but it does not limit + * to only getting from the saved_syn. It can either get the + * syn packet from: + * + * 1. the just-received SYN packet (only available when writing the + * SYNACK). It will be useful when it is not necessary to + * save the SYN packet for latter use. It is also the only way + * to get the SYN during syncookie mode because the syn + * packet cannot be saved during syncookie. + * + * OR + * + * 2. the earlier saved syn which was done by + * bpf_setsockopt(TCP_SAVE_SYN). + * + * The bpf_getsockopt(TCP_BPF_SYN*) option will hide where the + * SYN packet is obtained. + * + * If the bpf-prog does not need the IP[46] header, the + * bpf-prog can avoid parsing the IP header by using + * TCP_BPF_SYN. Otherwise, the bpf-prog can get both + * IP[46] and TCP header by using TCP_BPF_SYN_IP. + * + * >0: Total number of bytes copied + * -ENOSPC: Not enough space in optval. Only optlen number of + * bytes is copied. + * -ENOENT: The SYN skb is not available now and the earlier SYN pkt + * is not saved by setsockopt(TCP_SAVE_SYN). + */ + TCP_BPF_SYN = 1005, /* Copy the TCP header */ + TCP_BPF_SYN_IP = 1006, /* Copy the IP[46] and TCP header */ + TCP_BPF_SYN_MAC = 1007, /* Copy the MAC, IP[46], and TCP header */ +}; + +enum { + BPF_LOAD_HDR_OPT_TCP_SYN = (1ULL << 0), +}; + +/* args[0] value during BPF_SOCK_OPS_HDR_OPT_LEN_CB and + * BPF_SOCK_OPS_WRITE_HDR_OPT_CB. + */ +enum { + BPF_WRITE_HDR_TCP_CURRENT_MSS = 1, /* Kernel is finding the + * total option spaces + * required for an established + * sk in order to calculate the + * MSS. No skb is actually + * sent. + */ + BPF_WRITE_HDR_TCP_SYNACK_COOKIE = 2, /* Kernel is in syncookie mode + * when sending a SYN. + */ +}; + +struct bpf_perf_event_value { + __u64 counter; + __u64 enabled; + __u64 running; +}; + +enum { + BPF_DEVCG_ACC_MKNOD = (1ULL << 0), + BPF_DEVCG_ACC_READ = (1ULL << 1), + BPF_DEVCG_ACC_WRITE = (1ULL << 2), +}; + +enum { + BPF_DEVCG_DEV_BLOCK = (1ULL << 0), + BPF_DEVCG_DEV_CHAR = (1ULL << 1), +}; + +struct bpf_cgroup_dev_ctx { + /* access_type encoded as (BPF_DEVCG_ACC_* << 16) | BPF_DEVCG_DEV_* */ + __u32 access_type; + __u32 major; + __u32 minor; +}; + +struct bpf_raw_tracepoint_args { + __u64 args[0]; +}; + +/* DIRECT: Skip the FIB rules and go to FIB table associated with device + * OUTPUT: Do lookup from egress perspective; default is ingress + */ +enum { + BPF_FIB_LOOKUP_DIRECT = (1U << 0), + BPF_FIB_LOOKUP_OUTPUT = (1U << 1), +}; + +enum { + BPF_FIB_LKUP_RET_SUCCESS, /* lookup successful */ + BPF_FIB_LKUP_RET_BLACKHOLE, /* dest is blackholed; can be dropped */ + BPF_FIB_LKUP_RET_UNREACHABLE, /* dest is unreachable; can be dropped */ + BPF_FIB_LKUP_RET_PROHIBIT, /* dest not allowed; can be dropped */ + BPF_FIB_LKUP_RET_NOT_FWDED, /* packet is not forwarded */ + BPF_FIB_LKUP_RET_FWD_DISABLED, /* fwding is not enabled on ingress */ + BPF_FIB_LKUP_RET_UNSUPP_LWT, /* fwd requires encapsulation */ + BPF_FIB_LKUP_RET_NO_NEIGH, /* no neighbor entry for nh */ + BPF_FIB_LKUP_RET_FRAG_NEEDED, /* fragmentation required to fwd */ +}; + +struct bpf_fib_lookup { + /* input: network family for lookup (AF_INET, AF_INET6) + * output: network family of egress nexthop + */ + __u8 family; + + /* set if lookup is to consider L4 data - e.g., FIB rules */ + __u8 l4_protocol; + __be16 sport; + __be16 dport; + + /* total length of packet from network header - used for MTU check */ + __u16 tot_len; + + /* input: L3 device index for lookup + * output: device index from FIB lookup + */ + __u32 ifindex; + + union { + /* inputs to lookup */ + __u8 tos; /* AF_INET */ + __be32 flowinfo; /* AF_INET6, flow_label + priority */ + + /* output: metric of fib result (IPv4/IPv6 only) */ + __u32 rt_metric; + }; + + union { + __be32 ipv4_src; + __u32 ipv6_src[4]; /* in6_addr; network order */ + }; + + /* input to bpf_fib_lookup, ipv{4,6}_dst is destination address in + * network header. output: bpf_fib_lookup sets to gateway address + * if FIB lookup returns gateway route + */ + union { + __be32 ipv4_dst; + __u32 ipv6_dst[4]; /* in6_addr; network order */ + }; + + /* output */ + __be16 h_vlan_proto; + __be16 h_vlan_TCI; + __u8 smac[6]; /* ETH_ALEN */ + __u8 dmac[6]; /* ETH_ALEN */ +}; + +struct bpf_redir_neigh { + /* network family for lookup (AF_INET, AF_INET6) */ + __u32 nh_family; + /* network address of nexthop; skips fib lookup to find gateway */ + union { + __be32 ipv4_nh; + __u32 ipv6_nh[4]; /* in6_addr; network order */ + }; +}; + +enum bpf_task_fd_type { + BPF_FD_TYPE_RAW_TRACEPOINT, /* tp name */ + BPF_FD_TYPE_TRACEPOINT, /* tp name */ + BPF_FD_TYPE_KPROBE, /* (symbol + offset) or addr */ + BPF_FD_TYPE_KRETPROBE, /* (symbol + offset) or addr */ + BPF_FD_TYPE_UPROBE, /* filename + offset */ + BPF_FD_TYPE_URETPROBE, /* filename + offset */ +}; + +enum { + BPF_FLOW_DISSECTOR_F_PARSE_1ST_FRAG = (1U << 0), + BPF_FLOW_DISSECTOR_F_STOP_AT_FLOW_LABEL = (1U << 1), + BPF_FLOW_DISSECTOR_F_STOP_AT_ENCAP = (1U << 2), +}; + +struct bpf_flow_keys { + __u16 nhoff; + __u16 thoff; + __u16 addr_proto; /* ETH_P_* of valid addrs */ + __u8 is_frag; + __u8 is_first_frag; + __u8 is_encap; + __u8 ip_proto; + __be16 n_proto; + __be16 sport; + __be16 dport; + union { + struct { + __be32 ipv4_src; + __be32 ipv4_dst; + }; + struct { + __u32 ipv6_src[4]; /* in6_addr; network order */ + __u32 ipv6_dst[4]; /* in6_addr; network order */ + }; + }; + __u32 flags; + __be32 flow_label; +}; + +struct bpf_func_info { + __u32 insn_off; + __u32 type_id; +}; + +#define BPF_LINE_INFO_LINE_NUM(line_col) ((line_col) >> 10) +#define BPF_LINE_INFO_LINE_COL(line_col) ((line_col) & 0x3ff) + +struct bpf_line_info { + __u32 insn_off; + __u32 file_name_off; + __u32 line_off; + __u32 line_col; +}; + +struct bpf_spin_lock { + __u32 val; +}; + +struct bpf_sysctl { + __u32 write; /* Sysctl is being read (= 0) or written (= 1). + * Allows 1,2,4-byte read, but no write. + */ + __u32 file_pos; /* Sysctl file position to read from, write to. + * Allows 1,2,4-byte read an 4-byte write. + */ +}; + +struct bpf_sockopt { + __bpf_md_ptr(struct bpf_sock *, sk); + __bpf_md_ptr(void *, optval); + __bpf_md_ptr(void *, optval_end); + + __s32 level; + __s32 optname; + __s32 optlen; + __s32 retval; +}; + +struct bpf_pidns_info { + __u32 pid; + __u32 tgid; +}; + +/* User accessible data for SK_LOOKUP programs. Add new fields at the end. */ +struct bpf_sk_lookup { + __bpf_md_ptr(struct bpf_sock *, sk); /* Selected socket */ + + __u32 family; /* Protocol family (AF_INET, AF_INET6) */ + __u32 protocol; /* IP protocol (IPPROTO_TCP, IPPROTO_UDP) */ + __u32 remote_ip4; /* Network byte order */ + __u32 remote_ip6[4]; /* Network byte order */ + __u32 remote_port; /* Network byte order */ + __u32 local_ip4; /* Network byte order */ + __u32 local_ip6[4]; /* Network byte order */ + __u32 local_port; /* Host byte order */ +}; + +/* + * struct btf_ptr is used for typed pointer representation; the + * type id is used to render the pointer data as the appropriate type + * via the bpf_snprintf_btf() helper described above. A flags field - + * potentially to specify additional details about the BTF pointer + * (rather than its mode of display) - is included for future use. + * Display flags - BTF_F_* - are passed to bpf_snprintf_btf separately. + */ +struct btf_ptr { + void *ptr; + __u32 type_id; + __u32 flags; /* BTF ptr flags; unused at present. */ +}; + +/* + * Flags to control bpf_snprintf_btf() behaviour. + * - BTF_F_COMPACT: no formatting around type information + * - BTF_F_NONAME: no struct/union member names/types + * - BTF_F_PTR_RAW: show raw (unobfuscated) pointer values; + * equivalent to %px. + * - BTF_F_ZERO: show zero-valued struct/union members; they + * are not displayed by default + */ +enum { + BTF_F_COMPACT = (1ULL << 0), + BTF_F_NONAME = (1ULL << 1), + BTF_F_PTR_RAW = (1ULL << 2), + BTF_F_ZERO = (1ULL << 3), +}; + +#endif /* __LINUX_BPF_H__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/bpf_common.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/bpf_common.h new file mode 100644 index 000000000..afe7433b9 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/bpf_common.h @@ -0,0 +1,55 @@ +#ifndef __LINUX_BPF_COMMON_H__ +#define __LINUX_BPF_COMMON_H__ + +/* Instruction classes */ +#define BPF_CLASS(code) ((code) & 0x07) +#define BPF_LD 0x00 +#define BPF_LDX 0x01 +#define BPF_ST 0x02 +#define BPF_STX 0x03 +#define BPF_ALU 0x04 +#define BPF_JMP 0x05 +#define BPF_RET 0x06 +#define BPF_MISC 0x07 + +/* ld/ldx fields */ +#define BPF_SIZE(code) ((code) & 0x18) +#define BPF_W 0x00 +#define BPF_H 0x08 +#define BPF_B 0x10 +#define BPF_MODE(code) ((code) & 0xe0) +#define BPF_IMM 0x00 +#define BPF_ABS 0x20 +#define BPF_IND 0x40 +#define BPF_MEM 0x60 +#define BPF_LEN 0x80 +#define BPF_MSH 0xa0 + +/* alu/jmp fields */ +#define BPF_OP(code) ((code) & 0xf0) +#define BPF_ADD 0x00 +#define BPF_SUB 0x10 +#define BPF_MUL 0x20 +#define BPF_DIV 0x30 +#define BPF_OR 0x40 +#define BPF_AND 0x50 +#define BPF_LSH 0x60 +#define BPF_RSH 0x70 +#define BPF_NEG 0x80 +#define BPF_MOD 0x90 +#define BPF_XOR 0xa0 + +#define BPF_JA 0x00 +#define BPF_JEQ 0x10 +#define BPF_JGT 0x20 +#define BPF_JGE 0x30 +#define BPF_JSET 0x40 +#define BPF_SRC(code) ((code) & 0x08) +#define BPF_K 0x00 +#define BPF_X 0x08 + +#ifndef BPF_MAXINSNS +#define BPF_MAXINSNS 4096 +#endif + +#endif /* __LINUX_BPF_COMMON_H__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/byteorder.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/byteorder.h new file mode 100644 index 000000000..84273e7b3 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/byteorder.h @@ -0,0 +1,10 @@ +#ifndef _ASM_X86_BYTEORDER_H +#define _ASM_X86_BYTEORDER_H + +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +#include +#else +#include +#endif + +#endif /* _ASM_X86_BYTEORDER_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/byteorder/big_endian.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/byteorder/big_endian.h new file mode 100644 index 000000000..a4ef98d9c --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/byteorder/big_endian.h @@ -0,0 +1,105 @@ +#ifndef _LINUX_BYTEORDER_BIG_ENDIAN_H +#define _LINUX_BYTEORDER_BIG_ENDIAN_H + +#ifndef __BIG_ENDIAN +#define __BIG_ENDIAN 4321 +#endif +#ifndef __BIG_ENDIAN_BITFIELD +#define __BIG_ENDIAN_BITFIELD +#endif + +#include +#include + +#define __constant_htonl(x) ((__be32)(__u32)(x)) +#define __constant_ntohl(x) ((__u32)(__be32)(x)) +#define __constant_htons(x) ((__be16)(__u16)(x)) +#define __constant_ntohs(x) ((__u16)(__be16)(x)) +#define __constant_cpu_to_le64(x) ((__le64)___constant_swab64((x))) +#define __constant_le64_to_cpu(x) ___constant_swab64((__u64)(__le64)(x)) +#define __constant_cpu_to_le32(x) ((__le32)___constant_swab32((x))) +#define __constant_le32_to_cpu(x) ___constant_swab32((__u32)(__le32)(x)) +#define __constant_cpu_to_le16(x) ((__le16)___constant_swab16((x))) +#define __constant_le16_to_cpu(x) ___constant_swab16((__u16)(__le16)(x)) +#define __constant_cpu_to_be64(x) ((__be64)(__u64)(x)) +#define __constant_be64_to_cpu(x) ((__u64)(__be64)(x)) +#define __constant_cpu_to_be32(x) ((__be32)(__u32)(x)) +#define __constant_be32_to_cpu(x) ((__u32)(__be32)(x)) +#define __constant_cpu_to_be16(x) ((__be16)(__u16)(x)) +#define __constant_be16_to_cpu(x) ((__u16)(__be16)(x)) +#define __cpu_to_le64(x) ((__le64)__swab64((x))) +#define __le64_to_cpu(x) __swab64((__u64)(__le64)(x)) +#define __cpu_to_le32(x) ((__le32)__swab32((x))) +#define __le32_to_cpu(x) __swab32((__u32)(__le32)(x)) +#define __cpu_to_le16(x) ((__le16)__swab16((x))) +#define __le16_to_cpu(x) __swab16((__u16)(__le16)(x)) +#define __cpu_to_be64(x) ((__be64)(__u64)(x)) +#define __be64_to_cpu(x) ((__u64)(__be64)(x)) +#define __cpu_to_be32(x) ((__be32)(__u32)(x)) +#define __be32_to_cpu(x) ((__u32)(__be32)(x)) +#define __cpu_to_be16(x) ((__be16)(__u16)(x)) +#define __be16_to_cpu(x) ((__u16)(__be16)(x)) + +static __inline__ __le64 __cpu_to_le64p(const __u64 *p) +{ + return (__le64)__swab64p(p); +} +static __inline__ __u64 __le64_to_cpup(const __le64 *p) +{ + return __swab64p((__u64 *)p); +} +static __inline__ __le32 __cpu_to_le32p(const __u32 *p) +{ + return (__le32)__swab32p(p); +} +static __inline__ __u32 __le32_to_cpup(const __le32 *p) +{ + return __swab32p((__u32 *)p); +} +static __inline__ __le16 __cpu_to_le16p(const __u16 *p) +{ + return (__le16)__swab16p(p); +} +static __inline__ __u16 __le16_to_cpup(const __le16 *p) +{ + return __swab16p((__u16 *)p); +} +static __inline__ __be64 __cpu_to_be64p(const __u64 *p) +{ + return (__be64)*p; +} +static __inline__ __u64 __be64_to_cpup(const __be64 *p) +{ + return (__u64)*p; +} +static __inline__ __be32 __cpu_to_be32p(const __u32 *p) +{ + return (__be32)*p; +} +static __inline__ __u32 __be32_to_cpup(const __be32 *p) +{ + return (__u32)*p; +} +static __inline__ __be16 __cpu_to_be16p(const __u16 *p) +{ + return (__be16)*p; +} +static __inline__ __u16 __be16_to_cpup(const __be16 *p) +{ + return (__u16)*p; +} +#define __cpu_to_le64s(x) __swab64s((x)) +#define __le64_to_cpus(x) __swab64s((x)) +#define __cpu_to_le32s(x) __swab32s((x)) +#define __le32_to_cpus(x) __swab32s((x)) +#define __cpu_to_le16s(x) __swab16s((x)) +#define __le16_to_cpus(x) __swab16s((x)) +#define __cpu_to_be64s(x) do { (void)(x); } while (0) +#define __be64_to_cpus(x) do { (void)(x); } while (0) +#define __cpu_to_be32s(x) do { (void)(x); } while (0) +#define __be32_to_cpus(x) do { (void)(x); } while (0) +#define __cpu_to_be16s(x) do { (void)(x); } while (0) +#define __be16_to_cpus(x) do { (void)(x); } while (0) + + +#endif /* _LINUX_BYTEORDER_BIG_ENDIAN_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/byteorder/little_endian.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/byteorder/little_endian.h new file mode 100644 index 000000000..74e8a1591 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/byteorder/little_endian.h @@ -0,0 +1,105 @@ +#ifndef _LINUX_BYTEORDER_LITTLE_ENDIAN_H +#define _LINUX_BYTEORDER_LITTLE_ENDIAN_H + +#ifndef __LITTLE_ENDIAN +#define __LITTLE_ENDIAN 1234 +#endif +#ifndef __LITTLE_ENDIAN_BITFIELD +#define __LITTLE_ENDIAN_BITFIELD +#endif + +#include +#include + +#define __constant_htonl(x) ((__be32)___constant_swab32((x))) +#define __constant_ntohl(x) ___constant_swab32((__be32)(x)) +#define __constant_htons(x) ((__be16)___constant_swab16((x))) +#define __constant_ntohs(x) ___constant_swab16((__be16)(x)) +#define __constant_cpu_to_le64(x) ((__le64)(__u64)(x)) +#define __constant_le64_to_cpu(x) ((__u64)(__le64)(x)) +#define __constant_cpu_to_le32(x) ((__le32)(__u32)(x)) +#define __constant_le32_to_cpu(x) ((__u32)(__le32)(x)) +#define __constant_cpu_to_le16(x) ((__le16)(__u16)(x)) +#define __constant_le16_to_cpu(x) ((__u16)(__le16)(x)) +#define __constant_cpu_to_be64(x) ((__be64)___constant_swab64((x))) +#define __constant_be64_to_cpu(x) ___constant_swab64((__u64)(__be64)(x)) +#define __constant_cpu_to_be32(x) ((__be32)___constant_swab32((x))) +#define __constant_be32_to_cpu(x) ___constant_swab32((__u32)(__be32)(x)) +#define __constant_cpu_to_be16(x) ((__be16)___constant_swab16((x))) +#define __constant_be16_to_cpu(x) ___constant_swab16((__u16)(__be16)(x)) +#define __cpu_to_le64(x) ((__le64)(__u64)(x)) +#define __le64_to_cpu(x) ((__u64)(__le64)(x)) +#define __cpu_to_le32(x) ((__le32)(__u32)(x)) +#define __le32_to_cpu(x) ((__u32)(__le32)(x)) +#define __cpu_to_le16(x) ((__le16)(__u16)(x)) +#define __le16_to_cpu(x) ((__u16)(__le16)(x)) +#define __cpu_to_be64(x) ((__be64)__swab64((x))) +#define __be64_to_cpu(x) __swab64((__u64)(__be64)(x)) +#define __cpu_to_be32(x) ((__be32)__swab32((x))) +#define __be32_to_cpu(x) __swab32((__u32)(__be32)(x)) +#define __cpu_to_be16(x) ((__be16)__swab16((x))) +#define __be16_to_cpu(x) __swab16((__u16)(__be16)(x)) + +static __inline__ __le64 __cpu_to_le64p(const __u64 *p) +{ + return (__le64)*p; +} +static __inline__ __u64 __le64_to_cpup(const __le64 *p) +{ + return (__u64)*p; +} +static __inline__ __le32 __cpu_to_le32p(const __u32 *p) +{ + return (__le32)*p; +} +static __inline__ __u32 __le32_to_cpup(const __le32 *p) +{ + return (__u32)*p; +} +static __inline__ __le16 __cpu_to_le16p(const __u16 *p) +{ + return (__le16)*p; +} +static __inline__ __u16 __le16_to_cpup(const __le16 *p) +{ + return (__u16)*p; +} +static __inline__ __be64 __cpu_to_be64p(const __u64 *p) +{ + return (__be64)__swab64p(p); +} +static __inline__ __u64 __be64_to_cpup(const __be64 *p) +{ + return __swab64p((__u64 *)p); +} +static __inline__ __be32 __cpu_to_be32p(const __u32 *p) +{ + return (__be32)__swab32p(p); +} +static __inline__ __u32 __be32_to_cpup(const __be32 *p) +{ + return __swab32p((__u32 *)p); +} +static __inline__ __be16 __cpu_to_be16p(const __u16 *p) +{ + return (__be16)__swab16p(p); +} +static __inline__ __u16 __be16_to_cpup(const __be16 *p) +{ + return __swab16p((__u16 *)p); +} +#define __cpu_to_le64s(x) do { (void)(x); } while (0) +#define __le64_to_cpus(x) do { (void)(x); } while (0) +#define __cpu_to_le32s(x) do { (void)(x); } while (0) +#define __le32_to_cpus(x) do { (void)(x); } while (0) +#define __cpu_to_le16s(x) do { (void)(x); } while (0) +#define __le16_to_cpus(x) do { (void)(x); } while (0) +#define __cpu_to_be64s(x) __swab64s((x)) +#define __be64_to_cpus(x) __swab64s((x)) +#define __cpu_to_be32s(x) __swab32s((x)) +#define __be32_to_cpus(x) __swab32s((x)) +#define __cpu_to_be16s(x) __swab16s((x)) +#define __be16_to_cpus(x) __swab16s((x)) + + +#endif /* _LINUX_BYTEORDER_LITTLE_ENDIAN_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/icmp.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/icmp.h new file mode 100644 index 000000000..ab58cee37 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/icmp.h @@ -0,0 +1,97 @@ +/* + * INET An implementation of the TCP/IP protocol suite for the LINUX + * operating system. INET is implemented using the BSD Socket + * interface as the means of communication with the user level. + * + * Definitions for the ICMP protocol. + * + * Version: @(#)icmp.h 1.0.3 04/28/93 + * + * Author: Fred N. van Kempen, + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ +#ifndef _LINUX_ICMP_H +#define _LINUX_ICMP_H + +#include + +#define ICMP_ECHOREPLY 0 /* Echo Reply */ +#define ICMP_DEST_UNREACH 3 /* Destination Unreachable */ +#define ICMP_SOURCE_QUENCH 4 /* Source Quench */ +#define ICMP_REDIRECT 5 /* Redirect (change route) */ +#define ICMP_ECHO 8 /* Echo Request */ +#define ICMP_TIME_EXCEEDED 11 /* Time Exceeded */ +#define ICMP_PARAMETERPROB 12 /* Parameter Problem */ +#define ICMP_TIMESTAMP 13 /* Timestamp Request */ +#define ICMP_TIMESTAMPREPLY 14 /* Timestamp Reply */ +#define ICMP_INFO_REQUEST 15 /* Information Request */ +#define ICMP_INFO_REPLY 16 /* Information Reply */ +#define ICMP_ADDRESS 17 /* Address Mask Request */ +#define ICMP_ADDRESSREPLY 18 /* Address Mask Reply */ +#define NR_ICMP_TYPES 18 + + +/* Codes for UNREACH. */ +#define ICMP_NET_UNREACH 0 /* Network Unreachable */ +#define ICMP_HOST_UNREACH 1 /* Host Unreachable */ +#define ICMP_PROT_UNREACH 2 /* Protocol Unreachable */ +#define ICMP_PORT_UNREACH 3 /* Port Unreachable */ +#define ICMP_FRAG_NEEDED 4 /* Fragmentation Needed/DF set */ +#define ICMP_SR_FAILED 5 /* Source Route failed */ +#define ICMP_NET_UNKNOWN 6 +#define ICMP_HOST_UNKNOWN 7 +#define ICMP_HOST_ISOLATED 8 +#define ICMP_NET_ANO 9 +#define ICMP_HOST_ANO 10 +#define ICMP_NET_UNR_TOS 11 +#define ICMP_HOST_UNR_TOS 12 +#define ICMP_PKT_FILTERED 13 /* Packet filtered */ +#define ICMP_PREC_VIOLATION 14 /* Precedence violation */ +#define ICMP_PREC_CUTOFF 15 /* Precedence cut off */ +#define NR_ICMP_UNREACH 15 /* instead of hardcoding immediate value */ + +/* Codes for REDIRECT. */ +#define ICMP_REDIR_NET 0 /* Redirect Net */ +#define ICMP_REDIR_HOST 1 /* Redirect Host */ +#define ICMP_REDIR_NETTOS 2 /* Redirect Net for TOS */ +#define ICMP_REDIR_HOSTTOS 3 /* Redirect Host for TOS */ + +/* Codes for TIME_EXCEEDED. */ +#define ICMP_EXC_TTL 0 /* TTL count exceeded */ +#define ICMP_EXC_FRAGTIME 1 /* Fragment Reass time exceeded */ + + +struct icmphdr { + __u8 type; + __u8 code; + __sum16 checksum; + union { + struct { + __be16 id; + __be16 sequence; + } echo; + __be32 gateway; + struct { + __be16 __unused; + __be16 mtu; + } frag; + } un; +}; + + +/* + * constants for (set|get)sockopt + */ + +#define ICMP_FILTER 1 + +struct icmp_filter { + __u32 data; +}; + + +#endif /* _LINUX_ICMP_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/icmpv6.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/icmpv6.h new file mode 100644 index 000000000..eee9c2897 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/icmpv6.h @@ -0,0 +1,166 @@ +#ifndef _LINUX_ICMPV6_H +#define _LINUX_ICMPV6_H + +#include +#include + +struct icmp6hdr { + + __u8 icmp6_type; + __u8 icmp6_code; + __sum16 icmp6_cksum; + + + union { + __be32 un_data32[1]; + __be16 un_data16[2]; + __u8 un_data8[4]; + + struct icmpv6_echo { + __be16 identifier; + __be16 sequence; + } u_echo; + + struct icmpv6_nd_advt { +#if defined(__LITTLE_ENDIAN_BITFIELD) + __u32 reserved:5, + override:1, + solicited:1, + router:1, + reserved2:24; +#elif defined(__BIG_ENDIAN_BITFIELD) + __u32 router:1, + solicited:1, + override:1, + reserved:29; +#else +#error "Please fix " +#endif + } u_nd_advt; + + struct icmpv6_nd_ra { + __u8 hop_limit; +#if defined(__LITTLE_ENDIAN_BITFIELD) + __u8 reserved:3, + router_pref:2, + home_agent:1, + other:1, + managed:1; + +#elif defined(__BIG_ENDIAN_BITFIELD) + __u8 managed:1, + other:1, + home_agent:1, + router_pref:2, + reserved:3; +#else +#error "Please fix " +#endif + __be16 rt_lifetime; + } u_nd_ra; + + } icmp6_dataun; + +#define icmp6_identifier icmp6_dataun.u_echo.identifier +#define icmp6_sequence icmp6_dataun.u_echo.sequence +#define icmp6_pointer icmp6_dataun.un_data32[0] +#define icmp6_mtu icmp6_dataun.un_data32[0] +#define icmp6_unused icmp6_dataun.un_data32[0] +#define icmp6_maxdelay icmp6_dataun.un_data16[0] +#define icmp6_router icmp6_dataun.u_nd_advt.router +#define icmp6_solicited icmp6_dataun.u_nd_advt.solicited +#define icmp6_override icmp6_dataun.u_nd_advt.override +#define icmp6_ndiscreserved icmp6_dataun.u_nd_advt.reserved +#define icmp6_hop_limit icmp6_dataun.u_nd_ra.hop_limit +#define icmp6_addrconf_managed icmp6_dataun.u_nd_ra.managed +#define icmp6_addrconf_other icmp6_dataun.u_nd_ra.other +#define icmp6_rt_lifetime icmp6_dataun.u_nd_ra.rt_lifetime +#define icmp6_router_pref icmp6_dataun.u_nd_ra.router_pref +}; + + +#define ICMPV6_ROUTER_PREF_LOW 0x3 +#define ICMPV6_ROUTER_PREF_MEDIUM 0x0 +#define ICMPV6_ROUTER_PREF_HIGH 0x1 +#define ICMPV6_ROUTER_PREF_INVALID 0x2 + +#define ICMPV6_DEST_UNREACH 1 +#define ICMPV6_PKT_TOOBIG 2 +#define ICMPV6_TIME_EXCEED 3 +#define ICMPV6_PARAMPROB 4 + +#define ICMPV6_INFOMSG_MASK 0x80 + +#define ICMPV6_ECHO_REQUEST 128 +#define ICMPV6_ECHO_REPLY 129 +#define ICMPV6_MGM_QUERY 130 +#define ICMPV6_MGM_REPORT 131 +#define ICMPV6_MGM_REDUCTION 132 + +#define ICMPV6_NI_QUERY 139 +#define ICMPV6_NI_REPLY 140 + +#define ICMPV6_MLD2_REPORT 143 + +#define ICMPV6_DHAAD_REQUEST 144 +#define ICMPV6_DHAAD_REPLY 145 +#define ICMPV6_MOBILE_PREFIX_SOL 146 +#define ICMPV6_MOBILE_PREFIX_ADV 147 + +/* + * Codes for Destination Unreachable + */ +#define ICMPV6_NOROUTE 0 +#define ICMPV6_ADM_PROHIBITED 1 +#define ICMPV6_NOT_NEIGHBOUR 2 +#define ICMPV6_ADDR_UNREACH 3 +#define ICMPV6_PORT_UNREACH 4 +#define ICMPV6_POLICY_FAIL 5 +#define ICMPV6_REJECT_ROUTE 6 + +/* + * Codes for Time Exceeded + */ +#define ICMPV6_EXC_HOPLIMIT 0 +#define ICMPV6_EXC_FRAGTIME 1 + +/* + * Codes for Parameter Problem + */ +#define ICMPV6_HDR_FIELD 0 +#define ICMPV6_UNK_NEXTHDR 1 +#define ICMPV6_UNK_OPTION 2 + +/* + * constants for (set|get)sockopt + */ + +#define ICMPV6_FILTER 1 + +/* + * ICMPV6 filter + */ + +#define ICMPV6_FILTER_BLOCK 1 +#define ICMPV6_FILTER_PASS 2 +#define ICMPV6_FILTER_BLOCKOTHERS 3 +#define ICMPV6_FILTER_PASSONLY 4 + +struct icmp6_filter { + __u32 data[8]; +}; + +/* + * Definitions for MLDv2 + */ +#define MLD2_MODE_IS_INCLUDE 1 +#define MLD2_MODE_IS_EXCLUDE 2 +#define MLD2_CHANGE_TO_INCLUDE 3 +#define MLD2_CHANGE_TO_EXCLUDE 4 +#define MLD2_ALLOW_NEW_SOURCES 5 +#define MLD2_BLOCK_OLD_SOURCES 6 + +#define MLD2_ALL_MCR_INIT { { { 0xff,0x02,0,0,0,0,0,0,0,0,0,0,0,0,0,0x16 } } } + + +#endif /* _LINUX_ICMPV6_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/if_arp.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/if_arp.h new file mode 100644 index 000000000..7d3d741d2 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/if_arp.h @@ -0,0 +1,136 @@ +/* + * INET An implementation of the TCP/IP protocol suite for the LINUX + * operating system. INET is implemented using the BSD Socket + * interface as the means of communication with the user level. + * + * Global definitions for the ARP (RFC 826) protocol. + * + * Version: @(#)if_arp.h 1.0.1 04/16/93 + * + * Authors: Original taken from Berkeley UNIX 4.3, (c) UCB 1986-1988 + * Portions taken from the KA9Q/NOS (v2.00m PA0GRI) source. + * Ross Biro + * Fred N. van Kempen, + * Florian La Roche, + * Jonathan Layes + * Arnaldo Carvalho de Melo ARPHRD_HWX25 + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ +#ifndef _LINUX_IF_ARP_H +#define _LINUX_IF_ARP_H + +#include + +/* ARP protocol HARDWARE identifiers. */ +#define ARPHRD_NETROM 0 /* from KA9Q: NET/ROM pseudo */ +#define ARPHRD_ETHER 1 /* Ethernet 10Mbps */ +#define ARPHRD_EETHER 2 /* Experimental Ethernet */ +#define ARPHRD_AX25 3 /* AX.25 Level 2 */ +#define ARPHRD_PRONET 4 /* PROnet token ring */ +#define ARPHRD_CHAOS 5 /* Chaosnet */ +#define ARPHRD_IEEE802 6 /* IEEE 802.2 Ethernet/TR/TB */ +#define ARPHRD_ARCNET 7 /* ARCnet */ +#define ARPHRD_APPLETLK 8 /* APPLEtalk */ +#define ARPHRD_DLCI 15 /* Frame Relay DLCI */ +#define ARPHRD_ATM 19 /* ATM */ +#define ARPHRD_METRICOM 23 /* Metricom STRIP (new IANA id) */ +#define ARPHRD_IEEE1394 24 /* IEEE 1394 IPv4 - RFC 2734 */ +#define ARPHRD_EUI64 27 /* EUI-64 */ +#define ARPHRD_INFINIBAND 32 /* InfiniBand */ + +/* Dummy types for non ARP hardware */ +#define ARPHRD_SLIP 256 +#define ARPHRD_CSLIP 257 +#define ARPHRD_SLIP6 258 +#define ARPHRD_CSLIP6 259 +#define ARPHRD_RSRVD 260 /* Notional KISS type */ +#define ARPHRD_ADAPT 264 +#define ARPHRD_ROSE 270 +#define ARPHRD_X25 271 /* CCITT X.25 */ +#define ARPHRD_HWX25 272 /* Boards with X.25 in firmware */ +#define ARPHRD_CAN 280 /* Controller Area Network */ +#define ARPHRD_PPP 512 +#define ARPHRD_CISCO 513 /* Cisco HDLC */ +#define ARPHRD_HDLC ARPHRD_CISCO +#define ARPHRD_LAPB 516 /* LAPB */ +#define ARPHRD_DDCMP 517 /* Digital's DDCMP protocol */ +#define ARPHRD_RAWHDLC 518 /* Raw HDLC */ + +#define ARPHRD_TUNNEL 768 /* IPIP tunnel */ +#define ARPHRD_TUNNEL6 769 /* IP6IP6 tunnel */ +#define ARPHRD_FRAD 770 /* Frame Relay Access Device */ +#define ARPHRD_SKIP 771 /* SKIP vif */ +#define ARPHRD_LOOPBACK 772 /* Loopback device */ +#define ARPHRD_LOCALTLK 773 /* Localtalk device */ +#define ARPHRD_FDDI 774 /* Fiber Distributed Data Interface */ +#define ARPHRD_BIF 775 /* AP1000 BIF */ +#define ARPHRD_SIT 776 /* sit0 device - IPv6-in-IPv4 */ +#define ARPHRD_IPDDP 777 /* IP over DDP tunneller */ +#define ARPHRD_IPGRE 778 /* GRE over IP */ +#define ARPHRD_PIMREG 779 /* PIMSM register interface */ +#define ARPHRD_HIPPI 780 /* High Performance Parallel Interface */ +#define ARPHRD_ASH 781 /* Nexus 64Mbps Ash */ +#define ARPHRD_ECONET 782 /* Acorn Econet */ +#define ARPHRD_IRDA 783 /* Linux-IrDA */ +/* ARP works differently on different FC media .. so */ +#define ARPHRD_FCPP 784 /* Point to point fibrechannel */ +#define ARPHRD_FCAL 785 /* Fibrechannel arbitrated loop */ +#define ARPHRD_FCPL 786 /* Fibrechannel public loop */ +#define ARPHRD_FCFABRIC 787 /* Fibrechannel fabric */ + /* 787->799 reserved for fibrechannel media types */ +#define ARPHRD_IEEE802_TR 800 /* Magic type ident for TR */ +#define ARPHRD_IEEE80211 801 /* IEEE 802.11 */ +#define ARPHRD_IEEE80211_PRISM 802 /* IEEE 802.11 + Prism2 header */ +#define ARPHRD_IEEE80211_RADIOTAP 803 /* IEEE 802.11 + radiotap header */ +#define ARPHRD_IEEE802154 804 +#define ARPHRD_IEEE802154_MONITOR 805 /* IEEE 802.15.4 network monitor */ + +#define ARPHRD_PHONET 820 /* PhoNet media type */ +#define ARPHRD_PHONET_PIPE 821 /* PhoNet pipe header */ +#define ARPHRD_CAIF 822 /* CAIF media type */ +#define ARPHRD_IP6GRE 823 /* GRE over IPv6 */ +#define ARPHRD_NETLINK 824 /* Netlink header */ +#define ARPHRD_6LOWPAN 825 /* IPv6 over LoWPAN */ + +#define ARPHRD_VOID 0xFFFF /* Void type, nothing is known */ +#define ARPHRD_NONE 0xFFFE /* zero header length */ + +/* ARP protocol opcodes. */ +#define ARPOP_REQUEST 1 /* ARP request */ +#define ARPOP_REPLY 2 /* ARP reply */ +#define ARPOP_RREQUEST 3 /* RARP request */ +#define ARPOP_RREPLY 4 /* RARP reply */ +#define ARPOP_InREQUEST 8 /* InARP request */ +#define ARPOP_InREPLY 9 /* InARP reply */ +#define ARPOP_NAK 10 /* (ATM)ARP NAK */ + + +/* + * This structure defines an ethernet arp header. + */ + +struct arphdr { + __be16 ar_hrd; /* format of hardware address */ + __be16 ar_pro; /* format of protocol address */ + unsigned char ar_hln; /* length of hardware address */ + unsigned char ar_pln; /* length of protocol address */ + __be16 ar_op; /* ARP opcode (command) */ + +#if 0 + /* + * Ethernet looks like this : This bit is variable sized however... + */ + unsigned char ar_sha[ETH_ALEN]; /* sender hardware address */ + unsigned char ar_sip[4]; /* sender IP address */ + unsigned char ar_tha[ETH_ALEN]; /* target hardware address */ + unsigned char ar_tip[4]; /* target IP address */ +#endif + +}; + + +#endif /* _LINUX_IF_ARP_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/if_ether.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/if_ether.h new file mode 100644 index 000000000..8648dfddb --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/if_ether.h @@ -0,0 +1,150 @@ +/* + * INET An implementation of the TCP/IP protocol suite for the LINUX + * operating system. INET is implemented using the BSD Socket + * interface as the means of communication with the user level. + * + * Global definitions for the Ethernet IEEE 802.3 interface. + * + * Version: @(#)if_ether.h 1.0.1a 02/08/94 + * + * Author: Fred N. van Kempen, + * Donald Becker, + * Alan Cox, + * Steve Whitehouse, + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ + +#ifndef _LINUX_IF_ETHER_H +#define _LINUX_IF_ETHER_H + +#include + +/* + * IEEE 802.3 Ethernet magic constants. The frame sizes omit the preamble + * and FCS/CRC (frame check sequence). + */ + +#define ETH_ALEN 6 /* Octets in one ethernet addr */ +/* __ETH_HLEN is out of sync with the kernel's if_ether.h. In Cilium datapath + * we use ETH_HLEN which can be loaded via static data, and for L2-less devs + * it's 0. To avoid replacing every occurrence of ETH_HLEN in the datapath, + * we prefixed the kernel's ETH_HLEN instead. + */ +#define __ETH_HLEN 14 /* Total octets in header. */ +#define ETH_ZLEN 60 /* Min. octets in frame sans FCS */ +#define ETH_DATA_LEN 1500 /* Max. octets in payload */ +#define ETH_FRAME_LEN 1514 /* Max. octets in frame sans FCS */ +#define ETH_FCS_LEN 4 /* Octets in the FCS */ + +/* + * These are the defined Ethernet Protocol ID's. + */ + +#define ETH_P_LOOP 0x0060 /* Ethernet Loopback packet */ +#define ETH_P_PUP 0x0200 /* Xerox PUP packet */ +#define ETH_P_PUPAT 0x0201 /* Xerox PUP Addr Trans packet */ +#define ETH_P_TSN 0x22F0 /* TSN (IEEE 1722) packet */ +#define ETH_P_IP 0x0800 /* Internet Protocol packet */ +#define ETH_P_X25 0x0805 /* CCITT X.25 */ +#define ETH_P_ARP 0x0806 /* Address Resolution packet */ +#define ETH_P_BPQ 0x08FF /* G8BPQ AX.25 Ethernet Packet [ NOT AN OFFICIALLY REGISTERED ID ] */ +#define ETH_P_IEEEPUP 0x0a00 /* Xerox IEEE802.3 PUP packet */ +#define ETH_P_IEEEPUPAT 0x0a01 /* Xerox IEEE802.3 PUP Addr Trans packet */ +#define ETH_P_BATMAN 0x4305 /* B.A.T.M.A.N.-Advanced packet [ NOT AN OFFICIALLY REGISTERED ID ] */ +#define ETH_P_DEC 0x6000 /* DEC Assigned proto */ +#define ETH_P_DNA_DL 0x6001 /* DEC DNA Dump/Load */ +#define ETH_P_DNA_RC 0x6002 /* DEC DNA Remote Console */ +#define ETH_P_DNA_RT 0x6003 /* DEC DNA Routing */ +#define ETH_P_LAT 0x6004 /* DEC LAT */ +#define ETH_P_DIAG 0x6005 /* DEC Diagnostics */ +#define ETH_P_CUST 0x6006 /* DEC Customer use */ +#define ETH_P_SCA 0x6007 /* DEC Systems Comms Arch */ +#define ETH_P_TEB 0x6558 /* Trans Ether Bridging */ +#define ETH_P_RARP 0x8035 /* Reverse Addr Res packet */ +#define ETH_P_ATALK 0x809B /* Appletalk DDP */ +#define ETH_P_AARP 0x80F3 /* Appletalk AARP */ +#define ETH_P_8021Q 0x8100 /* 802.1Q VLAN Extended Header */ +#define ETH_P_IPX 0x8137 /* IPX over DIX */ +#define ETH_P_IPV6 0x86DD /* IPv6 over bluebook */ +#define ETH_P_PAUSE 0x8808 /* IEEE Pause frames. See 802.3 31B */ +#define ETH_P_SLOW 0x8809 /* Slow Protocol. See 802.3ad 43B */ +#define ETH_P_WCCP 0x883E /* Web-cache coordination protocol + * defined in draft-wilson-wrec-wccp-v2-00.txt */ +#define ETH_P_MPLS_UC 0x8847 /* MPLS Unicast traffic */ +#define ETH_P_MPLS_MC 0x8848 /* MPLS Multicast traffic */ +#define ETH_P_ATMMPOA 0x884c /* MultiProtocol Over ATM */ +#define ETH_P_PPP_DISC 0x8863 /* PPPoE discovery messages */ +#define ETH_P_PPP_SES 0x8864 /* PPPoE session messages */ +#define ETH_P_LINK_CTL 0x886c /* HPNA, wlan link local tunnel */ +#define ETH_P_ATMFATE 0x8884 /* Frame-based ATM Transport + * over Ethernet + */ +#define ETH_P_PAE 0x888E /* Port Access Entity (IEEE 802.1X) */ +#define ETH_P_AOE 0x88A2 /* ATA over Ethernet */ +#define ETH_P_8021AD 0x88A8 /* 802.1ad Service VLAN */ +#define ETH_P_802_EX1 0x88B5 /* 802.1 Local Experimental 1. */ +#define ETH_P_TIPC 0x88CA /* TIPC */ +#define ETH_P_8021AH 0x88E7 /* 802.1ah Backbone Service Tag */ +#define ETH_P_MVRP 0x88F5 /* 802.1Q MVRP */ +#define ETH_P_1588 0x88F7 /* IEEE 1588 Timesync */ +#define ETH_P_PRP 0x88FB /* IEC 62439-3 PRP/HSRv0 */ +#define ETH_P_FCOE 0x8906 /* Fibre Channel over Ethernet */ +#define ETH_P_TDLS 0x890D /* TDLS */ +#define ETH_P_FIP 0x8914 /* FCoE Initialization Protocol */ +#define ETH_P_80221 0x8917 /* IEEE 802.21 Media Independent Handover Protocol */ +#define ETH_P_LOOPBACK 0x9000 /* Ethernet loopback packet, per IEEE 802.3 */ +#define ETH_P_QINQ1 0x9100 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ +#define ETH_P_QINQ2 0x9200 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ +#define ETH_P_QINQ3 0x9300 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ +#define ETH_P_EDSA 0xDADA /* Ethertype DSA [ NOT AN OFFICIALLY REGISTERED ID ] */ +#define ETH_P_AF_IUCV 0xFBFB /* IBM af_iucv [ NOT AN OFFICIALLY REGISTERED ID ] */ + +#define ETH_P_802_3_MIN 0x0600 /* If the value in the ethernet type is less than this value + * then the frame is Ethernet II. Else it is 802.3 */ + +/* + * Non DIX types. Won't clash for 1500 types. + */ + +#define ETH_P_802_3 0x0001 /* Dummy type for 802.3 frames */ +#define ETH_P_AX25 0x0002 /* Dummy protocol id for AX.25 */ +#define ETH_P_ALL 0x0003 /* Every packet (be careful!!!) */ +#define ETH_P_802_2 0x0004 /* 802.2 frames */ +#define ETH_P_SNAP 0x0005 /* Internal only */ +#define ETH_P_DDCMP 0x0006 /* DEC DDCMP: Internal only */ +#define ETH_P_WAN_PPP 0x0007 /* Dummy type for WAN PPP frames*/ +#define ETH_P_PPP_MP 0x0008 /* Dummy type for PPP MP frames */ +#define ETH_P_LOCALTALK 0x0009 /* Localtalk pseudo type */ +#define ETH_P_CAN 0x000C /* CAN: Controller Area Network */ +#define ETH_P_CANFD 0x000D /* CANFD: CAN flexible data rate*/ +#define ETH_P_PPPTALK 0x0010 /* Dummy type for Atalk over PPP*/ +#define ETH_P_TR_802_2 0x0011 /* 802.2 frames */ +#define ETH_P_MOBITEX 0x0015 /* Mobitex (kaz@cafe.net) */ +#define ETH_P_CONTROL 0x0016 /* Card specific control frames */ +#define ETH_P_IRDA 0x0017 /* Linux-IrDA */ +#define ETH_P_ECONET 0x0018 /* Acorn Econet */ +#define ETH_P_HDLC 0x0019 /* HDLC frames */ +#define ETH_P_ARCNET 0x001A /* 1A for ArcNet :-) */ +#define ETH_P_DSA 0x001B /* Distributed Switch Arch. */ +#define ETH_P_TRAILER 0x001C /* Trailer switch tagging */ +#define ETH_P_PHONET 0x00F5 /* Nokia Phonet frames */ +#define ETH_P_IEEE802154 0x00F6 /* IEEE802.15.4 frame */ +#define ETH_P_CAIF 0x00F7 /* ST-Ericsson CAIF protocol */ +#define ETH_P_XDSA 0x00F8 /* Multiplexed DSA protocol */ + +/* + * This is an Ethernet frame header. + */ + +struct ethhdr { + unsigned char h_dest[ETH_ALEN]; /* destination eth addr */ + unsigned char h_source[ETH_ALEN]; /* source ether addr */ + __be16 h_proto; /* packet type ID field */ +} __attribute__((packed)); + + +#endif /* _LINUX_IF_ETHER_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/if_packet.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/if_packet.h new file mode 100644 index 000000000..4086a8e7f --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/if_packet.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef __LINUX_IF_PACKET_H +#define __LINUX_IF_PACKET_H + +#define PACKET_HOST 0 /* To us */ +#define PACKET_BROADCAST 1 /* To all */ +#define PACKET_MULTICAST 2 /* To group */ +#define PACKET_OTHERHOST 3 /* To someone else */ +#define PACKET_OUTGOING 4 /* Outgoing of any type */ +#define PACKET_LOOPBACK 5 /* MC/BRD frame looped back */ +#define PACKET_USER 6 /* To user space */ +#define PACKET_KERNEL 7 /* To kernel space */ +/* Unused, PACKET_FASTROUTE and PACKET_LOOPBACK are invisible to user space */ +#define PACKET_FASTROUTE 6 /* Fastrouted frame */ + +#endif // __LINUX_IF_PACKET_H diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/in.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/in.h new file mode 100644 index 000000000..75b2236d5 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/in.h @@ -0,0 +1,210 @@ +/* + * INET An implementation of the TCP/IP protocol suite for the LINUX + * operating system. INET is implemented using the BSD Socket + * interface as the means of communication with the user level. + * + * Definitions of the Internet Protocol. + * + * Version: @(#)in.h 1.0.1 04/21/93 + * + * Authors: Original taken from the GNU Project file. + * Fred N. van Kempen, + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ +#ifndef _LINUX_IN_H +#define _LINUX_IN_H + +#include + +/* Standard well-defined IP protocols. */ +enum { + IPPROTO_IP = 0, /* Dummy protocol for TCP */ +#define IPPROTO_IP IPPROTO_IP + IPPROTO_ICMP = 1, /* Internet Control Message Protocol */ +#define IPPROTO_ICMP IPPROTO_ICMP + IPPROTO_IGMP = 2, /* Internet Group Management Protocol */ +#define IPPROTO_IGMP IPPROTO_IGMP + IPPROTO_IPIP = 4, /* IPIP tunnels (older KA9Q tunnels use 94) */ +#define IPPROTO_IPIP IPPROTO_IPIP + IPPROTO_TCP = 6, /* Transmission Control Protocol */ +#define IPPROTO_TCP IPPROTO_TCP + IPPROTO_EGP = 8, /* Exterior Gateway Protocol */ +#define IPPROTO_EGP IPPROTO_EGP + IPPROTO_PUP = 12, /* PUP protocol */ +#define IPPROTO_PUP IPPROTO_PUP + IPPROTO_UDP = 17, /* User Datagram Protocol */ +#define IPPROTO_UDP IPPROTO_UDP + IPPROTO_IDP = 22, /* XNS IDP protocol */ +#define IPPROTO_IDP IPPROTO_IDP + IPPROTO_TP = 29, /* SO Transport Protocol Class 4 */ +#define IPPROTO_TP IPPROTO_TP + IPPROTO_DCCP = 33, /* Datagram Congestion Control Protocol */ +#define IPPROTO_DCCP IPPROTO_DCCP + IPPROTO_IPV6 = 41, /* IPv6-in-IPv4 tunnelling */ +#define IPPROTO_IPV6 IPPROTO_IPV6 + IPPROTO_RSVP = 46, /* RSVP Protocol */ +#define IPPROTO_RSVP IPPROTO_RSVP + IPPROTO_GRE = 47, /* Cisco GRE tunnels (rfc 1701,1702) */ +#define IPPROTO_GRE IPPROTO_GRE + IPPROTO_ESP = 50, /* Encapsulation Security Payload protocol */ +#define IPPROTO_ESP IPPROTO_ESP + IPPROTO_AH = 51, /* Authentication Header protocol */ +#define IPPROTO_AH IPPROTO_AH + IPPROTO_MTP = 92, /* Multicast Transport Protocol */ +#define IPPROTO_MTP IPPROTO_MTP + IPPROTO_BEETPH = 94, /* IP option pseudo header for BEET */ +#define IPPROTO_BEETPH IPPROTO_BEETPH + IPPROTO_ENCAP = 98, /* Encapsulation Header */ +#define IPPROTO_ENCAP IPPROTO_ENCAP + IPPROTO_PIM = 103, /* Protocol Independent Multicast */ +#define IPPROTO_PIM IPPROTO_PIM + IPPROTO_COMP = 108, /* Compression Header Protocol */ +#define IPPROTO_COMP IPPROTO_COMP + IPPROTO_SCTP = 132, /* Stream Control Transport Protocol */ +#define IPPROTO_SCTP IPPROTO_SCTP + IPPROTO_UDPLITE = 136, /* UDP-Lite (RFC 3828) */ +#define IPPROTO_UDPLITE IPPROTO_UDPLITE + IPPROTO_MPLS = 137, /* MPLS in IP (RFC 4023) */ +#define IPPROTO_MPLS IPPROTO_MPLS + IPPROTO_RAW = 255, /* Raw IP packets */ +#define IPPROTO_RAW IPPROTO_RAW + IPPROTO_MAX +}; + +/* Internet address. */ +struct in_addr { + __be32 s_addr; +}; + +#define IP_TOS 1 +#define IP_TTL 2 +#define IP_HDRINCL 3 +#define IP_OPTIONS 4 +#define IP_ROUTER_ALERT 5 +#define IP_RECVOPTS 6 +#define IP_RETOPTS 7 +#define IP_PKTINFO 8 +#define IP_PKTOPTIONS 9 +#define IP_MTU_DISCOVER 10 +#define IP_RECVERR 11 +#define IP_RECVTTL 12 +#define IP_RECVTOS 13 +#define IP_MTU 14 +#define IP_FREEBIND 15 +#define IP_IPSEC_POLICY 16 +#define IP_XFRM_POLICY 17 +#define IP_PASSSEC 18 +#define IP_TRANSPARENT 19 + +/* BSD compatibility */ +#define IP_RECVRETOPTS IP_RETOPTS + +/* TProxy original addresses */ +#define IP_ORIGDSTADDR 20 +#define IP_RECVORIGDSTADDR IP_ORIGDSTADDR + +#define IP_MINTTL 21 +#define IP_NODEFRAG 22 +#define IP_CHECKSUM 23 +#define IP_BIND_ADDRESS_NO_PORT 24 + +/* IP_MTU_DISCOVER values */ +#define IP_PMTUDISC_DONT 0 /* Never send DF frames */ +#define IP_PMTUDISC_WANT 1 /* Use per route hints */ +#define IP_PMTUDISC_DO 2 /* Always DF */ +#define IP_PMTUDISC_PROBE 3 /* Ignore dst pmtu */ +/* Always use interface mtu (ignores dst pmtu) but don't set DF flag. + * Also incoming ICMP frag_needed notifications will be ignored on + * this socket to prevent accepting spoofed ones. + */ +#define IP_PMTUDISC_INTERFACE 4 +/* weaker version of IP_PMTUDISC_INTERFACE, which allos packets to get + * fragmented if they exeed the interface mtu + */ +#define IP_PMTUDISC_OMIT 5 + +#define IP_MULTICAST_IF 32 +#define IP_MULTICAST_TTL 33 +#define IP_MULTICAST_LOOP 34 +#define IP_ADD_MEMBERSHIP 35 +#define IP_DROP_MEMBERSHIP 36 +#define IP_UNBLOCK_SOURCE 37 +#define IP_BLOCK_SOURCE 38 +#define IP_ADD_SOURCE_MEMBERSHIP 39 +#define IP_DROP_SOURCE_MEMBERSHIP 40 +#define IP_MSFILTER 41 +#define MCAST_JOIN_GROUP 42 +#define MCAST_BLOCK_SOURCE 43 +#define MCAST_UNBLOCK_SOURCE 44 +#define MCAST_LEAVE_GROUP 45 +#define MCAST_JOIN_SOURCE_GROUP 46 +#define MCAST_LEAVE_SOURCE_GROUP 47 +#define MCAST_MSFILTER 48 +#define IP_MULTICAST_ALL 49 +#define IP_UNICAST_IF 50 + +#define MCAST_EXCLUDE 0 +#define MCAST_INCLUDE 1 + +/* These need to appear somewhere around here */ +#define IP_DEFAULT_MULTICAST_TTL 1 +#define IP_DEFAULT_MULTICAST_LOOP 1 + +/* Request struct for multicast socket ops */ + +/* + * Definitions of the bits in an Internet address integer. + * On subnets, host and network parts are found according + * to the subnet mask, not these masks. + */ +#define IN_CLASSA(a) ((((long int) (a)) & 0x80000000) == 0) +#define IN_CLASSA_NET 0xff000000 +#define IN_CLASSA_NSHIFT 24 +#define IN_CLASSA_HOST (0xffffffff & ~IN_CLASSA_NET) +#define IN_CLASSA_MAX 128 + +#define IN_CLASSB(a) ((((long int) (a)) & 0xc0000000) == 0x80000000) +#define IN_CLASSB_NET 0xffff0000 +#define IN_CLASSB_NSHIFT 16 +#define IN_CLASSB_HOST (0xffffffff & ~IN_CLASSB_NET) +#define IN_CLASSB_MAX 65536 + +#define IN_CLASSC(a) ((((long int) (a)) & 0xe0000000) == 0xc0000000) +#define IN_CLASSC_NET 0xffffff00 +#define IN_CLASSC_NSHIFT 8 +#define IN_CLASSC_HOST (0xffffffff & ~IN_CLASSC_NET) + +#define IN_CLASSD(a) ((((long int) (a)) & 0xf0000000) == 0xe0000000) +#define IN_MULTICAST(a) IN_CLASSD(a) +#define IN_MULTICAST_NET 0xF0000000 + +#define IN_EXPERIMENTAL(a) ((((long int) (a)) & 0xf0000000) == 0xf0000000) +#define IN_BADCLASS(a) IN_EXPERIMENTAL((a)) + +/* Address to accept any incoming messages. */ +#define INADDR_ANY ((unsigned long int) 0x00000000) + +/* Address to send to all hosts. */ +#define INADDR_BROADCAST ((unsigned long int) 0xffffffff) + +/* Address indicating an error return. */ +#define INADDR_NONE ((unsigned long int) 0xffffffff) + +/* Network number for local host loopback. */ +#define IN_LOOPBACKNET 127 + +/* Address to loopback in software to local host. */ +#define INADDR_LOOPBACK 0x7f000001 /* 127.0.0.1 */ +#define IN_LOOPBACK(a) ((((long int) (a)) & 0xff000000) == 0x7f000000) + +/* Defines for Multicast INADDR */ +#define INADDR_UNSPEC_GROUP 0xe0000000U /* 224.0.0.0 */ +#define INADDR_ALLHOSTS_GROUP 0xe0000001U /* 224.0.0.1 */ +#define INADDR_ALLRTRS_GROUP 0xe0000002U /* 224.0.0.2 */ +#define INADDR_MAX_LOCAL_GROUP 0xe00000ffU /* 224.0.0.255 */ + +#endif /* _LINUX_IN_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/in6.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/in6.h new file mode 100644 index 000000000..73d21c808 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/in6.h @@ -0,0 +1,149 @@ +/* + * Types and definitions for AF_INET6 + * Linux INET6 implementation + * + * Authors: + * Pedro Roque + * + * Sources: + * IPv6 Program Interfaces for BSD Systems + * + * + * Advanced Sockets API for IPv6 + * + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ + +#ifndef _LINUX_IN6_H +#define _LINUX_IN6_H + +#include + +/* + * IPv6 address structure + */ + +struct in6_addr { + union { + __u8 u6_addr8[16]; + __be16 u6_addr16[8]; + __be32 u6_addr32[4]; + } in6_u; +#define s6_addr in6_u.u6_addr8 +#define s6_addr16 in6_u.u6_addr16 +#define s6_addr32 in6_u.u6_addr32 +}; + +/* + * Bitmask constant declarations to help applications select out the + * flow label and priority fields. + * + * Note that this are in host byte order while the flowinfo field of + * sockaddr_in6 is in network byte order. + */ + +#define IPV6_FLOWINFO_FLOWLABEL 0x000fffff +#define IPV6_FLOWINFO_PRIORITY 0x0ff00000 + +/* These definitions are obsolete */ +#define IPV6_PRIORITY_UNCHARACTERIZED 0x0000 +#define IPV6_PRIORITY_FILLER 0x0100 +#define IPV6_PRIORITY_UNATTENDED 0x0200 +#define IPV6_PRIORITY_RESERVED1 0x0300 +#define IPV6_PRIORITY_BULK 0x0400 +#define IPV6_PRIORITY_RESERVED2 0x0500 +#define IPV6_PRIORITY_INTERACTIVE 0x0600 +#define IPV6_PRIORITY_CONTROL 0x0700 +#define IPV6_PRIORITY_8 0x0800 +#define IPV6_PRIORITY_9 0x0900 +#define IPV6_PRIORITY_10 0x0a00 +#define IPV6_PRIORITY_11 0x0b00 +#define IPV6_PRIORITY_12 0x0c00 +#define IPV6_PRIORITY_13 0x0d00 +#define IPV6_PRIORITY_14 0x0e00 +#define IPV6_PRIORITY_15 0x0f00 + +/* + * IPV6 extension headers + */ +#define IPPROTO_HOPOPTS 0 /* IPv6 hop-by-hop options */ +#define IPPROTO_ROUTING 43 /* IPv6 routing header */ +#define IPPROTO_FRAGMENT 44 /* IPv6 fragmentation header */ +#define IPPROTO_ICMPV6 58 /* ICMPv6 */ +#define IPPROTO_NONE 59 /* IPv6 no next header */ +#define IPPROTO_DSTOPTS 60 /* IPv6 destination options */ +#define IPPROTO_MH 135 /* IPv6 mobility header */ + +/* + * IPv6 TLV options. + */ +#define IPV6_TLV_PAD1 0 +#define IPV6_TLV_PADN 1 +#define IPV6_TLV_ROUTERALERT 5 +#define IPV6_TLV_JUMBO 194 +#define IPV6_TLV_HAO 201 /* home address option */ + +/* + * IPV6 socket options + */ +#define IPV6_ADDRFORM 1 +#define IPV6_2292PKTINFO 2 +#define IPV6_2292HOPOPTS 3 +#define IPV6_2292DSTOPTS 4 +#define IPV6_2292RTHDR 5 +#define IPV6_2292PKTOPTIONS 6 +#define IPV6_CHECKSUM 7 +#define IPV6_2292HOPLIMIT 8 +#define IPV6_NEXTHOP 9 +#define IPV6_AUTHHDR 10 /* obsolete */ +#define IPV6_FLOWINFO 11 + +#define IPV6_UNICAST_HOPS 16 +#define IPV6_MULTICAST_IF 17 +#define IPV6_MULTICAST_HOPS 18 +#define IPV6_MULTICAST_LOOP 19 +#define IPV6_ADD_MEMBERSHIP 20 +#define IPV6_DROP_MEMBERSHIP 21 +#define IPV6_ROUTER_ALERT 22 +#define IPV6_MTU_DISCOVER 23 +#define IPV6_MTU 24 +#define IPV6_RECVERR 25 +#define IPV6_V6ONLY 26 +#define IPV6_JOIN_ANYCAST 27 +#define IPV6_LEAVE_ANYCAST 28 + +/* IPV6_MTU_DISCOVER values */ +#define IPV6_PMTUDISC_DONT 0 +#define IPV6_PMTUDISC_WANT 1 +#define IPV6_PMTUDISC_DO 2 +#define IPV6_PMTUDISC_PROBE 3 +/* same as IPV6_PMTUDISC_PROBE, provided for symetry with IPv4 + * also see comments on IP_PMTUDISC_INTERFACE + */ +#define IPV6_PMTUDISC_INTERFACE 4 +/* weaker version of IPV6_PMTUDISC_INTERFACE, which allows packets to + * get fragmented if they exceed the interface mtu + */ +#define IPV6_PMTUDISC_OMIT 5 + +/* Flowlabel */ +#define IPV6_FLOWLABEL_MGR 32 +#define IPV6_FLOWINFO_SEND 33 + +#define IPV6_IPSEC_POLICY 34 +#define IPV6_XFRM_POLICY 35 +#define IPV6_HDRINCL 36 + +/* + * Multicast Routing: + * see include/uapi/linux/mroute6.h. + * + * MRT6_BASE 200 + * ... + * MRT6_MAX + */ +#endif /* _LINUX_IN6_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/ioctl.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/ioctl.h new file mode 100644 index 000000000..0da2c7d18 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/ioctl.h @@ -0,0 +1,96 @@ +#ifndef _ASM_GENERIC_IOCTL_H +#define _ASM_GENERIC_IOCTL_H + +/* ioctl command encoding: 32 bits total, command in lower 16 bits, + * size of the parameter structure in the lower 14 bits of the + * upper 16 bits. + * Encoding the size of the parameter structure in the ioctl request + * is useful for catching programs compiled with old versions + * and to avoid overwriting user space outside the user buffer area. + * The highest 2 bits are reserved for indicating the ``access mode''. + * NOTE: This limits the max parameter size to 16kB -1 ! + */ + +/* + * The following is for compatibility across the various Linux + * platforms. The generic ioctl numbering scheme doesn't really enforce + * a type field. De facto, however, the top 8 bits of the lower 16 + * bits are indeed used as a type field, so we might just as well make + * this explicit here. Please be sure to use the decoding macros + * below from now on. + */ +#define _IOC_NRBITS 8 +#define _IOC_TYPEBITS 8 + +/* + * Let any architecture override either of the following before + * including this file. + */ + +#ifndef _IOC_SIZEBITS +# define _IOC_SIZEBITS 14 +#endif + +#ifndef _IOC_DIRBITS +# define _IOC_DIRBITS 2 +#endif + +#define _IOC_NRMASK ((1 << _IOC_NRBITS)-1) +#define _IOC_TYPEMASK ((1 << _IOC_TYPEBITS)-1) +#define _IOC_SIZEMASK ((1 << _IOC_SIZEBITS)-1) +#define _IOC_DIRMASK ((1 << _IOC_DIRBITS)-1) + +#define _IOC_NRSHIFT 0 +#define _IOC_TYPESHIFT (_IOC_NRSHIFT+_IOC_NRBITS) +#define _IOC_SIZESHIFT (_IOC_TYPESHIFT+_IOC_TYPEBITS) +#define _IOC_DIRSHIFT (_IOC_SIZESHIFT+_IOC_SIZEBITS) + +/* + * Direction bits, which any architecture can choose to override + * before including this file. + */ + +#ifndef _IOC_NONE +# define _IOC_NONE 0U +#endif + +#ifndef _IOC_WRITE +# define _IOC_WRITE 1U +#endif + +#ifndef _IOC_READ +# define _IOC_READ 2U +#endif + +#define _IOC(dir,type,nr,size) \ + (((dir) << _IOC_DIRSHIFT) | \ + ((type) << _IOC_TYPESHIFT) | \ + ((nr) << _IOC_NRSHIFT) | \ + ((size) << _IOC_SIZESHIFT)) + +#define _IOC_TYPECHECK(t) (sizeof(t)) + +/* used to create numbers */ +#define _IO(type,nr) _IOC(_IOC_NONE,(type),(nr),0) +#define _IOR(type,nr,size) _IOC(_IOC_READ,(type),(nr),(_IOC_TYPECHECK(size))) +#define _IOW(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size))) +#define _IOWR(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),(_IOC_TYPECHECK(size))) +#define _IOR_BAD(type,nr,size) _IOC(_IOC_READ,(type),(nr),sizeof(size)) +#define _IOW_BAD(type,nr,size) _IOC(_IOC_WRITE,(type),(nr),sizeof(size)) +#define _IOWR_BAD(type,nr,size) _IOC(_IOC_READ|_IOC_WRITE,(type),(nr),sizeof(size)) + +/* used to decode ioctl numbers.. */ +#define _IOC_DIR(nr) (((nr) >> _IOC_DIRSHIFT) & _IOC_DIRMASK) +#define _IOC_TYPE(nr) (((nr) >> _IOC_TYPESHIFT) & _IOC_TYPEMASK) +#define _IOC_NR(nr) (((nr) >> _IOC_NRSHIFT) & _IOC_NRMASK) +#define _IOC_SIZE(nr) (((nr) >> _IOC_SIZESHIFT) & _IOC_SIZEMASK) + +/* ...and for the drivers/sound files... */ + +#define IOC_IN (_IOC_WRITE << _IOC_DIRSHIFT) +#define IOC_OUT (_IOC_READ << _IOC_DIRSHIFT) +#define IOC_INOUT ((_IOC_WRITE|_IOC_READ) << _IOC_DIRSHIFT) +#define IOCSIZE_MASK (_IOC_SIZEMASK << _IOC_SIZESHIFT) +#define IOCSIZE_SHIFT (_IOC_SIZESHIFT) + +#endif /* _ASM_GENERIC_IOCTL_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/ip.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/ip.h new file mode 100644 index 000000000..a6a235630 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/ip.h @@ -0,0 +1,137 @@ +/* + * INET An implementation of the TCP/IP protocol suite for the LINUX + * operating system. INET is implemented using the BSD Socket + * interface as the means of communication with the user level. + * + * Definitions for the IP protocol. + * + * Version: @(#)ip.h 1.0.2 04/28/93 + * + * Authors: Fred N. van Kempen, + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ +#ifndef _LINUX_IP_H +#define _LINUX_IP_H + +#include +#include + +#define IPTOS_TOS_MASK 0x1E +#define IPTOS_TOS(tos) ((tos)&IPTOS_TOS_MASK) +#define IPTOS_LOWDELAY 0x10 +#define IPTOS_THROUGHPUT 0x08 +#define IPTOS_RELIABILITY 0x04 +#define IPTOS_MINCOST 0x02 + +#define IPTOS_PREC_MASK 0xE0 +#define IPTOS_PREC(tos) ((tos)&IPTOS_PREC_MASK) +#define IPTOS_PREC_NETCONTROL 0xe0 +#define IPTOS_PREC_INTERNETCONTROL 0xc0 +#define IPTOS_PREC_CRITIC_ECP 0xa0 +#define IPTOS_PREC_FLASHOVERRIDE 0x80 +#define IPTOS_PREC_FLASH 0x60 +#define IPTOS_PREC_IMMEDIATE 0x40 +#define IPTOS_PREC_PRIORITY 0x20 +#define IPTOS_PREC_ROUTINE 0x00 + + +/* IP options */ +#define IPOPT_COPY 0x80 +#define IPOPT_CLASS_MASK 0x60 +#define IPOPT_NUMBER_MASK 0x1f + +#define IPOPT_COPIED(o) ((o)&IPOPT_COPY) +#define IPOPT_CLASS(o) ((o)&IPOPT_CLASS_MASK) +#define IPOPT_NUMBER(o) ((o)&IPOPT_NUMBER_MASK) + +#define IPOPT_CONTROL 0x00 +#define IPOPT_RESERVED1 0x20 +#define IPOPT_MEASUREMENT 0x40 +#define IPOPT_RESERVED2 0x60 + +#define IPOPT_END (0 |IPOPT_CONTROL) +#define IPOPT_NOOP (1 |IPOPT_CONTROL) +#define IPOPT_SEC (2 |IPOPT_CONTROL|IPOPT_COPY) +#define IPOPT_LSRR (3 |IPOPT_CONTROL|IPOPT_COPY) +#define IPOPT_TIMESTAMP (4 |IPOPT_MEASUREMENT) +#define IPOPT_CIPSO (6 |IPOPT_CONTROL|IPOPT_COPY) +#define IPOPT_RR (7 |IPOPT_CONTROL) +#define IPOPT_SID (8 |IPOPT_CONTROL|IPOPT_COPY) +#define IPOPT_SSRR (9 |IPOPT_CONTROL|IPOPT_COPY) +#define IPOPT_RA (20|IPOPT_CONTROL|IPOPT_COPY) + +#define IPVERSION 4 +#define MAXTTL 255 +#define IPDEFTTL 64 + +#define IPOPT_OPTVAL 0 +#define IPOPT_OLEN 1 +#define IPOPT_OFFSET 2 +#define IPOPT_MINOFF 4 +#define MAX_IPOPTLEN 40 +#define IPOPT_NOP IPOPT_NOOP +#define IPOPT_EOL IPOPT_END +#define IPOPT_TS IPOPT_TIMESTAMP + +#define IPOPT_TS_TSONLY 0 /* timestamps only */ +#define IPOPT_TS_TSANDADDR 1 /* timestamps and addresses */ +#define IPOPT_TS_PRESPEC 3 /* specified modules only */ + +#define IPV4_BEET_PHMAXLEN 8 + +struct iphdr { +#if defined(__LITTLE_ENDIAN_BITFIELD) + __u8 ihl:4, + version:4; +#elif defined (__BIG_ENDIAN_BITFIELD) + __u8 version:4, + ihl:4; +#else +#error "Please fix " +#endif + __u8 tos; + __be16 tot_len; + __be16 id; + __be16 frag_off; + __u8 ttl; + __u8 protocol; + __sum16 check; + __be32 saddr; + __be32 daddr; + /*The options start here. */ +}; + + +struct ip_auth_hdr { + __u8 nexthdr; + __u8 hdrlen; /* This one is measured in 32 bit units! */ + __be16 reserved; + __be32 spi; + __be32 seq_no; /* Sequence number */ + __u8 auth_data[0]; /* Variable len but >=4. Mind the 64 bit alignment! */ +}; + +struct ip_esp_hdr { + __be32 spi; + __be32 seq_no; /* Sequence number */ + __u8 enc_data[0]; /* Variable len but >=8. Mind the 64 bit alignment! */ +}; + +struct ip_comp_hdr { + __u8 nexthdr; + __u8 flags; + __be16 cpi; +}; + +struct ip_beet_phdr { + __u8 nexthdr; + __u8 hdrlen; + __u8 padlen; + __u8 reserved; +}; + +#endif /* _LINUX_IP_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/ipv6.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/ipv6.h new file mode 100644 index 000000000..e045ffdf5 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/ipv6.h @@ -0,0 +1,159 @@ +#ifndef _IPV6_H +#define _IPV6_H + +#include +#include + +/* The latest drafts declared increase in minimal mtu up to 1280. */ + +#define IPV6_MIN_MTU 1280 + +/* + * Advanced API + * source interface/address selection, source routing, etc... + * *under construction* + */ + +#define IPV6_SRCRT_STRICT 0x01 /* Deprecated; will be removed */ +#define IPV6_SRCRT_TYPE_0 0 /* Deprecated; will be removed */ +#define IPV6_SRCRT_TYPE_2 2 /* IPv6 type 2 Routing Header */ + +/* + * routing header + */ +struct ipv6_rt_hdr { + __u8 nexthdr; + __u8 hdrlen; + __u8 type; + __u8 segments_left; + + /* + * type specific data + * variable length field + */ +}; + + +struct ipv6_opt_hdr { + __u8 nexthdr; + __u8 hdrlen; + /* + * TLV encoded option data follows. + */ +} __attribute__((packed)); /* required for some archs */ + +#define ipv6_destopt_hdr ipv6_opt_hdr +#define ipv6_hopopt_hdr ipv6_opt_hdr + +/* Router Alert option values (RFC2711) */ +#define IPV6_OPT_ROUTERALERT_MLD 0x0000 /* MLD(RFC2710) */ + +/* + * routing header type 0 (used in cmsghdr struct) + */ + +struct rt0_hdr { + struct ipv6_rt_hdr rt_hdr; + __u32 reserved; + struct in6_addr addr[0]; + +#define rt0_type rt_hdr.type +}; + +/* + * routing header type 2 + */ + +struct rt2_hdr { + struct ipv6_rt_hdr rt_hdr; + __u32 reserved; + struct in6_addr addr; + +#define rt2_type rt_hdr.type +}; + +/* + * home address option in destination options header + */ + +struct ipv6_destopt_hao { + __u8 type; + __u8 length; + struct in6_addr addr; +} __attribute__((packed)); + +/* + * IPv6 fixed header + * + * BEWARE, it is incorrect. The first 4 bits of flow_lbl + * are glued to priority now, forming "class". + */ + +struct ipv6hdr { +#if defined(__LITTLE_ENDIAN_BITFIELD) + __u8 priority:4, + version:4; +#elif defined(__BIG_ENDIAN_BITFIELD) + __u8 version:4, + priority:4; +#else +#error "Please fix " +#endif + __u8 flow_lbl[3]; + + __be16 payload_len; + __u8 nexthdr; + __u8 hop_limit; + + struct in6_addr saddr; + struct in6_addr daddr; +}; + + +/* index values for the variables in ipv6_devconf */ +enum { + DEVCONF_FORWARDING = 0, + DEVCONF_HOPLIMIT, + DEVCONF_MTU6, + DEVCONF_ACCEPT_RA, + DEVCONF_ACCEPT_REDIRECTS, + DEVCONF_AUTOCONF, + DEVCONF_DAD_TRANSMITS, + DEVCONF_RTR_SOLICITS, + DEVCONF_RTR_SOLICIT_INTERVAL, + DEVCONF_RTR_SOLICIT_DELAY, + DEVCONF_USE_TEMPADDR, + DEVCONF_TEMP_VALID_LFT, + DEVCONF_TEMP_PREFERED_LFT, + DEVCONF_REGEN_MAX_RETRY, + DEVCONF_MAX_DESYNC_FACTOR, + DEVCONF_MAX_ADDRESSES, + DEVCONF_FORCE_MLD_VERSION, + DEVCONF_ACCEPT_RA_DEFRTR, + DEVCONF_ACCEPT_RA_PINFO, + DEVCONF_ACCEPT_RA_RTR_PREF, + DEVCONF_RTR_PROBE_INTERVAL, + DEVCONF_ACCEPT_RA_RT_INFO_MAX_PLEN, + DEVCONF_PROXY_NDP, + DEVCONF_OPTIMISTIC_DAD, + DEVCONF_ACCEPT_SOURCE_ROUTE, + DEVCONF_MC_FORWARDING, + DEVCONF_DISABLE_IPV6, + DEVCONF_ACCEPT_DAD, + DEVCONF_FORCE_TLLAO, + DEVCONF_NDISC_NOTIFY, + DEVCONF_MLDV1_UNSOLICITED_REPORT_INTERVAL, + DEVCONF_MLDV2_UNSOLICITED_REPORT_INTERVAL, + DEVCONF_SUPPRESS_FRAG_NDISC, + DEVCONF_ACCEPT_RA_FROM_LOCAL, + DEVCONF_USE_OPTIMISTIC, + DEVCONF_ACCEPT_RA_MTU, + DEVCONF_STABLE_SECRET, + DEVCONF_USE_OIF_ADDRS_ONLY, + DEVCONF_ACCEPT_RA_MIN_HOP_LIMIT, + DEVCONF_IGNORE_ROUTES_WITH_LINKDOWN, + DEVCONF_MAX +}; + + +#endif /* _IPV6_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/perf_event.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/perf_event.h new file mode 100644 index 000000000..30dd3c8f8 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/perf_event.h @@ -0,0 +1,978 @@ +/* + * Performance events: + * + * Copyright (C) 2008-2009, Thomas Gleixner + * Copyright (C) 2008-2011, Red Hat, Inc., Ingo Molnar + * Copyright (C) 2008-2011, Red Hat, Inc., Peter Zijlstra + * + * Data type definitions, declarations, prototypes. + * + * Started by: Thomas Gleixner and Ingo Molnar + * + * For licencing details see kernel-base/COPYING + */ +#ifndef _LINUX_PERF_EVENT_H +#define _LINUX_PERF_EVENT_H + +#include +#include + +/* + * User-space ABI bits: + */ + +/* + * attr.type + */ +enum perf_type_id { + PERF_TYPE_HARDWARE = 0, + PERF_TYPE_SOFTWARE = 1, + PERF_TYPE_TRACEPOINT = 2, + PERF_TYPE_HW_CACHE = 3, + PERF_TYPE_RAW = 4, + PERF_TYPE_BREAKPOINT = 5, + + PERF_TYPE_MAX, /* non-ABI */ +}; + +/* + * Generalized performance event event_id types, used by the + * attr.event_id parameter of the sys_perf_event_open() + * syscall: + */ +enum perf_hw_id { + /* + * Common hardware events, generalized by the kernel: + */ + PERF_COUNT_HW_CPU_CYCLES = 0, + PERF_COUNT_HW_INSTRUCTIONS = 1, + PERF_COUNT_HW_CACHE_REFERENCES = 2, + PERF_COUNT_HW_CACHE_MISSES = 3, + PERF_COUNT_HW_BRANCH_INSTRUCTIONS = 4, + PERF_COUNT_HW_BRANCH_MISSES = 5, + PERF_COUNT_HW_BUS_CYCLES = 6, + PERF_COUNT_HW_STALLED_CYCLES_FRONTEND = 7, + PERF_COUNT_HW_STALLED_CYCLES_BACKEND = 8, + PERF_COUNT_HW_REF_CPU_CYCLES = 9, + + PERF_COUNT_HW_MAX, /* non-ABI */ +}; + +/* + * Generalized hardware cache events: + * + * { L1-D, L1-I, LLC, ITLB, DTLB, BPU, NODE } x + * { read, write, prefetch } x + * { accesses, misses } + */ +enum perf_hw_cache_id { + PERF_COUNT_HW_CACHE_L1D = 0, + PERF_COUNT_HW_CACHE_L1I = 1, + PERF_COUNT_HW_CACHE_LL = 2, + PERF_COUNT_HW_CACHE_DTLB = 3, + PERF_COUNT_HW_CACHE_ITLB = 4, + PERF_COUNT_HW_CACHE_BPU = 5, + PERF_COUNT_HW_CACHE_NODE = 6, + + PERF_COUNT_HW_CACHE_MAX, /* non-ABI */ +}; + +enum perf_hw_cache_op_id { + PERF_COUNT_HW_CACHE_OP_READ = 0, + PERF_COUNT_HW_CACHE_OP_WRITE = 1, + PERF_COUNT_HW_CACHE_OP_PREFETCH = 2, + + PERF_COUNT_HW_CACHE_OP_MAX, /* non-ABI */ +}; + +enum perf_hw_cache_op_result_id { + PERF_COUNT_HW_CACHE_RESULT_ACCESS = 0, + PERF_COUNT_HW_CACHE_RESULT_MISS = 1, + + PERF_COUNT_HW_CACHE_RESULT_MAX, /* non-ABI */ +}; + +/* + * Special "software" events provided by the kernel, even if the hardware + * does not support performance events. These events measure various + * physical and sw events of the kernel (and allow the profiling of them as + * well): + */ +enum perf_sw_ids { + PERF_COUNT_SW_CPU_CLOCK = 0, + PERF_COUNT_SW_TASK_CLOCK = 1, + PERF_COUNT_SW_PAGE_FAULTS = 2, + PERF_COUNT_SW_CONTEXT_SWITCHES = 3, + PERF_COUNT_SW_CPU_MIGRATIONS = 4, + PERF_COUNT_SW_PAGE_FAULTS_MIN = 5, + PERF_COUNT_SW_PAGE_FAULTS_MAJ = 6, + PERF_COUNT_SW_ALIGNMENT_FAULTS = 7, + PERF_COUNT_SW_EMULATION_FAULTS = 8, + PERF_COUNT_SW_DUMMY = 9, + PERF_COUNT_SW_BPF_OUTPUT = 10, + + PERF_COUNT_SW_MAX, /* non-ABI */ +}; + +/* + * Bits that can be set in attr.sample_type to request information + * in the overflow packets. + */ +enum perf_event_sample_format { + PERF_SAMPLE_IP = 1U << 0, + PERF_SAMPLE_TID = 1U << 1, + PERF_SAMPLE_TIME = 1U << 2, + PERF_SAMPLE_ADDR = 1U << 3, + PERF_SAMPLE_READ = 1U << 4, + PERF_SAMPLE_CALLCHAIN = 1U << 5, + PERF_SAMPLE_ID = 1U << 6, + PERF_SAMPLE_CPU = 1U << 7, + PERF_SAMPLE_PERIOD = 1U << 8, + PERF_SAMPLE_STREAM_ID = 1U << 9, + PERF_SAMPLE_RAW = 1U << 10, + PERF_SAMPLE_BRANCH_STACK = 1U << 11, + PERF_SAMPLE_REGS_USER = 1U << 12, + PERF_SAMPLE_STACK_USER = 1U << 13, + PERF_SAMPLE_WEIGHT = 1U << 14, + PERF_SAMPLE_DATA_SRC = 1U << 15, + PERF_SAMPLE_IDENTIFIER = 1U << 16, + PERF_SAMPLE_TRANSACTION = 1U << 17, + PERF_SAMPLE_REGS_INTR = 1U << 18, + + PERF_SAMPLE_MAX = 1U << 19, /* non-ABI */ +}; + +/* + * values to program into branch_sample_type when PERF_SAMPLE_BRANCH is set + * + * If the user does not pass priv level information via branch_sample_type, + * the kernel uses the event's priv level. Branch and event priv levels do + * not have to match. Branch priv level is checked for permissions. + * + * The branch types can be combined, however BRANCH_ANY covers all types + * of branches and therefore it supersedes all the other types. + */ +enum perf_branch_sample_type_shift { + PERF_SAMPLE_BRANCH_USER_SHIFT = 0, /* user branches */ + PERF_SAMPLE_BRANCH_KERNEL_SHIFT = 1, /* kernel branches */ + PERF_SAMPLE_BRANCH_HV_SHIFT = 2, /* hypervisor branches */ + + PERF_SAMPLE_BRANCH_ANY_SHIFT = 3, /* any branch types */ + PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT = 4, /* any call branch */ + PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT = 5, /* any return branch */ + PERF_SAMPLE_BRANCH_IND_CALL_SHIFT = 6, /* indirect calls */ + PERF_SAMPLE_BRANCH_ABORT_TX_SHIFT = 7, /* transaction aborts */ + PERF_SAMPLE_BRANCH_IN_TX_SHIFT = 8, /* in transaction */ + PERF_SAMPLE_BRANCH_NO_TX_SHIFT = 9, /* not in transaction */ + PERF_SAMPLE_BRANCH_COND_SHIFT = 10, /* conditional branches */ + + PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT = 11, /* call/ret stack */ + PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT = 12, /* indirect jumps */ + PERF_SAMPLE_BRANCH_CALL_SHIFT = 13, /* direct call */ + + PERF_SAMPLE_BRANCH_NO_FLAGS_SHIFT = 14, /* no flags */ + PERF_SAMPLE_BRANCH_NO_CYCLES_SHIFT = 15, /* no cycles */ + + PERF_SAMPLE_BRANCH_MAX_SHIFT /* non-ABI */ +}; + +enum perf_branch_sample_type { + PERF_SAMPLE_BRANCH_USER = 1U << PERF_SAMPLE_BRANCH_USER_SHIFT, + PERF_SAMPLE_BRANCH_KERNEL = 1U << PERF_SAMPLE_BRANCH_KERNEL_SHIFT, + PERF_SAMPLE_BRANCH_HV = 1U << PERF_SAMPLE_BRANCH_HV_SHIFT, + + PERF_SAMPLE_BRANCH_ANY = 1U << PERF_SAMPLE_BRANCH_ANY_SHIFT, + PERF_SAMPLE_BRANCH_ANY_CALL = 1U << PERF_SAMPLE_BRANCH_ANY_CALL_SHIFT, + PERF_SAMPLE_BRANCH_ANY_RETURN = 1U << PERF_SAMPLE_BRANCH_ANY_RETURN_SHIFT, + PERF_SAMPLE_BRANCH_IND_CALL = 1U << PERF_SAMPLE_BRANCH_IND_CALL_SHIFT, + PERF_SAMPLE_BRANCH_ABORT_TX = 1U << PERF_SAMPLE_BRANCH_ABORT_TX_SHIFT, + PERF_SAMPLE_BRANCH_IN_TX = 1U << PERF_SAMPLE_BRANCH_IN_TX_SHIFT, + PERF_SAMPLE_BRANCH_NO_TX = 1U << PERF_SAMPLE_BRANCH_NO_TX_SHIFT, + PERF_SAMPLE_BRANCH_COND = 1U << PERF_SAMPLE_BRANCH_COND_SHIFT, + + PERF_SAMPLE_BRANCH_CALL_STACK = 1U << PERF_SAMPLE_BRANCH_CALL_STACK_SHIFT, + PERF_SAMPLE_BRANCH_IND_JUMP = 1U << PERF_SAMPLE_BRANCH_IND_JUMP_SHIFT, + PERF_SAMPLE_BRANCH_CALL = 1U << PERF_SAMPLE_BRANCH_CALL_SHIFT, + + PERF_SAMPLE_BRANCH_NO_FLAGS = 1U << PERF_SAMPLE_BRANCH_NO_FLAGS_SHIFT, + PERF_SAMPLE_BRANCH_NO_CYCLES = 1U << PERF_SAMPLE_BRANCH_NO_CYCLES_SHIFT, + + PERF_SAMPLE_BRANCH_MAX = 1U << PERF_SAMPLE_BRANCH_MAX_SHIFT, +}; + +#define PERF_SAMPLE_BRANCH_PLM_ALL \ + (PERF_SAMPLE_BRANCH_USER|\ + PERF_SAMPLE_BRANCH_KERNEL|\ + PERF_SAMPLE_BRANCH_HV) + +/* + * Values to determine ABI of the registers dump. + */ +enum perf_sample_regs_abi { + PERF_SAMPLE_REGS_ABI_NONE = 0, + PERF_SAMPLE_REGS_ABI_32 = 1, + PERF_SAMPLE_REGS_ABI_64 = 2, +}; + +/* + * Values for the memory transaction event qualifier, mostly for + * abort events. Multiple bits can be set. + */ +enum { + PERF_TXN_ELISION = (1 << 0), /* From elision */ + PERF_TXN_TRANSACTION = (1 << 1), /* From transaction */ + PERF_TXN_SYNC = (1 << 2), /* Instruction is related */ + PERF_TXN_ASYNC = (1 << 3), /* Instruction not related */ + PERF_TXN_RETRY = (1 << 4), /* Retry possible */ + PERF_TXN_CONFLICT = (1 << 5), /* Conflict abort */ + PERF_TXN_CAPACITY_WRITE = (1 << 6), /* Capacity write abort */ + PERF_TXN_CAPACITY_READ = (1 << 7), /* Capacity read abort */ + + PERF_TXN_MAX = (1 << 8), /* non-ABI */ + + /* bits 32..63 are reserved for the abort code */ + + PERF_TXN_ABORT_MASK = (0xffffffffULL << 32), + PERF_TXN_ABORT_SHIFT = 32, +}; + +/* + * The format of the data returned by read() on a perf event fd, + * as specified by attr.read_format: + * + * struct read_format { + * { u64 value; + * { u64 time_enabled; } && PERF_FORMAT_TOTAL_TIME_ENABLED + * { u64 time_running; } && PERF_FORMAT_TOTAL_TIME_RUNNING + * { u64 id; } && PERF_FORMAT_ID + * } && !PERF_FORMAT_GROUP + * + * { u64 nr; + * { u64 time_enabled; } && PERF_FORMAT_TOTAL_TIME_ENABLED + * { u64 time_running; } && PERF_FORMAT_TOTAL_TIME_RUNNING + * { u64 value; + * { u64 id; } && PERF_FORMAT_ID + * } cntr[nr]; + * } && PERF_FORMAT_GROUP + * }; + */ +enum perf_event_read_format { + PERF_FORMAT_TOTAL_TIME_ENABLED = 1U << 0, + PERF_FORMAT_TOTAL_TIME_RUNNING = 1U << 1, + PERF_FORMAT_ID = 1U << 2, + PERF_FORMAT_GROUP = 1U << 3, + + PERF_FORMAT_MAX = 1U << 4, /* non-ABI */ +}; + +#define PERF_ATTR_SIZE_VER0 64 /* sizeof first published struct */ +#define PERF_ATTR_SIZE_VER1 72 /* add: config2 */ +#define PERF_ATTR_SIZE_VER2 80 /* add: branch_sample_type */ +#define PERF_ATTR_SIZE_VER3 96 /* add: sample_regs_user */ + /* add: sample_stack_user */ +#define PERF_ATTR_SIZE_VER4 104 /* add: sample_regs_intr */ +#define PERF_ATTR_SIZE_VER5 112 /* add: aux_watermark */ + +/* + * Hardware event_id to monitor via a performance monitoring event: + */ +struct perf_event_attr { + + /* + * Major type: hardware/software/tracepoint/etc. + */ + __u32 type; + + /* + * Size of the attr structure, for fwd/bwd compat. + */ + __u32 size; + + /* + * Type specific configuration information. + */ + __u64 config; + + union { + __u64 sample_period; + __u64 sample_freq; + }; + + __u64 sample_type; + __u64 read_format; + + __u64 disabled : 1, /* off by default */ + inherit : 1, /* children inherit it */ + pinned : 1, /* must always be on PMU */ + exclusive : 1, /* only group on PMU */ + exclude_user : 1, /* don't count user */ + exclude_kernel : 1, /* ditto kernel */ + exclude_hv : 1, /* ditto hypervisor */ + exclude_idle : 1, /* don't count when idle */ + mmap : 1, /* include mmap data */ + comm : 1, /* include comm data */ + freq : 1, /* use freq, not period */ + inherit_stat : 1, /* per task counts */ + enable_on_exec : 1, /* next exec enables */ + task : 1, /* trace fork/exit */ + watermark : 1, /* wakeup_watermark */ + /* + * precise_ip: + * + * 0 - SAMPLE_IP can have arbitrary skid + * 1 - SAMPLE_IP must have constant skid + * 2 - SAMPLE_IP requested to have 0 skid + * 3 - SAMPLE_IP must have 0 skid + * + * See also PERF_RECORD_MISC_EXACT_IP + */ + precise_ip : 2, /* skid constraint */ + mmap_data : 1, /* non-exec mmap data */ + sample_id_all : 1, /* sample_type all events */ + + exclude_host : 1, /* don't count in host */ + exclude_guest : 1, /* don't count in guest */ + + exclude_callchain_kernel : 1, /* exclude kernel callchains */ + exclude_callchain_user : 1, /* exclude user callchains */ + mmap2 : 1, /* include mmap with inode data */ + comm_exec : 1, /* flag comm events that are due to an exec */ + use_clockid : 1, /* use @clockid for time fields */ + context_switch : 1, /* context switch data */ + write_backward : 1, /* Write ring buffer from end to beginning */ + __reserved_1 : 36; + + union { + __u32 wakeup_events; /* wakeup every n events */ + __u32 wakeup_watermark; /* bytes before wakeup */ + }; + + __u32 bp_type; + union { + __u64 bp_addr; + __u64 config1; /* extension of config */ + }; + union { + __u64 bp_len; + __u64 config2; /* extension of config1 */ + }; + __u64 branch_sample_type; /* enum perf_branch_sample_type */ + + /* + * Defines set of user regs to dump on samples. + * See asm/perf_regs.h for details. + */ + __u64 sample_regs_user; + + /* + * Defines size of the user stack to dump on samples. + */ + __u32 sample_stack_user; + + __s32 clockid; + /* + * Defines set of regs to dump for each sample + * state captured on: + * - precise = 0: PMU interrupt + * - precise > 0: sampled instruction + * + * See asm/perf_regs.h for details. + */ + __u64 sample_regs_intr; + + /* + * Wakeup watermark for AUX area + */ + __u32 aux_watermark; + __u32 __reserved_2; /* align to __u64 */ +}; + +#define perf_flags(attr) (*(&(attr)->read_format + 1)) + +/* + * Ioctls that can be done on a perf event fd: + */ +#define PERF_EVENT_IOC_ENABLE _IO ('$', 0) +#define PERF_EVENT_IOC_DISABLE _IO ('$', 1) +#define PERF_EVENT_IOC_REFRESH _IO ('$', 2) +#define PERF_EVENT_IOC_RESET _IO ('$', 3) +#define PERF_EVENT_IOC_PERIOD _IOW('$', 4, __u64) +#define PERF_EVENT_IOC_SET_OUTPUT _IO ('$', 5) +#define PERF_EVENT_IOC_SET_FILTER _IOW('$', 6, char *) +#define PERF_EVENT_IOC_ID _IOR('$', 7, __u64 *) +#define PERF_EVENT_IOC_SET_BPF _IOW('$', 8, __u32) +#define PERF_EVENT_IOC_PAUSE_OUTPUT _IOW('$', 9, __u32) + +enum perf_event_ioc_flags { + PERF_IOC_FLAG_GROUP = 1U << 0, +}; + +/* + * Structure of the page that can be mapped via mmap + */ +struct perf_event_mmap_page { + __u32 version; /* version number of this structure */ + __u32 compat_version; /* lowest version this is compat with */ + + /* + * Bits needed to read the hw events in user-space. + * + * u32 seq, time_mult, time_shift, index, width; + * u64 count, enabled, running; + * u64 cyc, time_offset; + * s64 pmc = 0; + * + * do { + * seq = pc->lock; + * barrier() + * + * enabled = pc->time_enabled; + * running = pc->time_running; + * + * if (pc->cap_usr_time && enabled != running) { + * cyc = rdtsc(); + * time_offset = pc->time_offset; + * time_mult = pc->time_mult; + * time_shift = pc->time_shift; + * } + * + * index = pc->index; + * count = pc->offset; + * if (pc->cap_user_rdpmc && index) { + * width = pc->pmc_width; + * pmc = rdpmc(index - 1); + * } + * + * barrier(); + * } while (pc->lock != seq); + * + * NOTE: for obvious reason this only works on self-monitoring + * processes. + */ + __u32 lock; /* seqlock for synchronization */ + __u32 index; /* hardware event identifier */ + __s64 offset; /* add to hardware event value */ + __u64 time_enabled; /* time event active */ + __u64 time_running; /* time event on cpu */ + union { + __u64 capabilities; + struct { + __u64 cap_bit0 : 1, /* Always 0, deprecated, see commit 860f085b74e9 */ + cap_bit0_is_deprecated : 1, /* Always 1, signals that bit 0 is zero */ + + cap_user_rdpmc : 1, /* The RDPMC instruction can be used to read counts */ + cap_user_time : 1, /* The time_* fields are used */ + cap_user_time_zero : 1, /* The time_zero field is used */ + cap_____res : 59; + }; + }; + + /* + * If cap_user_rdpmc this field provides the bit-width of the value + * read using the rdpmc() or equivalent instruction. This can be used + * to sign extend the result like: + * + * pmc <<= 64 - width; + * pmc >>= 64 - width; // signed shift right + * count += pmc; + */ + __u16 pmc_width; + + /* + * If cap_usr_time the below fields can be used to compute the time + * delta since time_enabled (in ns) using rdtsc or similar. + * + * u64 quot, rem; + * u64 delta; + * + * quot = (cyc >> time_shift); + * rem = cyc & (((u64)1 << time_shift) - 1); + * delta = time_offset + quot * time_mult + + * ((rem * time_mult) >> time_shift); + * + * Where time_offset,time_mult,time_shift and cyc are read in the + * seqcount loop described above. This delta can then be added to + * enabled and possible running (if index), improving the scaling: + * + * enabled += delta; + * if (index) + * running += delta; + * + * quot = count / running; + * rem = count % running; + * count = quot * enabled + (rem * enabled) / running; + */ + __u16 time_shift; + __u32 time_mult; + __u64 time_offset; + /* + * If cap_usr_time_zero, the hardware clock (e.g. TSC) can be calculated + * from sample timestamps. + * + * time = timestamp - time_zero; + * quot = time / time_mult; + * rem = time % time_mult; + * cyc = (quot << time_shift) + (rem << time_shift) / time_mult; + * + * And vice versa: + * + * quot = cyc >> time_shift; + * rem = cyc & (((u64)1 << time_shift) - 1); + * timestamp = time_zero + quot * time_mult + + * ((rem * time_mult) >> time_shift); + */ + __u64 time_zero; + __u32 size; /* Header size up to __reserved[] fields. */ + + /* + * Hole for extension of the self monitor capabilities + */ + + __u8 __reserved[118*8+4]; /* align to 1k. */ + + /* + * Control data for the mmap() data buffer. + * + * User-space reading the @data_head value should issue an smp_rmb(), + * after reading this value. + * + * When the mapping is PROT_WRITE the @data_tail value should be + * written by userspace to reflect the last read data, after issueing + * an smp_mb() to separate the data read from the ->data_tail store. + * In this case the kernel will not over-write unread data. + * + * See perf_output_put_handle() for the data ordering. + * + * data_{offset,size} indicate the location and size of the perf record + * buffer within the mmapped area. + */ + __u64 data_head; /* head in the data section */ + __u64 data_tail; /* user-space written tail */ + __u64 data_offset; /* where the buffer starts */ + __u64 data_size; /* data buffer size */ + + /* + * AUX area is defined by aux_{offset,size} fields that should be set + * by the userspace, so that + * + * aux_offset >= data_offset + data_size + * + * prior to mmap()ing it. Size of the mmap()ed area should be aux_size. + * + * Ring buffer pointers aux_{head,tail} have the same semantics as + * data_{head,tail} and same ordering rules apply. + */ + __u64 aux_head; + __u64 aux_tail; + __u64 aux_offset; + __u64 aux_size; +}; + +#define PERF_RECORD_MISC_CPUMODE_MASK (7 << 0) +#define PERF_RECORD_MISC_CPUMODE_UNKNOWN (0 << 0) +#define PERF_RECORD_MISC_KERNEL (1 << 0) +#define PERF_RECORD_MISC_USER (2 << 0) +#define PERF_RECORD_MISC_HYPERVISOR (3 << 0) +#define PERF_RECORD_MISC_GUEST_KERNEL (4 << 0) +#define PERF_RECORD_MISC_GUEST_USER (5 << 0) + +/* + * Indicates that /proc/PID/maps parsing are truncated by time out. + */ +#define PERF_RECORD_MISC_PROC_MAP_PARSE_TIMEOUT (1 << 12) +/* + * PERF_RECORD_MISC_MMAP_DATA and PERF_RECORD_MISC_COMM_EXEC are used on + * different events so can reuse the same bit position. + * Ditto PERF_RECORD_MISC_SWITCH_OUT. + */ +#define PERF_RECORD_MISC_MMAP_DATA (1 << 13) +#define PERF_RECORD_MISC_COMM_EXEC (1 << 13) +#define PERF_RECORD_MISC_SWITCH_OUT (1 << 13) +/* + * Indicates that the content of PERF_SAMPLE_IP points to + * the actual instruction that triggered the event. See also + * perf_event_attr::precise_ip. + */ +#define PERF_RECORD_MISC_EXACT_IP (1 << 14) +/* + * Reserve the last bit to indicate some extended misc field + */ +#define PERF_RECORD_MISC_EXT_RESERVED (1 << 15) + +struct perf_event_header { + __u32 type; + __u16 misc; + __u16 size; +}; + +enum perf_event_type { + + /* + * If perf_event_attr.sample_id_all is set then all event types will + * have the sample_type selected fields related to where/when + * (identity) an event took place (TID, TIME, ID, STREAM_ID, CPU, + * IDENTIFIER) described in PERF_RECORD_SAMPLE below, it will be stashed + * just after the perf_event_header and the fields already present for + * the existing fields, i.e. at the end of the payload. That way a newer + * perf.data file will be supported by older perf tools, with these new + * optional fields being ignored. + * + * struct sample_id { + * { u32 pid, tid; } && PERF_SAMPLE_TID + * { u64 time; } && PERF_SAMPLE_TIME + * { u64 id; } && PERF_SAMPLE_ID + * { u64 stream_id;} && PERF_SAMPLE_STREAM_ID + * { u32 cpu, res; } && PERF_SAMPLE_CPU + * { u64 id; } && PERF_SAMPLE_IDENTIFIER + * } && perf_event_attr::sample_id_all + * + * Note that PERF_SAMPLE_IDENTIFIER duplicates PERF_SAMPLE_ID. The + * advantage of PERF_SAMPLE_IDENTIFIER is that its position is fixed + * relative to header.size. + */ + + /* + * The MMAP events record the PROT_EXEC mappings so that we can + * correlate userspace IPs to code. They have the following structure: + * + * struct { + * struct perf_event_header header; + * + * u32 pid, tid; + * u64 addr; + * u64 len; + * u64 pgoff; + * char filename[]; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_MMAP = 1, + + /* + * struct { + * struct perf_event_header header; + * u64 id; + * u64 lost; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_LOST = 2, + + /* + * struct { + * struct perf_event_header header; + * + * u32 pid, tid; + * char comm[]; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_COMM = 3, + + /* + * struct { + * struct perf_event_header header; + * u32 pid, ppid; + * u32 tid, ptid; + * u64 time; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_EXIT = 4, + + /* + * struct { + * struct perf_event_header header; + * u64 time; + * u64 id; + * u64 stream_id; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_THROTTLE = 5, + PERF_RECORD_UNTHROTTLE = 6, + + /* + * struct { + * struct perf_event_header header; + * u32 pid, ppid; + * u32 tid, ptid; + * u64 time; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_FORK = 7, + + /* + * struct { + * struct perf_event_header header; + * u32 pid, tid; + * + * struct read_format values; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_READ = 8, + + /* + * struct { + * struct perf_event_header header; + * + * # + * # Note that PERF_SAMPLE_IDENTIFIER duplicates PERF_SAMPLE_ID. + * # The advantage of PERF_SAMPLE_IDENTIFIER is that its position + * # is fixed relative to header. + * # + * + * { u64 id; } && PERF_SAMPLE_IDENTIFIER + * { u64 ip; } && PERF_SAMPLE_IP + * { u32 pid, tid; } && PERF_SAMPLE_TID + * { u64 time; } && PERF_SAMPLE_TIME + * { u64 addr; } && PERF_SAMPLE_ADDR + * { u64 id; } && PERF_SAMPLE_ID + * { u64 stream_id;} && PERF_SAMPLE_STREAM_ID + * { u32 cpu, res; } && PERF_SAMPLE_CPU + * { u64 period; } && PERF_SAMPLE_PERIOD + * + * { struct read_format values; } && PERF_SAMPLE_READ + * + * { u64 nr, + * u64 ips[nr]; } && PERF_SAMPLE_CALLCHAIN + * + * # + * # The RAW record below is opaque data wrt the ABI + * # + * # That is, the ABI doesn't make any promises wrt to + * # the stability of its content, it may vary depending + * # on event, hardware, kernel version and phase of + * # the moon. + * # + * # In other words, PERF_SAMPLE_RAW contents are not an ABI. + * # + * + * { u32 size; + * char data[size];}&& PERF_SAMPLE_RAW + * + * { u64 nr; + * { u64 from, to, flags } lbr[nr];} && PERF_SAMPLE_BRANCH_STACK + * + * { u64 abi; # enum perf_sample_regs_abi + * u64 regs[weight(mask)]; } && PERF_SAMPLE_REGS_USER + * + * { u64 size; + * char data[size]; + * u64 dyn_size; } && PERF_SAMPLE_STACK_USER + * + * { u64 weight; } && PERF_SAMPLE_WEIGHT + * { u64 data_src; } && PERF_SAMPLE_DATA_SRC + * { u64 transaction; } && PERF_SAMPLE_TRANSACTION + * { u64 abi; # enum perf_sample_regs_abi + * u64 regs[weight(mask)]; } && PERF_SAMPLE_REGS_INTR + * }; + */ + PERF_RECORD_SAMPLE = 9, + + /* + * The MMAP2 records are an augmented version of MMAP, they add + * maj, min, ino numbers to be used to uniquely identify each mapping + * + * struct { + * struct perf_event_header header; + * + * u32 pid, tid; + * u64 addr; + * u64 len; + * u64 pgoff; + * u32 maj; + * u32 min; + * u64 ino; + * u64 ino_generation; + * u32 prot, flags; + * char filename[]; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_MMAP2 = 10, + + /* + * Records that new data landed in the AUX buffer part. + * + * struct { + * struct perf_event_header header; + * + * u64 aux_offset; + * u64 aux_size; + * u64 flags; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_AUX = 11, + + /* + * Indicates that instruction trace has started + * + * struct { + * struct perf_event_header header; + * u32 pid; + * u32 tid; + * }; + */ + PERF_RECORD_ITRACE_START = 12, + + /* + * Records the dropped/lost sample number. + * + * struct { + * struct perf_event_header header; + * + * u64 lost; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_LOST_SAMPLES = 13, + + /* + * Records a context switch in or out (flagged by + * PERF_RECORD_MISC_SWITCH_OUT). See also + * PERF_RECORD_SWITCH_CPU_WIDE. + * + * struct { + * struct perf_event_header header; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_SWITCH = 14, + + /* + * CPU-wide version of PERF_RECORD_SWITCH with next_prev_pid and + * next_prev_tid that are the next (switching out) or previous + * (switching in) pid/tid. + * + * struct { + * struct perf_event_header header; + * u32 next_prev_pid; + * u32 next_prev_tid; + * struct sample_id sample_id; + * }; + */ + PERF_RECORD_SWITCH_CPU_WIDE = 15, + + PERF_RECORD_MAX, /* non-ABI */ +}; + +#define PERF_MAX_STACK_DEPTH 127 +#define PERF_MAX_CONTEXTS_PER_STACK 8 + +enum perf_callchain_context { + PERF_CONTEXT_HV = (__u64)-32, + PERF_CONTEXT_KERNEL = (__u64)-128, + PERF_CONTEXT_USER = (__u64)-512, + + PERF_CONTEXT_GUEST = (__u64)-2048, + PERF_CONTEXT_GUEST_KERNEL = (__u64)-2176, + PERF_CONTEXT_GUEST_USER = (__u64)-2560, + + PERF_CONTEXT_MAX = (__u64)-4095, +}; + +/** + * PERF_RECORD_AUX::flags bits + */ +#define PERF_AUX_FLAG_TRUNCATED 0x01 /* record was truncated to fit */ +#define PERF_AUX_FLAG_OVERWRITE 0x02 /* snapshot from overwrite mode */ + +#define PERF_FLAG_FD_NO_GROUP (1UL << 0) +#define PERF_FLAG_FD_OUTPUT (1UL << 1) +#define PERF_FLAG_PID_CGROUP (1UL << 2) /* pid=cgroup id, per-cpu mode only */ +#define PERF_FLAG_FD_CLOEXEC (1UL << 3) /* O_CLOEXEC */ + +union perf_mem_data_src { + __u64 val; + struct { + __u64 mem_op:5, /* type of opcode */ + mem_lvl:14, /* memory hierarchy level */ + mem_snoop:5, /* snoop mode */ + mem_lock:2, /* lock instr */ + mem_dtlb:7, /* tlb access */ + mem_rsvd:31; + }; +}; + +/* type of opcode (load/store/prefetch,code) */ +#define PERF_MEM_OP_NA 0x01 /* not available */ +#define PERF_MEM_OP_LOAD 0x02 /* load instruction */ +#define PERF_MEM_OP_STORE 0x04 /* store instruction */ +#define PERF_MEM_OP_PFETCH 0x08 /* prefetch */ +#define PERF_MEM_OP_EXEC 0x10 /* code (execution) */ +#define PERF_MEM_OP_SHIFT 0 + +/* memory hierarchy (memory level, hit or miss) */ +#define PERF_MEM_LVL_NA 0x01 /* not available */ +#define PERF_MEM_LVL_HIT 0x02 /* hit level */ +#define PERF_MEM_LVL_MISS 0x04 /* miss level */ +#define PERF_MEM_LVL_L1 0x08 /* L1 */ +#define PERF_MEM_LVL_LFB 0x10 /* Line Fill Buffer */ +#define PERF_MEM_LVL_L2 0x20 /* L2 */ +#define PERF_MEM_LVL_L3 0x40 /* L3 */ +#define PERF_MEM_LVL_LOC_RAM 0x80 /* Local DRAM */ +#define PERF_MEM_LVL_REM_RAM1 0x100 /* Remote DRAM (1 hop) */ +#define PERF_MEM_LVL_REM_RAM2 0x200 /* Remote DRAM (2 hops) */ +#define PERF_MEM_LVL_REM_CCE1 0x400 /* Remote Cache (1 hop) */ +#define PERF_MEM_LVL_REM_CCE2 0x800 /* Remote Cache (2 hops) */ +#define PERF_MEM_LVL_IO 0x1000 /* I/O memory */ +#define PERF_MEM_LVL_UNC 0x2000 /* Uncached memory */ +#define PERF_MEM_LVL_SHIFT 5 + +/* snoop mode */ +#define PERF_MEM_SNOOP_NA 0x01 /* not available */ +#define PERF_MEM_SNOOP_NONE 0x02 /* no snoop */ +#define PERF_MEM_SNOOP_HIT 0x04 /* snoop hit */ +#define PERF_MEM_SNOOP_MISS 0x08 /* snoop miss */ +#define PERF_MEM_SNOOP_HITM 0x10 /* snoop hit modified */ +#define PERF_MEM_SNOOP_SHIFT 19 + +/* locked instruction */ +#define PERF_MEM_LOCK_NA 0x01 /* not available */ +#define PERF_MEM_LOCK_LOCKED 0x02 /* locked transaction */ +#define PERF_MEM_LOCK_SHIFT 24 + +/* TLB access */ +#define PERF_MEM_TLB_NA 0x01 /* not available */ +#define PERF_MEM_TLB_HIT 0x02 /* hit level */ +#define PERF_MEM_TLB_MISS 0x04 /* miss level */ +#define PERF_MEM_TLB_L1 0x08 /* L1 */ +#define PERF_MEM_TLB_L2 0x10 /* L2 */ +#define PERF_MEM_TLB_WK 0x20 /* Hardware Walker*/ +#define PERF_MEM_TLB_OS 0x40 /* OS fault handler */ +#define PERF_MEM_TLB_SHIFT 26 + +#define PERF_MEM_S(a, s) \ + (((__u64)PERF_MEM_##a##_##s) << PERF_MEM_##a##_SHIFT) + +/* + * single taken branch record layout: + * + * from: source instruction (may not always be a branch insn) + * to: branch target + * mispred: branch target was mispredicted + * predicted: branch target was predicted + * + * support for mispred, predicted is optional. In case it + * is not supported mispred = predicted = 0. + * + * in_tx: running in a hardware transaction + * abort: aborting a hardware transaction + * cycles: cycles from last branch (or 0 if not supported) + */ +struct perf_branch_entry { + __u64 from; + __u64 to; + __u64 mispred:1, /* target mispredicted */ + predicted:1,/* target predicted */ + in_tx:1, /* in transaction */ + abort:1, /* transaction abort */ + cycles:16, /* cycle count to last branch */ + reserved:44; +}; + +#endif /* _LINUX_PERF_EVENT_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/socket.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/socket.h new file mode 100644 index 000000000..bb9aeb92c --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/socket.h @@ -0,0 +1,144 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +#ifndef __ASM_GENERIC_SOCKET_H +#define __ASM_GENERIC_SOCKET_H + +/* For setsockopt(2) */ +#define SOL_SOCKET 1 + +#define SO_DEBUG 1 +#define SO_REUSEADDR 2 +#define SO_TYPE 3 +#define SO_ERROR 4 +#define SO_DONTROUTE 5 +#define SO_BROADCAST 6 +#define SO_SNDBUF 7 +#define SO_RCVBUF 8 +#define SO_SNDBUFFORCE 32 +#define SO_RCVBUFFORCE 33 +#define SO_KEEPALIVE 9 +#define SO_OOBINLINE 10 +#define SO_NO_CHECK 11 +#define SO_PRIORITY 12 +#define SO_LINGER 13 +#define SO_BSDCOMPAT 14 +#define SO_REUSEPORT 15 +#ifndef SO_PASSCRED /* powerpc only differs in these */ +#define SO_PASSCRED 16 +#define SO_PEERCRED 17 +#define SO_RCVLOWAT 18 +#define SO_SNDLOWAT 19 +#define SO_RCVTIMEO_OLD 20 +#define SO_SNDTIMEO_OLD 21 +#endif + +/* Security levels - as per NRL IPv6 - don't actually do anything */ +#define SO_SECURITY_AUTHENTICATION 22 +#define SO_SECURITY_ENCRYPTION_TRANSPORT 23 +#define SO_SECURITY_ENCRYPTION_NETWORK 24 + +#define SO_BINDTODEVICE 25 + +/* Socket filtering */ +#define SO_ATTACH_FILTER 26 +#define SO_DETACH_FILTER 27 +#define SO_GET_FILTER SO_ATTACH_FILTER + +#define SO_PEERNAME 28 + +#define SO_ACCEPTCONN 30 + +#define SO_PEERSEC 31 +#define SO_PASSSEC 34 + +#define SO_MARK 36 + +#define SO_PROTOCOL 38 +#define SO_DOMAIN 39 + +#define SO_RXQ_OVFL 40 + +#define SO_WIFI_STATUS 41 +#define SCM_WIFI_STATUS SO_WIFI_STATUS +#define SO_PEEK_OFF 42 + +/* Instruct lower device to use last 4-bytes of skb data as FCS */ +#define SO_NOFCS 43 + +#define SO_LOCK_FILTER 44 + +#define SO_SELECT_ERR_QUEUE 45 + +#define SO_BUSY_POLL 46 + +#define SO_MAX_PACING_RATE 47 + +#define SO_BPF_EXTENSIONS 48 + +#define SO_INCOMING_CPU 49 + +#define SO_ATTACH_BPF 50 +#define SO_DETACH_BPF SO_DETACH_FILTER + +#define SO_ATTACH_REUSEPORT_CBPF 51 +#define SO_ATTACH_REUSEPORT_EBPF 52 + +#define SO_CNX_ADVICE 53 + +#define SCM_TIMESTAMPING_OPT_STATS 54 + +#define SO_MEMINFO 55 + +#define SO_INCOMING_NAPI_ID 56 + +#define SO_COOKIE 57 + +#define SCM_TIMESTAMPING_PKTINFO 58 + +#define SO_PEERGROUPS 59 + +#define SO_ZEROCOPY 60 + +#define SO_TXTIME 61 +#define SCM_TXTIME SO_TXTIME + +#define SO_BINDTOIFINDEX 62 + +#define SO_TIMESTAMP_OLD 29 +#define SO_TIMESTAMPNS_OLD 35 +#define SO_TIMESTAMPING_OLD 37 + +#define SO_TIMESTAMP_NEW 63 +#define SO_TIMESTAMPNS_NEW 64 +#define SO_TIMESTAMPING_NEW 65 + +#define SO_RCVTIMEO_NEW 66 +#define SO_SNDTIMEO_NEW 67 + +#define SO_DETACH_REUSEPORT_BPF 68 + +#if !defined(__KERNEL__) + +#if __BITS_PER_LONG == 64 || (defined(__x86_64__) && defined(__ILP32__)) +/* on 64-bit and x32, avoid the ?: operator */ +#define SO_TIMESTAMP SO_TIMESTAMP_OLD +#define SO_TIMESTAMPNS SO_TIMESTAMPNS_OLD +#define SO_TIMESTAMPING SO_TIMESTAMPING_OLD + +#define SO_RCVTIMEO SO_RCVTIMEO_OLD +#define SO_SNDTIMEO SO_SNDTIMEO_OLD +#else +#define SO_TIMESTAMP (sizeof(time_t) == sizeof(__kernel_long_t) ? SO_TIMESTAMP_OLD : SO_TIMESTAMP_NEW) +#define SO_TIMESTAMPNS (sizeof(time_t) == sizeof(__kernel_long_t) ? SO_TIMESTAMPNS_OLD : SO_TIMESTAMPNS_NEW) +#define SO_TIMESTAMPING (sizeof(time_t) == sizeof(__kernel_long_t) ? SO_TIMESTAMPING_OLD : SO_TIMESTAMPING_NEW) + +#define SO_RCVTIMEO (sizeof(time_t) == sizeof(__kernel_long_t) ? SO_RCVTIMEO_OLD : SO_RCVTIMEO_NEW) +#define SO_SNDTIMEO (sizeof(time_t) == sizeof(__kernel_long_t) ? SO_SNDTIMEO_OLD : SO_SNDTIMEO_NEW) +#endif + +#define SCM_TIMESTAMP SO_TIMESTAMP +#define SCM_TIMESTAMPNS SO_TIMESTAMPNS +#define SCM_TIMESTAMPING SO_TIMESTAMPING + +#endif + +#endif /* __ASM_GENERIC_SOCKET_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/swab.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/swab.h new file mode 100644 index 000000000..3dfc839e5 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/swab.h @@ -0,0 +1,286 @@ +#ifndef _LINUX_SWAB_H +#define _LINUX_SWAB_H + +#include + +/* + * casts are necessary for constants, because we never know how for sure + * how U/UL/ULL map to __u16, __u32, __u64. At least not in a portable way. + */ +#define ___constant_swab16(x) ((__u16)( \ + (((__u16)(x) & (__u16)0x00ffU) << 8) | \ + (((__u16)(x) & (__u16)0xff00U) >> 8))) + +#define ___constant_swab32(x) ((__u32)( \ + (((__u32)(x) & (__u32)0x000000ffUL) << 24) | \ + (((__u32)(x) & (__u32)0x0000ff00UL) << 8) | \ + (((__u32)(x) & (__u32)0x00ff0000UL) >> 8) | \ + (((__u32)(x) & (__u32)0xff000000UL) >> 24))) + +#define ___constant_swab64(x) ((__u64)( \ + (((__u64)(x) & (__u64)0x00000000000000ffULL) << 56) | \ + (((__u64)(x) & (__u64)0x000000000000ff00ULL) << 40) | \ + (((__u64)(x) & (__u64)0x0000000000ff0000ULL) << 24) | \ + (((__u64)(x) & (__u64)0x00000000ff000000ULL) << 8) | \ + (((__u64)(x) & (__u64)0x000000ff00000000ULL) >> 8) | \ + (((__u64)(x) & (__u64)0x0000ff0000000000ULL) >> 24) | \ + (((__u64)(x) & (__u64)0x00ff000000000000ULL) >> 40) | \ + (((__u64)(x) & (__u64)0xff00000000000000ULL) >> 56))) + +#define ___constant_swahw32(x) ((__u32)( \ + (((__u32)(x) & (__u32)0x0000ffffUL) << 16) | \ + (((__u32)(x) & (__u32)0xffff0000UL) >> 16))) + +#define ___constant_swahb32(x) ((__u32)( \ + (((__u32)(x) & (__u32)0x00ff00ffUL) << 8) | \ + (((__u32)(x) & (__u32)0xff00ff00UL) >> 8))) + +/* + * Implement the following as inlines, but define the interface using + * macros to allow constant folding when possible: + * ___swab16, ___swab32, ___swab64, ___swahw32, ___swahb32 + */ + +static __inline__ __u16 __fswab16(__u16 val) +{ +#ifdef __HAVE_BUILTIN_BSWAP16__ + return __builtin_bswap16(val); +#elif defined (__arch_swab16) + return __arch_swab16(val); +#else + return ___constant_swab16(val); +#endif +} + +static __inline__ __u32 __fswab32(__u32 val) +{ +#ifdef __HAVE_BUILTIN_BSWAP32__ + return __builtin_bswap32(val); +#elif defined(__arch_swab32) + return __arch_swab32(val); +#else + return ___constant_swab32(val); +#endif +} + +static __inline__ __u64 __fswab64(__u64 val) +{ +#ifdef __HAVE_BUILTIN_BSWAP64__ + return __builtin_bswap64(val); +#elif defined (__arch_swab64) + return __arch_swab64(val); +#elif defined(__SWAB_64_THRU_32__) + __u32 h = val >> 32; + __u32 l = val & ((1ULL << 32) - 1); + return (((__u64)__fswab32(l)) << 32) | ((__u64)(__fswab32(h))); +#else + return ___constant_swab64(val); +#endif +} + +static __inline__ __u32 __fswahw32(__u32 val) +{ +#ifdef __arch_swahw32 + return __arch_swahw32(val); +#else + return ___constant_swahw32(val); +#endif +} + +static __inline__ __u32 __fswahb32(__u32 val) +{ +#ifdef __arch_swahb32 + return __arch_swahb32(val); +#else + return ___constant_swahb32(val); +#endif +} + +/** + * __swab16 - return a byteswapped 16-bit value + * @x: value to byteswap + */ +#define __swab16(x) \ + (__builtin_constant_p((__u16)(x)) ? \ + ___constant_swab16(x) : \ + __fswab16(x)) + +/** + * __swab32 - return a byteswapped 32-bit value + * @x: value to byteswap + */ +#define __swab32(x) \ + (__builtin_constant_p((__u32)(x)) ? \ + ___constant_swab32(x) : \ + __fswab32(x)) + +/** + * __swab64 - return a byteswapped 64-bit value + * @x: value to byteswap + */ +#define __swab64(x) \ + (__builtin_constant_p((__u64)(x)) ? \ + ___constant_swab64(x) : \ + __fswab64(x)) + +/** + * __swahw32 - return a word-swapped 32-bit value + * @x: value to wordswap + * + * __swahw32(0x12340000) is 0x00001234 + */ +#define __swahw32(x) \ + (__builtin_constant_p((__u32)(x)) ? \ + ___constant_swahw32(x) : \ + __fswahw32(x)) + +/** + * __swahb32 - return a high and low byte-swapped 32-bit value + * @x: value to byteswap + * + * __swahb32(0x12345678) is 0x34127856 + */ +#define __swahb32(x) \ + (__builtin_constant_p((__u32)(x)) ? \ + ___constant_swahb32(x) : \ + __fswahb32(x)) + +/** + * __swab16p - return a byteswapped 16-bit value from a pointer + * @p: pointer to a naturally-aligned 16-bit value + */ +static __inline__ __u16 __swab16p(const __u16 *p) +{ +#ifdef __arch_swab16p + return __arch_swab16p(p); +#else + return __swab16(*p); +#endif +} + +/** + * __swab32p - return a byteswapped 32-bit value from a pointer + * @p: pointer to a naturally-aligned 32-bit value + */ +static __inline__ __u32 __swab32p(const __u32 *p) +{ +#ifdef __arch_swab32p + return __arch_swab32p(p); +#else + return __swab32(*p); +#endif +} + +/** + * __swab64p - return a byteswapped 64-bit value from a pointer + * @p: pointer to a naturally-aligned 64-bit value + */ +static __inline__ __u64 __swab64p(const __u64 *p) +{ +#ifdef __arch_swab64p + return __arch_swab64p(p); +#else + return __swab64(*p); +#endif +} + +/** + * __swahw32p - return a wordswapped 32-bit value from a pointer + * @p: pointer to a naturally-aligned 32-bit value + * + * See __swahw32() for details of wordswapping. + */ +static __inline__ __u32 __swahw32p(const __u32 *p) +{ +#ifdef __arch_swahw32p + return __arch_swahw32p(p); +#else + return __swahw32(*p); +#endif +} + +/** + * __swahb32p - return a high and low byteswapped 32-bit value from a pointer + * @p: pointer to a naturally-aligned 32-bit value + * + * See __swahb32() for details of high/low byteswapping. + */ +static __inline__ __u32 __swahb32p(const __u32 *p) +{ +#ifdef __arch_swahb32p + return __arch_swahb32p(p); +#else + return __swahb32(*p); +#endif +} + +/** + * __swab16s - byteswap a 16-bit value in-place + * @p: pointer to a naturally-aligned 16-bit value + */ +static __inline__ void __swab16s(__u16 *p) +{ +#ifdef __arch_swab16s + __arch_swab16s(p); +#else + *p = __swab16p(p); +#endif +} +/** + * __swab32s - byteswap a 32-bit value in-place + * @p: pointer to a naturally-aligned 32-bit value + */ +static __inline__ void __swab32s(__u32 *p) +{ +#ifdef __arch_swab32s + __arch_swab32s(p); +#else + *p = __swab32p(p); +#endif +} + +/** + * __swab64s - byteswap a 64-bit value in-place + * @p: pointer to a naturally-aligned 64-bit value + */ +static __inline__ void __swab64s(__u64 *p) +{ +#ifdef __arch_swab64s + __arch_swab64s(p); +#else + *p = __swab64p(p); +#endif +} + +/** + * __swahw32s - wordswap a 32-bit value in-place + * @p: pointer to a naturally-aligned 32-bit value + * + * See __swahw32() for details of wordswapping + */ +static __inline__ void __swahw32s(__u32 *p) +{ +#ifdef __arch_swahw32s + __arch_swahw32s(p); +#else + *p = __swahw32p(p); +#endif +} + +/** + * __swahb32s - high and low byteswap a 32-bit value in-place + * @p: pointer to a naturally-aligned 32-bit value + * + * See __swahb32() for details of high and low byte swapping + */ +static __inline__ void __swahb32s(__u32 *p) +{ +#ifdef __arch_swahb32s + __arch_swahb32s(p); +#else + *p = __swahb32p(p); +#endif +} + + +#endif /* _LINUX_SWAB_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/tcp.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/tcp.h new file mode 100644 index 000000000..bde4c5b35 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/tcp.h @@ -0,0 +1,89 @@ +/* + * INET An implementation of the TCP/IP protocol suite for the LINUX + * operating system. INET is implemented using the BSD Socket + * interface as the means of communication with the user level. + * + * Definitions for the TCP protocol. + * + * Version: @(#)tcp.h 1.0.2 04/28/93 + * + * Author: Fred N. van Kempen, + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ +#ifndef _LINUX_TCP_H +#define _LINUX_TCP_H + +#include + +struct tcphdr { + __be16 source; + __be16 dest; + __be32 seq; + __be32 ack_seq; +#if defined(__LITTLE_ENDIAN_BITFIELD) + __u16 res1:4, + doff:4, + fin:1, + syn:1, + rst:1, + psh:1, + ack:1, + urg:1, + ece:1, + cwr:1; +#elif defined(__BIG_ENDIAN_BITFIELD) + __u16 doff:4, + res1:4, + cwr:1, + ece:1, + urg:1, + ack:1, + psh:1, + rst:1, + syn:1, + fin:1; +#else +#error "Adjust your defines" +#endif + __be16 window; + __sum16 check; + __be16 urg_ptr; +}; + +/* + * The union cast uses a gcc extension to avoid aliasing problems + * (union is compatible to any of its members) + * This means this part of the code is -fstrict-aliasing safe now. + */ +union tcp_word_hdr { + struct tcphdr hdr; + __be32 words[5]; +}; + +#define tcp_flag_word(tp) ( ((union tcp_word_hdr *)(tp))->words [3]) + +enum { + TCP_FLAG_CWR = __constant_cpu_to_be32(0x00800000), + TCP_FLAG_ECE = __constant_cpu_to_be32(0x00400000), + TCP_FLAG_URG = __constant_cpu_to_be32(0x00200000), + TCP_FLAG_ACK = __constant_cpu_to_be32(0x00100000), + TCP_FLAG_PSH = __constant_cpu_to_be32(0x00080000), + TCP_FLAG_RST = __constant_cpu_to_be32(0x00040000), + TCP_FLAG_SYN = __constant_cpu_to_be32(0x00020000), + TCP_FLAG_FIN = __constant_cpu_to_be32(0x00010000), + TCP_RESERVED_BITS = __constant_cpu_to_be32(0x0F000000), + TCP_DATA_OFFSET = __constant_cpu_to_be32(0xF0000000) +}; + +/* + * TCP general constants + */ +#define TCP_MSS_DEFAULT 536U /* IPv4 (RFC1122, RFC2581) */ +#define TCP_MSS_DESIRED 1220U /* IPv6 (tunneled), EDNS0 (RFC3226) */ + + +#endif /* _LINUX_TCP_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/types.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/types.h new file mode 100644 index 000000000..abed7f764 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/types.h @@ -0,0 +1,9 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef _LINUX_TYPES_H +#define _LINUX_TYPES_H + +#include "../bpf/types_mapper.h" + +#endif /* _LINUX_TYPES_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/udp.h b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/udp.h new file mode 100644 index 000000000..ab05413c9 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/include/linux/udp.h @@ -0,0 +1,41 @@ +/* + * INET An implementation of the TCP/IP protocol suite for the LINUX + * operating system. INET is implemented using the BSD Socket + * interface as the means of communication with the user level. + * + * Definitions for the UDP protocol. + * + * Version: @(#)udp.h 1.0.2 04/28/93 + * + * Author: Fred N. van Kempen, + * + * This program is free software; you can redistribute it and/or + * modify it under the terms of the GNU General Public License + * as published by the Free Software Foundation; either version + * 2 of the License, or (at your option) any later version. + */ +#ifndef _LINUX_UDP_H +#define _LINUX_UDP_H + +#include + +struct udphdr { + __be16 source; + __be16 dest; + __be16 len; + __sum16 check; +}; + +/* UDP socket options */ +#define UDP_CORK 1 /* Never send partially complete segments */ +#define UDP_ENCAP 100 /* Set the socket to accept encapsulated packets */ +#define UDP_NO_CHECK6_TX 101 /* Disable sending checksum for UDP6X */ +#define UDP_NO_CHECK6_RX 102 /* Disable accpeting checksum for UDP6 */ + +/* UDP encapsulation types */ +#define UDP_ENCAP_ESPINUDP_NON_IKE 1 /* draft-ietf-ipsec-nat-t-ike-00/01 */ +#define UDP_ENCAP_ESPINUDP 2 /* draft-ietf-ipsec-udp-encaps-06 */ +#define UDP_ENCAP_L2TPINUDP 3 /* rfc2661 */ + + +#endif /* _LINUX_UDP_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/arp.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/arp.h new file mode 100644 index 000000000..48d508554 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/arp.h @@ -0,0 +1,93 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_ARP__ +#define __LIB_ARP__ + +#include +#include +#include "eth.h" +#include "dbg.h" +#include "drop.h" + +struct arp_eth { + unsigned char ar_sha[ETH_ALEN]; + __be32 ar_sip; + unsigned char ar_tha[ETH_ALEN]; + __be32 ar_tip; +} __packed; + +/* Check if packet is ARP request for IP */ +static __always_inline int arp_check(struct ethhdr *eth, + const struct arphdr *arp, + union macaddr *mac) +{ + union macaddr *dmac = (union macaddr *) ð->h_dest; + + return arp->ar_op == bpf_htons(ARPOP_REQUEST) && + arp->ar_hrd == bpf_htons(ARPHRD_ETHER) && + (eth_is_bcast(dmac) || !eth_addrcmp(dmac, mac)); +} + +static __always_inline int +arp_prepare_response(struct __ctx_buff *ctx, union macaddr *smac, __be32 sip, + union macaddr *dmac, __be32 tip) +{ + __be16 arpop = bpf_htons(ARPOP_REPLY); + + if (eth_store_saddr(ctx, smac->addr, 0) < 0 || + eth_store_daddr(ctx, dmac->addr, 0) < 0 || + ctx_store_bytes(ctx, 20, &arpop, sizeof(arpop), 0) < 0 || + /* sizeof(macadrr)=8 because of padding, use ETH_ALEN instead */ + ctx_store_bytes(ctx, 22, smac, ETH_ALEN, 0) < 0 || + ctx_store_bytes(ctx, 28, &sip, sizeof(sip), 0) < 0 || + ctx_store_bytes(ctx, 32, dmac, ETH_ALEN, 0) < 0 || + ctx_store_bytes(ctx, 38, &tip, sizeof(tip), 0) < 0) + return DROP_WRITE_ERROR; + + return 0; +} + +static __always_inline bool +arp_validate(const struct __ctx_buff *ctx, union macaddr *mac, + union macaddr *smac, __be32 *sip, __be32 *tip) +{ + void *data_end = (void *) (long) ctx->data_end; + void *data = (void *) (long) ctx->data; + struct arphdr *arp = data + ETH_HLEN; + struct ethhdr *eth = data; + struct arp_eth *arp_eth; + + if (data + ETH_HLEN + sizeof(*arp) + sizeof(*arp_eth) > data_end) + return false; + + if (!arp_check(eth, arp, mac)) + return false; + + arp_eth = data + ETH_HLEN + sizeof(*arp); + *smac = *(union macaddr *) ð->h_source; + *sip = arp_eth->ar_sip; + *tip = arp_eth->ar_tip; + + return true; +} + +static __always_inline int +arp_respond(struct __ctx_buff *ctx, union macaddr *smac, __be32 sip, + union macaddr *dmac, __be32 tip, int direction) +{ + int ret = arp_prepare_response(ctx, smac, sip, dmac, tip); + + if (unlikely(ret != 0)) + goto error; + + cilium_dbg_capture(ctx, DBG_CAPTURE_DELIVERY, + ctx_get_ifindex(ctx)); + return ctx_redirect(ctx, ctx_get_ifindex(ctx), direction); + +error: + return send_drop_notify_error(ctx, 0, ret, CTX_ACT_DROP, METRIC_EGRESS); +} + + +#endif /* __LIB_ARP__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/common.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/common.h new file mode 100644 index 000000000..423e1e8e3 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/common.h @@ -0,0 +1,937 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2021 Authors of Cilium */ + +#ifndef __LIB_COMMON_H_ +#define __LIB_COMMON_H_ + +#include +#include + +#include +#include +#include +#include + +#include "eth.h" +#include "endian.h" +#include "mono.h" +#include "config.h" + +/* FIXME: GH-3239 LRU logic is not handling timeouts gracefully enough + * #ifndef HAVE_LRU_HASH_MAP_TYPE + * #define NEEDS_TIMEOUT 1 + * #endif + */ +#define NEEDS_TIMEOUT 1 + +#ifndef AF_INET +#define AF_INET 2 +#endif + +#ifndef AF_INET6 +#define AF_INET6 10 +#endif + +#ifndef IP_DF +#define IP_DF 0x4000 +#endif + +#ifndef EVENT_SOURCE +#define EVENT_SOURCE 0 +#endif + +#ifndef THIS_MTU +/* If not available, fall back to generically detected MTU instead of more + * fine-grained per-device MTU. + */ +# define THIS_MTU MTU +#endif + +#define PORT_UDP_VXLAN 4789 +#define PORT_UDP_GENEVE 6081 +#define PORT_UDP_VXLAN_LINUX 8472 + +#ifdef PREALLOCATE_MAPS +#define CONDITIONAL_PREALLOC 0 +#else +#define CONDITIONAL_PREALLOC BPF_F_NO_PREALLOC +#endif + +/* TODO: ipsec v6 tunnel datapath still needs separate fixing */ +#ifndef ENABLE_IPSEC +# ifdef ENABLE_IPV6 +# define ENABLE_ENCAP_HOST_REMAP 1 +# endif +#endif + +/* XDP to SKB transferred meta data. */ +#define XFER_PKT_NO_SVC 1 /* Skip upper service handling. */ + +/* These are shared with test/bpf/check-complexity.sh, when modifying any of + * the below, that script should also be updated. + */ +#define CILIUM_CALL_DROP_NOTIFY 1 +#define CILIUM_CALL_ERROR_NOTIFY 2 +#define CILIUM_CALL_SEND_ICMP6_ECHO_REPLY 3 +#define CILIUM_CALL_HANDLE_ICMP6_NS 4 +#define CILIUM_CALL_SEND_ICMP6_TIME_EXCEEDED 5 +#define CILIUM_CALL_ARP 6 +#define CILIUM_CALL_IPV4_FROM_LXC 7 +#define CILIUM_CALL_NAT64 8 +#define CILIUM_CALL_NAT46 9 +#define CILIUM_CALL_IPV6_FROM_LXC 10 +#define CILIUM_CALL_IPV4_TO_LXC_POLICY_ONLY 11 +#define CILIUM_CALL_IPV4_TO_HOST_POLICY_ONLY CILIUM_CALL_IPV4_TO_LXC_POLICY_ONLY +#define CILIUM_CALL_IPV6_TO_LXC_POLICY_ONLY 12 +#define CILIUM_CALL_IPV6_TO_HOST_POLICY_ONLY CILIUM_CALL_IPV6_TO_LXC_POLICY_ONLY +#define CILIUM_CALL_IPV4_TO_ENDPOINT 13 +#define CILIUM_CALL_IPV6_TO_ENDPOINT 14 +#define CILIUM_CALL_IPV4_NODEPORT_NAT 15 +#define CILIUM_CALL_IPV6_NODEPORT_NAT 16 +#define CILIUM_CALL_IPV4_NODEPORT_REVNAT 17 +#define CILIUM_CALL_IPV6_NODEPORT_REVNAT 18 +#define CILIUM_CALL_IPV4_ENCAP_NODEPORT_NAT 19 +#define CILIUM_CALL_IPV4_NODEPORT_DSR 20 +#define CILIUM_CALL_IPV6_NODEPORT_DSR 21 +#define CILIUM_CALL_IPV4_FROM_HOST 22 +#define CILIUM_CALL_IPV6_FROM_HOST 23 +#define CILIUM_CALL_IPV6_ENCAP_NODEPORT_NAT 24 +#define CILIUM_CALL_SIZE 25 + +typedef __u64 mac_t; + +union v6addr { + struct { + __u32 p1; + __u32 p2; + __u32 p3; + __u32 p4; + }; + struct { + __u64 d1; + __u64 d2; + }; + __u8 addr[16]; +} __packed; + +static __always_inline bool validate_ethertype(struct __ctx_buff *ctx, + __u16 *proto) +{ + void *data = ctx_data(ctx); + void *data_end = ctx_data_end(ctx); + struct ethhdr *eth = data; + + if (ETH_HLEN == 0) { + /* The packet is received on L2-less device. Determine L3 + * protocol from skb->protocol. + */ + *proto = ctx_get_protocol(ctx); + return true; + } + + if (data + ETH_HLEN > data_end) + return false; + *proto = eth->h_proto; + if (bpf_ntohs(*proto) < ETH_P_802_3_MIN) + return false; /* non-Ethernet II unsupported */ + return true; +} + +static __always_inline __maybe_unused bool +____revalidate_data_pull(struct __ctx_buff *ctx, void **data_, void **data_end_, + void **l3, const __u32 l3_len, const bool pull, + __u8 eth_hlen) +{ + const __u64 tot_len = eth_hlen + l3_len; + void *data_end; + void *data; + + /* Verifier workaround, do this unconditionally: invalid size of register spill. */ + if (pull) + ctx_pull_data(ctx, tot_len); + data_end = ctx_data_end(ctx); + data = ctx_data(ctx); + if (data + tot_len > data_end) + return false; + + /* Verifier workaround: pointer arithmetic on pkt_end prohibited. */ + *data_ = data; + *data_end_ = data_end; + + *l3 = data + eth_hlen; + return true; +} + +static __always_inline __maybe_unused bool +__revalidate_data_pull(struct __ctx_buff *ctx, void **data, void **data_end, + void **l3, const __u32 l3_len, const bool pull) +{ + return ____revalidate_data_pull(ctx, data, data_end, l3, l3_len, pull, + ETH_HLEN); +} + +/* revalidate_data_pull() initializes the provided pointers from the ctx and + * ensures that the data is pulled in for access. Should be used the first + * time that the ctx data is accessed, subsequent calls can be made to + * revalidate_data() which is cheaper. + * Returns true if 'ctx' is long enough for an IP header of the provided type, + * false otherwise. + */ +#define revalidate_data_pull(ctx, data, data_end, ip) \ + __revalidate_data_pull(ctx, data, data_end, (void **)ip, sizeof(**ip), true) + +/* revalidate_data_maybe_pull() does the same as revalidate_data_maybe_pull() + * except that the skb data pull is controlled by the "pull" argument. + */ +#define revalidate_data_maybe_pull(ctx, data, data_end, ip, pull) \ + __revalidate_data_pull(ctx, data, data_end, (void **)ip, sizeof(**ip), pull) + + +/* revalidate_data() initializes the provided pointers from the ctx. + * Returns true if 'ctx' is long enough for an IP header of the provided type, + * false otherwise. + */ +#define revalidate_data(ctx, data, data_end, ip) \ + __revalidate_data_pull(ctx, data, data_end, (void **)ip, sizeof(**ip), false) + +#define revalidate_data_with_eth_hlen(ctx, data, data_end, ip, eth_len) \ + ____revalidate_data_pull(ctx, data, data_end, (void **)ip, \ + sizeof(**ip), false, eth_len) + +/* Macros for working with L3 cilium defined IPV6 addresses */ +#define BPF_V6(dst, ...) BPF_V6_1(dst, fetch_ipv6(__VA_ARGS__)) +#define BPF_V6_1(dst, ...) BPF_V6_4(dst, __VA_ARGS__) +#define BPF_V6_4(dst, a1, a2, a3, a4) \ + ({ \ + dst.p1 = a1; \ + dst.p2 = a2; \ + dst.p3 = a3; \ + dst.p4 = a4; \ + }) + +#define ENDPOINT_KEY_IPV4 1 +#define ENDPOINT_KEY_IPV6 2 + +/* Structure representing an IPv4 or IPv6 address, being used for: + * - key as endpoints map + * - key for tunnel endpoint map + * - value for tunnel endpoint map + */ +struct endpoint_key { + union { + struct { + __u32 ip4; + __u32 pad1; + __u32 pad2; + __u32 pad3; + }; + union v6addr ip6; + }; + __u8 family; + __u8 key; + __u16 pad5; +} __packed; + +#define ENDPOINT_F_HOST 1 /* Special endpoint representing local host */ + +/* Value of endpoint map */ +struct endpoint_info { + __u32 ifindex; + __u16 unused; /* used to be sec_label, no longer used */ + __u16 lxc_id; + __u32 flags; + mac_t mac; + mac_t node_mac; + __u32 pad[4]; +}; + +struct egress_info { + __u32 egress_ip; + __u32 tunnel_endpoint; +}; + +struct edt_id { + __u64 id; +}; + +struct edt_info { + __u64 bps; + __u64 t_last; + __u64 t_horizon_drop; + __u64 pad[4]; +}; + +struct remote_endpoint_info { + __u32 sec_label; + __u32 tunnel_endpoint; + __u8 key; +}; + +struct policy_key { + __u32 sec_label; + __u16 dport; + __u8 protocol; + __u8 egress:1, + pad:7; +}; + +struct policy_entry { + __be16 proxy_port; + __u8 deny:1, + pad:7; + __u8 pad0; + __u16 pad1; + __u16 pad2; + __u64 packets; + __u64 bytes; +}; + +struct metrics_key { + __u8 reason; /* 0: forwarded, >0 dropped */ + __u8 dir:2, /* 1: ingress 2: egress */ + pad:6; + __u16 reserved[3]; /* reserved for future extension */ +}; + + +struct metrics_value { + __u64 count; + __u64 bytes; +}; + +enum { + POLICY_INGRESS = 1, + POLICY_EGRESS = 2, +}; + +enum { + POLICY_MATCH_NONE = 0, + POLICY_MATCH_L3_ONLY = 1, + POLICY_MATCH_L3_L4 = 2, + POLICY_MATCH_L4_ONLY = 3, + POLICY_MATCH_ALL = 4, +}; + +enum { + CAPTURE_INGRESS = 1, + CAPTURE_EGRESS = 2, +}; + +enum { + CILIUM_NOTIFY_UNSPEC, + CILIUM_NOTIFY_DROP, + CILIUM_NOTIFY_DBG_MSG, + CILIUM_NOTIFY_DBG_CAPTURE, + CILIUM_NOTIFY_TRACE, + CILIUM_NOTIFY_POLICY_VERDICT, + CILIUM_NOTIFY_CAPTURE, +}; + +#define NOTIFY_COMMON_HDR \ + __u8 type; \ + __u8 subtype; \ + __u16 source; \ + __u32 hash; + +#define NOTIFY_CAPTURE_HDR \ + NOTIFY_COMMON_HDR \ + __u32 len_orig; /* Length of original packet */ \ + __u16 len_cap; /* Length of captured bytes */ \ + __u16 version; /* Capture header version */ + +#define __notify_common_hdr(t, s) \ + .type = (t), \ + .subtype = (s), \ + .source = EVENT_SOURCE, \ + .hash = get_hash_recalc(ctx) + +#define __notify_pktcap_hdr(o, c) \ + .len_orig = (o), \ + .len_cap = (c), \ + .version = NOTIFY_CAPTURE_VER + +/* Capture notifications version. Must be incremented when format changes. */ +#define NOTIFY_CAPTURE_VER 1 + +#ifndef TRACE_PAYLOAD_LEN +#define TRACE_PAYLOAD_LEN 128ULL +#endif + +#ifndef BPF_F_PSEUDO_HDR +# define BPF_F_PSEUDO_HDR (1ULL << 4) +#endif + +#define IS_ERR(x) (unlikely((x < 0) || (x == CTX_ACT_DROP))) + +/* Cilium IPSec code to indicate packet needs to be handled + * by IPSec stack. Maps to CTX_ACT_OK. + */ +#define IPSEC_ENDPOINT CTX_ACT_OK + +/* Return value to indicate that proxy redirection is required */ +#define POLICY_ACT_PROXY_REDIRECT (1 << 16) + +/* Cilium error codes, must NOT overlap with TC return codes. + * These also serve as drop reasons for metrics, + * where reason > 0 corresponds to -(DROP_*) + * + * These are shared with pkg/monitor/api/drop.go and api/v1/flow/flow.proto. + * When modifying any of the below, those files should also be updated. + */ +#define DROP_UNUSED1 -130 /* unused */ +#define DROP_UNUSED2 -131 /* unused */ +#define DROP_INVALID_SIP -132 +#define DROP_POLICY -133 +#define DROP_INVALID -134 +#define DROP_CT_INVALID_HDR -135 +#define DROP_FRAG_NEEDED -136 +#define DROP_CT_UNKNOWN_PROTO -137 +#define DROP_UNUSED4 -138 /* unused */ +#define DROP_UNKNOWN_L3 -139 +#define DROP_MISSED_TAIL_CALL -140 +#define DROP_WRITE_ERROR -141 +#define DROP_UNKNOWN_L4 -142 +#define DROP_UNKNOWN_ICMP_CODE -143 +#define DROP_UNKNOWN_ICMP_TYPE -144 +#define DROP_UNKNOWN_ICMP6_CODE -145 +#define DROP_UNKNOWN_ICMP6_TYPE -146 +#define DROP_NO_TUNNEL_KEY -147 +#define DROP_UNUSED5 -148 /* unused */ +#define DROP_UNUSED6 -149 /* unused */ +#define DROP_UNKNOWN_TARGET -150 +#define DROP_UNROUTABLE -151 +#define DROP_UNUSED7 -152 /* unused */ +#define DROP_CSUM_L3 -153 +#define DROP_CSUM_L4 -154 +#define DROP_CT_CREATE_FAILED -155 +#define DROP_INVALID_EXTHDR -156 +#define DROP_FRAG_NOSUPPORT -157 +#define DROP_NO_SERVICE -158 +#define DROP_UNUSED8 -159 /* unused */ +#define DROP_NO_TUNNEL_ENDPOINT -160 +#define DROP_UNUSED9 -161 /* unused */ +#define DROP_EDT_HORIZON -162 +#define DROP_UNKNOWN_CT -163 +#define DROP_HOST_UNREACHABLE -164 +#define DROP_NO_CONFIG -165 +#define DROP_UNSUPPORTED_L2 -166 +#define DROP_NAT_NO_MAPPING -167 +#define DROP_NAT_UNSUPP_PROTO -168 +#define DROP_NO_FIB -169 +#define DROP_ENCAP_PROHIBITED -170 +#define DROP_INVALID_IDENTITY -171 +#define DROP_UNKNOWN_SENDER -172 +#define DROP_NAT_NOT_NEEDED -173 /* Mapped as drop code, though drop not necessary. */ +#define DROP_IS_CLUSTER_IP -174 +#define DROP_FRAG_NOT_FOUND -175 +#define DROP_FORBIDDEN_ICMP6 -176 +#define DROP_NOT_IN_SRC_RANGE -177 +#define DROP_PROXY_LOOKUP_FAILED -178 +#define DROP_PROXY_SET_FAILED -179 +#define DROP_PROXY_UNKNOWN_PROTO -180 +#define DROP_POLICY_DENY -181 + +#define NAT_PUNT_TO_STACK DROP_NAT_NOT_NEEDED + +/* Cilium metrics reasons for forwarding packets and other stats. + * If reason is larger than below then this is a drop reason and + * value corresponds to -(DROP_*), see above. + * + * These are shared with pkg/monitor/api/drop.go. + * When modifying any of the below, those files should also be updated. + */ +#define REASON_FORWARDED 0 +#define REASON_PLAINTEXT 3 +#define REASON_DECRYPT 4 +#define REASON_LB_NO_BACKEND_SLOT 5 +#define REASON_LB_NO_BACKEND 6 +#define REASON_LB_REVNAT_UPDATE 7 +#define REASON_LB_REVNAT_STALE 8 +#define REASON_FRAG_PACKET 9 +#define REASON_FRAG_PACKET_UPDATE 10 +#define REASON_MISSED_CUSTOM_CALL 11 + +/* Lookup scope for externalTrafficPolicy=Local */ +#define LB_LOOKUP_SCOPE_EXT 0 +#define LB_LOOKUP_SCOPE_INT 1 + +/* Cilium metrics direction for dropping/forwarding packet */ +#define METRIC_INGRESS 1 +#define METRIC_EGRESS 2 +#define METRIC_SERVICE 3 + +/* Magic ctx->mark identifies packets origination and encryption status. + * + * The upper 16 bits plus lower 8 bits (e.g. mask 0XFFFF00FF) contain the + * packets security identity. The lower/upper halves are swapped to recover + * the identity. + * + * The 4 bits at 0X0F00 provide + * - the magic marker values which indicate whether the packet is coming from + * an ingress or egress proxy, a local process and its current encryption + * status. + * + * The 4 bits at 0xF000 provide + * - the key index to use for encryption when multiple keys are in-flight. + * In the IPsec case this becomes the SPI on the wire. + */ +#define MARK_MAGIC_HOST_MASK 0x0F00 +#define MARK_MAGIC_PROXY_INGRESS 0x0A00 +#define MARK_MAGIC_PROXY_EGRESS 0x0B00 +#define MARK_MAGIC_HOST 0x0C00 +#define MARK_MAGIC_DECRYPT 0x0D00 +#define MARK_MAGIC_ENCRYPT 0x0E00 +#define MARK_MAGIC_IDENTITY 0x0F00 /* mark carries identity */ +#define MARK_MAGIC_TO_PROXY 0x0200 + +#define MARK_MAGIC_KEY_ID 0xF000 +#define MARK_MAGIC_KEY_MASK 0xFF00 + +/* IPSec cannot be configured with NodePort BPF today, hence non-conflicting + * overlap with MARK_MAGIC_KEY_ID. + */ +#define MARK_MAGIC_SNAT_DONE 0x1500 + +/* MARK_MAGIC_HEALTH_IPIP_DONE can overlap with MARK_MAGIC_SNAT_DONE with both + * being mutual exclusive given former is only under DSR. Used to push health + * probe packets to ipip tunnel device & to avoid looping back. + */ +#define MARK_MAGIC_HEALTH_IPIP_DONE MARK_MAGIC_SNAT_DONE + +/* MARK_MAGIC_HEALTH can overlap with MARK_MAGIC_DECRYPT with both being + * mutual exclusive. Note, MARK_MAGIC_HEALTH is user-facing UAPI for LB! + */ +#define MARK_MAGIC_HEALTH MARK_MAGIC_DECRYPT + +/* IPv4 option used to carry service addr and port for DSR. Lower 16bits set to + * zero so that they can be OR'd with service port. + * + * Copy = 1 (option is copied to each fragment) + * Class = 0 (control option) + * Number = 26 (not used according to [1]) + * Len = 8 (option type (1) + option len (1) + addr (4) + port (2)) + * + * [1]: https://www.iana.org/assignments/ip-parameters/ip-parameters.xhtml + */ +#define DSR_IPV4_OPT_32 0x9a080000 +#define DSR_IPV4_OPT_MASK 0xffff0000 +#define DSR_IPV4_DPORT_MASK 0x0000ffff + +/* IPv6 option type of Destination Option used to carry service IPv6 addr and + * port for DSR. + * + * 0b00 - "skip over this option and continue processing the header" + * 0 - "Option Data does not change en-route" + * 11011 - Unassigned [1] + * + * [1]: https://www.iana.org/assignments/ipv6-parameters/ipv6-parameters.xhtml#ipv6-parameters-2 + */ +#define DSR_IPV6_OPT_TYPE 0x1B +#define DSR_IPV6_OPT_LEN 0x14 /* to store ipv6 addr + port */ +#define DSR_IPV6_EXT_LEN 0x2 /* = (sizeof(dsr_opt_v6) - 8) / 8 */ + +/* We cap key index at 4 bits because mark value is used to map ctx to key */ +#define MAX_KEY_INDEX 15 + +/* encrypt_key is the index into the encrypt map */ +struct encrypt_key { + __u32 ctx; +} __packed; + +/* encrypt_config is the current encryption context on the node */ +struct encrypt_config { + __u8 encrypt_key; +} __packed; + +/** + * or_encrypt_key - mask and shift key into encryption format + */ +static __always_inline __u32 or_encrypt_key(__u8 key) +{ + return (((__u32)key & 0x0F) << 12) | MARK_MAGIC_ENCRYPT; +} + +/* + * ctx->tc_index uses + * + * cilium_host @egress + * bpf_host -> bpf_lxc + */ +#define TC_INDEX_F_SKIP_INGRESS_PROXY 1 +#define TC_INDEX_F_SKIP_EGRESS_PROXY 2 +#define TC_INDEX_F_SKIP_NODEPORT 4 +#define TC_INDEX_F_SKIP_RECIRCULATION 8 +#define TC_INDEX_F_SKIP_HOST_FIREWALL 16 + +/* + * For use in ctx_{load,store}_meta(), which operates on sk_buff->cb. + * The verifier only exposes the first 5 slots in cb[], so this enum + * only contains 5 entries. Aliases are added to the slots to re-use + * them under different names in different parts of the datapath. + * Take care to not clobber slots used by other functions in the same + * code path. + */ +/* ctx_{load,store}_meta() usage: */ +enum { + CB_SRC_LABEL, +#define CB_PORT CB_SRC_LABEL /* Alias, non-overlapping */ +#define CB_HINT CB_SRC_LABEL /* Alias, non-overlapping */ +#define CB_PROXY_MAGIC CB_SRC_LABEL /* Alias, non-overlapping */ +#define CB_ENCRYPT_MAGIC CB_SRC_LABEL /* Alias, non-overlapping */ +#define CB_DST_ENDPOINT_ID CB_SRC_LABEL /* Alias, non-overlapping */ + CB_IFINDEX, +#define CB_ADDR_V4 CB_IFINDEX /* Alias, non-overlapping */ +#define CB_ADDR_V6_1 CB_IFINDEX /* Alias, non-overlapping */ +#define CB_ENCRYPT_IDENTITY CB_IFINDEX /* Alias, non-overlapping */ +#define CB_IPCACHE_SRC_LABEL CB_IFINDEX /* Alias, non-overlapping */ + CB_POLICY, +#define CB_ADDR_V6_2 CB_POLICY /* Alias, non-overlapping */ + CB_NAT46_STATE, +#define CB_NAT CB_NAT46_STATE /* Alias, non-overlapping */ +#define CB_ADDR_V6_3 CB_NAT46_STATE /* Alias, non-overlapping */ +#define CB_FROM_HOST CB_NAT46_STATE /* Alias, non-overlapping */ + CB_CT_STATE, +#define CB_ADDR_V6_4 CB_CT_STATE /* Alias, non-overlapping */ +#define CB_ENCRYPT_DST CB_CT_STATE /* Alias, non-overlapping, + * Not used by xfrm. + */ +#define CB_CUSTOM_CALLS CB_CT_STATE /* Alias, non-overlapping */ +}; + +/* State values for NAT46 */ +enum { + NAT46_CLEAR, + NAT64, + NAT46, +}; + +#define TUPLE_F_OUT 0 /* Outgoing flow */ +#define TUPLE_F_IN 1 /* Incoming flow */ +#define TUPLE_F_RELATED 2 /* Flow represents related packets */ +#define TUPLE_F_SERVICE 4 /* Flow represents packets to service */ + +#define CT_EGRESS 0 +#define CT_INGRESS 1 +#define CT_SERVICE 2 + +#ifdef ENABLE_NODEPORT +#define NAT_MIN_EGRESS NODEPORT_PORT_MIN_NAT +#else +#define NAT_MIN_EGRESS EPHEMERAL_MIN +#endif + +enum { + CT_NEW, + CT_ESTABLISHED, + CT_REPLY, + CT_RELATED, + CT_REOPENED, +}; + +/* Service flags (lb{4,6}_service->flags) */ +enum { + SVC_FLAG_EXTERNAL_IP = (1 << 0), /* External IPs */ + SVC_FLAG_NODEPORT = (1 << 1), /* NodePort service */ + SVC_FLAG_LOCAL_SCOPE = (1 << 2), /* externalTrafficPolicy=Local */ + SVC_FLAG_HOSTPORT = (1 << 3), /* hostPort forwarding */ + SVC_FLAG_AFFINITY = (1 << 4), /* sessionAffinity=clientIP */ + SVC_FLAG_LOADBALANCER = (1 << 5), /* LoadBalancer service */ + SVC_FLAG_ROUTABLE = (1 << 6), /* Not a surrogate/ClusterIP entry */ + SVC_FLAG_SOURCE_RANGE = (1 << 7), /* Check LoadBalancer source range */ +}; + +/* Service flags (lb{4,6}_service->flags2) */ +enum { + SVC_FLAG_LOCALREDIRECT = (1 << 0), /* local redirect */ +}; + +struct ipv6_ct_tuple { + /* Address fields are reversed, i.e., + * these field names are correct for reply direction traffic. + */ + union v6addr daddr; + union v6addr saddr; + /* The order of dport+sport must not be changed! + * These field names are correct for original direction traffic. + */ + __be16 dport; + __be16 sport; + __u8 nexthdr; + __u8 flags; +} __packed; + +struct ipv4_ct_tuple { + /* Address fields are reversed, i.e., + * these field names are correct for reply direction traffic. + */ + __be32 daddr; + __be32 saddr; + /* The order of dport+sport must not be changed! + * These field names are correct for original direction traffic. + */ + __be16 dport; + __be16 sport; + __u8 nexthdr; + __u8 flags; +} __packed; + +struct ct_entry { + __u64 rx_packets; + __u64 rx_bytes; + __u64 tx_packets; + __u64 tx_bytes; + __u32 lifetime; + __u16 rx_closing:1, + tx_closing:1, + nat46:1, + lb_loopback:1, + seen_non_syn:1, + node_port:1, + proxy_redirect:1, /* Connection is redirected to a proxy */ + dsr:1, + reserved:8; + __u16 rev_nat_index; + /* In the kernel ifindex is u32, so we need to check in cilium-agent + * that ifindex of a NodePort device is <= MAX(u16). + */ + __u16 ifindex; + + /* *x_flags_seen represents the OR of all TCP flags seen for the + * transmit/receive direction of this entry. + */ + __u8 tx_flags_seen; + __u8 rx_flags_seen; + + __u32 src_sec_id; /* Used from userspace proxies, do not change offset! */ + + /* last_*x_report is a timestamp of the last time a monitor + * notification was sent for the transmit/receive direction. + */ + __u32 last_tx_report; + __u32 last_rx_report; +}; + +struct lb6_key { + union v6addr address; /* Service virtual IPv6 address */ + __be16 dport; /* L4 port filter, if unset, all ports apply */ + __u16 backend_slot; /* Backend iterator, 0 indicates the svc frontend */ + __u8 proto; /* L4 protocol, currently not used (set to 0) */ + __u8 scope; /* LB_LOOKUP_SCOPE_* for externalTrafficPolicy=Local */ + __u8 pad[2]; +}; + +/* See lb4_service comments */ +struct lb6_service { + union { + __u32 backend_id; /* Backend ID in lb6_backends */ + __u32 affinity_timeout; /* In seconds, only for svc frontend */ + }; + __u16 count; + __u16 rev_nat_index; + __u8 flags; + __u8 flags2; + __u8 pad[2]; +}; + +/* See lb4_backend comments */ +struct lb6_backend { + union v6addr address; + __be16 port; + __u8 proto; + __u8 pad; +}; + +struct lb6_health { + struct lb6_backend peer; +}; + +struct lb6_reverse_nat { + union v6addr address; + __be16 port; +} __packed; + +struct ipv6_revnat_tuple { + __sock_cookie cookie; + union v6addr address; + __be16 port; + __u16 pad; +}; + +struct ipv6_revnat_entry { + union v6addr address; + __be16 port; + __u16 rev_nat_index; +}; + +struct lb4_key { + __be32 address; /* Service virtual IPv4 address */ + __be16 dport; /* L4 port filter, if unset, all ports apply */ + __u16 backend_slot; /* Backend iterator, 0 indicates the svc frontend */ + __u8 proto; /* L4 protocol, currently not used (set to 0) */ + __u8 scope; /* LB_LOOKUP_SCOPE_* for externalTrafficPolicy=Local */ + __u8 pad[2]; +}; + +struct lb4_service { + union { + __u32 backend_id; /* Backend ID in lb4_backends */ + __u32 affinity_timeout; /* In seconds, only for svc frontend */ + }; + /* For the service frontend, count denotes number of service backend + * slots (otherwise zero). + */ + __u16 count; + __u16 rev_nat_index; /* Reverse NAT ID in lb4_reverse_nat */ + __u8 flags; + __u8 flags2; + __u8 pad[2]; +}; + +struct lb4_backend { + __be32 address; /* Service endpoint IPv4 address */ + __be16 port; /* L4 port filter */ + __u8 proto; /* L4 protocol, currently not used (set to 0) */ + __u8 pad; +}; + +struct lb4_health { + struct lb4_backend peer; +}; + +struct lb4_reverse_nat { + __be32 address; + __be16 port; +} __packed; + +struct ipv4_revnat_tuple { + __sock_cookie cookie; + __be32 address; + __be16 port; + __u16 pad; +}; + +struct ipv4_revnat_entry { + __be32 address; + __be16 port; + __u16 rev_nat_index; +}; + +union lb4_affinity_client_id { + __u32 client_ip; + __net_cookie client_cookie; +} __packed; + +struct lb4_affinity_key { + union lb4_affinity_client_id client_id; + __u16 rev_nat_id; + __u8 netns_cookie:1, + reserved:7; + __u8 pad1; + __u32 pad2; +} __packed; + +union lb6_affinity_client_id { + union v6addr client_ip; + __net_cookie client_cookie; +} __packed; + +struct lb6_affinity_key { + union lb6_affinity_client_id client_id; + __u16 rev_nat_id; + __u8 netns_cookie:1, + reserved:7; + __u8 pad1; + __u32 pad2; +} __packed; + +struct lb_affinity_val { + __u64 last_used; + __u32 backend_id; + __u32 pad; +} __packed; + +struct lb_affinity_match { + __u32 backend_id; + __u16 rev_nat_id; + __u16 pad; +} __packed; + +struct ct_state { + __u16 rev_nat_index; + __u16 loopback:1, + node_port:1, + proxy_redirect:1, /* Connection is redirected to a proxy */ + dsr:1, + reserved:12; + __be32 addr; + __be32 svc_addr; + __u32 src_sec_id; + __u16 ifindex; + __u16 backend_id; /* Backend ID in lb4_backends */ +}; + +#define SRC_RANGE_STATIC_PREFIX(STRUCT) \ + (8 * (sizeof(STRUCT) - sizeof(struct bpf_lpm_trie_key))) + +struct lb4_src_range_key { + struct bpf_lpm_trie_key lpm_key; + __u16 rev_nat_id; + __u16 pad; + __u32 addr; +}; + +struct lb6_src_range_key { + struct bpf_lpm_trie_key lpm_key; + __u16 rev_nat_id; + __u16 pad; + union v6addr addr; +}; + +static __always_inline int redirect_ep(struct __ctx_buff *ctx __maybe_unused, + int ifindex __maybe_unused, + bool needs_backlog __maybe_unused) +{ + /* If our datapath has proper redirect support, we make use + * of it here, otherwise we terminate tc processing by letting + * stack handle forwarding e.g. in ipvlan case. + * + * Going via CPU backlog queue (aka needs_backlog) is required + * whenever we cannot do a fast ingress -> ingress switch but + * instead need an ingress -> egress netns traversal or vice + * versa. + */ +#ifdef ENABLE_HOST_REDIRECT + if (needs_backlog || !is_defined(ENABLE_REDIRECT_FAST)) { + return redirect(ifindex, 0); + } else { +# ifdef ENCAP_IFINDEX + /* When coming from overlay, we need to set packet type + * to HOST as otherwise we might get dropped in IP layer. + */ + ctx_change_type(ctx, PACKET_HOST); +# endif /* ENCAP_IFINDEX */ + return redirect_peer(ifindex, 0); + } +#else + return CTX_ACT_OK; +#endif /* ENABLE_HOST_REDIRECT */ +} + +struct lpm_v4_key { + struct bpf_lpm_trie_key lpm; + __u8 addr[4]; +}; + +struct lpm_v6_key { + struct bpf_lpm_trie_key lpm; + __u8 addr[16]; +}; + +struct lpm_val { + /* Just dummy for now. */ + __u8 flags; +}; + +#include "overloadable.h" + +#endif /* __LIB_COMMON_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/config.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/config.h new file mode 100644 index 000000000..1a015a023 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/config.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +#ifndef _H_LIB_CONFIG_H_ +#define _H_LIB_CONFIG_H_ + +/* Subset of kernel's include/linux/kconfig.h */ + +#define __ARG_PLACEHOLDER_1 0, +#define __take_second_arg(__ignored, val, ...) val + +#define __is_defined(x) ___is_defined(x) +#define ___is_defined(val) ____is_defined(__ARG_PLACEHOLDER_##val) +#define ____is_defined(arg1_or_junk) __take_second_arg(arg1_or_junk 1, 0) + +#define is_defined(option) __is_defined(option) + +#endif /* _H_LIB_CONFIG_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/conntrack.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/conntrack.h new file mode 100644 index 000000000..6c303dbbb --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/conntrack.h @@ -0,0 +1,1011 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_CONNTRACK_H_ +#define __LIB_CONNTRACK_H_ + +#include +#include + +#include + +#include "common.h" +#include "utils.h" +#include "ipv4.h" +#include "ipv6.h" +#include "dbg.h" +#include "l4.h" +#include "nat46.h" +#include "signal.h" + +#ifdef CONNTRACK +enum { + ACTION_UNSPEC, + ACTION_CREATE, + ACTION_CLOSE, +}; + +/* conn_is_dns returns true if the connection is DNS, false otherwise. + * + * @dport: Connection destination port. + * + * To reduce program complexity, we ignore nexthdr and dir here: + * nexthdr: The parser will not fill dport if nexthdr is not TCP/UDP. + * dir: Ideally we would only consider responses, but requests are likely + * to be small anyway. + */ +static __always_inline bool conn_is_dns(__u16 dport) +{ + return dport == bpf_htons(53); +} + +static __always_inline bool ct_entry_seen_both_syns(const struct ct_entry *entry) +{ + bool rx_syn = entry->rx_flags_seen & TCP_FLAG_SYN; + bool tx_syn = entry->tx_flags_seen & TCP_FLAG_SYN; + + return rx_syn && tx_syn; +} + +union tcp_flags { + struct { + __u8 upper_bits; + __u8 lower_bits; + __u16 pad; + }; + __u32 value; +}; + +/** + * Update the CT timeout and TCP flags for the specified entry. + * + * We track the OR'd accumulation of seen tcp flags in the entry, and the + * last time that a notification was sent. Multiple CPUs may enter this + * function with packets for the same connection, in which case it is possible + * for the CPUs to race to update the entry. In such a case, the critical + * update section may be entered in quick succession, leading to multiple + * updates of the entry and returning true for each CPU. The BPF architecture + * guarantees that entire 8-bit or 32-bit values will be set within the entry, + * so although the CPUs may race, the worst result is that multiple executions + * of this function return non-zero for the same connection within short + * succession, leading to multiple trace notifications being sent when one + * might otherwise expect such notifications to be aggregated. + * + * Returns how many bytes of the packet should be monitored: + * - Zero if this flow was recently monitored. + * - Non-zero if this flow has not been monitored recently. + */ +static __always_inline __u32 __ct_update_timeout(struct ct_entry *entry, + __u32 lifetime, int dir, + union tcp_flags flags, + __u8 report_mask) +{ + __u32 now = bpf_mono_now(); + __u8 accumulated_flags; + __u8 seen_flags = flags.lower_bits & report_mask; + __u32 last_report; + +#ifdef NEEDS_TIMEOUT + WRITE_ONCE(entry->lifetime, now + lifetime); +#endif + if (dir == CT_INGRESS) { + accumulated_flags = READ_ONCE(entry->rx_flags_seen); + last_report = READ_ONCE(entry->last_rx_report); + } else { + accumulated_flags = READ_ONCE(entry->tx_flags_seen); + last_report = READ_ONCE(entry->last_tx_report); + } + seen_flags |= accumulated_flags; + + /* It's possible for multiple CPUs to execute the branch statement here + * one after another, before the first CPU is able to execute the entry + * modifications within this branch. This is somewhat unlikely because + * packets for the same connection are typically steered towards the + * same CPU, but is possible in theory. + * + * If the branch is taken by multiple CPUs because of '*last_report', + * then this merely causes multiple notifications to be sent after + * CT_REPORT_INTERVAL rather than a single notification. '*last_report' + * will be updated by all CPUs and subsequent checks should not take + * this branch until the next CT_REPORT_INTERVAL. As such, the trace + * aggregation that uses the result of this function may reduce the + * number of packets per interval to a small integer value (max N_CPUS) + * rather than 1 notification per packet throughout the interval. + * + * Similar behaviour may happen with tcp_flags. The worst case race + * here would be that two or more CPUs argue over which flags have been + * seen and overwrite each other, with each CPU interleaving different + * values for which flags were seen. In practice, realistic connections + * are likely to progressively set SYN, ACK, then much later perhaps + * FIN and/or RST. Furthermore, unless such a traffic pattern were + * constantly received, this should self-correct as the stored + * tcp_flags is an OR'd set of flags and each time the above code is + * executed, it pulls the latest set of accumulated flags. Therefore + * even in the worst case such a conflict is likely only to cause a + * small number of additional notifications, which is still likely to + * be significantly less under this MONITOR_AGGREGATION mode than would + * otherwise be sent if the MONITOR_AGGREGATION level is set to none + * (ie, sending a notification for every packet). + */ + if (last_report + bpf_sec_to_mono(CT_REPORT_INTERVAL) < now || + accumulated_flags != seen_flags) { + /* verifier workaround: we don't use reference here. */ + if (dir == CT_INGRESS) { + WRITE_ONCE(entry->rx_flags_seen, seen_flags); + WRITE_ONCE(entry->last_rx_report, now); + } else { + WRITE_ONCE(entry->tx_flags_seen, seen_flags); + WRITE_ONCE(entry->last_tx_report, now); + } + return TRACE_PAYLOAD_LEN; + } + return 0; +} + +/** + * Update the CT timeouts for the specified entry. + * + * If CT_REPORT_INTERVAL has elapsed since the last update, updates the + * last_updated timestamp and returns true. Otherwise returns false. + */ +static __always_inline __u32 ct_update_timeout(struct ct_entry *entry, + bool tcp, int dir, + union tcp_flags seen_flags) +{ + __u32 lifetime = dir == CT_SERVICE ? + bpf_sec_to_mono(CT_SERVICE_LIFETIME_NONTCP) : + bpf_sec_to_mono(CT_CONNECTION_LIFETIME_NONTCP); + bool syn = seen_flags.value & TCP_FLAG_SYN; + + if (tcp) { + entry->seen_non_syn |= !syn; + if (entry->seen_non_syn) { + lifetime = dir == CT_SERVICE ? + bpf_sec_to_mono(CT_SERVICE_LIFETIME_TCP) : + bpf_sec_to_mono(CT_CONNECTION_LIFETIME_TCP); + } else { + lifetime = bpf_sec_to_mono(CT_SYN_TIMEOUT); + } + } + + return __ct_update_timeout(entry, lifetime, dir, seen_flags, + CT_REPORT_FLAGS); +} + +static __always_inline void ct_reset_closing(struct ct_entry *entry) +{ + entry->rx_closing = 0; + entry->tx_closing = 0; +} + +static __always_inline bool ct_entry_alive(const struct ct_entry *entry) +{ + return !entry->rx_closing || !entry->tx_closing; +} + +/* Helper for holding 2nd service entry alive in nodeport case. */ +static __always_inline bool __ct_entry_keep_alive(const void *map, + const void *tuple) +{ + struct ct_entry *entry; + + /* Lookup indicates to LRU that key/value is in use. */ + entry = map_lookup_elem(map, tuple); + if (entry) { + if (entry->node_port) { +#ifdef NEEDS_TIMEOUT + __u32 lifetime = (entry->seen_non_syn ? + bpf_sec_to_mono(CT_SERVICE_LIFETIME_TCP) : + bpf_sec_to_mono(CT_SERVICE_LIFETIME_NONTCP)) + + bpf_mono_now(); + WRITE_ONCE(entry->lifetime, lifetime); +#endif + if (!ct_entry_alive(entry)) + ct_reset_closing(entry); + } + return true; + } + return false; +} + +static __always_inline __u8 __ct_lookup(const void *map, struct __ctx_buff *ctx, + const void *tuple, int action, int dir, + struct ct_state *ct_state, + bool is_tcp, union tcp_flags seen_flags, + __u32 *monitor) +{ + struct ct_entry *entry; + int reopen; + + relax_verifier(); + + entry = map_lookup_elem(map, tuple); + if (entry) { + cilium_dbg(ctx, DBG_CT_MATCH, entry->lifetime, entry->rev_nat_index); + if (ct_entry_alive(entry)) + *monitor = ct_update_timeout(entry, is_tcp, dir, seen_flags); + if (ct_state) { + ct_state->rev_nat_index = entry->rev_nat_index; + ct_state->loopback = entry->lb_loopback; + ct_state->node_port = entry->node_port; + ct_state->ifindex = entry->ifindex; + ct_state->dsr = entry->dsr; + ct_state->proxy_redirect = entry->proxy_redirect; + /* See the ct_create4 comments re the rx_bytes hack */ + if (dir == CT_SERVICE) + ct_state->backend_id = entry->rx_bytes; + } + +#ifdef ENABLE_NAT46 + /* This packet needs nat46 translation */ + if (entry->nat46 && !ctx_load_meta(ctx, CB_NAT46_STATE)) + ctx_store_meta(ctx, CB_NAT46_STATE, NAT46); +#endif +#ifdef CONNTRACK_ACCOUNTING + /* FIXME: This is slow, per-cpu counters? */ + if (dir == CT_INGRESS) { + __sync_fetch_and_add(&entry->rx_packets, 1); + __sync_fetch_and_add(&entry->rx_bytes, ctx_full_len(ctx)); + } else if (dir == CT_EGRESS) { + __sync_fetch_and_add(&entry->tx_packets, 1); + __sync_fetch_and_add(&entry->tx_bytes, ctx_full_len(ctx)); + } +#endif + switch (action) { + case ACTION_CREATE: + reopen = entry->rx_closing | entry->tx_closing; + reopen |= seen_flags.value & TCP_FLAG_SYN; + if (unlikely(reopen == (TCP_FLAG_SYN|0x1))) { + ct_reset_closing(entry); + *monitor = ct_update_timeout(entry, is_tcp, dir, seen_flags); + return CT_REOPENED; + } + break; + + case ACTION_CLOSE: + /* If we got an RST and have not seen both SYNs, + * terminate the connection. (For CT_SERVICE, we do not + * see both directions, so flags of established + * connections would not include both SYNs.) + */ + if (!ct_entry_seen_both_syns(entry) && + (seen_flags.value & TCP_FLAG_RST) && + dir != CT_SERVICE) { + entry->rx_closing = 1; + entry->tx_closing = 1; + } else if (dir == CT_INGRESS) { + entry->rx_closing = 1; + } else { + entry->tx_closing = 1; + } + + *monitor = TRACE_PAYLOAD_LEN; + if (ct_entry_alive(entry)) + break; + __ct_update_timeout(entry, bpf_sec_to_mono(CT_CLOSE_TIMEOUT), + dir, seen_flags, CT_REPORT_FLAGS); + break; + } + + return CT_ESTABLISHED; + } + + *monitor = TRACE_PAYLOAD_LEN; + return CT_NEW; +} + +static __always_inline int +ipv6_extract_tuple(struct __ctx_buff *ctx, struct ipv6_ct_tuple *tuple, + int *l4_off) +{ + int ret, l3_off = ETH_HLEN; + void *data, *data_end; + struct ipv6hdr *ip6; + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return DROP_INVALID; + + tuple->nexthdr = ip6->nexthdr; + ipv6_addr_copy(&tuple->daddr, (union v6addr *)&ip6->daddr); + ipv6_addr_copy(&tuple->saddr, (union v6addr *)&ip6->saddr); + + ret = ipv6_hdrlen(ctx, l3_off, &tuple->nexthdr); + if (ret < 0) + return ret; + + if (unlikely(tuple->nexthdr != IPPROTO_TCP && + tuple->nexthdr != IPPROTO_UDP)) + return DROP_CT_UNKNOWN_PROTO; + + if (ret < 0) + return ret; + + *l4_off = l3_off + ret; + return CTX_ACT_OK; +} + +static __always_inline void ct_flip_tuple_dir6(struct ipv6_ct_tuple *tuple) +{ + if (tuple->flags & TUPLE_F_IN) + tuple->flags &= ~TUPLE_F_IN; + else + tuple->flags |= TUPLE_F_IN; +} + +static __always_inline void +__ipv6_ct_tuple_reverse(struct ipv6_ct_tuple *tuple) +{ + union v6addr tmp_addr = {}; + __be16 tmp; + + ipv6_addr_copy(&tmp_addr, &tuple->saddr); + ipv6_addr_copy(&tuple->saddr, &tuple->daddr); + ipv6_addr_copy(&tuple->daddr, &tmp_addr); + + tmp = tuple->sport; + tuple->sport = tuple->dport; + tuple->dport = tmp; +} + +static __always_inline void +ipv6_ct_tuple_reverse(struct ipv6_ct_tuple *tuple) +{ + __ipv6_ct_tuple_reverse(tuple); + ct_flip_tuple_dir6(tuple); +} + +/* Offset must point to IPv6 */ +static __always_inline int ct_lookup6(const void *map, + struct ipv6_ct_tuple *tuple, + struct __ctx_buff *ctx, int l4_off, + int dir, struct ct_state *ct_state, + __u32 *monitor) +{ + int ret = CT_NEW, action = ACTION_UNSPEC; + bool is_tcp = tuple->nexthdr == IPPROTO_TCP; + union tcp_flags tcp_flags = { .value = 0 }; + + /* The tuple is created in reverse order initially to find a + * potential reverse flow. This is required because the RELATED + * or REPLY state takes precedence over ESTABLISHED due to + * policy requirements. + * + * tuple->flags separates entries that could otherwise be overlapping. + */ + if (dir == CT_INGRESS) + tuple->flags = TUPLE_F_OUT; + else if (dir == CT_EGRESS) + tuple->flags = TUPLE_F_IN; + else if (dir == CT_SERVICE) + tuple->flags = TUPLE_F_SERVICE; + else + return DROP_CT_INVALID_HDR; + + switch (tuple->nexthdr) { + case IPPROTO_ICMPV6: + if (1) { + __be16 identifier = 0; + __u8 type; + + if (ctx_load_bytes(ctx, l4_off, &type, 1) < 0) + return DROP_CT_INVALID_HDR; + if ((type == ICMPV6_ECHO_REQUEST || type == ICMPV6_ECHO_REPLY) && + ctx_load_bytes(ctx, l4_off + offsetof(struct icmp6hdr, + icmp6_dataun.u_echo.identifier), + &identifier, 2) < 0) + return DROP_CT_INVALID_HDR; + + tuple->sport = 0; + tuple->dport = 0; + + switch (type) { + case ICMPV6_DEST_UNREACH: + case ICMPV6_PKT_TOOBIG: + case ICMPV6_TIME_EXCEED: + case ICMPV6_PARAMPROB: + tuple->flags |= TUPLE_F_RELATED; + break; + + case ICMPV6_ECHO_REPLY: + tuple->sport = identifier; + break; + + case ICMPV6_ECHO_REQUEST: + tuple->dport = identifier; + /* fall through */ + default: + action = ACTION_CREATE; + break; + } + } + break; + + case IPPROTO_TCP: + if (1) { + if (ctx_load_bytes(ctx, l4_off + 12, &tcp_flags, 2) < 0) + return DROP_CT_INVALID_HDR; + + if (unlikely(tcp_flags.value & (TCP_FLAG_RST|TCP_FLAG_FIN))) + action = ACTION_CLOSE; + else + action = ACTION_CREATE; + } + + /* load sport + dport into tuple */ + if (ctx_load_bytes(ctx, l4_off, &tuple->dport, 4) < 0) + return DROP_CT_INVALID_HDR; + break; + + case IPPROTO_UDP: + /* load sport + dport into tuple */ + if (ctx_load_bytes(ctx, l4_off, &tuple->dport, 4) < 0) + return DROP_CT_INVALID_HDR; + + action = ACTION_CREATE; + break; + + default: + /* Can't handle extension headers yet */ + return DROP_CT_UNKNOWN_PROTO; + } + + /* Lookup the reverse direction + * + * This will find an existing flow in the reverse direction. + * The reverse direction is the one where reverse nat index is stored. + */ + cilium_dbg3(ctx, DBG_CT_LOOKUP6_1, (__u32) tuple->saddr.p4, (__u32) tuple->daddr.p4, + (bpf_ntohs(tuple->sport) << 16) | bpf_ntohs(tuple->dport)); + cilium_dbg3(ctx, DBG_CT_LOOKUP6_2, (tuple->nexthdr << 8) | tuple->flags, 0, 0); + ret = __ct_lookup(map, ctx, tuple, action, dir, ct_state, is_tcp, + tcp_flags, monitor); + if (ret != CT_NEW) { + if (likely(ret == CT_ESTABLISHED || ret == CT_REOPENED)) { + if (unlikely(tuple->flags & TUPLE_F_RELATED)) + ret = CT_RELATED; + else + ret = CT_REPLY; + } + goto out; + } + + /* Lookup entry in forward direction */ + if (dir != CT_SERVICE) { + ipv6_ct_tuple_reverse(tuple); + ret = __ct_lookup(map, ctx, tuple, action, dir, ct_state, + is_tcp, tcp_flags, monitor); + } + +#ifdef ENABLE_NAT46 + ctx_store_meta(ctx, CB_NAT46_STATE, NAT46_CLEAR); +#endif +out: + cilium_dbg(ctx, DBG_CT_VERDICT, ret < 0 ? -ret : ret, ct_state->rev_nat_index); + if (conn_is_dns(tuple->dport)) + *monitor = MTU; + return ret; +} + +static __always_inline int +ipv4_extract_tuple(struct __ctx_buff *ctx, struct ipv4_ct_tuple *tuple, + int *l4_off) +{ + int l3_off = ETH_HLEN; + void *data, *data_end; + struct iphdr *ip4; + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + tuple->nexthdr = ip4->protocol; + + if (unlikely(tuple->nexthdr != IPPROTO_TCP && + tuple->nexthdr != IPPROTO_UDP)) + return DROP_CT_UNKNOWN_PROTO; + + tuple->daddr = ip4->daddr; + tuple->saddr = ip4->saddr; + + *l4_off = l3_off + ipv4_hdrlen(ip4); + return CTX_ACT_OK; +} + +static __always_inline void ct_flip_tuple_dir4(struct ipv4_ct_tuple *tuple) +{ + if (tuple->flags & TUPLE_F_IN) + tuple->flags &= ~TUPLE_F_IN; + else + tuple->flags |= TUPLE_F_IN; +} + +static __always_inline void +__ipv4_ct_tuple_reverse(struct ipv4_ct_tuple *tuple) +{ + __be32 tmp_addr = tuple->saddr; + __be16 tmp; + + tuple->saddr = tuple->daddr; + tuple->daddr = tmp_addr; + + tmp = tuple->sport; + tuple->sport = tuple->dport; + tuple->dport = tmp; +} + +static __always_inline void +ipv4_ct_tuple_reverse(struct ipv4_ct_tuple *tuple) +{ + __ipv4_ct_tuple_reverse(tuple); + ct_flip_tuple_dir4(tuple); +} + +static __always_inline int ipv4_ct_extract_l4_ports(struct __ctx_buff *ctx, + int off, + int dir __maybe_unused, + struct ipv4_ct_tuple *tuple, + bool *has_l4_header __maybe_unused) +{ +#ifdef ENABLE_IPV4_FRAGMENTS + void *data, *data_end; + struct iphdr *ip4; + + /* This function is called from ct_lookup4(), which is sometimes called + * after data has been invalidated (see handle_ipv4_from_lxc()) + */ + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_CT_INVALID_HDR; + + return ipv4_handle_fragmentation(ctx, ip4, off, dir, + (struct ipv4_frag_l4ports *)&tuple->dport, + has_l4_header); +#else + /* load sport + dport into tuple */ + if (ctx_load_bytes(ctx, off, &tuple->dport, 4) < 0) + return DROP_CT_INVALID_HDR; +#endif + + return CTX_ACT_OK; +} + +static __always_inline void ct4_cilium_dbg_tuple(struct __ctx_buff *ctx, __u8 type, + const struct ipv4_ct_tuple *tuple, + __u32 rev_nat_index, int dir) +{ + __be32 addr = (dir == CT_INGRESS) ? tuple->saddr : tuple->daddr; + + cilium_dbg(ctx, type, addr, rev_nat_index); +} + +/* Offset must point to IPv4 header */ +static __always_inline int ct_lookup4(const void *map, + struct ipv4_ct_tuple *tuple, + struct __ctx_buff *ctx, int off, int dir, + struct ct_state *ct_state, __u32 *monitor) +{ + int err, ret = CT_NEW, action = ACTION_UNSPEC; + bool is_tcp = tuple->nexthdr == IPPROTO_TCP, + has_l4_header = true; + union tcp_flags tcp_flags = { .value = 0 }; + + /* The tuple is created in reverse order initially to find a + * potential reverse flow. This is required because the RELATED + * or REPLY state takes precedence over ESTABLISHED due to + * policy requirements. + * + * tuple->flags separates entries that could otherwise be overlapping. + */ + if (dir == CT_INGRESS) + tuple->flags = TUPLE_F_OUT; + else if (dir == CT_EGRESS) + tuple->flags = TUPLE_F_IN; + else if (dir == CT_SERVICE) + tuple->flags = TUPLE_F_SERVICE; + else + return DROP_CT_INVALID_HDR; + + switch (tuple->nexthdr) { + case IPPROTO_ICMP: + if (1) { + __be16 identifier = 0; + __u8 type; + + if (ctx_load_bytes(ctx, off, &type, 1) < 0) + return DROP_CT_INVALID_HDR; + if ((type == ICMP_ECHO || type == ICMP_ECHOREPLY) && + ctx_load_bytes(ctx, off + offsetof(struct icmphdr, un.echo.id), + &identifier, 2) < 0) + return DROP_CT_INVALID_HDR; + + tuple->sport = 0; + tuple->dport = 0; + + switch (type) { + case ICMP_DEST_UNREACH: + case ICMP_TIME_EXCEEDED: + case ICMP_PARAMETERPROB: + tuple->flags |= TUPLE_F_RELATED; + break; + + case ICMP_ECHOREPLY: + tuple->sport = identifier; + break; + case ICMP_ECHO: + tuple->dport = identifier; + /* fall through */ + default: + action = ACTION_CREATE; + break; + } + } + break; + + case IPPROTO_TCP: + err = ipv4_ct_extract_l4_ports(ctx, off, dir, tuple, &has_l4_header); + if (err < 0) + return err; + + action = ACTION_CREATE; + + if (has_l4_header) { + if (ctx_load_bytes(ctx, off + 12, &tcp_flags, 2) < 0) + return DROP_CT_INVALID_HDR; + + if (unlikely(tcp_flags.value & (TCP_FLAG_RST|TCP_FLAG_FIN))) + action = ACTION_CLOSE; + } + break; + + case IPPROTO_UDP: + err = ipv4_ct_extract_l4_ports(ctx, off, dir, tuple, NULL); + if (err < 0) + return err; + + action = ACTION_CREATE; + break; + + default: + /* Can't handle extension headers yet */ + return DROP_CT_UNKNOWN_PROTO; + } + + /* Lookup the reverse direction + * + * This will find an existing flow in the reverse direction. + */ +#ifndef QUIET_CT + cilium_dbg3(ctx, DBG_CT_LOOKUP4_1, tuple->saddr, tuple->daddr, + (bpf_ntohs(tuple->sport) << 16) | bpf_ntohs(tuple->dport)); + cilium_dbg3(ctx, DBG_CT_LOOKUP4_2, (tuple->nexthdr << 8) | tuple->flags, 0, 0); +#endif + ret = __ct_lookup(map, ctx, tuple, action, dir, ct_state, is_tcp, + tcp_flags, monitor); + if (ret != CT_NEW) { + if (likely(ret == CT_ESTABLISHED || ret == CT_REOPENED)) { + if (unlikely(tuple->flags & TUPLE_F_RELATED)) + ret = CT_RELATED; + else + ret = CT_REPLY; + } + goto out; + } + + relax_verifier(); + + /* Lookup entry in forward direction */ + if (dir != CT_SERVICE) { + ipv4_ct_tuple_reverse(tuple); + ret = __ct_lookup(map, ctx, tuple, action, dir, ct_state, + is_tcp, tcp_flags, monitor); + } +out: + cilium_dbg(ctx, DBG_CT_VERDICT, ret < 0 ? -ret : ret, ct_state->rev_nat_index); + if (conn_is_dns(tuple->dport)) + *monitor = MTU; + return ret; +} + +static __always_inline void +ct_update6_backend_id(const void *map, const struct ipv6_ct_tuple *tuple, + const struct ct_state *state) +{ + struct ct_entry *entry; + + entry = map_lookup_elem(map, tuple); + if (!entry) + return; + + /* See the ct_create4 comments re the rx_bytes hack */ + entry->rx_bytes = state->backend_id; +} + +static __always_inline void +ct_update6_rev_nat_index(const void *map, const struct ipv6_ct_tuple *tuple, + const struct ct_state *state) +{ + struct ct_entry *entry; + + entry = map_lookup_elem(map, tuple); + if (!entry) + return; + + entry->rev_nat_index = state->rev_nat_index; +} + +/* Offset must point to IPv6 */ +static __always_inline int ct_create6(const void *map_main, const void *map_related, + struct ipv6_ct_tuple *tuple, + struct __ctx_buff *ctx, const int dir, + const struct ct_state *ct_state, + bool proxy_redirect) +{ + /* Create entry in original direction */ + struct ct_entry entry = { }; + bool is_tcp = tuple->nexthdr == IPPROTO_TCP; + union tcp_flags seen_flags = { .value = 0 }; + + /* Note if this is a proxy connection so that replies can be redirected + * back to the proxy. + */ + entry.proxy_redirect = proxy_redirect; + + /* See the ct_create4 comments re the rx_bytes hack */ + if (dir == CT_SERVICE) + entry.rx_bytes = ct_state->backend_id; + + entry.lb_loopback = ct_state->loopback; + entry.node_port = ct_state->node_port; + relax_verifier(); + entry.dsr = ct_state->dsr; + entry.ifindex = ct_state->ifindex; + + entry.rev_nat_index = ct_state->rev_nat_index; + seen_flags.value |= is_tcp ? TCP_FLAG_SYN : 0; + ct_update_timeout(&entry, is_tcp, dir, seen_flags); + + if (dir == CT_INGRESS) { + entry.rx_packets = 1; + entry.rx_bytes = ctx_full_len(ctx); + } else if (dir == CT_EGRESS) { + entry.tx_packets = 1; + entry.tx_bytes = ctx_full_len(ctx); + } + + cilium_dbg3(ctx, DBG_CT_CREATED6, entry.rev_nat_index, ct_state->src_sec_id, 0); + + entry.src_sec_id = ct_state->src_sec_id; + if (map_update_elem(map_main, tuple, &entry, 0) < 0) { + send_signal_ct_fill_up(ctx, SIGNAL_PROTO_V6); + return DROP_CT_CREATE_FAILED; + } + + if (map_related != NULL) { + /* Create an ICMPv6 entry to relate errors */ + struct ipv6_ct_tuple icmp_tuple = { + .nexthdr = IPPROTO_ICMPV6, + .sport = 0, + .dport = 0, + .flags = tuple->flags | TUPLE_F_RELATED, + }; + + entry.seen_non_syn = true; /* For ICMP, there is no SYN. */ + + ipv6_addr_copy(&icmp_tuple.daddr, &tuple->daddr); + ipv6_addr_copy(&icmp_tuple.saddr, &tuple->saddr); + + if (map_update_elem(map_related, &icmp_tuple, &entry, 0) < 0) { + send_signal_ct_fill_up(ctx, SIGNAL_PROTO_V6); + return DROP_CT_CREATE_FAILED; + } + } + return 0; +} + +static __always_inline void ct_update4_backend_id(const void *map, + const struct ipv4_ct_tuple *tuple, + const struct ct_state *state) +{ + struct ct_entry *entry; + + entry = map_lookup_elem(map, tuple); + if (!entry) + return; + + /* See the ct_create4 comments re the rx_bytes hack */ + entry->rx_bytes = state->backend_id; +} + +static __always_inline void +ct_update4_rev_nat_index(const void *map, const struct ipv4_ct_tuple *tuple, + const struct ct_state *state) +{ + struct ct_entry *entry; + + entry = map_lookup_elem(map, tuple); + if (!entry) + return; + + entry->rev_nat_index = state->rev_nat_index; +} + +static __always_inline int ct_create4(const void *map_main, + const void *map_related, + struct ipv4_ct_tuple *tuple, + struct __ctx_buff *ctx, const int dir, + const struct ct_state *ct_state, + bool proxy_redirect) +{ + /* Create entry in original direction */ + struct ct_entry entry = { }; + bool is_tcp = tuple->nexthdr == IPPROTO_TCP; + union tcp_flags seen_flags = { .value = 0 }; + + /* Note if this is a proxy connection so that replies can be redirected + * back to the proxy. + */ + entry.proxy_redirect = proxy_redirect; + + entry.lb_loopback = ct_state->loopback; + entry.node_port = ct_state->node_port; + relax_verifier(); + entry.dsr = ct_state->dsr; + entry.ifindex = ct_state->ifindex; + + /* Previously, the rx_bytes field was not used for entries with + * the dir=CT_SERVICE (see GH#7060). Therefore, we can safely abuse + * this field to save the backend_id. + */ + if (dir == CT_SERVICE) + entry.rx_bytes = ct_state->backend_id; + entry.rev_nat_index = ct_state->rev_nat_index; + seen_flags.value |= is_tcp ? TCP_FLAG_SYN : 0; + ct_update_timeout(&entry, is_tcp, dir, seen_flags); + + if (dir == CT_INGRESS) { + entry.rx_packets = 1; + entry.rx_bytes = ctx_full_len(ctx); + } else if (dir == CT_EGRESS) { + entry.tx_packets = 1; + entry.tx_bytes = ctx_full_len(ctx); + } + +#ifdef ENABLE_NAT46 + if (ctx_load_meta(ctx, CB_NAT46_STATE) == NAT64) + entry.nat46 = dir == CT_EGRESS; +#endif + + cilium_dbg3(ctx, DBG_CT_CREATED4, entry.rev_nat_index, + ct_state->src_sec_id, ct_state->addr); + + entry.src_sec_id = ct_state->src_sec_id; + if (map_update_elem(map_main, tuple, &entry, 0) < 0) { + send_signal_ct_fill_up(ctx, SIGNAL_PROTO_V4); + return DROP_CT_CREATE_FAILED; + } + + if (ct_state->addr && ct_state->loopback) { + __u8 flags = tuple->flags; + __be32 saddr, daddr; + + saddr = tuple->saddr; + daddr = tuple->daddr; + + /* We are looping back into the origin endpoint through a + * service, set up a conntrack tuple for the reply to ensure we + * do rev NAT before attempting to route the destination + * address which will not point back to the right source. + */ + tuple->flags = TUPLE_F_IN; + if (dir == CT_INGRESS) { + tuple->saddr = ct_state->addr; + tuple->daddr = ct_state->svc_addr; + } else { + tuple->saddr = ct_state->svc_addr; + tuple->daddr = ct_state->addr; + } + + if (map_update_elem(map_main, tuple, &entry, 0) < 0) { + send_signal_ct_fill_up(ctx, SIGNAL_PROTO_V4); + return DROP_CT_CREATE_FAILED; + } + + tuple->saddr = saddr; + tuple->daddr = daddr; + tuple->flags = flags; + } + + if (map_related != NULL) { + /* Create an ICMP entry to relate errors */ + struct ipv4_ct_tuple icmp_tuple = { + .daddr = tuple->daddr, + .saddr = tuple->saddr, + .nexthdr = IPPROTO_ICMP, + .sport = 0, + .dport = 0, + .flags = tuple->flags | TUPLE_F_RELATED, + }; + + entry.seen_non_syn = true; /* For ICMP, there is no SYN. */ + /* Previous map update succeeded, we could delete it in case + * the below throws an error, but we might as well just let + * it time out. + */ + if (map_update_elem(map_related, &icmp_tuple, &entry, 0) < 0) { + send_signal_ct_fill_up(ctx, SIGNAL_PROTO_V4); + return DROP_CT_CREATE_FAILED; + } + } + return 0; +} +#else /* !CONNTRACK */ +static __always_inline int +ct_lookup6(const void *map __maybe_unused, + struct ipv6_ct_tuple *tuple __maybe_unused, + struct __ctx_buff *ctx __maybe_unused, int off __maybe_unused, + int dir __maybe_unused, struct ct_state *ct_state __maybe_unused, + __u32 *monitor __maybe_unused) +{ + return 0; +} + +static __always_inline int +ct_lookup4(const void *map __maybe_unused, + struct ipv4_ct_tuple *tuple __maybe_unused, + struct __ctx_buff *ctx __maybe_unused, int off __maybe_unused, + int dir __maybe_unused, struct ct_state *ct_state __maybe_unused, + __u32 *monitor __maybe_unused) +{ + return 0; +} + +static __always_inline void +ct_update6_backend_id(const void *map __maybe_unused, + const struct ipv6_ct_tuple *tuple __maybe_unused, + const struct ct_state *state __maybe_unused) +{ +} + +static __always_inline void +ct_update6_rev_nat_index(const void *map __maybe_unused, + const struct ipv6_ct_tuple *tuple __maybe_unused, + const struct ct_state *state __maybe_unused) +{ +} + +static __always_inline int +ct_create6(const void *map_main __maybe_unused, + const void *map_related __maybe_unused, + struct ipv6_ct_tuple *tuple __maybe_unused, + struct __ctx_buff *ctx __maybe_unused, const int dir __maybe_unused, + struct ct_state *ct_state __maybe_unused, + bool from_proxy __maybe_unused) +{ + return 0; +} + +static __always_inline void +ct_update4_backend_id(const void *map __maybe_unused, + const struct ipv4_ct_tuple *tuple __maybe_unused, + const struct ct_state *state __maybe_unused) +{ +} + +static __always_inline void +ct_update4_rev_nat_index(const void *map __maybe_unused, + const struct ipv4_ct_tuple *tuple __maybe_unused, + const struct ct_state *state __maybe_unused) +{ +} + +static __always_inline int +ct_create4(const void *map_main __maybe_unused, + const void *map_related __maybe_unused, + struct ipv4_ct_tuple *tuple __maybe_unused, + struct __ctx_buff *ctx __maybe_unused, const int dir __maybe_unused, + const struct ct_state *ct_state __maybe_unused, + bool proxy_redirect __maybe_unused) +{ + return 0; +} + +#endif /* CONNTRACK */ +#endif /* __LIB_CONNTRACK_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/conntrack_map.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/conntrack_map.h new file mode 100644 index 000000000..6349cfbd7 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/conntrack_map.h @@ -0,0 +1,83 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_CONNTRACK_MAP_H_ +#define __LIB_CONNTRACK_MAP_H_ + +#include "common.h" +#include "config.h" + +#if defined(CT_MAP_TCP4) && defined(CT_MAP_TCP6) +#ifdef HAVE_LRU_HASH_MAP_TYPE +#define CT_MAP_TYPE BPF_MAP_TYPE_LRU_HASH +#else +#define CT_MAP_TYPE BPF_MAP_TYPE_HASH +#endif + +#ifdef ENABLE_IPV6 +struct bpf_elf_map __section_maps CT_MAP_TCP6 = { + .type = CT_MAP_TYPE, + .size_key = sizeof(struct ipv6_ct_tuple), + .size_value = sizeof(struct ct_entry), + .pinning = PIN_GLOBAL_NS, + .max_elem = CT_MAP_SIZE_TCP, +#ifndef HAVE_LRU_HASH_MAP_TYPE + .flags = CONDITIONAL_PREALLOC, +#endif +}; + +struct bpf_elf_map __section_maps CT_MAP_ANY6 = { + .type = CT_MAP_TYPE, + .size_key = sizeof(struct ipv6_ct_tuple), + .size_value = sizeof(struct ct_entry), + .pinning = PIN_GLOBAL_NS, + .max_elem = CT_MAP_SIZE_ANY, +#ifndef HAVE_LRU_HASH_MAP_TYPE + .flags = CONDITIONAL_PREALLOC, +#endif +}; + +static __always_inline struct bpf_elf_map * +get_ct_map6(const struct ipv6_ct_tuple *tuple) +{ + if (tuple->nexthdr == IPPROTO_TCP) + return &CT_MAP_TCP6; + + return &CT_MAP_ANY6; +} +#endif + +#ifdef ENABLE_IPV4 +struct bpf_elf_map __section_maps CT_MAP_TCP4 = { + .type = CT_MAP_TYPE, + .size_key = sizeof(struct ipv4_ct_tuple), + .size_value = sizeof(struct ct_entry), + .pinning = PIN_GLOBAL_NS, + .max_elem = CT_MAP_SIZE_TCP, +#ifndef HAVE_LRU_HASH_MAP_TYPE + .flags = CONDITIONAL_PREALLOC, +#endif +}; + +struct bpf_elf_map __section_maps CT_MAP_ANY4 = { + .type = CT_MAP_TYPE, + .size_key = sizeof(struct ipv4_ct_tuple), + .size_value = sizeof(struct ct_entry), + .pinning = PIN_GLOBAL_NS, + .max_elem = CT_MAP_SIZE_ANY, +#ifndef HAVE_LRU_HASH_MAP_TYPE + .flags = CONDITIONAL_PREALLOC, +#endif +}; + +static __always_inline struct bpf_elf_map * +get_ct_map4(const struct ipv4_ct_tuple *tuple) +{ + if (tuple->nexthdr == IPPROTO_TCP) + return &CT_MAP_TCP4; + + return &CT_MAP_ANY4; +} +#endif +#endif +#endif /* __LIB_CONNTRACK_MAP_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/csum.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/csum.h new file mode 100644 index 000000000..d4cd1b688 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/csum.h @@ -0,0 +1,67 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_CSUM_H_ +#define __LIB_CSUM_H_ + +#include +#include +#include + +#define TCP_CSUM_OFF (offsetof(struct tcphdr, check)) +#define UDP_CSUM_OFF (offsetof(struct udphdr, check)) + +struct csum_offset { + __u16 offset; + __u16 flags; +}; + +/** + * Determins the L4 checksum field offset and required flags + * @arg nexthdr L3 nextheader field + * @arg off Pointer to uninitialied struct csum_offset struct + * + * Sets off.offset to offset from start of L4 header to L4 checksum field + * and off.flags to the required flags, namely BPF_F_MARK_MANGLED_0 for UDP. + * For unknown L4 protocols or L4 protocols which do not have a checksum + * field, off is initialied to 0. + */ +static __always_inline void csum_l4_offset_and_flags(__u8 nexthdr, + struct csum_offset *off) +{ + switch (nexthdr) { + case IPPROTO_TCP: + off->offset = TCP_CSUM_OFF; + break; + + case IPPROTO_UDP: + off->offset = UDP_CSUM_OFF; + off->flags = BPF_F_MARK_MANGLED_0; + break; + + case IPPROTO_ICMPV6: + off->offset = offsetof(struct icmp6hdr, icmp6_cksum); + break; + + case IPPROTO_ICMP: + break; + } +} + +/** + * Helper to change L4 checksum + * @arg ctx Packet + * @arg l4_off Offset to L4 header + * @arg csum Pointer to csum_offset as extracted by csum_l4_offset_and_flags() + * @arg from From value or 0 if to contains csum diff + * @arg to To value or a csum diff + * @arg flags Additional flags to be passed to l4_csum_replace() + */ +static __always_inline int csum_l4_replace(struct __ctx_buff *ctx, __u64 l4_off, + const struct csum_offset *csum, + __be32 from, __be32 to, int flags) +{ + return l4_csum_replace(ctx, l4_off + csum->offset, from, to, flags | csum->flags); +} + +#endif /* __LB_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/dbg.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/dbg.h new file mode 100644 index 000000000..eeb36bf3d --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/dbg.h @@ -0,0 +1,265 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_DBG__ +#define __LIB_DBG__ + +/* Trace types */ +enum { + DBG_UNSPEC, + DBG_GENERIC, /* Generic, no message, useful to dump random integers */ + DBG_LOCAL_DELIVERY, + DBG_ENCAP, + DBG_LXC_FOUND, + DBG_POLICY_DENIED, + DBG_CT_LOOKUP, /* unused */ + DBG_CT_LOOKUP_REV, /* unused */ + DBG_CT_MATCH, + DBG_CT_CREATED, /* unused */ + DBG_CT_CREATED2, /* unused */ + DBG_ICMP6_HANDLE, + DBG_ICMP6_REQUEST, + DBG_ICMP6_NS, + DBG_ICMP6_TIME_EXCEEDED, + DBG_CT_VERDICT, + DBG_DECAP, + DBG_PORT_MAP, + DBG_ERROR_RET, + DBG_TO_HOST, + DBG_TO_STACK, + DBG_PKT_HASH, + DBG_LB6_LOOKUP_FRONTEND, + DBG_LB6_LOOKUP_FRONTEND_FAIL, + DBG_LB6_LOOKUP_BACKEND_SLOT, + DBG_LB6_LOOKUP_BACKEND_SLOT_SUCCESS, + DBG_LB6_LOOKUP_BACKEND_SLOT_V2_FAIL, + DBG_LB6_LOOKUP_BACKEND_FAIL, + DBG_LB6_REVERSE_NAT_LOOKUP, + DBG_LB6_REVERSE_NAT, + DBG_LB4_LOOKUP_FRONTEND, + DBG_LB4_LOOKUP_FRONTEND_FAIL, + DBG_LB4_LOOKUP_BACKEND_SLOT, + DBG_LB4_LOOKUP_BACKEND_SLOT_SUCCESS, + DBG_LB4_LOOKUP_BACKEND_SLOT_V2_FAIL, + DBG_LB4_LOOKUP_BACKEND_FAIL, + DBG_LB4_REVERSE_NAT_LOOKUP, + DBG_LB4_REVERSE_NAT, + DBG_LB4_LOOPBACK_SNAT, + DBG_LB4_LOOPBACK_SNAT_REV, + DBG_CT_LOOKUP4, + DBG_RR_BACKEND_SLOT_SEL, + DBG_REV_PROXY_LOOKUP, + DBG_REV_PROXY_FOUND, + DBG_REV_PROXY_UPDATE, + DBG_L4_POLICY, + DBG_NETDEV_IN_CLUSTER, /* arg1: security-context, arg2: unused */ + DBG_NETDEV_ENCAP4, /* arg1 encap lookup key, arg2: identity */ + DBG_CT_LOOKUP4_1, /* arg1: saddr + * arg2: daddr + * arg3: (sport << 16) | dport + */ + DBG_CT_LOOKUP4_2, /* arg1: (nexthdr << 8) | flags + * arg2: direction + * arg3: unused + */ + DBG_CT_CREATED4, /* arg1: (unused << 16) | rev_nat_index + * arg2: src sec-id + * arg3: lb address + */ + DBG_CT_LOOKUP6_1, /* arg1: saddr (last 4 bytes) + * arg2: daddr (last 4 bytes) + * arg3: (sport << 16) | dport + */ + DBG_CT_LOOKUP6_2, /* arg1: (nexthdr << 8) | flags + * arg2: direction + * arg3: unused + */ + DBG_CT_CREATED6, /* arg1: (unused << 16) | rev_nat_index + * arg2: src sec-id + * arg3: unused + */ + DBG_SKIP_PROXY, /* arg1: ctx->tc_index + * arg2: unused + */ + DBG_L4_CREATE, /* arg1: src sec-id + * arg2: dst sec-id + * arg3: (dport << 16) | protocol + */ + DBG_IP_ID_MAP_FAILED4, /* arg1: daddr + * arg2: unused + * arg3: unused + */ + DBG_IP_ID_MAP_FAILED6, /* arg1: daddr (last 4 bytes) + * arg2: unused + * arg3: unused + */ + DBG_IP_ID_MAP_SUCCEED4, /* arg1: daddr + * arg2: identity + * arg3: unused + */ + DBG_IP_ID_MAP_SUCCEED6, /* arg1: daddr (last 4 bytes) + * arg2: identity + * arg3: unused + */ + DBG_LB_STALE_CT, /* arg1: svc rev_nat_id + * arg2: stale CT rev_nat_id + * arg3: unused + */ + DBG_INHERIT_IDENTITY, /* arg1: ctx->mark + * arg2: unused + */ + DBG_SK_LOOKUP4, /* arg1: saddr + * arg2: daddr + * arg3: (sport << 16) | dport + */ + DBG_SK_LOOKUP6, /* arg1: saddr (last 4 bytes) + * arg2: daddr (last 4 bytes) + * arg3: (sport << 16) | dport + */ + DBG_SK_ASSIGN, /* arg1: result + * arg2: unuseds + */ +}; + +/* Capture types */ +enum { + DBG_CAPTURE_UNSPEC, + DBG_CAPTURE_FROM_RESERVED1, + DBG_CAPTURE_FROM_RESERVED2, + DBG_CAPTURE_FROM_RESERVED3, + DBG_CAPTURE_DELIVERY, + DBG_CAPTURE_FROM_LB, + DBG_CAPTURE_AFTER_V46, + DBG_CAPTURE_AFTER_V64, + DBG_CAPTURE_PROXY_PRE, + DBG_CAPTURE_PROXY_POST, + DBG_CAPTURE_SNAT_PRE, + DBG_CAPTURE_SNAT_POST, +}; + +#ifndef EVENT_SOURCE +#define EVENT_SOURCE 0 +#endif + +#ifdef DEBUG +#include "events.h" +#endif + +#ifdef DEBUG +#include "common.h" +#include "utils.h" + +/* This takes both literals and modifiers, e.g., + * printk("hello\n"); + * printk("%d\n", ret); + * + * Three caveats when using this: + * - message needs to end with newline + * + * - only a subset of specifier are supported: + * https://elixir.bootlin.com/linux/v5.7.7/source/kernel/trace/bpf_trace.c#L325 + * + * - cannot use more than 3 format specifiers in the format string + * because BPF helpers take a maximum of 5 arguments + */ +# define printk(fmt, ...) \ + ({ \ + const char ____fmt[] = fmt; \ + trace_printk(____fmt, sizeof(____fmt), \ + ##__VA_ARGS__); \ + }) + +struct debug_msg { + NOTIFY_COMMON_HDR + __u32 arg1; + __u32 arg2; + __u32 arg3; +}; + +static __always_inline void cilium_dbg(struct __ctx_buff *ctx, __u8 type, + __u32 arg1, __u32 arg2) +{ + struct debug_msg msg = { + __notify_common_hdr(CILIUM_NOTIFY_DBG_MSG, type), + .arg1 = arg1, + .arg2 = arg2, + }; + + ctx_event_output(ctx, &EVENTS_MAP, BPF_F_CURRENT_CPU, + &msg, sizeof(msg)); +} + +static __always_inline void cilium_dbg3(struct __ctx_buff *ctx, __u8 type, + __u32 arg1, __u32 arg2, __u32 arg3) +{ + struct debug_msg msg = { + __notify_common_hdr(CILIUM_NOTIFY_DBG_MSG, type), + .arg1 = arg1, + .arg2 = arg2, + .arg3 = arg3, + }; + + ctx_event_output(ctx, &EVENTS_MAP, BPF_F_CURRENT_CPU, + &msg, sizeof(msg)); +} + +struct debug_capture_msg { + NOTIFY_CAPTURE_HDR + __u32 arg1; + __u32 arg2; +}; + +static __always_inline void cilium_dbg_capture2(struct __ctx_buff *ctx, __u8 type, + __u32 arg1, __u32 arg2) +{ + __u64 ctx_len = ctx_full_len(ctx); + __u64 cap_len = min_t(__u64, TRACE_PAYLOAD_LEN, ctx_len); + struct debug_capture_msg msg = { + __notify_common_hdr(CILIUM_NOTIFY_DBG_CAPTURE, type), + __notify_pktcap_hdr(ctx_len, cap_len), + .arg1 = arg1, + .arg2 = arg2, + }; + + ctx_event_output(ctx, &EVENTS_MAP, + (cap_len << 32) | BPF_F_CURRENT_CPU, + &msg, sizeof(msg)); +} + +static __always_inline void cilium_dbg_capture(struct __ctx_buff *ctx, __u8 type, + __u32 arg1) +{ + cilium_dbg_capture2(ctx, type, arg1, 0); +} +#else +# define printk(fmt, ...) \ + do { } while (0) + +static __always_inline +void cilium_dbg(struct __ctx_buff *ctx __maybe_unused, __u8 type __maybe_unused, + __u32 arg1 __maybe_unused, __u32 arg2 __maybe_unused) +{ +} + +static __always_inline +void cilium_dbg3(struct __ctx_buff *ctx __maybe_unused, + __u8 type __maybe_unused, __u32 arg1 __maybe_unused, + __u32 arg2 __maybe_unused, __u32 arg3 __maybe_unused) +{ +} + +static __always_inline +void cilium_dbg_capture(struct __ctx_buff *ctx __maybe_unused, + __u8 type __maybe_unused, __u32 arg1 __maybe_unused) +{ +} + +static __always_inline +void cilium_dbg_capture2(struct __ctx_buff *ctx __maybe_unused, + __u8 type __maybe_unused, __u32 arg1 __maybe_unused, + __u32 arg2 __maybe_unused) +{ +} + +#endif +#endif /* __LIB_DBG__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/drop.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/drop.h new file mode 100644 index 000000000..95aaafa93 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/drop.h @@ -0,0 +1,105 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +/* + * Drop & error notification via perf event ring buffer + * + * API: + * int send_drop_notify(ctx, src, dst, dst_id, reason, exitcode, __u8 direction) + * int send_drop_notify_error(ctx, error, exitcode, __u8 direction) + * + * If DROP_NOTIFY is not defined, the API will be compiled in as a NOP. + */ + +#ifndef __LIB_DROP__ +#define __LIB_DROP__ + +#include "dbg.h" +#include "events.h" +#include "common.h" +#include "utils.h" +#include "metrics.h" + +#ifdef DROP_NOTIFY +struct drop_notify { + NOTIFY_CAPTURE_HDR + __u32 src_label; + __u32 dst_label; + __u32 dst_id; + __u32 unused; +}; + +__section_tail(CILIUM_MAP_CALLS, CILIUM_CALL_DROP_NOTIFY) +int __send_drop_notify(struct __ctx_buff *ctx) +{ + /* Mask needed to calm verifier. */ + int error = ctx_load_meta(ctx, 2) & 0xFFFFFFFF; + __u64 ctx_len = ctx_full_len(ctx); + __u64 cap_len = min_t(__u64, TRACE_PAYLOAD_LEN, ctx_len); + struct drop_notify msg; + + if (error < 0) + error = -error; + + msg = (typeof(msg)) { + __notify_common_hdr(CILIUM_NOTIFY_DROP, error), + __notify_pktcap_hdr(ctx_len, cap_len), + .src_label = ctx_load_meta(ctx, 0), + .dst_label = ctx_load_meta(ctx, 1), + .dst_id = ctx_load_meta(ctx, 3), + }; + + ctx_event_output(ctx, &EVENTS_MAP, + (cap_len << 32) | BPF_F_CURRENT_CPU, + &msg, sizeof(msg)); + + return ctx_load_meta(ctx, 4); +} + +/** + * send_drop_notify + * @ctx: socket buffer + * @src: source identity + * @dst: destination identity + * @dst_id: designated destination endpoint ID + * @reason: Reason for drop + * @exitcode: error code to return to the kernel + * + * Generate a notification to indicate a packet was dropped. + * + * NOTE: This is terminal function and will cause the BPF program to exit + */ +static __always_inline int send_drop_notify(struct __ctx_buff *ctx, __u32 src, + __u32 dst, __u32 dst_id, int reason, + int exitcode, __u8 direction) +{ + ctx_store_meta(ctx, 0, src); + ctx_store_meta(ctx, 1, dst); + ctx_store_meta(ctx, 2, reason); + ctx_store_meta(ctx, 3, dst_id); + ctx_store_meta(ctx, 4, exitcode); + + update_metrics(ctx_full_len(ctx), direction, -reason); + ep_tail_call(ctx, CILIUM_CALL_DROP_NOTIFY); + + return exitcode; +} +#else +static __always_inline +int send_drop_notify(struct __ctx_buff *ctx, __u32 src __maybe_unused, + __u32 dst __maybe_unused, __u32 dst_id __maybe_unused, + int reason, int exitcode, __u8 direction) +{ + update_metrics(ctx_full_len(ctx), direction, -reason); + return exitcode; +} +#endif /* DROP_NOTIFY */ + +static __always_inline int send_drop_notify_error(struct __ctx_buff *ctx, __u32 src, + int error, int exitcode, + __u8 direction) +{ + return send_drop_notify(ctx, src, 0, 0, error, exitcode, direction); +} + +#endif /* __LIB_DROP__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/edt.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/edt.h new file mode 100644 index 000000000..453200007 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/edt.h @@ -0,0 +1,85 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __EDT_H_ +#define __EDT_H_ + +#include + +#include "common.h" +#include "time.h" +#include "maps.h" + +/* From XDP layer, we neither go through an egress hook nor qdisc + * from here, hence nothing to be set. + */ +#if defined(ENABLE_BANDWIDTH_MANAGER) && __ctx_is == __ctx_skb +static __always_inline void edt_set_aggregate(struct __ctx_buff *ctx, + __u32 aggregate) +{ + /* 16 bit as current used aggregate, and preserved in host ns. */ + ctx->queue_mapping = aggregate; +} + +static __always_inline __u32 edt_get_aggregate(struct __ctx_buff *ctx) +{ + __u32 aggregate = ctx->queue_mapping; + + /* We need to reset queue mapping here such that new mapping will + * be performed based on skb hash. See netdev_pick_tx(). + */ + ctx->queue_mapping = 0; + + return aggregate; +} + +static __always_inline int edt_sched_departure(struct __ctx_buff *ctx) +{ + __u64 delay, now, t, t_next; + struct edt_id aggregate; + struct edt_info *info; + __u16 proto; + + if (!validate_ethertype(ctx, &proto)) + return CTX_ACT_OK; + if (proto != bpf_htons(ETH_P_IP) && + proto != bpf_htons(ETH_P_IPV6)) + return CTX_ACT_OK; + + aggregate.id = edt_get_aggregate(ctx); + if (!aggregate.id) + return CTX_ACT_OK; + + info = map_lookup_elem(&THROTTLE_MAP, &aggregate); + if (!info) + return CTX_ACT_OK; + + now = ktime_get_ns(); + t = ctx->tstamp; + if (t < now) + t = now; + delay = ((__u64)ctx_wire_len(ctx)) * NSEC_PER_SEC / info->bps; + t_next = READ_ONCE(info->t_last) + delay; + if (t_next <= t) { + WRITE_ONCE(info->t_last, t); + return CTX_ACT_OK; + } + /* FQ implements a drop horizon, see also 39d010504e6b ("net_sched: + * sch_fq: add horizon attribute"). However, we explicitly need the + * drop horizon here to i) avoid having t_last messed up and ii) to + * potentially allow for per aggregate control. + */ + if (t_next - now >= info->t_horizon_drop) + return CTX_ACT_DROP; + WRITE_ONCE(info->t_last, t_next); + ctx->tstamp = t_next; + return CTX_ACT_OK; +} +#else +static __always_inline void +edt_set_aggregate(struct __ctx_buff *ctx __maybe_unused, + __u32 aggregate __maybe_unused) +{ +} +#endif /* ENABLE_BANDWIDTH_MANAGER */ +#endif /* __EDT_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/encap.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/encap.h new file mode 100644 index 000000000..dfd87bd82 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/encap.h @@ -0,0 +1,248 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_ENCAP_H_ +#define __LIB_ENCAP_H_ + +#include "common.h" +#include "dbg.h" +#include "trace.h" +#include "l3.h" + +#ifdef ENCAP_IFINDEX +#ifdef ENABLE_IPSEC +static __always_inline int +encap_and_redirect_nomark_ipsec(struct __ctx_buff *ctx, __u32 tunnel_endpoint, + __u8 key, __u32 seclabel) +{ + /* Traffic from local host in tunnel mode will be passed to + * cilium_host. In non-IPSec case traffic with non-local dst + * will then be redirected to tunnel device. In IPSec case + * though we need to traverse xfrm path still. The mark + + * cb[4] hints will not survive a veth pair xmit to ingress + * however so below encap_and_redirect_ipsec will not work. + * Instead pass hints via cb[0], cb[4] (cb is not cleared + * by dev_ctx_forward) and catch hints with bpf_host + * prog that will populate mark/cb as expected by xfrm and 2nd + * traversal into bpf_host. Remember we can't use cb[0-3] + * in both cases because xfrm layer would overwrite them. We + * use cb[4] here so it doesn't need to be reset by + * bpf_host. + */ + ctx_store_meta(ctx, CB_ENCRYPT_MAGIC, or_encrypt_key(key)); + ctx_store_meta(ctx, CB_ENCRYPT_IDENTITY, seclabel); + ctx_store_meta(ctx, CB_ENCRYPT_DST, tunnel_endpoint); + return IPSEC_ENDPOINT; +} + +static __always_inline int +encap_and_redirect_ipsec(struct __ctx_buff *ctx, __u32 tunnel_endpoint, + __u8 key, __u32 seclabel) +{ + /* IPSec is performed by the stack on any packets with the + * MARK_MAGIC_ENCRYPT bit set. During the process though we + * lose the lxc context (seclabel and tunnel endpoint). The + * tunnel endpoint can be looked up from daddr but the sec + * label is stashed in the mark and extracted in bpf_host + * to send ctx onto tunnel for encap. + */ + set_encrypt_key_mark(ctx, key); + set_identity_mark(ctx, seclabel); + ctx_store_meta(ctx, CB_ENCRYPT_DST, tunnel_endpoint); + return IPSEC_ENDPOINT; +} +#endif /* ENABLE_IPSEC */ + +static __always_inline int +encap_remap_v6_host_address(struct __ctx_buff *ctx __maybe_unused, + const bool egress __maybe_unused) +{ +#ifdef ENABLE_ENCAP_HOST_REMAP + struct csum_offset csum = {}; + union v6addr host_ip; + void *data, *data_end; + struct ipv6hdr *ip6; + union v6addr *which; + __u8 nexthdr; + __u16 proto; + __be32 sum; + __u32 noff; + __u64 off; + int ret; + + validate_ethertype(ctx, &proto); + if (proto != bpf_htons(ETH_P_IPV6)) + return 0; + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return DROP_INVALID; + /* For requests routed via tunnel with external v6 node IP + * we need to remap their source address to the router address + * as otherwise replies are not routed via tunnel but public + * address instead. + */ + if (egress) { + BPF_V6(host_ip, HOST_IP); + which = (union v6addr *)&ip6->saddr; + } else { + BPF_V6(host_ip, ROUTER_IP); + which = (union v6addr *)&ip6->daddr; + } + if (ipv6_addrcmp(which, &host_ip)) + return 0; + nexthdr = ip6->nexthdr; + ret = ipv6_hdrlen(ctx, ETH_HLEN, &nexthdr); + if (ret < 0) + return ret; + off = ((void *)ip6 - data) + ret; + if (egress) { + BPF_V6(host_ip, ROUTER_IP); + noff = ETH_HLEN + offsetof(struct ipv6hdr, saddr); + } else { + BPF_V6(host_ip, HOST_IP); + noff = ETH_HLEN + offsetof(struct ipv6hdr, daddr); + } + sum = csum_diff(which, 16, &host_ip, 16, 0); + csum_l4_offset_and_flags(nexthdr, &csum); + if (ctx_store_bytes(ctx, noff, &host_ip, 16, 0) < 0) + return DROP_WRITE_ERROR; + if (csum.offset && + csum_l4_replace(ctx, off, &csum, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; +#endif /* ENABLE_ENCAP_HOST_REMAP */ + return 0; +} + +static __always_inline int +__encap_with_nodeid(struct __ctx_buff *ctx, __u32 tunnel_endpoint, + __u32 seclabel, __u32 monitor) +{ + struct bpf_tunnel_key key = {}; + __u32 node_id; + int ret; + + /* When encapsulating, a packet originating from the local host is + * being considered as a packet from a remote node as it is being + * received. + */ + if (seclabel == HOST_ID) + seclabel = LOCAL_NODE_ID; + + node_id = bpf_htonl(tunnel_endpoint); + key.tunnel_id = seclabel; + key.remote_ipv4 = node_id; + key.tunnel_ttl = 64; + + cilium_dbg(ctx, DBG_ENCAP, node_id, seclabel); + + ret = ctx_set_tunnel_key(ctx, &key, sizeof(key), BPF_F_ZERO_CSUM_TX); + if (unlikely(ret < 0)) + return DROP_WRITE_ERROR; + + send_trace_notify(ctx, TRACE_TO_OVERLAY, seclabel, 0, 0, ENCAP_IFINDEX, + 0, monitor); + return 0; +} + +static __always_inline int +__encap_and_redirect_with_nodeid(struct __ctx_buff *ctx, __u32 tunnel_endpoint, + __u32 seclabel, __u32 monitor) +{ + int ret = __encap_with_nodeid(ctx, tunnel_endpoint, seclabel, monitor); + if (ret != 0) + return ret; + + return redirect(ENCAP_IFINDEX, 0); +} + +/* encap_and_redirect_with_nodeid returns IPSEC_ENDPOINT after ctx meta-data is + * set when IPSec is enabled. Caller should pass the ctx to the stack at this + * point. Otherwise returns CTX_ACT_TX on successful redirect to tunnel device. + * On error returns CTX_ACT_DROP, DROP_NO_TUNNEL_ENDPOINT or DROP_WRITE_ERROR. + */ +static __always_inline int +encap_and_redirect_with_nodeid(struct __ctx_buff *ctx, __u32 tunnel_endpoint, + __u8 key __maybe_unused, __u32 seclabel, + __u32 monitor) +{ +#ifdef ENABLE_IPSEC + if (key) + return encap_and_redirect_nomark_ipsec(ctx, tunnel_endpoint, key, seclabel); +#endif + return __encap_and_redirect_with_nodeid(ctx, tunnel_endpoint, seclabel, monitor); +} + +/* encap_and_redirect based on ENABLE_IPSEC flag and from_host bool will decide + * which version of code to call. With IPSec enabled and from_host set use the + * IPSec branch which configures metadata for IPSec kernel stack. Otherwise + * packet is redirected to output tunnel device and ctx will not be seen by + * IP stack. + * + * Returns IPSEC_ENDPOINT when ctx needs to be handed to IP stack for IPSec + * handling, CTX_ACT_DROP, DROP_NO_TUNNEL_ENDPOINT or DROP_WRITE_ERROR on error, + * and finally on successful redirect returns CTX_ACT_TX. + */ +static __always_inline int +encap_and_redirect_lxc(struct __ctx_buff *ctx, __u32 tunnel_endpoint, + __u8 encrypt_key __maybe_unused, + struct endpoint_key *key, __u32 seclabel, __u32 monitor) +{ + struct endpoint_key *tunnel; + + if (tunnel_endpoint) { +#ifdef ENABLE_IPSEC + if (encrypt_key) + return encap_and_redirect_ipsec(ctx, tunnel_endpoint, + encrypt_key, seclabel); +#endif +#if !defined(ENABLE_NODEPORT) && (defined(ENABLE_IPSEC) || defined(ENABLE_HOST_FIREWALL)) + /* For IPSec and the host firewall, traffic from a pod to a remote node + * is sent through the tunnel. In the case of node --> VIP@remote pod, + * packets may be DNATed when they enter the remote node. If kube-proxy + * is used, the response needs to go through the stack on the way to + * the tunnel, to apply the correct reverse DNAT. + * See #14674 for details. + */ + return __encap_with_nodeid(ctx, tunnel_endpoint, seclabel, monitor); +#else + return __encap_and_redirect_with_nodeid(ctx, tunnel_endpoint, seclabel, monitor); +#endif /* !ENABLE_NODEPORT && (ENABLE_IPSEC || ENABLE_HOST_FIREWALL) */ + } + + tunnel = map_lookup_elem(&TUNNEL_MAP, key); + if (!tunnel) + return DROP_NO_TUNNEL_ENDPOINT; + +#ifdef ENABLE_IPSEC + if (tunnel->key) { + __u8 min_encrypt_key = get_min_encrypt_key(tunnel->key); + + return encap_and_redirect_ipsec(ctx, tunnel->ip4, + min_encrypt_key, + seclabel); + } +#endif + return __encap_and_redirect_with_nodeid(ctx, tunnel->ip4, seclabel, monitor); +} + +static __always_inline int +encap_and_redirect_netdev(struct __ctx_buff *ctx, struct endpoint_key *k, + __u32 seclabel, __u32 monitor) +{ + struct endpoint_key *tunnel; + + tunnel = map_lookup_elem(&TUNNEL_MAP, k); + if (!tunnel) + return DROP_NO_TUNNEL_ENDPOINT; + +#ifdef ENABLE_IPSEC + if (tunnel->key) { + __u8 key = get_min_encrypt_key(tunnel->key); + + return encap_and_redirect_nomark_ipsec(ctx, tunnel->ip4, + key, seclabel); + } +#endif + return __encap_and_redirect_with_nodeid(ctx, tunnel->ip4, seclabel, monitor); +} +#endif /* ENCAP_IFINDEX */ +#endif /* __LIB_ENCAP_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/encrypt.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/encrypt.h new file mode 100644 index 000000000..63acd8aac --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/encrypt.h @@ -0,0 +1,84 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __LIB_ENCRYPT_H_ +#define __LIB_ENCRYPT_H_ + +#include +#include +#include +#include + +#include "lib/common.h" + +#ifdef ENABLE_IPSEC +static __always_inline int +do_decrypt(struct __ctx_buff *ctx, __u16 proto) +{ + void *data, *data_end; + __u8 protocol = 0; + bool decrypted; +#ifdef ENABLE_IPV6 + struct ipv6hdr *ip6; +#endif +#ifdef ENABLE_IPV4 + struct iphdr *ip4; +#endif + + decrypted = ((ctx->mark & MARK_MAGIC_HOST_MASK) == MARK_MAGIC_DECRYPT); + + switch (proto) { +#ifdef ENABLE_IPV6 + case bpf_htons(ETH_P_IPV6): + if (!revalidate_data_pull(ctx, &data, &data_end, &ip6)) { + ctx->mark = 0; + return CTX_ACT_OK; + } + protocol = ip6->nexthdr; + break; +#endif +#ifdef ENABLE_IPV4 + case bpf_htons(ETH_P_IP): + if (!revalidate_data_pull(ctx, &data, &data_end, &ip4)) { + ctx->mark = 0; + return CTX_ACT_OK; + } + protocol = ip4->protocol; + break; +#endif + default: + return CTX_ACT_OK; + } + + if (!decrypted) { + /* Allow all non-ESP packets up the stack per normal case + * without encryption enabled. + */ + if (protocol != IPPROTO_ESP) + return CTX_ACT_OK; + /* Decrypt "key" is determined by SPI */ + ctx->mark = MARK_MAGIC_DECRYPT; + /* We are going to pass this up the stack for IPsec decryption + * but eth_type_trans may already have labeled this as an + * OTHERHOST type packet. To avoid being dropped by IP stack + * before IPSec can be processed mark as a HOST packet. + */ + ctx_change_type(ctx, PACKET_HOST); + return CTX_ACT_OK; + } + ctx->mark = 0; +#ifdef ENABLE_ENDPOINT_ROUTES + return CTX_ACT_OK; +#else + return redirect(CILIUM_IFINDEX, 0); +#endif /* ENABLE_ROUTING */ +} +#else +static __always_inline int +do_decrypt(struct __ctx_buff __maybe_unused *ctx, __u16 __maybe_unused proto) +{ + return CTX_ACT_OK; +} +#endif /* ENABLE_IPSEC */ +#endif /* __LIB_ENCRYPT_H_ */ + diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/endian.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/endian.h new file mode 100644 index 000000000..4752ff9fe --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/endian.h @@ -0,0 +1,40 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_ENDIAN_H_ +#define __LIB_ENDIAN_H_ + +#include +#include + +#if defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +# define __bpf_ntohs(x) __builtin_bswap16(x) +# define __bpf_htons(x) __builtin_bswap16(x) +# define __bpf_ntohl(x) __builtin_bswap32(x) +# define __bpf_htonl(x) __builtin_bswap32(x) +#elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && \ + __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ +# define __bpf_ntohs(x) (x) +# define __bpf_htons(x) (x) +# define __bpf_ntohl(x) (x) +# define __bpf_htonl(x) (x) +#else +# error "Endianness detection needs to be set up for your compiler?!" +#endif + +#define bpf_htons(x) \ + (__builtin_constant_p(x) ? \ + __constant_htons(x) : __bpf_htons(x)) +#define bpf_ntohs(x) \ + (__builtin_constant_p(x) ? \ + __constant_ntohs(x) : __bpf_ntohs(x)) + +#define bpf_htonl(x) \ + (__builtin_constant_p(x) ? \ + __constant_htonl(x) : __bpf_htonl(x)) +#define bpf_ntohl(x) \ + (__builtin_constant_p(x) ? \ + __constant_ntohl(x) : __bpf_ntohl(x)) + +#endif /* __LIB_ENDIAN_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/eps.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/eps.h new file mode 100644 index 000000000..06aa158a0 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/eps.h @@ -0,0 +1,157 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2017-2020 Authors of Cilium */ + +#ifndef __LIB_EPS_H_ +#define __LIB_EPS_H_ + +#include +#include + +#include "maps.h" + +static __always_inline __maybe_unused struct endpoint_info * +__lookup_ip6_endpoint(const union v6addr *ip6) +{ + struct endpoint_key key = {}; + + key.ip6 = *ip6; + key.family = ENDPOINT_KEY_IPV6; + + return map_lookup_elem(&ENDPOINTS_MAP, &key); +} + +static __always_inline __maybe_unused struct endpoint_info * +lookup_ip6_endpoint(struct ipv6hdr *ip6) +{ + return __lookup_ip6_endpoint((union v6addr *)&ip6->daddr); +} + +static __always_inline __maybe_unused struct endpoint_info * +__lookup_ip4_endpoint(__u32 ip) +{ + struct endpoint_key key = {}; + + key.ip4 = ip; + key.family = ENDPOINT_KEY_IPV4; + + return map_lookup_elem(&ENDPOINTS_MAP, &key); +} + +static __always_inline __maybe_unused struct endpoint_info * +lookup_ip4_endpoint(const struct iphdr *ip4) +{ + return __lookup_ip4_endpoint(ip4->daddr); +} + +#ifdef SOCKMAP +static __always_inline void * +lookup_ip4_endpoint_policy_map(__u32 ip) +{ + struct endpoint_key key = {}; + + key.ip4 = ip; + key.family = ENDPOINT_KEY_IPV4; + + return map_lookup_elem(&EP_POLICY_MAP, &key); +} +#endif + +/* IPCACHE_STATIC_PREFIX gets sizeof non-IP, non-prefix part of ipcache_key */ +#define IPCACHE_STATIC_PREFIX \ + (8 * (sizeof(struct ipcache_key) - sizeof(struct bpf_lpm_trie_key) \ + - sizeof(union v6addr))) +#define IPCACHE_PREFIX_LEN(PREFIX) (IPCACHE_STATIC_PREFIX + (PREFIX)) + +/* EGRESS_STATIC_PREFIX gets sizeof non-IP, non-prefix part of ipcache_key */ +#define EGRESS_STATIC_PREFIX \ + (8 * (sizeof(struct egress_key) - sizeof(struct bpf_lpm_trie_key) \ + - 4)) +#define EGRESS_PREFIX_LEN(PREFIX) (EGRESS_STATIC_PREFIX + (PREFIX)) +#define EGRESS_IPV4_PREFIX EGRESS_PREFIX_LEN(32) + +#define V6_CACHE_KEY_LEN (sizeof(union v6addr)*8) + +static __always_inline __maybe_unused struct remote_endpoint_info * +ipcache_lookup6(struct bpf_elf_map *map, const union v6addr *addr, + __u32 prefix) +{ + struct ipcache_key key = { + .lpm_key = { IPCACHE_PREFIX_LEN(prefix), {} }, + .family = ENDPOINT_KEY_IPV6, + .ip6 = *addr, + }; + ipv6_addr_clear_suffix(&key.ip6, prefix); + return map_lookup_elem(map, &key); +} + +#define V4_CACHE_KEY_LEN (sizeof(__u32)*8) + +static __always_inline __maybe_unused struct remote_endpoint_info * +ipcache_lookup4(struct bpf_elf_map *map, __be32 addr, __u32 prefix) +{ + struct ipcache_key key = { + .lpm_key = { IPCACHE_PREFIX_LEN(prefix), {} }, + .family = ENDPOINT_KEY_IPV4, + .ip4 = addr, + }; + key.ip4 &= GET_PREFIX(prefix); + return map_lookup_elem(map, &key); +} + +#ifndef HAVE_LPM_TRIE_MAP_TYPE +/* Define a function with the following NAME which iterates through PREFIXES + * (a list of integers ordered from high to low representing prefix length), + * performing a lookup in MAP using LOOKUP_FN to find a provided IP of type + * IPTYPE. + */ +#define LPM_LOOKUP_FN(NAME, IPTYPE, PREFIXES, MAP, LOOKUP_FN) \ +static __always_inline __maybe_unused struct remote_endpoint_info * \ +NAME(IPTYPE addr) \ +{ \ + int prefixes[] = { PREFIXES }; \ + const int size = ARRAY_SIZE(prefixes); \ + struct remote_endpoint_info *info; \ + int i; \ + \ +_Pragma("unroll") \ + for (i = 0; i < size; i++) { \ + info = LOOKUP_FN(&MAP, addr, prefixes[i]); \ + if (info != NULL) \ + return info; \ + } \ + \ + return NULL; \ +} +#ifdef IPCACHE6_PREFIXES +LPM_LOOKUP_FN(lookup_ip6_remote_endpoint, union v6addr *, IPCACHE6_PREFIXES, + IPCACHE_MAP, ipcache_lookup6) +#endif +#ifdef IPCACHE4_PREFIXES +LPM_LOOKUP_FN(lookup_ip4_remote_endpoint, __be32, IPCACHE4_PREFIXES, + IPCACHE_MAP, ipcache_lookup4) +#endif +#undef LPM_LOOKUP_FN +#else /* HAVE_LPM_TRIE_MAP_TYPE */ +#define lookup_ip6_remote_endpoint(addr) \ + ipcache_lookup6(&IPCACHE_MAP, addr, V6_CACHE_KEY_LEN) +#define lookup_ip4_remote_endpoint(addr) \ + ipcache_lookup4(&IPCACHE_MAP, addr, V4_CACHE_KEY_LEN) +#endif /* HAVE_LPM_TRIE_MAP_TYPE */ + +#ifdef ENABLE_EGRESS_GATEWAY +static __always_inline __maybe_unused struct egress_info * +egress_lookup4(struct bpf_elf_map *map, __be32 sip, __be32 dip) +{ + struct egress_key key = { + .lpm_key = { EGRESS_IPV4_PREFIX, {} }, + .sip = sip, + .dip = dip, + }; + return map_lookup_elem(map, &key); +} + +#define lookup_ip4_egress_endpoint(sip, dip) \ + egress_lookup4(&EGRESS_MAP, sip, dip) +#endif /* ENABLE_EGRESS_GATEWAY */ + +#endif /* __LIB_EPS_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/eth.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/eth.h new file mode 100644 index 000000000..ec02ff5d3 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/eth.h @@ -0,0 +1,119 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_ETH__ +#define __LIB_ETH__ + +#include + +#ifndef ETH_HLEN +#define ETH_HLEN __ETH_HLEN +#endif + +#ifndef ETH_ALEN +#define ETH_ALEN 6 +#endif + +union macaddr { + struct { + __u32 p1; + __u16 p2; + }; + __u8 addr[6]; +}; + +static __always_inline int eth_addrcmp(const union macaddr *a, + const union macaddr *b) +{ + int tmp; + + tmp = a->p1 - b->p1; + if (!tmp) + tmp = a->p2 - b->p2; + + return tmp; +} + +static __always_inline int eth_is_bcast(const union macaddr *a) +{ + union macaddr bcast; + + bcast.p1 = 0xffffffff; + bcast.p2 = 0xffff; + + if (!eth_addrcmp(a, &bcast)) + return 1; + else + return 0; +} + +static __always_inline int eth_load_saddr(struct __ctx_buff *ctx, __u8 *mac, + int off) +{ + return ctx_load_bytes(ctx, off + ETH_ALEN, mac, ETH_ALEN); +} + +static __always_inline int eth_store_saddr_aligned(struct __ctx_buff *ctx, + const __u8 *mac, int off) +{ + return ctx_store_bytes(ctx, off + ETH_ALEN, mac, ETH_ALEN, 0); +} + +static __always_inline int eth_store_saddr(struct __ctx_buff *ctx, + const __u8 *mac, int off) +{ +#if !CTX_DIRECT_WRITE_OK + return eth_store_saddr_aligned(ctx, mac, off); +#else + void *data_end = ctx_data_end(ctx); + void *data = ctx_data(ctx); + + if (ctx_no_room(data + off + ETH_ALEN * 2, data_end)) + return -EFAULT; + /* Need to use builtin here since mac came potentially from + * struct bpf_fib_lookup where it's not aligned on stack. :( + */ + __bpf_memcpy_builtin(data + off + ETH_ALEN, mac, ETH_ALEN); + return 0; +#endif +} + +static __always_inline int eth_load_daddr(struct __ctx_buff *ctx, __u8 *mac, + int off) +{ + return ctx_load_bytes(ctx, off, mac, ETH_ALEN); +} + +static __always_inline int eth_store_daddr_aligned(struct __ctx_buff *ctx, + const __u8 *mac, int off) +{ + return ctx_store_bytes(ctx, off, mac, ETH_ALEN, 0); +} + +static __always_inline int eth_store_daddr(struct __ctx_buff *ctx, + const __u8 *mac, int off) +{ +#if !CTX_DIRECT_WRITE_OK + return eth_store_daddr_aligned(ctx, mac, off); +#else + void *data_end = ctx_data_end(ctx); + void *data = ctx_data(ctx); + + if (ctx_no_room(data + off + ETH_ALEN, data_end)) + return -EFAULT; + /* Need to use builtin here since mac came potentially from + * struct bpf_fib_lookup where it's not aligned on stack. :( + */ + __bpf_memcpy_builtin(data + off, mac, ETH_ALEN); + return 0; +#endif +} + +static __always_inline int eth_store_proto(struct __ctx_buff *ctx, + const __u16 proto, int off) +{ + return ctx_store_bytes(ctx, off + ETH_ALEN + ETH_ALEN, + &proto, sizeof(proto), 0); +} + +#endif /* __LIB_ETH__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/events.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/events.h new file mode 100644 index 000000000..48142b90c --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/events.h @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_EVENTS_H_ +#define __LIB_EVENTS_H_ + +#include + +struct bpf_elf_map __section_maps EVENTS_MAP = { + .type = BPF_MAP_TYPE_PERF_EVENT_ARRAY, + .size_key = sizeof(__u32), + .size_value = sizeof(__u32), + .pinning = PIN_GLOBAL_NS, + .max_elem = __NR_CPUS__, +}; + +#endif /* __LIB_EVENTS_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/fib.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/fib.h new file mode 100644 index 000000000..04ab4af61 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/fib.h @@ -0,0 +1,129 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __LIB_FIB_H_ +#define __LIB_FIB_H_ + +#include +#include + +#include "common.h" +#include "l3.h" + +#ifdef ENABLE_IPV6 +static __always_inline int +redirect_direct_v6(struct __ctx_buff *ctx __maybe_unused, + int l3_off __maybe_unused, + struct ipv6hdr *ip6 __maybe_unused) +{ + bool no_neigh = is_defined(ENABLE_SKIP_FIB); + int ret, oif = DIRECT_ROUTING_DEV_IFINDEX; + struct bpf_redir_neigh *nh = NULL; +# ifndef ENABLE_SKIP_FIB + struct bpf_redir_neigh nh_params; + struct bpf_fib_lookup fib_params = { + .family = AF_INET6, + .ifindex = ctx->ingress_ifindex, + }; + + ipv6_addr_copy((union v6addr *)&fib_params.ipv6_src, + (union v6addr *)&ip6->saddr); + ipv6_addr_copy((union v6addr *)&fib_params.ipv6_dst, + (union v6addr *)&ip6->daddr); + + ret = fib_lookup(ctx, &fib_params, sizeof(fib_params), + BPF_FIB_LOOKUP_DIRECT); + switch (ret) { + case BPF_FIB_LKUP_RET_SUCCESS: + break; + case BPF_FIB_LKUP_RET_NO_NEIGH: + nh_params.nh_family = fib_params.family; + __bpf_memcpy_builtin(&nh_params.ipv6_nh, &fib_params.ipv6_dst, + sizeof(nh_params.ipv6_nh)); + no_neigh = true; + nh = &nh_params; + break; + default: + return CTX_ACT_DROP; + } + + oif = fib_params.ifindex; +# endif /* ENABLE_SKIP_FIB */ + + ret = ipv6_l3(ctx, l3_off, NULL, NULL, METRIC_EGRESS); + if (unlikely(ret != CTX_ACT_OK)) + return ret; + if (no_neigh) + return redirect_neigh(oif, nh, nh ? sizeof(*nh) : 0, 0); +# ifndef ENABLE_SKIP_FIB + if (eth_store_daddr(ctx, fib_params.dmac, 0) < 0) + return CTX_ACT_DROP; + if (eth_store_saddr(ctx, fib_params.smac, 0) < 0) + return CTX_ACT_DROP; + return redirect(oif, 0); +# endif /* ENABLE_SKIP_FIB */ + return CTX_ACT_DROP; +} +#endif /* ENABLE_IPV6 */ + +#ifdef ENABLE_IPV4 +static __always_inline int +redirect_direct_v4(struct __ctx_buff *ctx __maybe_unused, + int l3_off __maybe_unused, + struct iphdr *ip4 __maybe_unused) +{ + /* For deployments with just single external dev, redirect_neigh() + * will resolve the GW and do L2 resolution for us. For multi-device + * deployments we perform a FIB lookup prior to the redirect. If the + * neigh entry cannot be resolved, we ask redirect_neigh() to do it, + * otherwise we can directly call redirect(). + */ + bool no_neigh = is_defined(ENABLE_SKIP_FIB); + int ret, oif = DIRECT_ROUTING_DEV_IFINDEX; + struct bpf_redir_neigh *nh = NULL; +# ifndef ENABLE_SKIP_FIB + struct bpf_redir_neigh nh_params; + struct bpf_fib_lookup fib_params = { + .family = AF_INET, + .ifindex = ctx->ingress_ifindex, + .ipv4_src = ip4->saddr, + .ipv4_dst = ip4->daddr, + }; + + ret = fib_lookup(ctx, &fib_params, sizeof(fib_params), + BPF_FIB_LOOKUP_DIRECT); + switch (ret) { + case BPF_FIB_LKUP_RET_SUCCESS: + break; + case BPF_FIB_LKUP_RET_NO_NEIGH: + /* GW could also be v6, so copy union. */ + nh_params.nh_family = fib_params.family; + __bpf_memcpy_builtin(&nh_params.ipv6_nh, &fib_params.ipv6_dst, + sizeof(nh_params.ipv6_nh)); + no_neigh = true; + nh = &nh_params; + break; + default: + return CTX_ACT_DROP; + } + + oif = fib_params.ifindex; +# endif /* ENABLE_SKIP_FIB */ + + ret = ipv4_l3(ctx, l3_off, NULL, NULL, ip4); + if (unlikely(ret != CTX_ACT_OK)) + return ret; + if (no_neigh) + return redirect_neigh(oif, nh, nh ? sizeof(*nh) : 0, 0); +# ifndef ENABLE_SKIP_FIB + if (eth_store_daddr(ctx, fib_params.dmac, 0) < 0) + return CTX_ACT_DROP; + if (eth_store_saddr(ctx, fib_params.smac, 0) < 0) + return CTX_ACT_DROP; + return redirect(oif, 0); +# endif /* ENABLE_SKIP_FIB */ + return CTX_ACT_DROP; +} +#endif /* ENABLE_IPV4 */ + +#endif /* __LIB_FIB_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/ghash.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/ghash.h new file mode 100644 index 000000000..cedf2bb4b --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/ghash.h @@ -0,0 +1,42 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2002-2020 Authors of the Linux kernel */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __GHASH_H_ +#define __GHASH_H_ + +#include +#include + +/* + * This hash multiplies the input by a large odd number and takes the + * high bits. Since multiplication propagates changes to the most + * significant end only, it is essential that the high bits of the + * product be used for the hash value. + * + * Chuck Lever verified the effectiveness of this technique: + * http://www.citi.umich.edu/techreports/reports/citi-tr-00-1.pdf + * + * Although a random odd number will do, it turns out that the golden + * ratio phi = (sqrt(5)-1)/2, or its negative, has particularly nice + * properties. (See Knuth vol 3, section 6.4, exercise 9.) + * + * These are the negative, (1 - phi) = phi**2 = (3 - sqrt(5))/2, + * which is very slightly easier to multiply by and makes no + * difference to the hash distribution. + */ +#define GOLDEN_RATIO_32 0x61C88647 +#define GOLDEN_RATIO_64 0x61C8864680B583EBull + +static __always_inline __u32 hash_32(__u32 val, __u32 bits) +{ + /* High bits are more random, so use them. */ + return (val * GOLDEN_RATIO_32) >> (32 - bits); +} + +static __always_inline __u32 hash_64(__u64 val, __u32 bits) +{ + return (val * GOLDEN_RATIO_64) >> (64 - bits); +} + +#endif /* __GHASH_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/hash.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/hash.h new file mode 100644 index 000000000..001ea44ed --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/hash.h @@ -0,0 +1,37 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __HASH_H_ +#define __HASH_H_ + +#include "common.h" +#include "jhash.h" + +/* The daddr is explicitly excluded from the hash here in order to allow for + * backend selection to choose the same backend even on different service VIPs. + */ +static __always_inline __u32 hash_from_tuple_v4(const struct ipv4_ct_tuple *tuple) +{ + return jhash_3words(tuple->saddr, + ((__u32)tuple->dport << 16) | tuple->sport, + tuple->nexthdr, HASH_INIT4_SEED); +} + +static __always_inline __u32 hash_from_tuple_v6(const struct ipv6_ct_tuple *tuple) +{ + __u32 a, b, c; + + a = tuple->saddr.p1; + b = tuple->saddr.p2; + c = tuple->saddr.p3; + __jhash_mix(a, b, c); + a += tuple->saddr.p4; + b += ((__u32)tuple->dport << 16) | tuple->sport; + c += tuple->nexthdr; + __jhash_mix(a, b, c); + a += HASH_INIT6_SEED; + __jhash_final(a, b, c); + return c; +} + +#endif /* __HASH_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/host_firewall.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/host_firewall.h new file mode 100644 index 000000000..f1cd1dc66 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/host_firewall.h @@ -0,0 +1,425 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_HOST_FIREWALL_H_ +#define __LIB_HOST_FIREWALL_H_ + +/* Only compile in if host firewall is enabled and file is included from + * bpf_host. + */ +#if defined(ENABLE_HOST_FIREWALL) && defined(IS_BPF_HOST) + +# include "policy.h" +# include "policy_log.h" + +# ifdef ENABLE_IPV6 +static __always_inline int +ipv6_host_policy_egress(struct __ctx_buff *ctx, __u32 src_id, __u32 *monitor) +{ + int ret, verdict, l3_off = ETH_HLEN, l4_off, hdrlen; + struct ct_state ct_state_new = {}, ct_state = {}; + __u8 policy_match_type = POLICY_MATCH_NONE; + __u8 audited = 0; + struct remote_endpoint_info *info; + struct ipv6_ct_tuple tuple = {}; + __u32 dst_id = 0; + union v6addr orig_dip; + void *data, *data_end; + struct ipv6hdr *ip6; + + /* Only enforce host policies for packets from host IPs. */ + if (src_id != HOST_ID) + return CTX_ACT_OK; + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return DROP_INVALID; + + /* Lookup connection in conntrack map. */ + tuple.nexthdr = ip6->nexthdr; + ipv6_addr_copy(&tuple.saddr, (union v6addr *)&ip6->saddr); + ipv6_addr_copy(&tuple.daddr, (union v6addr *)&ip6->daddr); + ipv6_addr_copy(&orig_dip, (union v6addr *)&ip6->daddr); + hdrlen = ipv6_hdrlen(ctx, ETH_HLEN, &tuple.nexthdr); + if (hdrlen < 0) + return hdrlen; + l4_off = l3_off + hdrlen; + ret = ct_lookup6(get_ct_map6(&tuple), &tuple, ctx, l4_off, CT_EGRESS, + &ct_state, monitor); + if (ret < 0) + return ret; + + /* Retrieve destination identity. */ + info = lookup_ip6_remote_endpoint(&orig_dip); + if (info && info->sec_label) + dst_id = info->sec_label; + cilium_dbg(ctx, info ? DBG_IP_ID_MAP_SUCCEED6 : DBG_IP_ID_MAP_FAILED6, + orig_dip.p4, dst_id); + + /* Perform policy lookup. */ + verdict = policy_can_egress6(ctx, &tuple, src_id, dst_id, + &policy_match_type, &audited); + + /* Reply traffic and related are allowed regardless of policy verdict. */ + if (ret != CT_REPLY && ret != CT_RELATED && verdict < 0) { + send_policy_verdict_notify(ctx, dst_id, tuple.dport, + tuple.nexthdr, POLICY_EGRESS, 1, + verdict, policy_match_type, audited); + return verdict; + } + + switch (ret) { + case CT_NEW: + send_policy_verdict_notify(ctx, dst_id, tuple.dport, + tuple.nexthdr, POLICY_EGRESS, 1, + verdict, policy_match_type, audited); + ct_state_new.src_sec_id = HOST_ID; + ret = ct_create6(get_ct_map6(&tuple), &CT_MAP_ANY6, &tuple, + ctx, CT_EGRESS, &ct_state_new, verdict > 0); + if (IS_ERR(ret)) + return ret; + break; + + case CT_REOPENED: + send_policy_verdict_notify(ctx, dst_id, tuple.dport, + tuple.nexthdr, POLICY_EGRESS, 1, + verdict, policy_match_type, audited); + case CT_ESTABLISHED: + case CT_RELATED: + case CT_REPLY: + break; + + default: + return DROP_UNKNOWN_CT; + } + + return CTX_ACT_OK; +} + +static __always_inline int +ipv6_host_policy_ingress(struct __ctx_buff *ctx, __u32 *src_id) +{ + struct ct_state ct_state_new = {}, ct_state = {}; + __u8 policy_match_type = POLICY_MATCH_NONE; + __u8 audited = 0; + __u32 monitor = 0, dst_id = WORLD_ID; + struct remote_endpoint_info *info; + int ret, verdict, l4_off, hdrlen; + struct ipv6_ct_tuple tuple = {}; + union v6addr orig_sip; + void *data, *data_end; + struct ipv6hdr *ip6; + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return DROP_INVALID; + + /* Retrieve destination identity. */ + ipv6_addr_copy(&tuple.daddr, (union v6addr *)&ip6->daddr); + info = lookup_ip6_remote_endpoint(&tuple.daddr); + if (info && info->sec_label) + dst_id = info->sec_label; + cilium_dbg(ctx, info ? DBG_IP_ID_MAP_SUCCEED6 : DBG_IP_ID_MAP_FAILED6, + tuple.daddr.p4, dst_id); + + /* Only enforce host policies for packets to host IPs. */ + if (dst_id != HOST_ID) + return CTX_ACT_OK; + + /* Lookup connection in conntrack map. */ + tuple.nexthdr = ip6->nexthdr; + ipv6_addr_copy(&tuple.saddr, (union v6addr *)&ip6->saddr); + ipv6_addr_copy(&orig_sip, (union v6addr *)&ip6->saddr); + hdrlen = ipv6_hdrlen(ctx, ETH_HLEN, &tuple.nexthdr); + if (hdrlen < 0) + return hdrlen; + l4_off = ETH_HLEN + hdrlen; + ret = ct_lookup6(get_ct_map6(&tuple), &tuple, ctx, l4_off, CT_INGRESS, + &ct_state, &monitor); + if (ret < 0) + return ret; + + /* Retrieve source identity. */ + info = lookup_ip6_remote_endpoint(&orig_sip); + if (info && info->sec_label) + *src_id = info->sec_label; + cilium_dbg(ctx, info ? DBG_IP_ID_MAP_SUCCEED6 : DBG_IP_ID_MAP_FAILED6, + orig_sip.p4, *src_id); + + /* Perform policy lookup */ + verdict = policy_can_access_ingress(ctx, *src_id, dst_id, tuple.dport, + tuple.nexthdr, false, + &policy_match_type, &audited); + + /* Reply traffic and related are allowed regardless of policy verdict. */ + if (ret != CT_REPLY && ret != CT_RELATED && verdict < 0) { + send_policy_verdict_notify(ctx, *src_id, tuple.dport, + tuple.nexthdr, POLICY_INGRESS, 1, + verdict, policy_match_type, audited); + return verdict; + } + + switch (ret) { + case CT_NEW: + send_policy_verdict_notify(ctx, *src_id, tuple.dport, + tuple.nexthdr, POLICY_INGRESS, 1, + verdict, policy_match_type, audited); + + /* Create new entry for connection in conntrack map. */ + ct_state_new.src_sec_id = *src_id; + ct_state_new.node_port = ct_state.node_port; + ret = ct_create6(get_ct_map6(&tuple), &CT_MAP_ANY6, &tuple, + ctx, CT_INGRESS, &ct_state_new, verdict > 0); + if (IS_ERR(ret)) + return ret; + + case CT_REOPENED: + send_policy_verdict_notify(ctx, *src_id, tuple.dport, + tuple.nexthdr, POLICY_INGRESS, 1, + verdict, policy_match_type, audited); + case CT_ESTABLISHED: + case CT_RELATED: + case CT_REPLY: + break; + + default: + return DROP_UNKNOWN_CT; + } + + /* This change is necessary for packets redirected from the lxc device to + * the host device. + */ + ctx_change_type(ctx, PACKET_HOST); + return CTX_ACT_OK; +} +# endif /* ENABLE_IPV6 */ + +# ifdef ENABLE_IPV4 +# ifndef ENABLE_MASQUERADE +static __always_inline int +whitelist_snated_egress_connections(struct __ctx_buff *ctx, __u32 ipcache_srcid) +{ + struct ct_state ct_state_new = {}, ct_state = {}; + struct ipv4_ct_tuple tuple = {}; + void *data, *data_end; + struct iphdr *ip4; + __u32 monitor = 0; + int ret, l4_off; + + /* If kube-proxy is in use (no BPF-based masquerading), packets from + * pods may be SNATed. The response packet will therefore have a host + * IP as the destination IP. + * To avoid enforcing host policies for response packets to pods, we + * need to create a CT entry for the forward, SNATed packet from the + * pod. Response packets will thus match this CT entry and bypass host + * policies. + * We know the packet is a SNATed packet if the srcid from ipcache is + * HOST_ID, but the actual srcid (derived from the packet mark) isn't. + */ + if (ipcache_srcid == HOST_ID) { + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + tuple.nexthdr = ip4->protocol; + tuple.daddr = ip4->daddr; + tuple.saddr = ip4->saddr; + l4_off = ETH_HLEN + ipv4_hdrlen(ip4); + ret = ct_lookup4(get_ct_map4(&tuple), &tuple, ctx, l4_off, + CT_EGRESS, &ct_state, &monitor); + if (ret < 0) + return ret; + if (ret == CT_NEW) { + ret = ct_create4(get_ct_map4(&tuple), &CT_MAP_ANY4, + &tuple, ctx, CT_EGRESS, &ct_state_new, + false); + if (IS_ERR(ret)) + return ret; + } + } + + return CTX_ACT_OK; +} +# endif + +static __always_inline int +ipv4_host_policy_egress(struct __ctx_buff *ctx, __u32 src_id, + __u32 ipcache_srcid __maybe_unused, __u32 *monitor) +{ + struct ct_state ct_state_new = {}, ct_state = {}; + int ret, verdict, l4_off, l3_off = ETH_HLEN; + __u8 policy_match_type = POLICY_MATCH_NONE; + __u8 audited = 0; + struct remote_endpoint_info *info; + struct ipv4_ct_tuple tuple = {}; + __u32 dst_id = 0; + void *data, *data_end; + struct iphdr *ip4; + + if (src_id != HOST_ID) { +# ifndef ENABLE_MASQUERADE + return whitelist_snated_egress_connections(ctx, ipcache_srcid); +# else + /* Only enforce host policies for packets from host IPs. */ + return CTX_ACT_OK; +# endif + } + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + /* Lookup connection in conntrack map. */ + tuple.nexthdr = ip4->protocol; + tuple.daddr = ip4->daddr; + tuple.saddr = ip4->saddr; + l4_off = l3_off + ipv4_hdrlen(ip4); + ret = ct_lookup4(get_ct_map4(&tuple), &tuple, ctx, l4_off, CT_EGRESS, + &ct_state, monitor); + if (ret < 0) + return ret; + + /* Retrieve destination identity. */ + info = lookup_ip4_remote_endpoint(ip4->daddr); + if (info && info->sec_label) + dst_id = info->sec_label; + cilium_dbg(ctx, info ? DBG_IP_ID_MAP_SUCCEED4 : DBG_IP_ID_MAP_FAILED4, + ip4->daddr, dst_id); + + /* Perform policy lookup. */ + verdict = policy_can_egress4(ctx, &tuple, src_id, dst_id, + &policy_match_type, &audited); + + /* Reply traffic and related are allowed regardless of policy verdict. */ + if (ret != CT_REPLY && ret != CT_RELATED && verdict < 0) { + send_policy_verdict_notify(ctx, dst_id, tuple.dport, + tuple.nexthdr, POLICY_EGRESS, 0, + verdict, policy_match_type, audited); + return verdict; + } + + switch (ret) { + case CT_NEW: + send_policy_verdict_notify(ctx, dst_id, tuple.dport, + tuple.nexthdr, POLICY_EGRESS, 0, + verdict, policy_match_type, audited); + ct_state_new.src_sec_id = HOST_ID; + ret = ct_create4(get_ct_map4(&tuple), &CT_MAP_ANY4, &tuple, + ctx, CT_EGRESS, &ct_state_new, verdict > 0); + if (IS_ERR(ret)) + return ret; + break; + + case CT_REOPENED: + send_policy_verdict_notify(ctx, dst_id, tuple.dport, + tuple.nexthdr, POLICY_EGRESS, 0, + verdict, policy_match_type, audited); + case CT_ESTABLISHED: + case CT_RELATED: + case CT_REPLY: + break; + + default: + return DROP_UNKNOWN_CT; + } + + return CTX_ACT_OK; +} + +static __always_inline int +ipv4_host_policy_ingress(struct __ctx_buff *ctx, __u32 *src_id) +{ + struct ct_state ct_state_new = {}, ct_state = {}; + int ret, verdict, l4_off, l3_off = ETH_HLEN; + __u8 policy_match_type = POLICY_MATCH_NONE; + __u8 audited = 0; + __u32 monitor = 0, dst_id = WORLD_ID; + struct remote_endpoint_info *info; + struct ipv4_ct_tuple tuple = {}; + bool is_untracked_fragment = false; + void *data, *data_end; + struct iphdr *ip4; + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + /* Retrieve destination identity. */ + info = lookup_ip4_remote_endpoint(ip4->daddr); + if (info && info->sec_label) + dst_id = info->sec_label; + cilium_dbg(ctx, info ? DBG_IP_ID_MAP_SUCCEED4 : DBG_IP_ID_MAP_FAILED4, + ip4->daddr, dst_id); + + /* Only enforce host policies for packets to host IPs. */ + if (dst_id != HOST_ID) + return CTX_ACT_OK; + + /* Lookup connection in conntrack map. */ + tuple.nexthdr = ip4->protocol; + tuple.daddr = ip4->daddr; + tuple.saddr = ip4->saddr; + l4_off = l3_off + ipv4_hdrlen(ip4); +# ifndef ENABLE_IPV4_FRAGMENTS + /* Indicate that this is a datagram fragment for which we cannot + * retrieve L4 ports. Do not set flag if we support fragmentation. + */ + is_untracked_fragment = ipv4_is_fragment(ip4); +# endif + ret = ct_lookup4(get_ct_map4(&tuple), &tuple, ctx, l4_off, CT_INGRESS, + &ct_state, &monitor); + if (ret < 0) + return ret; + + /* Retrieve source identity. */ + info = lookup_ip4_remote_endpoint(ip4->saddr); + if (info && info->sec_label) + *src_id = info->sec_label; + cilium_dbg(ctx, info ? DBG_IP_ID_MAP_SUCCEED4 : DBG_IP_ID_MAP_FAILED4, + ip4->saddr, *src_id); + + /* Perform policy lookup */ + verdict = policy_can_access_ingress(ctx, *src_id, dst_id, tuple.dport, + tuple.nexthdr, + is_untracked_fragment, + &policy_match_type, &audited); + + /* Reply traffic and related are allowed regardless of policy verdict. */ + if (ret != CT_REPLY && ret != CT_RELATED && verdict < 0) { + send_policy_verdict_notify(ctx, *src_id, tuple.dport, + tuple.nexthdr, POLICY_INGRESS, 0, + verdict, policy_match_type, audited); + return verdict; + } + + switch (ret) { + case CT_NEW: + send_policy_verdict_notify(ctx, *src_id, tuple.dport, + tuple.nexthdr, POLICY_INGRESS, 0, + verdict, policy_match_type, audited); + + /* Create new entry for connection in conntrack map. */ + ct_state_new.src_sec_id = *src_id; + ct_state_new.node_port = ct_state.node_port; + ret = ct_create4(get_ct_map4(&tuple), &CT_MAP_ANY4, &tuple, + ctx, CT_INGRESS, &ct_state_new, verdict > 0); + if (IS_ERR(ret)) + return ret; + + case CT_REOPENED: + send_policy_verdict_notify(ctx, *src_id, tuple.dport, + tuple.nexthdr, POLICY_INGRESS, 0, + verdict, policy_match_type, audited); + case CT_ESTABLISHED: + case CT_RELATED: + case CT_REPLY: + break; + + default: + return DROP_UNKNOWN_CT; + } + + /* This change is necessary for packets redirected from the lxc device to + * the host device. + */ + ctx_change_type(ctx, PACKET_HOST); + return CTX_ACT_OK; +} +# endif /* ENABLE_IPV4 */ +#endif /* ENABLE_HOST_FIREWALL && IS_BPF_HOST */ +#endif /* __LIB_HOST_FIREWALL_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/icmp6.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/icmp6.h new file mode 100644 index 000000000..2401132e9 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/icmp6.h @@ -0,0 +1,533 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#if !defined(__LIB_ICMP6__) && defined(ENABLE_IPV6) +#define __LIB_ICMP6__ + +#include +#include +#include "common.h" +#include "eth.h" +#include "drop.h" +#include "eps.h" + +#define ICMP6_TYPE_OFFSET (sizeof(struct ipv6hdr) + offsetof(struct icmp6hdr, icmp6_type)) +#define ICMP6_CSUM_OFFSET (sizeof(struct ipv6hdr) + offsetof(struct icmp6hdr, icmp6_cksum)) +#define ICMP6_ND_TARGET_OFFSET (sizeof(struct ipv6hdr) + sizeof(struct icmp6hdr)) +#define ICMP6_ND_OPTS (sizeof(struct ipv6hdr) + sizeof(struct icmp6hdr) + sizeof(struct in6_addr)) + +#define ICMP6_UNREACH_MSG_TYPE 1 +#define ICMP6_PARAM_ERR_MSG_TYPE 4 +#define ICMP6_ECHO_REQUEST_MSG_TYPE 128 +#define ICMP6_ECHO_REPLY_MSG_TYPE 129 +#define ICMP6_MULT_LIST_QUERY_TYPE 130 +#define ICMP6_NS_MSG_TYPE 135 +#define ICMP6_NA_MSG_TYPE 136 +#define ICMP6_RR_MSG_TYPE 138 +#define ICMP6_INV_NS_MSG_TYPE 141 +#define ICMP6_MULT_LIST_REPORT_V2_TYPE 143 +#define ICMP6_SEND_NS_MSG_TYPE 148 +#define ICMP6_SEND_NA_MSG_TYPE 149 +#define ICMP6_MULT_RA_MSG_TYPE 151 +#define ICMP6_MULT_RT_MSG_TYPE 153 + +#define SKIP_HOST_FIREWALL -2 + +/* If no specific action is specified, drop unknown neighbour solicitation + * messages. + */ +#ifndef ACTION_UNKNOWN_ICMP6_NS +#define ACTION_UNKNOWN_ICMP6_NS DROP_UNKNOWN_TARGET +#endif + +static __always_inline __u8 icmp6_load_type(struct __ctx_buff *ctx, int nh_off) +{ + __u8 type; + + ctx_load_bytes(ctx, nh_off + ICMP6_TYPE_OFFSET, &type, sizeof(type)); + return type; +} + +static __always_inline int icmp6_send_reply(struct __ctx_buff *ctx, int nh_off) +{ + union macaddr smac, dmac = NODE_MAC; + const int csum_off = nh_off + ICMP6_CSUM_OFFSET; + union v6addr sip, dip, router_ip; + __be32 sum; + + if (ipv6_load_saddr(ctx, nh_off, &sip) < 0 || + ipv6_load_daddr(ctx, nh_off, &dip) < 0) + return DROP_INVALID; + + BPF_V6(router_ip, ROUTER_IP); + /* ctx->saddr = ctx->daddr */ + if (ipv6_store_saddr(ctx, router_ip.addr, nh_off) < 0) + return DROP_WRITE_ERROR; + /* ctx->daddr = ctx->saddr */ + if (ipv6_store_daddr(ctx, sip.addr, nh_off) < 0) + return DROP_WRITE_ERROR; + + /* fixup checksums */ + sum = csum_diff(sip.addr, 16, router_ip.addr, 16, 0); + if (l4_csum_replace(ctx, csum_off, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + + sum = csum_diff(dip.addr, 16, sip.addr, 16, 0); + if (l4_csum_replace(ctx, csum_off, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + + /* dmac = smac, smac = dmac */ + if (eth_load_saddr(ctx, smac.addr, 0) < 0) + return DROP_INVALID; + + if (eth_store_daddr(ctx, smac.addr, 0) < 0 || + eth_store_saddr(ctx, dmac.addr, 0) < 0) + return DROP_WRITE_ERROR; + + cilium_dbg_capture(ctx, DBG_CAPTURE_DELIVERY, ctx_get_ifindex(ctx)); + + return redirect_self(ctx); +} + +static __always_inline int __icmp6_send_echo_reply(struct __ctx_buff *ctx, + int nh_off) +{ + struct icmp6hdr icmp6hdr __align_stack_8 = {}, icmp6hdr_old __align_stack_8; + int csum_off = nh_off + ICMP6_CSUM_OFFSET; + __be32 sum; + + cilium_dbg(ctx, DBG_ICMP6_REQUEST, nh_off, 0); + + if (ctx_load_bytes(ctx, nh_off + sizeof(struct ipv6hdr), &icmp6hdr_old, + sizeof(icmp6hdr_old)) < 0) + return DROP_INVALID; + + /* fill icmp6hdr */ + icmp6hdr.icmp6_type = 129; + icmp6hdr.icmp6_code = 0; + icmp6hdr.icmp6_cksum = icmp6hdr_old.icmp6_cksum; + icmp6hdr.icmp6_dataun.un_data32[0] = 0; + icmp6hdr.icmp6_identifier = icmp6hdr_old.icmp6_identifier; + icmp6hdr.icmp6_sequence = icmp6hdr_old.icmp6_sequence; + + if (ctx_store_bytes(ctx, nh_off + sizeof(struct ipv6hdr), &icmp6hdr, + sizeof(icmp6hdr), 0) < 0) + return DROP_WRITE_ERROR; + + /* fixup checksum */ + sum = csum_diff(&icmp6hdr_old, sizeof(icmp6hdr_old), + &icmp6hdr, sizeof(icmp6hdr), 0); + + if (l4_csum_replace(ctx, csum_off, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + + return icmp6_send_reply(ctx, nh_off); +} + +#ifndef SKIP_ICMPV6_ECHO_HANDLING +__section_tail(CILIUM_MAP_CALLS, CILIUM_CALL_SEND_ICMP6_ECHO_REPLY) +int tail_icmp6_send_echo_reply(struct __ctx_buff *ctx) +{ + int ret, nh_off = ctx_load_meta(ctx, 0); + __u8 direction = ctx_load_meta(ctx, 1); + + ctx_store_meta(ctx, 0, 0); + ret = __icmp6_send_echo_reply(ctx, nh_off); + if (IS_ERR(ret)) + return send_drop_notify_error(ctx, 0, ret, CTX_ACT_DROP, direction); + return ret; +} +#endif + +/* + * icmp6_send_echo_reply + * @ctx: socket buffer + * @nh_off: offset to the IPv6 header + * + * Send an ICMPv6 echo reply in return to an ICMPv6 echo reply. + * + * NOTE: This is terminal function and will cause the BPF program to exit + */ +static __always_inline int icmp6_send_echo_reply(struct __ctx_buff *ctx, + int nh_off, __u8 direction) +{ + ctx_store_meta(ctx, 0, nh_off); + ctx_store_meta(ctx, 1, direction); + + ep_tail_call(ctx, CILIUM_CALL_SEND_ICMP6_ECHO_REPLY); + + return DROP_MISSED_TAIL_CALL; +} + +/* + * send_icmp6_ndisc_adv + * @ctx: socket buffer + * @nh_off: offset to the IPv6 header + * @mac: device mac address + * @to_router: ndisc is sent to router, otherwise ndisc is sent to an endpoint. + * + * Send an ICMPv6 nadv reply in return to an ICMPv6 ndisc. + */ +static __always_inline int send_icmp6_ndisc_adv(struct __ctx_buff *ctx, + int nh_off, union macaddr *mac, bool to_router) +{ + struct icmp6hdr icmp6hdr __align_stack_8 = {}, icmp6hdr_old __align_stack_8; + __u8 opts[8], opts_old[8]; + const int csum_off = nh_off + ICMP6_CSUM_OFFSET; + __be32 sum; + + if (ctx_load_bytes(ctx, nh_off + sizeof(struct ipv6hdr), &icmp6hdr_old, + sizeof(icmp6hdr_old)) < 0) + return DROP_INVALID; + + /* fill icmp6hdr */ + icmp6hdr.icmp6_type = 136; + icmp6hdr.icmp6_code = 0; + icmp6hdr.icmp6_cksum = icmp6hdr_old.icmp6_cksum; + icmp6hdr.icmp6_dataun.un_data32[0] = 0; + + if (to_router) { + icmp6hdr.icmp6_router = 1; + icmp6hdr.icmp6_solicited = 1; + icmp6hdr.icmp6_override = 0; + } else { + icmp6hdr.icmp6_router = 0; + icmp6hdr.icmp6_solicited = 1; + icmp6hdr.icmp6_override = 1; + } + + if (ctx_store_bytes(ctx, nh_off + sizeof(struct ipv6hdr), &icmp6hdr, + sizeof(icmp6hdr), 0) < 0) + return DROP_WRITE_ERROR; + + /* fixup checksums */ + sum = csum_diff(&icmp6hdr_old, sizeof(icmp6hdr_old), + &icmp6hdr, sizeof(icmp6hdr), 0); + if (l4_csum_replace(ctx, csum_off, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + + /* get old options */ + if (ctx_load_bytes(ctx, nh_off + ICMP6_ND_OPTS, opts_old, sizeof(opts_old)) < 0) + return DROP_INVALID; + + opts[0] = 2; + opts[1] = 1; + opts[2] = mac->addr[0]; + opts[3] = mac->addr[1]; + opts[4] = mac->addr[2]; + opts[5] = mac->addr[3]; + opts[6] = mac->addr[4]; + opts[7] = mac->addr[5]; + + /* store ND_OPT_TARGET_LL_ADDR option */ + if (ctx_store_bytes(ctx, nh_off + ICMP6_ND_OPTS, opts, sizeof(opts), 0) < 0) + return DROP_WRITE_ERROR; + + /* fixup checksum */ + sum = csum_diff(opts_old, sizeof(opts_old), opts, sizeof(opts), 0); + if (l4_csum_replace(ctx, csum_off, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + + return icmp6_send_reply(ctx, nh_off); +} + +static __always_inline __be32 compute_icmp6_csum(char data[80], __u16 payload_len, + struct ipv6hdr *ipv6hdr) +{ + __be32 sum; + + /* compute checksum with new payload length */ + sum = csum_diff(NULL, 0, data, payload_len, 0); + sum = ipv6_pseudohdr_checksum(ipv6hdr, IPPROTO_ICMPV6, payload_len, + sum); + return sum; +} + +#ifdef BPF_HAVE_CHANGE_TAIL +static __always_inline int __icmp6_send_time_exceeded(struct __ctx_buff *ctx, + int nh_off) +{ + /* FIXME: Fix code below to not require this init */ + char data[80] = {}; + struct icmp6hdr *icmp6hoplim; + struct ipv6hdr *ipv6hdr; + char *upper; /* icmp6 or tcp or udp */ + const int csum_off = nh_off + ICMP6_CSUM_OFFSET; + __be32 sum = 0; + __u16 payload_len = 0; /* FIXME: Uninit of this causes verifier bug */ + __u8 icmp6_nexthdr = IPPROTO_ICMPV6; + int trimlen; + + /* initialize pointers to offsets in data */ + icmp6hoplim = (struct icmp6hdr *)data; + ipv6hdr = (struct ipv6hdr *)(data + 8); + upper = (data + 48); + + /* fill icmp6hdr */ + icmp6hoplim->icmp6_type = 3; + icmp6hoplim->icmp6_code = 0; + icmp6hoplim->icmp6_cksum = 0; + icmp6hoplim->icmp6_dataun.un_data32[0] = 0; + + cilium_dbg(ctx, DBG_ICMP6_TIME_EXCEEDED, 0, 0); + + /* read original v6 hdr into offset 8 */ + if (ctx_load_bytes(ctx, nh_off, ipv6hdr, sizeof(*ipv6hdr)) < 0) + return DROP_INVALID; + + if (ipv6_store_nexthdr(ctx, &icmp6_nexthdr, nh_off) < 0) + return DROP_WRITE_ERROR; + + /* read original v6 payload into offset 48 */ + switch (ipv6hdr->nexthdr) { + case IPPROTO_ICMPV6: + case IPPROTO_UDP: + if (ctx_load_bytes(ctx, nh_off + sizeof(struct ipv6hdr), + upper, 8) < 0) + return DROP_INVALID; + sum = compute_icmp6_csum(data, 56, ipv6hdr); + payload_len = bpf_htons(56); + trimlen = 56 - bpf_ntohs(ipv6hdr->payload_len); + if (ctx_change_tail(ctx, ctx_full_len(ctx) + trimlen, 0) < 0) + return DROP_WRITE_ERROR; + /* trim or expand buffer and copy data buffer after ipv6 header */ + if (ctx_store_bytes(ctx, nh_off + sizeof(struct ipv6hdr), + data, 56, 0) < 0) + return DROP_WRITE_ERROR; + if (ipv6_store_paylen(ctx, nh_off, &payload_len) < 0) + return DROP_WRITE_ERROR; + + break; + /* copy header without options */ + case IPPROTO_TCP: + if (ctx_load_bytes(ctx, nh_off + sizeof(struct ipv6hdr), + upper, 20) < 0) + return DROP_INVALID; + sum = compute_icmp6_csum(data, 68, ipv6hdr); + payload_len = bpf_htons(68); + /* trim or expand buffer and copy data buffer after ipv6 header */ + trimlen = 68 - bpf_ntohs(ipv6hdr->payload_len); + if (ctx_change_tail(ctx, ctx_full_len(ctx) + trimlen, 0) < 0) + return DROP_WRITE_ERROR; + if (ctx_store_bytes(ctx, nh_off + sizeof(struct ipv6hdr), + data, 68, 0) < 0) + return DROP_WRITE_ERROR; + if (ipv6_store_paylen(ctx, nh_off, &payload_len) < 0) + return DROP_WRITE_ERROR; + + break; + default: + return DROP_UNKNOWN_L4; + } + + if (l4_csum_replace(ctx, csum_off, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + + return icmp6_send_reply(ctx, nh_off); +} +#endif + +#ifndef SKIP_ICMPV6_HOPLIMIT_HANDLING +__section_tail(CILIUM_MAP_CALLS, CILIUM_CALL_SEND_ICMP6_TIME_EXCEEDED) +int tail_icmp6_send_time_exceeded(struct __ctx_buff *ctx __maybe_unused) +{ +# ifdef BPF_HAVE_CHANGE_TAIL + int ret, nh_off = ctx_load_meta(ctx, 0); + __u8 direction = ctx_load_meta(ctx, 1); + + ctx_store_meta(ctx, 0, 0); + ret = __icmp6_send_time_exceeded(ctx, nh_off); + if (IS_ERR(ret)) + return send_drop_notify_error(ctx, 0, ret, CTX_ACT_DROP, + direction); + return ret; +# else + return 0; +# endif +} +#endif + +/* + * icmp6_send_time_exceeded + * @ctx: socket buffer + * @nh_off: offset to the IPv6 header + * @direction: direction of packet (can be ingress or egress) + * Send a ICMPv6 time exceeded in response to an IPv6 frame. + * + * NOTE: This is terminal function and will cause the BPF program to exit + */ +static __always_inline int icmp6_send_time_exceeded(struct __ctx_buff *ctx, + int nh_off, __u8 direction) +{ + ctx_store_meta(ctx, 0, nh_off); + ctx_store_meta(ctx, 1, direction); + + ep_tail_call(ctx, CILIUM_CALL_SEND_ICMP6_TIME_EXCEEDED); + + return DROP_MISSED_TAIL_CALL; +} + +static __always_inline int __icmp6_handle_ns(struct __ctx_buff *ctx, int nh_off) +{ + union v6addr target, router; + struct endpoint_info *ep; + + if (ctx_load_bytes(ctx, nh_off + ICMP6_ND_TARGET_OFFSET, target.addr, + sizeof(((struct ipv6hdr *)NULL)->saddr)) < 0) + return DROP_INVALID; + + cilium_dbg(ctx, DBG_ICMP6_NS, target.p3, target.p4); + + BPF_V6(router, ROUTER_IP); + + if (ipv6_addrcmp(&target, &router) == 0) { + union macaddr router_mac = NODE_MAC; + + return send_icmp6_ndisc_adv(ctx, nh_off, &router_mac, true); + } + + ep = __lookup_ip6_endpoint(&target); + if (ep) { + union macaddr router_mac = NODE_MAC; + + return send_icmp6_ndisc_adv(ctx, nh_off, &router_mac, false); + } + + /* Unknown target address, drop */ + return ACTION_UNKNOWN_ICMP6_NS; +} + +#ifndef SKIP_ICMPV6_NS_HANDLING +__section_tail(CILIUM_MAP_CALLS, CILIUM_CALL_HANDLE_ICMP6_NS) +int tail_icmp6_handle_ns(struct __ctx_buff *ctx) +{ + int ret, nh_off = ctx_load_meta(ctx, 0); + __u8 direction = ctx_load_meta(ctx, 1); + + ctx_store_meta(ctx, 0, 0); + ret = __icmp6_handle_ns(ctx, nh_off); + if (IS_ERR(ret)) + return send_drop_notify_error(ctx, 0, ret, CTX_ACT_DROP, direction); + return ret; +} +#endif + +/* + * icmp6_handle_ns + * @ctx: socket buffer + * @nh_off: offset to the IPv6 header + * @direction: direction of packet(ingress or egress) + * + * Respond to ICMPv6 Neighbour Solicitation + * + * NOTE: This is terminal function and will cause the BPF program to exit + */ +static __always_inline int icmp6_handle_ns(struct __ctx_buff *ctx, int nh_off, + __u8 direction) +{ + ctx_store_meta(ctx, 0, nh_off); + ctx_store_meta(ctx, 1, direction); + + ep_tail_call(ctx, CILIUM_CALL_HANDLE_ICMP6_NS); + + return DROP_MISSED_TAIL_CALL; +} + +static __always_inline int icmp6_handle(struct __ctx_buff *ctx, int nh_off, + struct ipv6hdr *ip6, __u8 direction) +{ + union v6addr router_ip; + __u8 type = icmp6_load_type(ctx, nh_off); + + cilium_dbg(ctx, DBG_ICMP6_HANDLE, type, 0); + BPF_V6(router_ip, ROUTER_IP); + + switch (type) { + case ICMP6_NS_MSG_TYPE: + return icmp6_handle_ns(ctx, nh_off, direction); + case ICMPV6_ECHO_REQUEST: + if (!ipv6_addrcmp((union v6addr *) &ip6->daddr, &router_ip)) + return icmp6_send_echo_reply(ctx, nh_off, direction); + break; + } + + /* All branching above will have issued a tail call, all + * remaining traffic is subject to forwarding to containers. + */ + return 0; +} + +static __always_inline int +icmp6_host_handle(struct __ctx_buff *ctx __maybe_unused) +{ + __u8 type __maybe_unused; + + type = icmp6_load_type(ctx, ETH_HLEN); + if (type == ICMP6_NS_MSG_TYPE) + return icmp6_handle_ns(ctx, ETH_HLEN, METRIC_INGRESS); + +#ifdef ENABLE_HOST_FIREWALL + /* When the host firewall is enabled, we drop and allow ICMPv6 messages + * according to RFC4890, except for echo request and reply messages which + * are handled by host policies and can be dropped. + * | ICMPv6 Message | Action | Type | + * |---------------------------------|-----------------|------| + * | ICMPv6-unreach | CTX_ACT_OK | 1 | + * | ICMPv6-too-big | CTX_ACT_OK | 2 | + * | ICMPv6-timed | CTX_ACT_OK | 3 | + * | ICMPv6-parameter | CTX_ACT_OK | 4 | + * | ICMPv6-err-private-exp-100 | CTX_ACT_DROP | 100 | + * | ICMPv6-err-private-exp-101 | CTX_ACT_DROP | 101 | + * | ICMPv6-err-expansion | CTX_ACT_DROP | 127 | + * | ICMPv6-echo-message | Firewall | 128 | + * | ICMPv6-echo-reply | Firewall | 129 | + * | ICMPv6-mult-list-query | CTX_ACT_OK | 130 | + * | ICMPv6-mult-list-report | CTX_ACT_OK | 131 | + * | ICMPv6-mult-list-done | CTX_ACT_OK | 132 | + * | ICMPv6-router-solici | CTX_ACT_OK | 133 | + * | ICMPv6-router-advert | CTX_ACT_OK | 134 | + * | ICMPv6-neighbor-solicit | icmp6_handle_ns | 135 | + * | ICMPv6-neighbor-advert | CTX_ACT_OK | 136 | + * | ICMPv6-redirect-message | CTX_ACT_DROP | 137 | + * | ICMPv6-router-renumber | CTX_ACT_OK | 138 | + * | ICMPv6-node-info-query | CTX_ACT_DROP | 139 | + * | ICMPv6-node-info-response | CTX_ACT_DROP | 140 | + * | ICMPv6-inv-neighbor-solicit | CTX_ACT_OK | 141 | + * | ICMPv6-inv-neighbor-advert | CTX_ACT_OK | 142 | + * | ICMPv6-mult-list-report-v2 | CTX_ACT_OK | 143 | + * | ICMPv6-home-agent-disco-request | CTX_ACT_DROP | 144 | + * | ICMPv6-home-agent-disco-reply | CTX_ACT_DROP | 145 | + * | ICMPv6-mobile-solicit | CTX_ACT_DROP | 146 | + * | ICMPv6-mobile-advert | CTX_ACT_DROP | 147 | + * | ICMPv6-send-solicit | CTX_ACT_OK | 148 | + * | ICMPv6-send-advert | CTX_ACT_OK | 149 | + * | ICMPv6-mobile-exp | CTX_ACT_DROP | 150 | + * | ICMPv6-mult-router-advert | CTX_ACT_OK | 151 | + * | ICMPv6-mult-router-solicit | CTX_ACT_OK | 152 | + * | ICMPv6-mult-router-term | CTX_ACT_OK | 153 | + * | ICMPv6-FMIPv6 | CTX_ACT_DROP | 154 | + * | ICMPv6-rpl-control | CTX_ACT_DROP | 155 | + * | ICMPv6-info-private-exp-200 | CTX_ACT_DROP | 200 | + * | ICMPv6-info-private-exp-201 | CTX_ACT_DROP | 201 | + * | ICMPv6-info-expansion | CTX_ACT_DROP | 255 | + * | ICMPv6-unallocated | CTX_ACT_DROP | | + * | ICMPv6-unassigned | CTX_ACT_DROP | | + */ + + if (type == ICMP6_ECHO_REQUEST_MSG_TYPE || type == ICMP6_ECHO_REPLY_MSG_TYPE) + /* Decision is deferred to the host policies. */ + return CTX_ACT_OK; + + if ((ICMP6_UNREACH_MSG_TYPE <= type && type <= ICMP6_PARAM_ERR_MSG_TYPE) || + (ICMP6_MULT_LIST_QUERY_TYPE <= type && type <= ICMP6_NA_MSG_TYPE) || + (ICMP6_INV_NS_MSG_TYPE <= type && type <= ICMP6_MULT_LIST_REPORT_V2_TYPE) || + (ICMP6_SEND_NS_MSG_TYPE <= type && type <= ICMP6_SEND_NA_MSG_TYPE) || + (ICMP6_MULT_RA_MSG_TYPE <= type && type <= ICMP6_MULT_RT_MSG_TYPE)) + return SKIP_HOST_FIREWALL; + return DROP_FORBIDDEN_ICMP6; +#else + return CTX_ACT_OK; +#endif /* ENABLE_HOST_FIREWALL */ +} + +#endif diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/identity.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/identity.h new file mode 100644 index 000000000..96fd339e4 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/identity.h @@ -0,0 +1,69 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_IDENTITY_H_ +#define __LIB_IDENTITY_H_ + +#include "drop.h" +#include "dbg.h" + +/** + * identity_is_reserved is used to determine whether an identity is one of the + * reserved identities that are not handed out to endpoints. + * + * Specifically, it should return true if the identity is one of these: + * - IdentityUnknown + * - ReservedIdentityHost + * - ReservedIdentityWorld + * - ReservedIdentityRemoteNode + * + * The following identities are given to endpoints so return false for these: + * - ReservedIdentityUnmanaged + * - ReservedIdentityHealth + * - ReservedIdentityInit + * + * Identities 128 and higher are guaranteed to be generated based on user input. + */ +static __always_inline bool identity_is_reserved(__u32 identity) +{ + return identity < UNMANAGED_ID || identity == REMOTE_NODE_ID; +} + +static __always_inline bool inherit_identity_from_host(struct __ctx_buff *ctx, + __u32 *identity) +{ + __u32 magic = ctx->mark & MARK_MAGIC_HOST_MASK; + bool from_proxy = false; + + /* Packets from the ingress proxy must skip the proxy when the + * destination endpoint evaluates the policy. As the packet would loop + * and/or the connection be reset otherwise. + */ + if (magic == MARK_MAGIC_PROXY_INGRESS) { + *identity = get_identity(ctx); + ctx->tc_index |= TC_INDEX_F_SKIP_INGRESS_PROXY; + from_proxy = true; + /* (Return) packets from the egress proxy must skip the redirection to + * the proxy, as the packet would loop and/or the connection be reset + * otherwise. + */ + } else if (magic == MARK_MAGIC_PROXY_EGRESS) { + *identity = get_identity(ctx); + ctx->tc_index |= TC_INDEX_F_SKIP_EGRESS_PROXY; + from_proxy = true; + } else if (magic == MARK_MAGIC_IDENTITY) { + *identity = get_identity(ctx); + } else if (magic == MARK_MAGIC_HOST) { + *identity = HOST_ID; + } else { + *identity = WORLD_ID; + } + + /* Reset packet mark to avoid hitting routing rules again */ + ctx->mark = 0; + cilium_dbg(ctx, DBG_INHERIT_IDENTITY, *identity, 0); + + return from_proxy; +} + +#endif diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/ids.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/ids.h new file mode 100644 index 000000000..9ee879202 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/ids.h @@ -0,0 +1,13 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2021 Authors of Cilium */ + +#ifndef __LIB_IDS_H_ +#define __LIB_IDS_H_ + +#define CILIUM_MAP_POLICY 1 +#define CILIUM_MAP_CALLS 2 +#define CILIUM_MAP_MAGLEV4 3 +#define CILIUM_MAP_MAGLEV6 4 +#define CILIUM_MAP_CUSTOM_CALLS 5 + +#endif /* __LIB_IDS_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/ipv4.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/ipv4.h new file mode 100644 index 000000000..e95704079 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/ipv4.h @@ -0,0 +1,162 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_IPV4__ +#define __LIB_IPV4__ + +#include + +#include "dbg.h" +#include "metrics.h" + +struct ipv4_frag_id { + __be32 daddr; + __be32 saddr; + __be16 id; /* L4 datagram identifier */ + __u8 proto; + __u8 pad; +} __packed; + +struct ipv4_frag_l4ports { + __be16 sport; + __be16 dport; +} __packed; + +#ifdef ENABLE_IPV4_FRAGMENTS +struct bpf_elf_map __section_maps IPV4_FRAG_DATAGRAMS_MAP = { + .type = BPF_MAP_TYPE_LRU_HASH, + .size_key = sizeof(struct ipv4_frag_id), + .size_value = sizeof(struct ipv4_frag_l4ports), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_IPV4_FRAG_MAP_MAX_ENTRIES, +}; +#endif + +static __always_inline int ipv4_load_daddr(struct __ctx_buff *ctx, int off, + __u32 *dst) +{ + return ctx_load_bytes(ctx, off + offsetof(struct iphdr, daddr), dst, 4); +} + +static __always_inline int ipv4_dec_ttl(struct __ctx_buff *ctx, int off, + const struct iphdr *ip4) +{ + __u8 new_ttl, ttl = ip4->ttl; + + if (ttl <= 1) + return 1; + + new_ttl = ttl - 1; + /* l3_csum_replace() takes at min 2 bytes, zero extended. */ + l3_csum_replace(ctx, off + offsetof(struct iphdr, check), ttl, new_ttl, 2); + ctx_store_bytes(ctx, off + offsetof(struct iphdr, ttl), &new_ttl, sizeof(new_ttl), 0); + + return 0; +} + +static __always_inline int ipv4_hdrlen(const struct iphdr *ip4) +{ + return ip4->ihl * 4; +} + +static __always_inline bool ipv4_is_fragment(const struct iphdr *ip4) +{ + /* The frag_off portion of the header consists of: + * + * +----+----+----+----------------------------------+ + * | RS | DF | MF | ...13 bits of fragment offset... | + * +----+----+----+----------------------------------+ + * + * If "More fragments" or the offset is nonzero, then this is an IP + * fragment (RFC791). + */ + return ip4->frag_off & bpf_htons(0x3FFF); +} + +static __always_inline bool ipv4_is_not_first_fragment(const struct iphdr *ip4) +{ + /* Ignore "More fragments" bit to catch all fragments but the first */ + return ip4->frag_off & bpf_htons(0x1FFF); +} + +/* Simply a reverse of ipv4_is_not_first_fragment to avoid double negative. */ +static __always_inline bool ipv4_has_l4_header(const struct iphdr *ip4) +{ + return !ipv4_is_not_first_fragment(ip4); +} + +static __always_inline bool ipv4_is_in_subnet(__be32 addr, + __be32 subnet, int prefixlen) +{ + return (addr & bpf_htonl(~((1 << (32 - prefixlen)) - 1))) == subnet; +} + +#ifdef ENABLE_IPV4_FRAGMENTS +static __always_inline int +ipv4_frag_get_l4ports(const struct ipv4_frag_id *frag_id, + struct ipv4_frag_l4ports *ports) +{ + struct ipv4_frag_l4ports *tmp; + + tmp = map_lookup_elem(&IPV4_FRAG_DATAGRAMS_MAP, frag_id); + if (!tmp) + return DROP_FRAG_NOT_FOUND; + + /* Do not make ports a pointer to map data, copy from map */ + memcpy(ports, tmp, sizeof(*ports)); + return 0; +} + +static __always_inline int +ipv4_handle_fragmentation(struct __ctx_buff *ctx, + const struct iphdr *ip4, int l4_off, int ct_dir, + struct ipv4_frag_l4ports *ports, + bool *has_l4_header) +{ + int ret, dir; + bool is_fragment, not_first_fragment; + + struct ipv4_frag_id frag_id = { + .daddr = ip4->daddr, + .saddr = ip4->saddr, + .id = ip4->id, + .proto = ip4->protocol, + .pad = 0, + }; + + is_fragment = ipv4_is_fragment(ip4); + dir = ct_to_metrics_dir(ct_dir); + + if (unlikely(is_fragment)) { + update_metrics(ctx_full_len(ctx), dir, REASON_FRAG_PACKET); + + not_first_fragment = ipv4_is_not_first_fragment(ip4); + if (has_l4_header) + *has_l4_header = !not_first_fragment; + + if (likely(not_first_fragment)) + return ipv4_frag_get_l4ports(&frag_id, ports); + } + + /* load sport + dport into tuple */ + ret = ctx_load_bytes(ctx, l4_off, ports, 4); + if (ret < 0) + return ret; + + if (unlikely(is_fragment)) { + /* First logical fragment for this datagram (not necessarily the first + * we receive). Fragment has L4 header, create an entry in datagrams map. + */ + if (map_update_elem(&IPV4_FRAG_DATAGRAMS_MAP, &frag_id, ports, BPF_ANY)) + update_metrics(ctx_full_len(ctx), dir, REASON_FRAG_PACKET_UPDATE); + + /* Do not return an error if map update failed, as nothing prevents us + * to process the current packet normally. + */ + } + + return 0; +} +#endif + +#endif /* __LIB_IPV4__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/ipv6.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/ipv6.h new file mode 100644 index 000000000..65a324570 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/ipv6.h @@ -0,0 +1,262 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_IPV6__ +#define __LIB_IPV6__ + +#include + +#include "dbg.h" + +#define IPV6_FLOWINFO_MASK bpf_htonl(0x0FFFFFFF) +#define IPV6_FLOWLABEL_MASK bpf_htonl(0x000FFFFF) +#define IPV6_FLOWLABEL_STATELESS_FLAG bpf_htonl(0x00080000) + +#define IPV6_TCLASS_MASK (IPV6_FLOWINFO_MASK & ~IPV6_FLOWLABEL_MASK) +#define IPV6_TCLASS_SHIFT 20 + +/* Number of extension headers that can be skipped */ +#define IPV6_MAX_HEADERS 4 + +#define NEXTHDR_HOP 0 /* Hop-by-hop option header. */ +#define NEXTHDR_TCP 6 /* TCP segment. */ +#define NEXTHDR_UDP 17 /* UDP message. */ +#define NEXTHDR_IPV6 41 /* IPv6 in IPv6 */ +#define NEXTHDR_ROUTING 43 /* Routing header. */ +#define NEXTHDR_FRAGMENT 44 /* Fragmentation/reassembly header. */ +#define NEXTHDR_GRE 47 /* GRE header. */ +#define NEXTHDR_ESP 50 /* Encapsulating security payload. */ +#define NEXTHDR_AUTH 51 /* Authentication header. */ +#define NEXTHDR_ICMP 58 /* ICMP for IPv6. */ +#define NEXTHDR_NONE 59 /* No next header */ +#define NEXTHDR_DEST 60 /* Destination options header. */ +#define NEXTHDR_SCTP 132 /* SCTP message. */ +#define NEXTHDR_MOBILITY 135 /* Mobility header. */ + +#define NEXTHDR_MAX 255 + +static __always_inline int ipv6_optlen(const struct ipv6_opt_hdr *opthdr) +{ + return (opthdr->hdrlen + 1) << 3; +} + +static __always_inline int ipv6_authlen(const struct ipv6_opt_hdr *opthdr) +{ + return (opthdr->hdrlen + 2) << 2; +} + +static __always_inline int ipv6_hdrlen(struct __ctx_buff *ctx, int l3_off, + __u8 *nexthdr) +{ + int i, len = sizeof(struct ipv6hdr); + struct ipv6_opt_hdr opthdr __align_stack_8; + __u8 nh = *nexthdr; + +#pragma unroll + for (i = 0; i < IPV6_MAX_HEADERS; i++) { + switch (nh) { + case NEXTHDR_NONE: + return DROP_INVALID_EXTHDR; + + case NEXTHDR_FRAGMENT: + return DROP_FRAG_NOSUPPORT; + + case NEXTHDR_HOP: + case NEXTHDR_ROUTING: + case NEXTHDR_AUTH: + case NEXTHDR_DEST: + if (ctx_load_bytes(ctx, l3_off + len, &opthdr, sizeof(opthdr)) < 0) + return DROP_INVALID; + + nh = opthdr.nexthdr; + if (nh == NEXTHDR_AUTH) + len += ipv6_authlen(&opthdr); + else + len += ipv6_optlen(&opthdr); + break; + + default: + *nexthdr = nh; + return len; + } + } + + /* Reached limit of supported extension headers */ + return DROP_INVALID_EXTHDR; +} + +static __always_inline void ipv6_addr_copy(union v6addr *dst, + const union v6addr *src) +{ + dst->d1 = src->d1; + dst->d2 = src->d2; +} + +static __always_inline __u64 ipv6_addrcmp(const union v6addr *a, + const union v6addr *b) +{ + __u64 tmp; + + tmp = a->d1 - b->d1; + if (!tmp) + tmp = a->d2 - b->d2; + return tmp; +} + +/* Only works with contiguous masks. */ +static __always_inline int ipv6_addr_in_net(const union v6addr *addr, + const union v6addr *net, + const union v6addr *mask) +{ + return ((addr->p1 & mask->p1) == net->p1) + && (!mask->p2 + || (((addr->p2 & mask->p2) == net->p2) + && (!mask->p3 + || (((addr->p3 & mask->p3) == net->p3) + && (!mask->p4 || ((addr->p4 & mask->p4) == net->p4)))))); +} + +#define GET_PREFIX(PREFIX) \ + bpf_htonl(PREFIX <= 0 ? 0 : PREFIX < 32 ? ((1<p1 &= GET_PREFIX(prefix); + prefix -= 32; + addr->p2 &= GET_PREFIX(prefix); + prefix -= 32; + addr->p3 &= GET_PREFIX(prefix); + prefix -= 32; + addr->p4 &= GET_PREFIX(prefix); +} + +static __always_inline int ipv6_match_prefix_64(const union v6addr *addr, + const union v6addr *prefix) +{ + int tmp; + + tmp = addr->p1 - prefix->p1; + if (!tmp) + tmp = addr->p2 - prefix->p2; + + return !tmp; +} + +static __always_inline int ipv6_dec_hoplimit(struct __ctx_buff *ctx, int off) +{ + __u8 hl; + + if (ctx_load_bytes(ctx, off + offsetof(struct ipv6hdr, hop_limit), + &hl, sizeof(hl)) < 0) + return DROP_INVALID; + + if (hl <= 1) + return 1; + hl--; + if (ctx_store_bytes(ctx, off + offsetof(struct ipv6hdr, hop_limit), + &hl, sizeof(hl), BPF_F_RECOMPUTE_CSUM) < 0) + return DROP_WRITE_ERROR; + return 0; +} + +static __always_inline int ipv6_load_saddr(struct __ctx_buff *ctx, int off, + union v6addr *dst) +{ + return ctx_load_bytes(ctx, off + offsetof(struct ipv6hdr, saddr), dst->addr, + sizeof(((struct ipv6hdr *)NULL)->saddr)); +} + +/* Assumes that caller fixes checksum csum_diff() and l4_csum_replace() */ +static __always_inline int ipv6_store_saddr(struct __ctx_buff *ctx, __u8 *addr, + int off) +{ + return ctx_store_bytes(ctx, off + offsetof(struct ipv6hdr, saddr), addr, 16, 0); +} + +static __always_inline int ipv6_load_daddr(struct __ctx_buff *ctx, int off, + union v6addr *dst) +{ + return ctx_load_bytes(ctx, off + offsetof(struct ipv6hdr, daddr), dst->addr, + sizeof(((struct ipv6hdr *)NULL)->daddr)); +} + +/* Assumes that caller fixes checksum csum_diff() and l4_csum_replace() */ +static __always_inline int ipv6_store_daddr(struct __ctx_buff *ctx, __u8 *addr, + int off) +{ + return ctx_store_bytes(ctx, off + offsetof(struct ipv6hdr, daddr), addr, 16, 0); +} + +static __always_inline int ipv6_load_nexthdr(struct __ctx_buff *ctx, int off, + __u8 *nexthdr) +{ + return ctx_load_bytes(ctx, off + offsetof(struct ipv6hdr, nexthdr), nexthdr, + sizeof(__u8)); +} + +/* Assumes that caller fixes checksum csum_diff() and l4_csum_replace() */ +static __always_inline int ipv6_store_nexthdr(struct __ctx_buff *ctx, __u8 *nexthdr, + int off) +{ + return ctx_store_bytes(ctx, off + offsetof(struct ipv6hdr, nexthdr), nexthdr, + sizeof(__u8), 0); +} + +static __always_inline int ipv6_load_paylen(struct __ctx_buff *ctx, int off, + __be16 *len) +{ + return ctx_load_bytes(ctx, off + offsetof(struct ipv6hdr, payload_len), + len, sizeof(*len)); +} + +/* Assumes that caller fixes checksum csum_diff() and l4_csum_replace() */ +static __always_inline int ipv6_store_paylen(struct __ctx_buff *ctx, int off, + __be16 *len) +{ + return ctx_store_bytes(ctx, off + offsetof(struct ipv6hdr, payload_len), + len, sizeof(*len), 0); +} + +static __always_inline int ipv6_store_flowlabel(struct __ctx_buff *ctx, int off, + __be32 label) +{ + __be32 old; + + /* use traffic class from packet */ + if (ctx_load_bytes(ctx, off, &old, 4) < 0) + return DROP_INVALID; + + old &= IPV6_TCLASS_MASK; + old = bpf_htonl(0x60000000) | label | old; + + if (ctx_store_bytes(ctx, off, &old, 4, BPF_F_RECOMPUTE_CSUM) < 0) + return DROP_WRITE_ERROR; + + return 0; +} + +static __always_inline __be32 ipv6_pseudohdr_checksum(struct ipv6hdr *hdr, + __u8 next_hdr, + __u16 payload_len, __be32 sum) +{ + __be32 len = bpf_htonl((__u32)payload_len); + __be32 nexthdr = bpf_htonl((__u32)next_hdr); + + sum = csum_diff(NULL, 0, &hdr->saddr, sizeof(struct in6_addr), sum); + sum = csum_diff(NULL, 0, &hdr->daddr, sizeof(struct in6_addr), sum); + sum = csum_diff(NULL, 0, &len, sizeof(len), sum); + sum = csum_diff(NULL, 0, &nexthdr, sizeof(nexthdr), sum); + + return sum; +} + +/* + * Ipv4 mapped address - 0:0:0:0:0:FFFF::/96 + */ +static __always_inline int ipv6_addr_is_mapped(const union v6addr *addr) +{ + return addr->p1 == 0 && addr->p2 == 0 && addr->p3 == 0xFFFF0000; +} +#endif /* __LIB_IPV6__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/jhash.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/jhash.h new file mode 100644 index 000000000..1fdfec7e1 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/jhash.h @@ -0,0 +1,109 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2006 Bob Jenkins */ +/* Copyright (C) 2006-2020 Authors of the Linux kernel */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __JHASH_H_ +#define __JHASH_H_ + +#include +#include + +#define JHASH_INITVAL 0xdeadbeef + +static __always_inline __u32 rol32(__u32 word, __u32 shift) +{ + return (word << shift) | (word >> ((-shift) & 31)); +} + +#define __jhash_mix(a, b, c) \ +{ \ + a -= c; a ^= rol32(c, 4); c += b; \ + b -= a; b ^= rol32(a, 6); a += c; \ + c -= b; c ^= rol32(b, 8); b += a; \ + a -= c; a ^= rol32(c, 16); c += b; \ + b -= a; b ^= rol32(a, 19); a += c; \ + c -= b; c ^= rol32(b, 4); b += a; \ +} + +#define __jhash_final(a, b, c) \ +{ \ + c ^= b; c -= rol32(b, 14); \ + a ^= c; a -= rol32(c, 11); \ + b ^= a; b -= rol32(a, 25); \ + c ^= b; c -= rol32(b, 16); \ + a ^= c; a -= rol32(c, 4); \ + b ^= a; b -= rol32(a, 14); \ + c ^= b; c -= rol32(b, 24); \ +} + +static __always_inline __u32 jhash(const void *key, __u32 length, + __u32 initval) +{ + const unsigned char *k = key; + __u32 a, b, c; + + if (!__builtin_constant_p(length)) + __throw_build_bug(); + + a = b = c = JHASH_INITVAL + length + initval; + + while (length > 12) { + a += *(__u32 *)(k); + b += *(__u32 *)(k + 4); + c += *(__u32 *)(k + 8); + + __jhash_mix(a, b, c); + length -= 12; + k += 12; + } + + switch (length) { + case 12: c += (__u32)k[11] << 24; + case 11: c += (__u32)k[10] << 16; + case 10: c += (__u32)k[9] << 8; + case 9: c += (__u32)k[8]; + case 8: b += (__u32)k[7] << 24; + case 7: b += (__u32)k[6] << 16; + case 6: b += (__u32)k[5] << 8; + case 5: b += (__u32)k[4]; + case 4: a += (__u32)k[3] << 24; + case 3: a += (__u32)k[2] << 16; + case 2: a += (__u32)k[1] << 8; + case 1: a += (__u32)k[0]; + + __jhash_final(a, b, c); + case 0: /* Nothing left to add */ + break; + } + + return c; +} + +static __always_inline __u32 __jhash_nwords(__u32 a, __u32 b, __u32 c, + __u32 initval) +{ + a += initval; + b += initval; + c += initval; + __jhash_final(a, b, c); + return c; +} + +static __always_inline __u32 jhash_3words(__u32 a, __u32 b, __u32 c, + __u32 initval) +{ + return __jhash_nwords(a, b, c, initval + JHASH_INITVAL + (3 << 2)); +} + +static __always_inline __u32 jhash_2words(__u32 a, __u32 b, __u32 initval) +{ + return __jhash_nwords(a, b, 0, initval + JHASH_INITVAL + (2 << 2)); +} + +static __always_inline __u32 jhash_1word(__u32 a, __u32 initval) +{ + return __jhash_nwords(a, 0, 0, initval + JHASH_INITVAL + (1 << 2)); +} + +#endif /* __JHASH_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/l3.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/l3.h new file mode 100644 index 000000000..4fbbed4ca --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/l3.h @@ -0,0 +1,188 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_L3_H_ +#define __LIB_L3_H_ + +#include "common.h" +#include "ipv6.h" +#include "ipv4.h" +#include "eps.h" +#include "eth.h" +#include "dbg.h" +#include "l4.h" +#include "icmp6.h" +#include "csum.h" + +#ifdef ENABLE_IPV6 +static __always_inline int ipv6_l3(struct __ctx_buff *ctx, int l3_off, + const __u8 *smac, const __u8 *dmac, + __u8 direction) +{ + int ret; + + ret = ipv6_dec_hoplimit(ctx, l3_off); + if (IS_ERR(ret)) + return ret; + if (ret > 0) { + /* Hoplimit was reached */ + return icmp6_send_time_exceeded(ctx, l3_off, direction); + } + + if (smac && eth_store_saddr(ctx, smac, 0) < 0) + return DROP_WRITE_ERROR; + if (dmac && eth_store_daddr(ctx, dmac, 0) < 0) + return DROP_WRITE_ERROR; + + return CTX_ACT_OK; +} +#endif /* ENABLE_IPV6 */ + +static __always_inline int ipv4_l3(struct __ctx_buff *ctx, int l3_off, + const __u8 *smac, const __u8 *dmac, + struct iphdr *ip4) +{ + if (ipv4_dec_ttl(ctx, l3_off, ip4)) { + /* FIXME: Send ICMP TTL */ + return DROP_INVALID; + } + + if (smac && eth_store_saddr(ctx, smac, 0) < 0) + return DROP_WRITE_ERROR; + if (dmac && eth_store_daddr(ctx, dmac, 0) < 0) + return DROP_WRITE_ERROR; + + return CTX_ACT_OK; +} + +#ifndef SKIP_POLICY_MAP +#ifdef ENABLE_IPV6 +/* Performs IPv6 L2/L3 handling and delivers the packet to the destination pod + * on the same node, either via the stack or via a redirect call. + * Depending on the configuration, it may also enforce ingress policies for the + * destination pod via a tail call. + */ +static __always_inline int ipv6_local_delivery(struct __ctx_buff *ctx, int l3_off, + __u32 seclabel, + const struct endpoint_info *ep, + __u8 direction, + bool from_host __maybe_unused) +{ + mac_t router_mac = ep->node_mac; + mac_t lxc_mac = ep->mac; + int ret; + + cilium_dbg(ctx, DBG_LOCAL_DELIVERY, ep->lxc_id, seclabel); + + /* This will invalidate the size check */ + ret = ipv6_l3(ctx, l3_off, (__u8 *) &router_mac, (__u8 *) &lxc_mac, direction); + if (ret != CTX_ACT_OK) + return ret; + +#ifdef LOCAL_DELIVERY_METRICS + /* + * Special LXC case for updating egress forwarding metrics. + * Note that the packet could still be dropped but it would show up + * as an ingress drop counter in metrics. + */ + update_metrics(ctx_full_len(ctx), direction, REASON_FORWARDED); +#endif + +#if defined(USE_BPF_PROG_FOR_INGRESS_POLICY) && \ + !defined(FORCE_LOCAL_POLICY_EVAL_AT_SOURCE) + ctx->mark |= MARK_MAGIC_IDENTITY; + set_identity_mark(ctx, seclabel); + + return redirect_ep(ctx, ep->ifindex, from_host); +#else + /* Jumps to destination pod's BPF program to enforce ingress policies. */ + ctx_store_meta(ctx, CB_SRC_LABEL, seclabel); + ctx_store_meta(ctx, CB_IFINDEX, ep->ifindex); + ctx_store_meta(ctx, CB_FROM_HOST, from_host ? 1 : 0); + + tail_call_dynamic(ctx, &POLICY_CALL_MAP, ep->lxc_id); + return DROP_MISSED_TAIL_CALL; +#endif +} +#endif /* ENABLE_IPV6 */ + +/* Performs IPv4 L2/L3 handling and delivers the packet to the destination pod + * on the same node, either via the stack or via a redirect call. + * Depending on the configuration, it may also enforce ingress policies for the + * destination pod via a tail call. + */ +static __always_inline int ipv4_local_delivery(struct __ctx_buff *ctx, int l3_off, + __u32 seclabel, struct iphdr *ip4, + const struct endpoint_info *ep, + __u8 direction __maybe_unused, + bool from_host __maybe_unused) +{ + mac_t router_mac = ep->node_mac; + mac_t lxc_mac = ep->mac; + int ret; + + cilium_dbg(ctx, DBG_LOCAL_DELIVERY, ep->lxc_id, seclabel); + + ret = ipv4_l3(ctx, l3_off, (__u8 *) &router_mac, (__u8 *) &lxc_mac, ip4); + if (ret != CTX_ACT_OK) + return ret; + +#ifdef LOCAL_DELIVERY_METRICS + /* + * Special LXC case for updating egress forwarding metrics. + * Note that the packet could still be dropped but it would show up + * as an ingress drop counter in metrics. + */ + update_metrics(ctx_full_len(ctx), direction, REASON_FORWARDED); +#endif + +#if defined(USE_BPF_PROG_FOR_INGRESS_POLICY) && \ + !defined(FORCE_LOCAL_POLICY_EVAL_AT_SOURCE) + ctx->mark |= MARK_MAGIC_IDENTITY; + set_identity_mark(ctx, seclabel); + + return redirect_ep(ctx, ep->ifindex, from_host); +#else + /* Jumps to destination pod's BPF program to enforce ingress policies. */ + ctx_store_meta(ctx, CB_SRC_LABEL, seclabel); + ctx_store_meta(ctx, CB_IFINDEX, ep->ifindex); + ctx_store_meta(ctx, CB_FROM_HOST, from_host ? 1 : 0); + + tail_call_dynamic(ctx, &POLICY_CALL_MAP, ep->lxc_id); + return DROP_MISSED_TAIL_CALL; +#endif +} +#endif /* SKIP_POLICY_MAP */ + +static __always_inline __u8 get_encrypt_key(__u32 ctx) +{ + struct encrypt_key key = {.ctx = ctx}; + struct encrypt_config *cfg; + + cfg = map_lookup_elem(&ENCRYPT_MAP, &key); + /* Having no key info for a context is the same as no encryption */ + if (!cfg) + return 0; + return cfg->encrypt_key; +} + +static __always_inline __u8 get_min_encrypt_key(__u8 peer_key) +{ + __u8 local_key = get_encrypt_key(0); + + /* If both ends can encrypt/decrypt use smaller of the two this + * way both ends will have keys installed assuming key IDs are + * always increasing. However, we have to handle roll-over case + * and to do this safely we assume keys are no more than one ahead. + * We expect user/control-place to accomplish this. Notice zero + * will always be returned if either local or peer have the zero + * key indicating no encryption. + */ + if (peer_key == MAX_KEY_INDEX) + return local_key == 1 ? peer_key : local_key; + if (local_key == MAX_KEY_INDEX) + return peer_key == 1 ? local_key : peer_key; + return local_key < peer_key ? local_key : peer_key; +} + +#endif diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/l4.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/l4.h new file mode 100644 index 000000000..6cae7a5fc --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/l4.h @@ -0,0 +1,54 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_L4_H_ +#define __LIB_L4_H_ + +#include +#include +#include "common.h" +#include "dbg.h" +#include "csum.h" + +#define TCP_DPORT_OFF (offsetof(struct tcphdr, dest)) +#define TCP_SPORT_OFF (offsetof(struct tcphdr, source)) +#define UDP_DPORT_OFF (offsetof(struct udphdr, dest)) +#define UDP_SPORT_OFF (offsetof(struct udphdr, source)) + + +/** + * Modify L4 port and correct checksum + * @arg ctx: packet + * @arg l4_off: offset to L4 header + * @arg off: offset from L4 header to source or destination port + * @arg csum_off: offset from L4 header to 16bit checksum field in L4 header + * @arg port: new port value + * @arg old_port: old port value (for checksum correction) + * + * Overwrites a TCP or UDP port with new value and fixes up the checksum + * in the L4 header and of ctx->csum. + * + * NOTE: Calling this function will invalidate any pkt context offset + * validation for direct packet access. + * + * Return 0 on success or a negative DROP_* reason + */ +static __always_inline int l4_modify_port(struct __ctx_buff *ctx, int l4_off, + int off, struct csum_offset *csum_off, + __be16 port, __be16 old_port) +{ + if (csum_l4_replace(ctx, l4_off, csum_off, old_port, port, sizeof(port)) < 0) + return DROP_CSUM_L4; + + if (ctx_store_bytes(ctx, l4_off + off, &port, sizeof(port), 0) < 0) + return DROP_WRITE_ERROR; + + return 0; +} + +static __always_inline int l4_load_port(struct __ctx_buff *ctx, int off, + __be16 *port) +{ + return ctx_load_bytes(ctx, off, port, sizeof(__be16)); +} +#endif diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/lb.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/lb.h new file mode 100644 index 000000000..312fda550 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/lb.h @@ -0,0 +1,1491 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LB_H_ +#define __LB_H_ + +#include "csum.h" +#include "conntrack.h" +#include "ipv4.h" +#include "hash.h" +#include "ids.h" + +#ifdef ENABLE_IPV6 +struct bpf_elf_map __section_maps LB6_REVERSE_NAT_MAP = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(__u16), + .size_value = sizeof(struct lb6_reverse_nat), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, + .flags = CONDITIONAL_PREALLOC, +}; + +struct bpf_elf_map __section_maps LB6_SERVICES_MAP_V2 = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(struct lb6_key), + .size_value = sizeof(struct lb6_service), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, + .flags = CONDITIONAL_PREALLOC, +}; + +struct bpf_elf_map __section_maps LB6_BACKEND_MAP = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(__u16), + .size_value = sizeof(struct lb6_backend), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, + .flags = CONDITIONAL_PREALLOC, +}; + +#ifdef ENABLE_SESSION_AFFINITY +struct bpf_elf_map __section_maps LB6_AFFINITY_MAP = { + .type = BPF_MAP_TYPE_LRU_HASH, + .size_key = sizeof(struct lb6_affinity_key), + .size_value = sizeof(struct lb_affinity_val), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, +}; +#endif + +#ifdef ENABLE_SRC_RANGE_CHECK +struct bpf_elf_map __section_maps LB6_SRC_RANGE_MAP = { + .type = BPF_MAP_TYPE_LPM_TRIE, + .size_key = sizeof(struct lb6_src_range_key), + .size_value = sizeof(__u8), + .pinning = PIN_GLOBAL_NS, + .max_elem = LB6_SRC_RANGE_MAP_SIZE, + .flags = BPF_F_NO_PREALLOC, +}; +#endif + +#ifdef ENABLE_HEALTH_CHECK +struct bpf_elf_map __section_maps LB6_HEALTH_MAP = { + .type = BPF_MAP_TYPE_LRU_HASH, + .size_key = sizeof(__sock_cookie), + .size_value = sizeof(struct lb6_health), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, +}; +#endif + +#if LB_SELECTION == LB_SELECTION_MAGLEV +struct bpf_elf_map __section_maps LB6_MAGLEV_MAP_INNER = { + .type = BPF_MAP_TYPE_ARRAY, + .size_key = sizeof(__u32), + .size_value = sizeof(__u16) * LB_MAGLEV_LUT_SIZE, + .pinning = PIN_NONE, + .max_elem = 1, + .inner_idx = NO_PREPOPULATE, + .id = CILIUM_MAP_MAGLEV6, +}; + +struct bpf_elf_map __section_maps LB6_MAGLEV_MAP_OUTER = { + .type = BPF_MAP_TYPE_HASH_OF_MAPS, + .size_key = sizeof(__u16), + .size_value = sizeof(__u32), + .pinning = PIN_GLOBAL_NS, + .inner_id = CILIUM_MAP_MAGLEV6, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, + .flags = CONDITIONAL_PREALLOC, +}; +#endif /* LB_SELECTION == LB_SELECTION_MAGLEV */ +#endif /* ENABLE_IPV6 */ + +#ifdef ENABLE_IPV4 +struct bpf_elf_map __section_maps LB4_REVERSE_NAT_MAP = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(__u16), + .size_value = sizeof(struct lb4_reverse_nat), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, + .flags = CONDITIONAL_PREALLOC, +}; + +struct bpf_elf_map __section_maps LB4_SERVICES_MAP_V2 = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(struct lb4_key), + .size_value = sizeof(struct lb4_service), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, + .flags = CONDITIONAL_PREALLOC, +}; + +struct bpf_elf_map __section_maps LB4_BACKEND_MAP = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(__u16), + .size_value = sizeof(struct lb4_backend), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, + .flags = CONDITIONAL_PREALLOC, +}; + +#ifdef ENABLE_SESSION_AFFINITY +struct bpf_elf_map __section_maps LB4_AFFINITY_MAP = { + .type = BPF_MAP_TYPE_LRU_HASH, + .size_key = sizeof(struct lb4_affinity_key), + .size_value = sizeof(struct lb_affinity_val), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, +}; +#endif + +#ifdef ENABLE_SRC_RANGE_CHECK +struct bpf_elf_map __section_maps LB4_SRC_RANGE_MAP = { + .type = BPF_MAP_TYPE_LPM_TRIE, + .size_key = sizeof(struct lb4_src_range_key), + .size_value = sizeof(__u8), + .pinning = PIN_GLOBAL_NS, + .max_elem = LB4_SRC_RANGE_MAP_SIZE, + .flags = BPF_F_NO_PREALLOC, +}; +#endif + +#ifdef ENABLE_HEALTH_CHECK +struct bpf_elf_map __section_maps LB4_HEALTH_MAP = { + .type = BPF_MAP_TYPE_LRU_HASH, + .size_key = sizeof(__sock_cookie), + .size_value = sizeof(struct lb4_health), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, +}; +#endif + +#if LB_SELECTION == LB_SELECTION_MAGLEV +struct bpf_elf_map __section_maps LB4_MAGLEV_MAP_INNER = { + .type = BPF_MAP_TYPE_ARRAY, + .size_key = sizeof(__u32), + .size_value = sizeof(__u16) * LB_MAGLEV_LUT_SIZE, + .pinning = PIN_NONE, + .max_elem = 1, + .inner_idx = NO_PREPOPULATE, + .id = CILIUM_MAP_MAGLEV4, +}; + +struct bpf_elf_map __section_maps LB4_MAGLEV_MAP_OUTER = { + .type = BPF_MAP_TYPE_HASH_OF_MAPS, + .size_key = sizeof(__u16), + .size_value = sizeof(__u32), + .pinning = PIN_GLOBAL_NS, + .inner_id = CILIUM_MAP_MAGLEV4, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, + .flags = CONDITIONAL_PREALLOC, +}; +#endif /* LB_SELECTION == LB_SELECTION_MAGLEV */ +#endif /* ENABLE_IPV4 */ + +#ifdef ENABLE_SESSION_AFFINITY +struct bpf_elf_map __section_maps LB_AFFINITY_MATCH_MAP = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(struct lb_affinity_match), + .size_value = sizeof(__u8), /* dummy value, map is used as a set */ + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_LB_MAP_MAX_ENTRIES, + .flags = CONDITIONAL_PREALLOC, +}; +#endif + +#define REV_NAT_F_TUPLE_SADDR 1 +#ifndef DSR_XLATE_MODE +# define DSR_XLATE_MODE 0 +# define DSR_XLATE_FRONTEND 1 +#endif +#ifdef LB_DEBUG +#define cilium_dbg_lb cilium_dbg +#else +#define cilium_dbg_lb(a, b, c, d) +#endif + +static __always_inline +bool lb4_svc_is_loadbalancer(const struct lb4_service *svc __maybe_unused) +{ +#ifdef ENABLE_LOADBALANCER + return svc->flags & SVC_FLAG_LOADBALANCER; +#else + return false; +#endif /* ENABLE_LOADBALANCER */ +} + +static __always_inline +bool lb6_svc_is_loadbalancer(const struct lb6_service *svc __maybe_unused) +{ +#ifdef ENABLE_LOADBALANCER + return svc->flags & SVC_FLAG_LOADBALANCER; +#else + return false; +#endif /* ENABLE_LOADBALANCER */ +} + +static __always_inline +bool lb4_svc_is_nodeport(const struct lb4_service *svc __maybe_unused) +{ +#ifdef ENABLE_NODEPORT + return svc->flags & SVC_FLAG_NODEPORT; +#else + return false; +#endif /* ENABLE_NODEPORT */ +} + +static __always_inline +bool lb6_svc_is_nodeport(const struct lb6_service *svc __maybe_unused) +{ +#ifdef ENABLE_NODEPORT + return svc->flags & SVC_FLAG_NODEPORT; +#else + return false; +#endif /* ENABLE_NODEPORT */ +} + +static __always_inline +bool lb4_svc_is_external_ip(const struct lb4_service *svc __maybe_unused) +{ +#ifdef ENABLE_EXTERNAL_IP + return svc->flags & SVC_FLAG_EXTERNAL_IP; +#else + return false; +#endif +} + +static __always_inline +bool lb6_svc_is_external_ip(const struct lb6_service *svc __maybe_unused) +{ +#ifdef ENABLE_EXTERNAL_IP + return svc->flags & SVC_FLAG_EXTERNAL_IP; +#else + return false; +#endif +} + +static __always_inline +bool lb4_svc_is_hostport(const struct lb4_service *svc __maybe_unused) +{ +#ifdef ENABLE_HOSTPORT + return svc->flags & SVC_FLAG_HOSTPORT; +#else + return false; +#endif /* ENABLE_HOSTPORT */ +} + +static __always_inline +bool lb6_svc_is_hostport(const struct lb6_service *svc __maybe_unused) +{ +#ifdef ENABLE_HOSTPORT + return svc->flags & SVC_FLAG_HOSTPORT; +#else + return false; +#endif /* ENABLE_HOSTPORT */ +} + +static __always_inline +bool lb4_svc_has_src_range_check(const struct lb4_service *svc __maybe_unused) +{ +#ifdef ENABLE_SRC_RANGE_CHECK + return svc->flags & SVC_FLAG_SOURCE_RANGE; +#else + return false; +#endif /* ENABLE_SRC_RANGE_CHECK */ +} + +static __always_inline +bool lb6_svc_has_src_range_check(const struct lb6_service *svc __maybe_unused) +{ +#ifdef ENABLE_SRC_RANGE_CHECK + return svc->flags & SVC_FLAG_SOURCE_RANGE; +#else + return false; +#endif /* ENABLE_SRC_RANGE_CHECK */ +} + +static __always_inline bool lb_skip_l4_dnat(void) +{ + return DSR_XLATE_MODE == DSR_XLATE_FRONTEND; +} + +static __always_inline +bool lb4_svc_is_local_scope(const struct lb4_service *svc) +{ + return svc->flags & SVC_FLAG_LOCAL_SCOPE; +} + +static __always_inline +bool lb6_svc_is_local_scope(const struct lb6_service *svc) +{ + return svc->flags & SVC_FLAG_LOCAL_SCOPE; +} + +static __always_inline +bool lb4_svc_is_affinity(const struct lb4_service *svc) +{ + return svc->flags & SVC_FLAG_AFFINITY; +} + +static __always_inline +bool lb6_svc_is_affinity(const struct lb6_service *svc) +{ + return svc->flags & SVC_FLAG_AFFINITY; +} + +static __always_inline bool __lb_svc_is_routable(__u8 flags) +{ + return (flags & SVC_FLAG_ROUTABLE) != 0; +} + +static __always_inline +bool lb4_svc_is_routable(const struct lb4_service *svc) +{ + return __lb_svc_is_routable(svc->flags); +} + +static __always_inline +bool lb6_svc_is_routable(const struct lb6_service *svc) +{ + return __lb_svc_is_routable(svc->flags); +} + +static __always_inline +bool lb4_svc_is_localredirect(const struct lb4_service *svc __maybe_unused) +{ + return svc->flags2 & SVC_FLAG_LOCALREDIRECT; +} + +static __always_inline int extract_l4_port(struct __ctx_buff *ctx, __u8 nexthdr, + int l4_off, + int dir __maybe_unused, + __be16 *port, + __maybe_unused struct iphdr *ip4) +{ + int ret; + + switch (nexthdr) { + case IPPROTO_TCP: + case IPPROTO_UDP: +#ifdef ENABLE_IPV4_FRAGMENTS + if (ip4) { + struct ipv4_frag_l4ports ports = { }; + + ret = ipv4_handle_fragmentation(ctx, ip4, l4_off, + dir, &ports, NULL); + if (IS_ERR(ret)) + return ret; + *port = ports.dport; + break; + } +#endif + /* Port offsets for UDP and TCP are the same */ + ret = l4_load_port(ctx, l4_off + TCP_DPORT_OFF, port); + if (IS_ERR(ret)) + return ret; + break; + + case IPPROTO_ICMPV6: + case IPPROTO_ICMP: + /* No need to perform a service lookup for ICMP packets */ + return DROP_NO_SERVICE; + + default: + /* Pass unknown L4 to stack */ + return DROP_UNKNOWN_L4; + } + + return 0; +} + +static __always_inline int reverse_map_l4_port(struct __ctx_buff *ctx, __u8 nexthdr, + __be16 port, int l4_off, + struct csum_offset *csum_off) +{ + switch (nexthdr) { + case IPPROTO_TCP: + case IPPROTO_UDP: + if (port) { + __be16 old_port; + int ret; + + /* Port offsets for UDP and TCP are the same */ + ret = l4_load_port(ctx, l4_off + TCP_SPORT_OFF, &old_port); + if (IS_ERR(ret)) + return ret; + + if (port != old_port) { + ret = l4_modify_port(ctx, l4_off, TCP_SPORT_OFF, + csum_off, port, old_port); + if (IS_ERR(ret)) + return ret; + } + } + break; + + case IPPROTO_ICMPV6: + case IPPROTO_ICMP: + return CTX_ACT_OK; + + default: + return DROP_UNKNOWN_L4; + } + + return 0; +} + +#ifdef ENABLE_IPV6 +static __always_inline int __lb6_rev_nat(struct __ctx_buff *ctx, int l4_off, + struct csum_offset *csum_off, + struct ipv6_ct_tuple *tuple, int flags, + struct lb6_reverse_nat *nat) +{ + union v6addr old_saddr; + union v6addr tmp; + __u8 *new_saddr; + __be32 sum; + int ret; + + cilium_dbg_lb(ctx, DBG_LB6_REVERSE_NAT, nat->address.p4, nat->port); + + if (nat->port) { + ret = reverse_map_l4_port(ctx, tuple->nexthdr, nat->port, l4_off, csum_off); + if (IS_ERR(ret)) + return ret; + } + + if (flags & REV_NAT_F_TUPLE_SADDR) { + ipv6_addr_copy(&old_saddr, &tuple->saddr); + ipv6_addr_copy(&tuple->saddr, &nat->address); + new_saddr = tuple->saddr.addr; + } else { + if (ipv6_load_saddr(ctx, ETH_HLEN, &old_saddr) < 0) + return DROP_INVALID; + + ipv6_addr_copy(&tmp, &nat->address); + new_saddr = tmp.addr; + } + + ret = ipv6_store_saddr(ctx, new_saddr, ETH_HLEN); + if (IS_ERR(ret)) + return DROP_WRITE_ERROR; + + sum = csum_diff(old_saddr.addr, 16, new_saddr, 16, 0); + if (csum_l4_replace(ctx, l4_off, csum_off, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + + return 0; +} + +/** Perform IPv6 reverse NAT based on reverse NAT index + * @arg ctx packet + * @arg l4_off offset to L4 + * @arg csum_off offset to L4 checksum field + * @arg csum_flags checksum flags + * @arg index reverse NAT index + * @arg tuple tuple + * @arg saddr_tuple If set, tuple address will be updated with new source address + */ +static __always_inline int lb6_rev_nat(struct __ctx_buff *ctx, int l4_off, + struct csum_offset *csum_off, __u16 index, + struct ipv6_ct_tuple *tuple, int flags) +{ + struct lb6_reverse_nat *nat; + + cilium_dbg_lb(ctx, DBG_LB6_REVERSE_NAT_LOOKUP, index, 0); + nat = map_lookup_elem(&LB6_REVERSE_NAT_MAP, &index); + if (nat == NULL) + return 0; + + return __lb6_rev_nat(ctx, l4_off, csum_off, tuple, flags, nat); +} + +/** Extract IPv6 LB key from packet + * @arg ctx Packet + * @arg tuple Tuple + * @arg l4_off Offset to L4 header + * @arg key Pointer to store LB key in + * @arg csum_off Pointer to store L4 checksum field offset and flags + * @arg dir Flow direction + * + * Expects the ctx to be validated for direct packet access up to L4. Fills + * lb6_key based on L4 nexthdr. + * + * Returns: + * - CTX_ACT_OK on successful extraction + * - DROP_UNKNOWN_L4 if packet should be ignore (sent to stack) + * - Negative error code + */ +static __always_inline int lb6_extract_key(struct __ctx_buff *ctx __maybe_unused, + struct ipv6_ct_tuple *tuple, + int l4_off __maybe_unused, + struct lb6_key *key, + struct csum_offset *csum_off, + int dir) +{ + union v6addr *addr; + /* FIXME(brb): set after adding support for different L4 protocols in LB */ + key->proto = 0; + addr = (dir == CT_INGRESS) ? &tuple->saddr : &tuple->daddr; + ipv6_addr_copy(&key->address, addr); + csum_l4_offset_and_flags(tuple->nexthdr, csum_off); + + return extract_l4_port(ctx, tuple->nexthdr, l4_off, dir, &key->dport, + NULL); +} + +static __always_inline +bool lb6_src_range_ok(const struct lb6_service *svc __maybe_unused, + const union v6addr *saddr __maybe_unused) +{ +#ifdef ENABLE_SRC_RANGE_CHECK + struct lb6_src_range_key key; + + if (!lb6_svc_has_src_range_check(svc)) + return true; + + key = (typeof(key)) { + .lpm_key = { SRC_RANGE_STATIC_PREFIX(key), {} }, + .rev_nat_id = svc->rev_nat_index, + .addr = *saddr, + }; + + if (map_lookup_elem(&LB6_SRC_RANGE_MAP, &key)) + return true; + + return false; +#else + return true; +#endif /* ENABLE_SRC_RANGE_CHECK */ +} + +static __always_inline +struct lb6_service *lb6_lookup_service(struct lb6_key *key, + const bool scope_switch) +{ + struct lb6_service *svc; + + key->scope = LB_LOOKUP_SCOPE_EXT; + key->backend_slot = 0; + svc = map_lookup_elem(&LB6_SERVICES_MAP_V2, key); + if (svc) { + if (!scope_switch || !lb6_svc_is_local_scope(svc)) + return svc->count ? svc : NULL; + key->scope = LB_LOOKUP_SCOPE_INT; + svc = map_lookup_elem(&LB6_SERVICES_MAP_V2, key); + if (svc && svc->count) + return svc; + } + + return NULL; +} + +static __always_inline struct lb6_backend *__lb6_lookup_backend(__u16 backend_id) +{ + return map_lookup_elem(&LB6_BACKEND_MAP, &backend_id); +} + +static __always_inline struct lb6_backend * +lb6_lookup_backend(struct __ctx_buff *ctx __maybe_unused, __u16 backend_id) +{ + struct lb6_backend *backend; + + backend = __lb6_lookup_backend(backend_id); + if (!backend) + cilium_dbg_lb(ctx, DBG_LB6_LOOKUP_BACKEND_FAIL, backend_id, 0); + + return backend; +} + +static __always_inline +struct lb6_service *__lb6_lookup_backend_slot(struct lb6_key *key) +{ + return map_lookup_elem(&LB6_SERVICES_MAP_V2, key); +} + +static __always_inline +struct lb6_service *lb6_lookup_backend_slot(struct __ctx_buff *ctx __maybe_unused, + struct lb6_key *key, __u16 slot) +{ + struct lb6_service *svc; + + key->backend_slot = slot; + cilium_dbg_lb(ctx, DBG_LB6_LOOKUP_BACKEND_SLOT, key->backend_slot, key->dport); + svc = __lb6_lookup_backend_slot(key); + if (svc) + return svc; + + cilium_dbg_lb(ctx, DBG_LB6_LOOKUP_BACKEND_SLOT_V2_FAIL, key->backend_slot, key->dport); + + return NULL; +} + +/* Backend slot 0 is always reserved for the service frontend. */ +#if LB_SELECTION == LB_SELECTION_RANDOM +static __always_inline __u16 +lb6_select_backend_id(struct __ctx_buff *ctx, + struct lb6_key *key, + const struct ipv6_ct_tuple *tuple __maybe_unused, + const struct lb6_service *svc) +{ + __u32 slot = (get_prandom_u32() % svc->count) + 1; + struct lb6_service *be = lb6_lookup_backend_slot(ctx, key, slot); + + return be ? be->backend_id : 0; +} +#elif LB_SELECTION == LB_SELECTION_MAGLEV +static __always_inline __u16 +lb6_select_backend_id(struct __ctx_buff *ctx __maybe_unused, + struct lb6_key *key __maybe_unused, + const struct ipv6_ct_tuple *tuple, + const struct lb6_service *svc) +{ + __u32 zero = 0, index = svc->rev_nat_index; + __u16 *backend_ids; + void *maglev_lut; + + maglev_lut = map_lookup_elem(&LB6_MAGLEV_MAP_OUTER, &index); + if (unlikely(!maglev_lut)) + return 0; + + backend_ids = map_lookup_elem(maglev_lut, &zero); + if (unlikely(!backend_ids)) + return 0; + + index = hash_from_tuple_v6(tuple) % LB_MAGLEV_LUT_SIZE; + return map_array_get_16(backend_ids, index, (LB_MAGLEV_LUT_SIZE - 1) << 1); +} +#else +# error "Invalid load balancer backend selection algorithm!" +#endif /* LB_SELECTION */ + +static __always_inline int lb6_xlate(struct __ctx_buff *ctx, + union v6addr *new_dst, __u8 nexthdr, + int l3_off, int l4_off, + struct csum_offset *csum_off, + const struct lb6_key *key, + const struct lb6_backend *backend, + const bool skip_l3_xlate) +{ + if (skip_l3_xlate) + goto l4_xlate; + + ipv6_store_daddr(ctx, new_dst->addr, l3_off); + if (csum_off) { + __be32 sum = csum_diff(key->address.addr, 16, new_dst->addr, + 16, 0); + + if (csum_l4_replace(ctx, l4_off, csum_off, 0, sum, + BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + } + +l4_xlate: + if (likely(backend->port) && key->dport != backend->port && + (nexthdr == IPPROTO_TCP || nexthdr == IPPROTO_UDP)) { + __be16 tmp = backend->port; + int ret; + + /* Port offsets for UDP and TCP are the same */ + ret = l4_modify_port(ctx, l4_off, TCP_DPORT_OFF, csum_off, + tmp, key->dport); + if (IS_ERR(ret)) + return ret; + } + + return CTX_ACT_OK; +} + +#ifdef ENABLE_SESSION_AFFINITY +static __always_inline __u32 +__lb6_affinity_backend_id(const struct lb6_service *svc, bool netns_cookie, + union lb6_affinity_client_id *id) +{ + struct lb6_affinity_key key = { + .rev_nat_id = svc->rev_nat_index, + .netns_cookie = netns_cookie, + }; + struct lb_affinity_val *val; + + ipv6_addr_copy(&key.client_id.client_ip, &id->client_ip); + + val = map_lookup_elem(&LB6_AFFINITY_MAP, &key); + if (val != NULL) { + __u32 now = bpf_mono_now(); + struct lb_affinity_match match = { + .rev_nat_id = svc->rev_nat_index, + .backend_id = val->backend_id, + }; + + if (READ_ONCE(val->last_used) + + bpf_sec_to_mono(svc->affinity_timeout) <= now) { + map_delete_elem(&LB6_AFFINITY_MAP, &key); + return 0; + } + + if (!map_lookup_elem(&LB_AFFINITY_MATCH_MAP, &match)) { + map_delete_elem(&LB6_AFFINITY_MAP, &key); + return 0; + } + + WRITE_ONCE(val->last_used, now); + return val->backend_id; + } + + return 0; +} + +static __always_inline __u32 +lb6_affinity_backend_id_by_addr(const struct lb6_service *svc, + union lb6_affinity_client_id *id) +{ + return __lb6_affinity_backend_id(svc, false, id); +} + +static __always_inline void +__lb6_update_affinity(const struct lb6_service *svc, bool netns_cookie, + union lb6_affinity_client_id *id, __u32 backend_id) +{ + __u32 now = bpf_mono_now(); + struct lb6_affinity_key key = { + .rev_nat_id = svc->rev_nat_index, + .netns_cookie = netns_cookie, + }; + struct lb_affinity_val val = { + .backend_id = backend_id, + .last_used = now, + }; + + ipv6_addr_copy(&key.client_id.client_ip, &id->client_ip); + + map_update_elem(&LB6_AFFINITY_MAP, &key, &val, 0); +} + +static __always_inline void +lb6_update_affinity_by_addr(const struct lb6_service *svc, + union lb6_affinity_client_id *id, __u32 backend_id) +{ + __lb6_update_affinity(svc, false, id, backend_id); +} +#endif /* ENABLE_SESSION_AFFINITY */ + +static __always_inline __u32 +lb6_affinity_backend_id_by_netns(const struct lb6_service *svc __maybe_unused, + union lb6_affinity_client_id *id __maybe_unused) +{ +#if defined(ENABLE_SESSION_AFFINITY) + return __lb6_affinity_backend_id(svc, true, id); +#else + return 0; +#endif +} + +static __always_inline void +lb6_update_affinity_by_netns(const struct lb6_service *svc __maybe_unused, + union lb6_affinity_client_id *id __maybe_unused, + __u32 backend_id __maybe_unused) +{ +#if defined(ENABLE_SESSION_AFFINITY) + __lb6_update_affinity(svc, true, id, backend_id); +#endif +} + +static __always_inline int lb6_local(const void *map, struct __ctx_buff *ctx, + int l3_off, int l4_off, + struct csum_offset *csum_off, + struct lb6_key *key, + struct ipv6_ct_tuple *tuple, + const struct lb6_service *svc, + struct ct_state *state, + const bool skip_l3_xlate) +{ + __u32 monitor; /* Deliberately ignored; regular CT will determine monitoring. */ + union v6addr *addr; + __u8 flags = tuple->flags; + struct lb6_backend *backend; + __u32 backend_id = 0; + int ret; +#ifdef ENABLE_SESSION_AFFINITY + union lb6_affinity_client_id client_id; + + ipv6_addr_copy(&client_id.client_ip, &tuple->saddr); +#endif + + /* See lb4_local comments re svc endpoint lookup process */ + ret = ct_lookup6(map, tuple, ctx, l4_off, CT_SERVICE, state, &monitor); + switch (ret) { + case CT_NEW: +#ifdef ENABLE_SESSION_AFFINITY + if (lb6_svc_is_affinity(svc)) { + backend_id = lb6_affinity_backend_id_by_addr(svc, &client_id); + if (backend_id != 0) { + backend = lb6_lookup_backend(ctx, backend_id); + if (backend == NULL) + backend_id = 0; + } + } +#endif + if (backend_id == 0) { + backend_id = lb6_select_backend_id(ctx, key, tuple, svc); + backend = lb6_lookup_backend(ctx, backend_id); + if (backend == NULL) + goto drop_no_service; + } + + state->backend_id = backend_id; + state->rev_nat_index = svc->rev_nat_index; + + ret = ct_create6(map, NULL, tuple, ctx, CT_SERVICE, state, false); + /* Fail closed, if the conntrack entry create fails drop + * service lookup. + */ + if (IS_ERR(ret)) + goto drop_no_service; + goto update_state; + case CT_REOPENED: + case CT_ESTABLISHED: + case CT_RELATED: + case CT_REPLY: + /* See lb4_local comment */ + if (state->rev_nat_index == 0) { + state->rev_nat_index = svc->rev_nat_index; + ct_update6_rev_nat_index(map, tuple, state); + } + break; + default: + goto drop_no_service; + } + + /* See lb4_local comment */ + if (state->rev_nat_index != svc->rev_nat_index) { +#ifdef ENABLE_SESSION_AFFINITY + if (lb6_svc_is_affinity(svc)) + backend_id = lb6_affinity_backend_id_by_addr(svc, + &client_id); +#endif + if (!backend_id) { + backend_id = lb6_select_backend_id(ctx, key, tuple, svc); + if (!backend_id) + goto drop_no_service; + } + + state->backend_id = backend_id; + ct_update6_backend_id(map, tuple, state); + state->rev_nat_index = svc->rev_nat_index; + ct_update6_rev_nat_index(map, tuple, state); + } + /* If the lookup fails it means the user deleted the backend out from + * underneath us. To resolve this fall back to hash. If this is a TCP + * session we are likely to get a TCP RST. + */ + backend = lb6_lookup_backend(ctx, state->backend_id); + if (!backend) { + key->backend_slot = 0; + svc = lb6_lookup_service(key, false); + if (!svc) + goto drop_no_service; + backend_id = lb6_select_backend_id(ctx, key, tuple, svc); + backend = lb6_lookup_backend(ctx, backend_id); + if (!backend) + goto drop_no_service; + state->backend_id = backend_id; + ct_update6_backend_id(map, tuple, state); + } + +update_state: + /* Restore flags so that SERVICE flag is only used in used when the + * service lookup happens and future lookups use EGRESS or INGRESS. + */ + tuple->flags = flags; + ipv6_addr_copy(&tuple->daddr, &backend->address); + addr = &tuple->daddr; + state->rev_nat_index = svc->rev_nat_index; + +#ifdef ENABLE_SESSION_AFFINITY + if (lb6_svc_is_affinity(svc)) + lb6_update_affinity_by_addr(svc, &client_id, + state->backend_id); +#endif + return lb_skip_l4_dnat() ? CTX_ACT_OK : + lb6_xlate(ctx, addr, tuple->nexthdr, l3_off, l4_off, + csum_off, key, backend, skip_l3_xlate); +drop_no_service: + tuple->flags = flags; + return DROP_NO_SERVICE; +} +#else +/* Stubs for v4-in-v6 socket cgroup hook case when only v4 is enabled to avoid + * additional map management. + */ +static __always_inline +struct lb6_service *lb6_lookup_service(struct lb6_key *key __maybe_unused, + const bool scope_switch __maybe_unused) +{ + return NULL; +} + +static __always_inline +struct lb6_service *__lb6_lookup_backend_slot(struct lb6_key *key __maybe_unused) +{ + return NULL; +} + +static __always_inline struct lb6_backend * +__lb6_lookup_backend(__u16 backend_id __maybe_unused) +{ + return NULL; +} +#endif /* ENABLE_IPV6 */ + +#ifdef ENABLE_IPV4 +static __always_inline int __lb4_rev_nat(struct __ctx_buff *ctx, int l3_off, int l4_off, + struct csum_offset *csum_off, + struct ipv4_ct_tuple *tuple, int flags, + const struct lb4_reverse_nat *nat, + const struct ct_state *ct_state, bool has_l4_header) +{ + __be32 old_sip, new_sip, sum = 0; + int ret; + + cilium_dbg_lb(ctx, DBG_LB4_REVERSE_NAT, nat->address, nat->port); + + if (nat->port && has_l4_header) { + ret = reverse_map_l4_port(ctx, tuple->nexthdr, nat->port, l4_off, csum_off); + if (IS_ERR(ret)) + return ret; + } + + if (flags & REV_NAT_F_TUPLE_SADDR) { + old_sip = tuple->saddr; + tuple->saddr = new_sip = nat->address; + } else { + ret = ctx_load_bytes(ctx, l3_off + offsetof(struct iphdr, saddr), &old_sip, 4); + if (IS_ERR(ret)) + return ret; + + new_sip = nat->address; + } + + if (ct_state->loopback) { + /* The packet was looped back to the sending endpoint on the + * forward service translation. This implies that the original + * source address of the packet is the source address of the + * current packet. We therefore need to make the current source + * address the new destination address. + */ + __be32 old_dip; + + ret = ctx_load_bytes(ctx, l3_off + offsetof(struct iphdr, daddr), &old_dip, 4); + if (IS_ERR(ret)) + return ret; + + cilium_dbg_lb(ctx, DBG_LB4_LOOPBACK_SNAT_REV, old_dip, old_sip); + + ret = ctx_store_bytes(ctx, l3_off + offsetof(struct iphdr, daddr), &old_sip, 4, 0); + if (IS_ERR(ret)) + return DROP_WRITE_ERROR; + + sum = csum_diff(&old_dip, 4, &old_sip, 4, 0); + + /* Update the tuple address which is representing the destination address */ + tuple->saddr = old_sip; + } + + ret = ctx_store_bytes(ctx, l3_off + offsetof(struct iphdr, saddr), + &new_sip, 4, 0); + if (IS_ERR(ret)) + return DROP_WRITE_ERROR; + + sum = csum_diff(&old_sip, 4, &new_sip, 4, sum); + if (l3_csum_replace(ctx, l3_off + offsetof(struct iphdr, check), 0, sum, 0) < 0) + return DROP_CSUM_L3; + + if (csum_off->offset && + csum_l4_replace(ctx, l4_off, csum_off, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + + return 0; +} + + +/** Perform IPv4 reverse NAT based on reverse NAT index + * @arg ctx packet + * @arg l3_off offset to L3 + * @arg l4_off offset to L4 + * @arg csum_off offset to L4 checksum field + * @arg csum_flags checksum flags + * @arg index reverse NAT index + * @arg tuple tuple + */ +static __always_inline int lb4_rev_nat(struct __ctx_buff *ctx, int l3_off, int l4_off, + struct csum_offset *csum_off, + struct ct_state *ct_state, + struct ipv4_ct_tuple *tuple, int flags, bool has_l4_header) +{ + struct lb4_reverse_nat *nat; + + cilium_dbg_lb(ctx, DBG_LB4_REVERSE_NAT_LOOKUP, ct_state->rev_nat_index, 0); + nat = map_lookup_elem(&LB4_REVERSE_NAT_MAP, &ct_state->rev_nat_index); + if (nat == NULL) + return 0; + + return __lb4_rev_nat(ctx, l3_off, l4_off, csum_off, tuple, flags, nat, + ct_state, has_l4_header); +} + +/** Extract IPv4 LB key from packet + * @arg ctx Packet + * @arg ip4 Pointer to L3 header + * @arg l4_off Offset to L4 header + * @arg key Pointer to store LB key in + * @arg csum_off Pointer to store L4 checksum field offset in + * @arg dir Flow direction + * + * Returns: + * - CTX_ACT_OK on successful extraction + * - DROP_UNKNOWN_L4 if packet should be ignore (sent to stack) + * - Negative error code + */ +static __always_inline int lb4_extract_key(struct __ctx_buff *ctx __maybe_unused, + struct iphdr *ip4, + int l4_off __maybe_unused, + struct lb4_key *key, + struct csum_offset *csum_off, + int dir) +{ + /* FIXME: set after adding support for different L4 protocols in LB */ + key->proto = 0; + key->address = (dir == CT_INGRESS) ? ip4->saddr : ip4->daddr; + if (ipv4_has_l4_header(ip4)) + csum_l4_offset_and_flags(ip4->protocol, csum_off); + + return extract_l4_port(ctx, ip4->protocol, l4_off, dir, &key->dport, ip4); +} + +static __always_inline +bool lb4_src_range_ok(const struct lb4_service *svc __maybe_unused, + __u32 saddr __maybe_unused) +{ +#ifdef ENABLE_SRC_RANGE_CHECK + struct lb4_src_range_key key; + + if (!lb4_svc_has_src_range_check(svc)) + return true; + + key = (typeof(key)) { + .lpm_key = { SRC_RANGE_STATIC_PREFIX(key), {} }, + .rev_nat_id = svc->rev_nat_index, + .addr = saddr, + }; + + if (map_lookup_elem(&LB4_SRC_RANGE_MAP, &key)) + return true; + + return false; +#else + return true; +#endif /* ENABLE_SRC_RANGE_CHECK */ +} + +static __always_inline +struct lb4_service *lb4_lookup_service(struct lb4_key *key, + const bool scope_switch) +{ + struct lb4_service *svc; + + key->scope = LB_LOOKUP_SCOPE_EXT; + key->backend_slot = 0; + svc = map_lookup_elem(&LB4_SERVICES_MAP_V2, key); + if (svc) { + if (!scope_switch || !lb4_svc_is_local_scope(svc)) + return svc->count ? svc : NULL; + key->scope = LB_LOOKUP_SCOPE_INT; + svc = map_lookup_elem(&LB4_SERVICES_MAP_V2, key); + if (svc && svc->count) + return svc; + } + + return NULL; +} + +static __always_inline struct lb4_backend *__lb4_lookup_backend(__u16 backend_id) +{ + return map_lookup_elem(&LB4_BACKEND_MAP, &backend_id); +} + +static __always_inline struct lb4_backend * +lb4_lookup_backend(struct __ctx_buff *ctx __maybe_unused, __u16 backend_id) +{ + struct lb4_backend *backend; + + backend = __lb4_lookup_backend(backend_id); + if (!backend) + cilium_dbg_lb(ctx, DBG_LB4_LOOKUP_BACKEND_FAIL, backend_id, 0); + + return backend; +} + +static __always_inline +struct lb4_service *__lb4_lookup_backend_slot(struct lb4_key *key) +{ + return map_lookup_elem(&LB4_SERVICES_MAP_V2, key); +} + +static __always_inline +struct lb4_service *lb4_lookup_backend_slot(struct __ctx_buff *ctx __maybe_unused, + struct lb4_key *key, __u16 slot) +{ + struct lb4_service *svc; + + key->backend_slot = slot; + cilium_dbg_lb(ctx, DBG_LB4_LOOKUP_BACKEND_SLOT, key->backend_slot, key->dport); + svc = __lb4_lookup_backend_slot(key); + if (svc) + return svc; + + cilium_dbg_lb(ctx, DBG_LB4_LOOKUP_BACKEND_SLOT_V2_FAIL, key->backend_slot, key->dport); + + return NULL; +} + +/* Backend slot 0 is always reserved for the service frontend. */ +#if LB_SELECTION == LB_SELECTION_RANDOM +static __always_inline __u16 +lb4_select_backend_id(struct __ctx_buff *ctx, + struct lb4_key *key, + const struct ipv4_ct_tuple *tuple __maybe_unused, + const struct lb4_service *svc) +{ + __u32 slot = (get_prandom_u32() % svc->count) + 1; + struct lb4_service *be = lb4_lookup_backend_slot(ctx, key, slot); + + return be ? be->backend_id : 0; +} +#elif LB_SELECTION == LB_SELECTION_MAGLEV +static __always_inline __u16 +lb4_select_backend_id(struct __ctx_buff *ctx __maybe_unused, + struct lb4_key *key __maybe_unused, + const struct ipv4_ct_tuple *tuple, + const struct lb4_service *svc) +{ + __u32 zero = 0, index = svc->rev_nat_index; + __u16 *backend_ids; + void *maglev_lut; + + maglev_lut = map_lookup_elem(&LB4_MAGLEV_MAP_OUTER, &index); + if (unlikely(!maglev_lut)) + return 0; + + backend_ids = map_lookup_elem(maglev_lut, &zero); + if (unlikely(!backend_ids)) + return 0; + + index = hash_from_tuple_v4(tuple) % LB_MAGLEV_LUT_SIZE; + return map_array_get_16(backend_ids, index, (LB_MAGLEV_LUT_SIZE - 1) << 1); +} +#else +# error "Invalid load balancer backend selection algorithm!" +#endif /* LB_SELECTION */ + +static __always_inline int +lb4_xlate(struct __ctx_buff *ctx, __be32 *new_daddr, __be32 *new_saddr __maybe_unused, + __be32 *old_saddr __maybe_unused, __u8 nexthdr __maybe_unused, int l3_off, + int l4_off, struct csum_offset *csum_off, struct lb4_key *key, + const struct lb4_backend *backend __maybe_unused, bool has_l4_header, + const bool skip_l3_xlate) +{ + __be32 sum; + int ret; + + if (skip_l3_xlate) + goto l4_xlate; + + ret = ctx_store_bytes(ctx, l3_off + offsetof(struct iphdr, daddr), + new_daddr, 4, 0); + if (ret < 0) + return DROP_WRITE_ERROR; + + sum = csum_diff(&key->address, 4, new_daddr, 4, 0); +#ifndef DISABLE_LOOPBACK_LB + if (new_saddr && *new_saddr) { + cilium_dbg_lb(ctx, DBG_LB4_LOOPBACK_SNAT, *old_saddr, *new_saddr); + + ret = ctx_store_bytes(ctx, l3_off + offsetof(struct iphdr, saddr), + new_saddr, 4, 0); + if (ret < 0) + return DROP_WRITE_ERROR; + + sum = csum_diff(old_saddr, 4, new_saddr, 4, sum); + } +#endif /* DISABLE_LOOPBACK_LB */ + if (l3_csum_replace(ctx, l3_off + offsetof(struct iphdr, check), + 0, sum, 0) < 0) + return DROP_CSUM_L3; + if (csum_off->offset) { + if (csum_l4_replace(ctx, l4_off, csum_off, 0, sum, + BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + } + +l4_xlate: + if (likely(backend->port) && key->dport != backend->port && + (nexthdr == IPPROTO_TCP || nexthdr == IPPROTO_UDP) && + has_l4_header) { + __be16 tmp = backend->port; + + /* Port offsets for UDP and TCP are the same */ + ret = l4_modify_port(ctx, l4_off, TCP_DPORT_OFF, csum_off, + tmp, key->dport); + if (IS_ERR(ret)) + return ret; + } + + return CTX_ACT_OK; +} + +#ifdef ENABLE_SESSION_AFFINITY +static __always_inline __u32 +__lb4_affinity_backend_id(const struct lb4_service *svc, bool netns_cookie, + const union lb4_affinity_client_id *id) +{ + struct lb4_affinity_key key = { + .rev_nat_id = svc->rev_nat_index, + .netns_cookie = netns_cookie, + .client_id = *id, + }; + struct lb_affinity_val *val; + + val = map_lookup_elem(&LB4_AFFINITY_MAP, &key); + if (val != NULL) { + __u32 now = bpf_mono_now(); + struct lb_affinity_match match = { + .rev_nat_id = svc->rev_nat_index, + .backend_id = val->backend_id, + }; + + /* We have seconds granularity for timing values here. + * To ensure that session affinity timeout works properly we don't include + * the upper bound from the time range. + * Session is sticky for range [current, last_used + affinity_timeout) + */ + if (READ_ONCE(val->last_used) + + bpf_sec_to_mono(svc->affinity_timeout) <= now) { + map_delete_elem(&LB4_AFFINITY_MAP, &key); + return 0; + } + + if (!map_lookup_elem(&LB_AFFINITY_MATCH_MAP, &match)) { + map_delete_elem(&LB4_AFFINITY_MAP, &key); + return 0; + } + + WRITE_ONCE(val->last_used, now); + return val->backend_id; + } + + return 0; +} + +static __always_inline __u32 +lb4_affinity_backend_id_by_addr(const struct lb4_service *svc, + union lb4_affinity_client_id *id) +{ + return __lb4_affinity_backend_id(svc, false, id); +} + +static __always_inline void +__lb4_update_affinity(const struct lb4_service *svc, bool netns_cookie, + const union lb4_affinity_client_id *id, + __u32 backend_id) +{ + __u32 now = bpf_mono_now(); + struct lb4_affinity_key key = { + .rev_nat_id = svc->rev_nat_index, + .netns_cookie = netns_cookie, + .client_id = *id, + }; + struct lb_affinity_val val = { + .backend_id = backend_id, + .last_used = now, + }; + + map_update_elem(&LB4_AFFINITY_MAP, &key, &val, 0); +} + +static __always_inline void +lb4_update_affinity_by_addr(const struct lb4_service *svc, + union lb4_affinity_client_id *id, __u32 backend_id) +{ + __lb4_update_affinity(svc, false, id, backend_id); +} +#endif /* ENABLE_SESSION_AFFINITY */ + +static __always_inline __u32 +lb4_affinity_backend_id_by_netns(const struct lb4_service *svc __maybe_unused, + union lb4_affinity_client_id *id __maybe_unused) +{ +#if defined(ENABLE_SESSION_AFFINITY) + return __lb4_affinity_backend_id(svc, true, id); +#else + return 0; +#endif +} + +static __always_inline void +lb4_update_affinity_by_netns(const struct lb4_service *svc __maybe_unused, + union lb4_affinity_client_id *id __maybe_unused, + __u32 backend_id __maybe_unused) +{ +#if defined(ENABLE_SESSION_AFFINITY) + __lb4_update_affinity(svc, true, id, backend_id); +#endif +} + +static __always_inline int lb4_local(const void *map, struct __ctx_buff *ctx, + int l3_off, int l4_off, + struct csum_offset *csum_off, + struct lb4_key *key, + struct ipv4_ct_tuple *tuple, + const struct lb4_service *svc, + struct ct_state *state, __be32 saddr, + bool has_l4_header, + const bool skip_l3_xlate) +{ + __u32 monitor; /* Deliberately ignored; regular CT will determine monitoring. */ + __be32 new_saddr = 0, new_daddr; + __u8 flags = tuple->flags; + struct lb4_backend *backend; + __u32 backend_id = 0; + int ret; +#ifdef ENABLE_SESSION_AFFINITY + union lb4_affinity_client_id client_id = { + .client_ip = saddr, + }; +#endif + ret = ct_lookup4(map, tuple, ctx, l4_off, CT_SERVICE, state, &monitor); + switch (ret) { + case CT_NEW: +#ifdef ENABLE_SESSION_AFFINITY + if (lb4_svc_is_affinity(svc)) { + backend_id = lb4_affinity_backend_id_by_addr(svc, &client_id); + if (backend_id != 0) { + backend = lb4_lookup_backend(ctx, backend_id); + if (backend == NULL) + backend_id = 0; + } + } +#endif + if (backend_id == 0) { + /* No CT entry has been found, so select a svc endpoint */ + backend_id = lb4_select_backend_id(ctx, key, tuple, svc); + backend = lb4_lookup_backend(ctx, backend_id); + if (backend == NULL) + goto drop_no_service; + } + + state->backend_id = backend_id; + state->rev_nat_index = svc->rev_nat_index; + + ret = ct_create4(map, NULL, tuple, ctx, CT_SERVICE, state, false); + /* Fail closed, if the conntrack entry create fails drop + * service lookup. + */ + if (IS_ERR(ret)) + goto drop_no_service; + goto update_state; + case CT_REOPENED: + case CT_ESTABLISHED: + case CT_RELATED: + case CT_REPLY: + /* For backward-compatibility we need to update reverse NAT + * index in the CT_SERVICE entry for old connections, as later + * in the code we check whether the right backend is used. + * Having it set to 0 would trigger a new backend selection + * which would in many cases would pick a different backend. + */ + if (unlikely(state->rev_nat_index == 0)) { + state->rev_nat_index = svc->rev_nat_index; + ct_update4_rev_nat_index(map, tuple, state); + } + break; + default: + goto drop_no_service; + } + + /* If the CT_SERVICE entry is from a non-related connection (e.g. + * endpoint has been removed, but its CT entries were not (it is + * totally possible due to the bug in DumpReliablyWithCallback)), + * then a wrong (=from unrelated service) backend can be selected. + * To avoid this, check that reverse NAT indices match. If not, + * select a new backend. + */ + if (state->rev_nat_index != svc->rev_nat_index) { +#ifdef ENABLE_SESSION_AFFINITY + if (lb4_svc_is_affinity(svc)) + backend_id = lb4_affinity_backend_id_by_addr(svc, + &client_id); +#endif + if (!backend_id) { + backend_id = lb4_select_backend_id(ctx, key, tuple, svc); + if (!backend_id) + goto drop_no_service; + } + + state->backend_id = backend_id; + ct_update4_backend_id(map, tuple, state); + state->rev_nat_index = svc->rev_nat_index; + ct_update4_rev_nat_index(map, tuple, state); + } + /* If the lookup fails it means the user deleted the backend out from + * underneath us. To resolve this fall back to hash. If this is a TCP + * session we are likely to get a TCP RST. + */ + backend = lb4_lookup_backend(ctx, state->backend_id); + if (!backend) { + key->backend_slot = 0; + svc = lb4_lookup_service(key, false); + if (!svc) + goto drop_no_service; + backend_id = lb4_select_backend_id(ctx, key, tuple, svc); + backend = lb4_lookup_backend(ctx, backend_id); + if (!backend) + goto drop_no_service; + state->backend_id = backend_id; + ct_update4_backend_id(map, tuple, state); + } + +update_state: + /* Restore flags so that SERVICE flag is only used in used when the + * service lookup happens and future lookups use EGRESS or INGRESS. + */ + tuple->flags = flags; + state->rev_nat_index = svc->rev_nat_index; + state->addr = new_daddr = backend->address; + +#ifdef ENABLE_SESSION_AFFINITY + if (lb4_svc_is_affinity(svc)) + lb4_update_affinity_by_addr(svc, &client_id, + state->backend_id); +#endif + +#ifndef DISABLE_LOOPBACK_LB + /* Special loopback case: The origin endpoint has transmitted to a + * service which is being translated back to the source. This would + * result in a packet with identical source and destination address. + * Linux considers such packets as martian source and will drop unless + * received on a loopback device. Perform NAT on the source address + * to make it appear from an outside address. + */ + if (saddr == backend->address) { + new_saddr = IPV4_LOOPBACK; + state->loopback = 1; + state->addr = new_saddr; + state->svc_addr = saddr; + } + + if (!state->loopback) +#endif + tuple->daddr = backend->address; + + return lb_skip_l4_dnat() ? CTX_ACT_OK : + lb4_xlate(ctx, &new_daddr, &new_saddr, &saddr, + tuple->nexthdr, l3_off, l4_off, csum_off, key, + backend, has_l4_header, skip_l3_xlate); +drop_no_service: + tuple->flags = flags; + return DROP_NO_SERVICE; +} +#endif /* ENABLE_IPV4 */ +#endif /* __LB_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/lxc.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/lxc.h new file mode 100644 index 000000000..6768e628d --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/lxc.h @@ -0,0 +1,94 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_LXC_H_ +#define __LIB_LXC_H_ + +#include "common.h" +#include "utils.h" +#include "ipv6.h" +#include "ipv4.h" +#include "eth.h" +#include "dbg.h" +#include "trace.h" +#include "csum.h" +#include "l4.h" +#include "proxy.h" + +#define TEMPLATE_LXC_ID 0xffff + +#ifndef DISABLE_SIP_VERIFICATION +static __always_inline +int is_valid_lxc_src_ip(struct ipv6hdr *ip6 __maybe_unused) +{ +#ifdef ENABLE_IPV6 + union v6addr valid = {}; + + BPF_V6(valid, LXC_IP); + + return !ipv6_addrcmp((union v6addr *) &ip6->saddr, &valid); +#else + return 0; +#endif +} + +static __always_inline +int is_valid_lxc_src_ipv4(const struct iphdr *ip4 __maybe_unused) +{ +#ifdef ENABLE_IPV4 + return ip4->saddr == LXC_IPV4; +#else + /* Can't send IPv4 if no IPv4 address is configured */ + return 0; +#endif +} +#else +static __always_inline +int is_valid_lxc_src_ip(struct ipv6hdr *ip6 __maybe_unused) +{ + return 1; +} + +static __always_inline +int is_valid_lxc_src_ipv4(struct iphdr *ip4 __maybe_unused) +{ + return 1; +} +#endif + +/** + * ctx_redirect_to_proxy_hairpin redirects to the proxy by hairpining the + * packet out the incoming interface + */ +static __always_inline int +ctx_redirect_to_proxy_hairpin(struct __ctx_buff *ctx, __be16 proxy_port) +{ + union macaddr host_mac = HOST_IFINDEX_MAC; + union macaddr router_mac = NODE_MAC; + void *data_end = (void *) (long) ctx->data_end; + void *data = (void *) (long) ctx->data; + struct iphdr *ip4; + int ret; + + ctx_store_meta(ctx, CB_PROXY_MAGIC, + MARK_MAGIC_TO_PROXY | (proxy_port << 16)); + bpf_barrier(); /* verifier workaround */ + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + ret = ipv4_l3(ctx, ETH_HLEN, (__u8 *) &router_mac, (__u8 *) &host_mac, ip4); + if (IS_ERR(ret)) + return ret; + + cilium_dbg(ctx, DBG_CAPTURE_PROXY_PRE, proxy_port, 0); + + /* Note that the actual __ctx_buff preparation for submitting the + * packet to the proxy will occur in a subsequent program via + * ctx_redirect_to_proxy_first(). + */ + + return redirect(HOST_IFINDEX, 0); +} + +#endif /* __LIB_LXC_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/maps.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/maps.h new file mode 100644 index 000000000..7464e7593 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/maps.h @@ -0,0 +1,213 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2021 Authors of Cilium */ + +#ifndef __LIB_MAPS_H_ +#define __LIB_MAPS_H_ + +#include "common.h" +#include "ipv6.h" +#include "ids.h" + +#include "bpf/compiler.h" + +struct bpf_elf_map __section_maps ENDPOINTS_MAP = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(struct endpoint_key), + .size_value = sizeof(struct endpoint_info), + .pinning = PIN_GLOBAL_NS, + .max_elem = ENDPOINTS_MAP_SIZE, + .flags = CONDITIONAL_PREALLOC, +}; + +struct bpf_elf_map __section_maps METRICS_MAP = { + .type = BPF_MAP_TYPE_PERCPU_HASH, + .size_key = sizeof(struct metrics_key), + .size_value = sizeof(struct metrics_value), + .pinning = PIN_GLOBAL_NS, + .max_elem = METRICS_MAP_SIZE, + .flags = CONDITIONAL_PREALLOC, +}; + +#ifndef SKIP_POLICY_MAP +/* Global map to jump into policy enforcement of receiving endpoint */ +struct bpf_elf_map __section_maps POLICY_CALL_MAP = { + .type = BPF_MAP_TYPE_PROG_ARRAY, + .id = CILIUM_MAP_POLICY, + .size_key = sizeof(__u32), + .size_value = sizeof(__u32), + .pinning = PIN_GLOBAL_NS, + .max_elem = POLICY_PROG_MAP_SIZE, +}; +#endif /* SKIP_POLICY_MAP */ + +#ifdef ENABLE_BANDWIDTH_MANAGER +struct bpf_elf_map __section_maps THROTTLE_MAP = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(struct edt_id), + .size_value = sizeof(struct edt_info), + .pinning = PIN_GLOBAL_NS, + .max_elem = THROTTLE_MAP_SIZE, + .flags = BPF_F_NO_PREALLOC, +}; +#endif /* ENABLE_BANDWIDTH_MANAGER */ + +/* Map to link endpoint id to per endpoint cilium_policy map */ +#ifdef SOCKMAP +struct bpf_elf_map __section_maps EP_POLICY_MAP = { + .type = BPF_MAP_TYPE_HASH_OF_MAPS, + .size_key = sizeof(struct endpoint_key), + .size_value = sizeof(int), + .pinning = PIN_GLOBAL_NS, + .max_elem = ENDPOINTS_MAP_SIZE, +}; +#endif + +#ifdef POLICY_MAP +/* Per-endpoint policy enforcement map */ +struct bpf_elf_map __section_maps POLICY_MAP = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(struct policy_key), + .size_value = sizeof(struct policy_entry), + .pinning = PIN_GLOBAL_NS, + .max_elem = POLICY_MAP_SIZE, + .flags = CONDITIONAL_PREALLOC, +}; +#endif + +#ifndef SKIP_CALLS_MAP +/* Private per EP map for internal tail calls */ +struct bpf_elf_map __section_maps CALLS_MAP = { + .type = BPF_MAP_TYPE_PROG_ARRAY, + .id = CILIUM_MAP_CALLS, + .size_key = sizeof(__u32), + .size_value = sizeof(__u32), + .pinning = PIN_GLOBAL_NS, + .max_elem = CILIUM_CALL_SIZE, +}; +#endif /* SKIP_CALLS_MAP */ + +#ifdef ENCAP_IFINDEX + +struct bpf_elf_map __section_maps TUNNEL_MAP = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(struct endpoint_key), + .size_value = sizeof(struct endpoint_key), + .pinning = PIN_GLOBAL_NS, + .max_elem = TUNNEL_ENDPOINT_MAP_SIZE, + .flags = CONDITIONAL_PREALLOC, +}; + +#endif + +#if defined(ENABLE_CUSTOM_CALLS) && defined(CUSTOM_CALLS_MAP) +/* Private per-EP map for tail calls to user-defined programs. + * CUSTOM_CALLS_MAP is a per-EP map name, only defined for programs that need + * to use the map, so we do not want to compile this definition if + * CUSTOM_CALLS_MAP has not been #define-d. + */ +struct bpf_elf_map __section_maps CUSTOM_CALLS_MAP = { + .type = BPF_MAP_TYPE_PROG_ARRAY, + .id = CILIUM_MAP_CUSTOM_CALLS, + .size_key = sizeof(__u32), + .size_value = sizeof(__u32), + .pinning = PIN_GLOBAL_NS, + .max_elem = 4, /* ingress and egress, IPv4 and IPv6 */ +}; + +#define CUSTOM_CALLS_IDX_IPV4_INGRESS 0 +#define CUSTOM_CALLS_IDX_IPV4_EGRESS 1 +#define CUSTOM_CALLS_IDX_IPV6_INGRESS 2 +#define CUSTOM_CALLS_IDX_IPV6_EGRESS 3 +#endif /* ENABLE_CUSTOM_CALLS && CUSTOM_CALLS_MAP */ + +#ifdef HAVE_LPM_TRIE_MAP_TYPE +#define LPM_MAP_TYPE BPF_MAP_TYPE_LPM_TRIE +#else +#define LPM_MAP_TYPE BPF_MAP_TYPE_HASH +#endif + +#ifndef HAVE_LPM_TRIE_MAP_TYPE +/* Define a function with the following NAME which iterates through PREFIXES + * (a list of integers ordered from high to low representing prefix length), + * performing a lookup in MAP using LOOKUP_FN to find a provided IP of type + * IPTYPE. + */ +#define LPM_LOOKUP_FN(NAME, IPTYPE, PREFIXES, MAP, LOOKUP_FN) \ +static __always_inline int __##NAME(IPTYPE addr) \ +{ \ + int prefixes[] = { PREFIXES }; \ + const int size = ARRAY_SIZE(prefixes); \ + int i; \ + \ +_Pragma("unroll") \ + for (i = 0; i < size; i++) \ + if (LOOKUP_FN(&MAP, addr, prefixes[i])) \ + return 1; \ + \ + return 0; \ +} +#endif /* HAVE_LPM_TRIE_MAP_TYPE */ + +#ifndef SKIP_UNDEF_LPM_LOOKUP_FN +#undef LPM_LOOKUP_FN +#endif + +struct ipcache_key { + struct bpf_lpm_trie_key lpm_key; + __u16 pad1; + __u8 pad2; + __u8 family; + union { + struct { + __u32 ip4; + __u32 pad4; + __u32 pad5; + __u32 pad6; + }; + union v6addr ip6; + }; +} __packed; + +/* Global IP -> Identity map for applying egress label-based policy */ +struct bpf_elf_map __section_maps IPCACHE_MAP = { + .type = LPM_MAP_TYPE, + .size_key = sizeof(struct ipcache_key), + .size_value = sizeof(struct remote_endpoint_info), + .pinning = PIN_GLOBAL_NS, + .max_elem = IPCACHE_MAP_SIZE, + .flags = BPF_F_NO_PREALLOC, +}; + +struct bpf_elf_map __section_maps ENCRYPT_MAP = { + .type = BPF_MAP_TYPE_ARRAY, + .size_key = sizeof(struct encrypt_key), + .size_value = sizeof(struct encrypt_config), + .pinning = PIN_GLOBAL_NS, + .max_elem = 1, +}; + +struct egress_key { + struct bpf_lpm_trie_key lpm_key; + __u32 sip; + __u32 dip; +}; + +#ifdef ENABLE_EGRESS_GATEWAY +struct bpf_elf_map __section_maps EGRESS_MAP = { + .type = LPM_MAP_TYPE, + .size_key = sizeof(struct egress_key), + .size_value = sizeof(struct egress_info), + .pinning = PIN_GLOBAL_NS, + .max_elem = EGRESS_MAP_SIZE, + .flags = BPF_F_NO_PREALLOC, +}; +#endif /* ENABLE_EGRESS_GATEWAY */ + +#ifndef SKIP_CALLS_MAP +static __always_inline void ep_tail_call(struct __ctx_buff *ctx, + const __u32 index) +{ + tail_call_static(ctx, &CALLS_MAP, index); +} +#endif /* SKIP_CALLS_MAP */ +#endif diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/metrics.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/metrics.h new file mode 100644 index 000000000..1402ff472 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/metrics.h @@ -0,0 +1,64 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2018-2020 Authors of Cilium */ + +/* + * Data metrics collection functions + * + */ +#ifndef __LIB_METRICS__ +#define __LIB_METRICS__ + +#include "common.h" +#include "utils.h" +#include "maps.h" +#include "dbg.h" + +/** + * update_metrics + * @direction: 1: Ingress 2: Egress + * @reason: reason for forwarding or dropping packet. + * reason is 0 if packet is being forwarded, else reason + * is the drop error code. + * Update the metrics map. + */ +static __always_inline void update_metrics(__u64 bytes, __u8 direction, + __u8 reason) +{ + struct metrics_value *entry, newEntry = {}; + struct metrics_key key = {}; + + key.reason = reason; + key.dir = direction; + + + entry = map_lookup_elem(&METRICS_MAP, &key); + if (entry) { + entry->count += 1; + entry->bytes += bytes; + } else { + newEntry.count = 1; + newEntry.bytes = bytes; + map_update_elem(&METRICS_MAP, &key, &newEntry, 0); + } +} + +/** + * ct_to_metrics_dir + * @direction: 1: Ingress 2: Egress 3: Service + * Convert a CT direction into the corresponding one for metrics. + */ +static __always_inline __u8 ct_to_metrics_dir(__u8 ct_dir) +{ + switch (ct_dir) { + case CT_INGRESS: + return METRIC_INGRESS; + case CT_EGRESS: + return METRIC_EGRESS; + case CT_SERVICE: + return METRIC_SERVICE; + default: + return 0; + } +} + +#endif /* __LIB_METRICS__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/mono.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/mono.h new file mode 100644 index 000000000..b3bd70f50 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/mono.h @@ -0,0 +1,17 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __LIB_MONO_H_ +#define __LIB_MONO_H_ + +/* Moved out from time.h to avoid circular header dependency. */ +#if defined(BPF_HAVE_JIFFIES) && defined(ENABLE_JIFFIES) && KERNEL_HZ != 1 +# define BPF_MONO_SCALER 8 +# define bpf_mono_now() (jiffies >> BPF_MONO_SCALER) +# define bpf_sec_to_mono(s) (bpf_sec_to_jiffies(s) >> BPF_MONO_SCALER) +#else +# define bpf_mono_now() bpf_ktime_get_sec() +# define bpf_sec_to_mono(s) (s) +#endif /* BPF_HAVE_JIFFIES && ENABLE_JIFFIES */ + +#endif /* __LIB_MONO_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/nat.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/nat.h new file mode 100644 index 000000000..b847dc9ea --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/nat.h @@ -0,0 +1,1103 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2019-2020 Authors of Cilium */ + +/* Simple NAT engine in BPF. */ +#ifndef __LIB_NAT__ +#define __LIB_NAT__ + +#include +#include +#include +#include +#include +#include + +#include "common.h" +#include "drop.h" +#include "signal.h" +#include "conntrack.h" +#include "conntrack_map.h" +#include "icmp6.h" + +enum { + NAT_DIR_EGRESS = TUPLE_F_OUT, + NAT_DIR_INGRESS = TUPLE_F_IN, +}; + +struct nat_entry { + __u64 created; + __u64 host_local; /* Only single bit used. */ + __u64 pad1; /* Future use. */ + __u64 pad2; /* Future use. */ +}; + +#define NAT_CONTINUE_XLATE 0 + +#ifdef HAVE_LRU_HASH_MAP_TYPE +# define NAT_MAP_TYPE BPF_MAP_TYPE_LRU_HASH +#else +# define NAT_MAP_TYPE BPF_MAP_TYPE_HASH +#endif + +#ifdef HAVE_LARGE_INSN_LIMIT +# define SNAT_COLLISION_RETRIES 128 +# define SNAT_SIGNAL_THRES 64 +#else +# define SNAT_COLLISION_RETRIES 32 +# define SNAT_SIGNAL_THRES 16 +#endif + +static __always_inline __be16 __snat_clamp_port_range(__u16 start, __u16 end, + __u16 val) +{ + return (val % (__u16)(end - start)) + start; +} + +static __always_inline __maybe_unused __be16 +__snat_try_keep_port(__u16 start, __u16 end, __u16 val) +{ + return val >= start && val <= end ? val : + __snat_clamp_port_range(start, end, get_prandom_u32()); +} + +static __always_inline __maybe_unused void * +__snat_lookup(const void *map, const void *tuple) +{ + return map_lookup_elem(map, tuple); +} + +static __always_inline __maybe_unused int +__snat_update(const void *map, const void *otuple, const void *ostate, + const void *rtuple, const void *rstate) +{ + int ret; + + ret = map_update_elem(map, rtuple, rstate, BPF_NOEXIST); + if (!ret) { + ret = map_update_elem(map, otuple, ostate, BPF_NOEXIST); + if (ret) + map_delete_elem(map, rtuple); + } + return ret; +} + +static __always_inline __maybe_unused void +__snat_delete(const void *map, const void *otuple, const void *rtuple) +{ + map_delete_elem(map, otuple); + map_delete_elem(map, rtuple); +} + +struct ipv4_nat_entry { + struct nat_entry common; + union { + struct { + __be32 to_saddr; + __be16 to_sport; + }; + struct { + __be32 to_daddr; + __be16 to_dport; + }; + }; +}; + +struct ipv4_nat_target { + __be32 addr; + const __u16 min_port; /* host endianness */ + const __u16 max_port; /* host endianness */ + bool src_from_world; +}; + +#if defined(ENABLE_IPV4) && defined(ENABLE_NODEPORT) +struct bpf_elf_map __section_maps SNAT_MAPPING_IPV4 = { + .type = NAT_MAP_TYPE, + .size_key = sizeof(struct ipv4_ct_tuple), + .size_value = sizeof(struct ipv4_nat_entry), + .pinning = PIN_GLOBAL_NS, + .max_elem = SNAT_MAPPING_IPV4_SIZE, +#ifndef HAVE_LRU_HASH_MAP_TYPE + .flags = CONDITIONAL_PREALLOC, +#endif +}; + +#ifdef ENABLE_IP_MASQ_AGENT +struct bpf_elf_map __section_maps IP_MASQ_AGENT_IPV4 = { + .type = BPF_MAP_TYPE_LPM_TRIE, + .size_key = sizeof(struct lpm_v4_key), + .size_value = sizeof(struct lpm_val), + .pinning = PIN_GLOBAL_NS, + .max_elem = 16384, + .flags = BPF_F_NO_PREALLOC, +}; +#endif + +static __always_inline +struct ipv4_nat_entry *snat_v4_lookup(const struct ipv4_ct_tuple *tuple) +{ + return __snat_lookup(&SNAT_MAPPING_IPV4, tuple); +} + +static __always_inline int snat_v4_update(const struct ipv4_ct_tuple *otuple, + const struct ipv4_nat_entry *ostate, + const struct ipv4_ct_tuple *rtuple, + const struct ipv4_nat_entry *rstate) +{ + return __snat_update(&SNAT_MAPPING_IPV4, otuple, ostate, + rtuple, rstate); +} + +static __always_inline void snat_v4_delete(const struct ipv4_ct_tuple *otuple, + const struct ipv4_ct_tuple *rtuple) +{ + __snat_delete(&SNAT_MAPPING_IPV4, otuple, rtuple); +} + +static __always_inline void snat_v4_swap_tuple(const struct ipv4_ct_tuple *otuple, + struct ipv4_ct_tuple *rtuple) +{ + memset(rtuple, 0, sizeof(*rtuple)); + rtuple->nexthdr = otuple->nexthdr; + rtuple->daddr = otuple->saddr; + rtuple->saddr = otuple->daddr; + rtuple->dport = otuple->sport; + rtuple->sport = otuple->dport; + rtuple->flags = otuple->flags == NAT_DIR_EGRESS ? + NAT_DIR_INGRESS : NAT_DIR_EGRESS; +} + +static __always_inline int snat_v4_reverse_tuple(const struct ipv4_ct_tuple *otuple, + struct ipv4_ct_tuple *rtuple) +{ + struct ipv4_nat_entry *ostate; + + ostate = snat_v4_lookup(otuple); + if (ostate) { + snat_v4_swap_tuple(otuple, rtuple); + rtuple->daddr = ostate->to_saddr; + rtuple->dport = ostate->to_sport; + } + + return ostate ? 0 : -1; +} + +static __always_inline void snat_v4_ct_canonicalize(struct ipv4_ct_tuple *otuple) +{ + __be32 addr = otuple->saddr; + + otuple->flags = NAT_DIR_EGRESS; + /* Workaround #5848. */ + otuple->saddr = otuple->daddr; + otuple->daddr = addr; +} + +static __always_inline void snat_v4_delete_tuples(struct ipv4_ct_tuple *otuple) +{ + struct ipv4_ct_tuple rtuple; + + if (otuple->flags & TUPLE_F_IN) + return; + snat_v4_ct_canonicalize(otuple); + if (!snat_v4_reverse_tuple(otuple, &rtuple)) + snat_v4_delete(otuple, &rtuple); +} + +static __always_inline int snat_v4_new_mapping(struct __ctx_buff *ctx, + struct ipv4_ct_tuple *otuple, + struct ipv4_nat_entry *ostate, + const struct ipv4_nat_target *target) +{ + int ret = DROP_NAT_NO_MAPPING, retries; + struct ipv4_nat_entry rstate; + struct ipv4_ct_tuple rtuple; + __u16 port; + + memset(&rstate, 0, sizeof(rstate)); + memset(ostate, 0, sizeof(*ostate)); + + rstate.to_daddr = otuple->saddr; + rstate.to_dport = otuple->sport; + + ostate->to_saddr = target->addr; + + snat_v4_swap_tuple(otuple, &rtuple); + port = __snat_try_keep_port(target->min_port, + target->max_port, + bpf_ntohs(otuple->sport)); + + rtuple.dport = ostate->to_sport = bpf_htons(port); + rtuple.daddr = target->addr; + + if (otuple->saddr == target->addr) { + ostate->common.host_local = 1; + rstate.common.host_local = ostate->common.host_local; + } + +#pragma unroll + for (retries = 0; retries < SNAT_COLLISION_RETRIES; retries++) { + if (!snat_v4_lookup(&rtuple)) { + ostate->common.created = bpf_mono_now(); + rstate.common.created = ostate->common.created; + + ret = snat_v4_update(otuple, ostate, &rtuple, &rstate); + if (!ret) + break; + } + + port = __snat_clamp_port_range(target->min_port, + target->max_port, + retries ? port + 1 : + get_prandom_u32()); + rtuple.dport = ostate->to_sport = bpf_htons(port); + } + + if (retries > SNAT_SIGNAL_THRES) + send_signal_nat_fill_up(ctx, SIGNAL_PROTO_V4); + return !ret ? 0 : DROP_NAT_NO_MAPPING; +} + +static __always_inline int snat_v4_track_local(struct __ctx_buff *ctx, + const struct ipv4_ct_tuple *tuple, + const struct ipv4_nat_entry *state, + int dir, __u32 off, + const struct ipv4_nat_target *target) +{ + struct ct_state ct_state; + struct ipv4_ct_tuple tmp; + bool needs_ct = false; + __u32 monitor = 0; + int ret, where; + + if (state && state->common.host_local) { + needs_ct = true; + } else if (!state && dir == NAT_DIR_EGRESS) { + if (tuple->saddr == target->addr) + needs_ct = true; + } + if (!needs_ct) + return 0; + + memset(&ct_state, 0, sizeof(ct_state)); + memcpy(&tmp, tuple, sizeof(tmp)); + + where = dir == NAT_DIR_INGRESS ? CT_INGRESS : CT_EGRESS; + + ret = ct_lookup4(get_ct_map4(&tmp), &tmp, ctx, off, where, + &ct_state, &monitor); + if (ret < 0) { + return ret; + } else if (ret == CT_NEW) { + ret = ct_create4(get_ct_map4(&tmp), NULL, &tmp, ctx, + where, &ct_state, false); + if (IS_ERR(ret)) + return ret; + } + + return 0; +} + +static __always_inline int snat_v4_handle_mapping(struct __ctx_buff *ctx, + struct ipv4_ct_tuple *tuple, + struct ipv4_nat_entry **state, + struct ipv4_nat_entry *tmp, + int dir, __u32 off, + const struct ipv4_nat_target *target) +{ + int ret; + + *state = snat_v4_lookup(tuple); + ret = snat_v4_track_local(ctx, tuple, *state, dir, off, target); + if (ret < 0) + return ret; + else if (*state) + return NAT_CONTINUE_XLATE; + else if (dir == NAT_DIR_INGRESS) + return tuple->nexthdr != IPPROTO_ICMP && + bpf_ntohs(tuple->dport) < target->min_port ? + NAT_PUNT_TO_STACK : DROP_NAT_NO_MAPPING; + else + return snat_v4_new_mapping(ctx, tuple, (*state = tmp), target); +} + +static __always_inline int snat_v4_rewrite_egress(struct __ctx_buff *ctx, + struct ipv4_ct_tuple *tuple, + struct ipv4_nat_entry *state, + __u32 off, bool has_l4_header) +{ + struct csum_offset csum = {}; + __be32 sum_l4 = 0, sum; + int ret; + + if (state->to_saddr == tuple->saddr && + state->to_sport == tuple->sport) + return 0; + sum = csum_diff(&tuple->saddr, 4, &state->to_saddr, 4, 0); + if (has_l4_header) { + csum_l4_offset_and_flags(tuple->nexthdr, &csum); + + if (state->to_sport != tuple->sport) { + switch (tuple->nexthdr) { + case IPPROTO_TCP: + case IPPROTO_UDP: + ret = l4_modify_port(ctx, off, + offsetof(struct tcphdr, source), + &csum, state->to_sport, + tuple->sport); + if (ret < 0) + return ret; + break; + case IPPROTO_ICMP: { + __be32 from, to; + + if (ctx_store_bytes(ctx, off + + offsetof(struct icmphdr, un.echo.id), + &state->to_sport, + sizeof(state->to_sport), 0) < 0) + return DROP_WRITE_ERROR; + from = tuple->sport; + to = state->to_sport; + sum_l4 = csum_diff(&from, 4, &to, 4, 0); + csum.offset = offsetof(struct icmphdr, checksum); + break; + }} + } + } + if (ctx_store_bytes(ctx, ETH_HLEN + offsetof(struct iphdr, saddr), + &state->to_saddr, 4, 0) < 0) + return DROP_WRITE_ERROR; + if (l3_csum_replace(ctx, ETH_HLEN + offsetof(struct iphdr, check), + 0, sum, 0) < 0) + return DROP_CSUM_L3; + if (tuple->nexthdr == IPPROTO_ICMP) + sum = sum_l4; + if (csum.offset && + csum_l4_replace(ctx, off, &csum, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + return 0; +} + +static __always_inline int snat_v4_rewrite_ingress(struct __ctx_buff *ctx, + struct ipv4_ct_tuple *tuple, + struct ipv4_nat_entry *state, + __u32 off) +{ + struct csum_offset csum = {}; + __be32 sum_l4 = 0, sum; + int ret; + + if (state->to_daddr == tuple->daddr && + state->to_dport == tuple->dport) + return 0; + sum = csum_diff(&tuple->daddr, 4, &state->to_daddr, 4, 0); + csum_l4_offset_and_flags(tuple->nexthdr, &csum); + if (state->to_dport != tuple->dport) { + switch (tuple->nexthdr) { + case IPPROTO_TCP: + case IPPROTO_UDP: + ret = l4_modify_port(ctx, off, + offsetof(struct tcphdr, dest), + &csum, state->to_dport, + tuple->dport); + if (ret < 0) + return ret; + break; + case IPPROTO_ICMP: { + __be32 from, to; + + if (ctx_store_bytes(ctx, off + + offsetof(struct icmphdr, un.echo.id), + &state->to_dport, + sizeof(state->to_dport), 0) < 0) + return DROP_WRITE_ERROR; + from = tuple->dport; + to = state->to_dport; + sum_l4 = csum_diff(&from, 4, &to, 4, 0); + csum.offset = offsetof(struct icmphdr, checksum); + break; + }} + } + if (ctx_store_bytes(ctx, ETH_HLEN + offsetof(struct iphdr, daddr), + &state->to_daddr, 4, 0) < 0) + return DROP_WRITE_ERROR; + if (l3_csum_replace(ctx, ETH_HLEN + offsetof(struct iphdr, check), + 0, sum, 0) < 0) + return DROP_CSUM_L3; + if (tuple->nexthdr == IPPROTO_ICMP) + sum = sum_l4; + if (csum.offset && + csum_l4_replace(ctx, off, &csum, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + return 0; +} + +static __always_inline bool snat_v4_can_skip(const struct ipv4_nat_target *target, + const struct ipv4_ct_tuple *tuple, int dir, + bool from_endpoint, bool icmp_echoreply) +{ + __u16 dport = bpf_ntohs(tuple->dport), sport = bpf_ntohs(tuple->sport); + + if (dir == NAT_DIR_EGRESS && + ((!from_endpoint && !target->src_from_world && sport < NAT_MIN_EGRESS) || + icmp_echoreply)) + return true; + if (dir == NAT_DIR_INGRESS && (dport < target->min_port || dport > target->max_port)) + return true; + + return false; +} + +static __always_inline __maybe_unused int snat_v4_create_dsr(struct __ctx_buff *ctx, + __be32 to_saddr, + __be16 to_sport) +{ + void *data, *data_end; + struct ipv4_ct_tuple tuple = {}; + struct ipv4_nat_entry state = {}; + struct iphdr *ip4; + struct { + __be16 sport; + __be16 dport; + } l4hdr; + __u32 off; + int ret; + + build_bug_on(sizeof(struct ipv4_nat_entry) > 64); + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + tuple.nexthdr = ip4->protocol; + tuple.daddr = ip4->saddr; + tuple.saddr = ip4->daddr; + tuple.flags = NAT_DIR_EGRESS; + + off = ((void *)ip4 - data) + ipv4_hdrlen(ip4); + + switch (tuple.nexthdr) { + case IPPROTO_TCP: + case IPPROTO_UDP: + if (ctx_load_bytes(ctx, off, &l4hdr, sizeof(l4hdr)) < 0) + return DROP_INVALID; + tuple.dport = l4hdr.sport; + tuple.sport = l4hdr.dport; + break; + default: + /* NodePort svc can be reached only via TCP or UDP, so + * drop the rest. + */ + return DROP_NAT_UNSUPP_PROTO; + } + + state.common.created = bpf_mono_now(); + state.to_saddr = to_saddr; + state.to_sport = to_sport; + + ret = map_update_elem(&SNAT_MAPPING_IPV4, &tuple, &state, 0); + if (ret) + return ret; + + return CTX_ACT_OK; +} + +static __always_inline __maybe_unused int snat_v4_process(struct __ctx_buff *ctx, int dir, + const struct ipv4_nat_target *target, + bool from_endpoint) +{ + struct icmphdr icmphdr __align_stack_8; + struct ipv4_nat_entry *state, tmp; + struct ipv4_ct_tuple tuple = {}; + void *data, *data_end; + struct iphdr *ip4; + struct { + __be16 sport; + __be16 dport; + } l4hdr; + bool icmp_echoreply = false; + __u64 off; + int ret; + + build_bug_on(sizeof(struct ipv4_nat_entry) > 64); + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + tuple.nexthdr = ip4->protocol; + tuple.daddr = ip4->daddr; + tuple.saddr = ip4->saddr; + tuple.flags = dir; + off = ((void *)ip4 - data) + ipv4_hdrlen(ip4); + switch (tuple.nexthdr) { + case IPPROTO_TCP: + case IPPROTO_UDP: + if (ctx_load_bytes(ctx, off, &l4hdr, sizeof(l4hdr)) < 0) + return DROP_INVALID; + tuple.dport = l4hdr.dport; + tuple.sport = l4hdr.sport; + break; + case IPPROTO_ICMP: + if (ctx_load_bytes(ctx, off, &icmphdr, sizeof(icmphdr)) < 0) + return DROP_INVALID; + if (icmphdr.type != ICMP_ECHO && + icmphdr.type != ICMP_ECHOREPLY) + return DROP_NAT_UNSUPP_PROTO; + if (icmphdr.type == ICMP_ECHO) { + tuple.dport = 0; + tuple.sport = icmphdr.un.echo.id; + } else { + tuple.dport = icmphdr.un.echo.id; + tuple.sport = 0; + icmp_echoreply = true; + } + break; + default: + return NAT_PUNT_TO_STACK; + }; + + if (snat_v4_can_skip(target, &tuple, dir, from_endpoint, icmp_echoreply)) + return NAT_PUNT_TO_STACK; + ret = snat_v4_handle_mapping(ctx, &tuple, &state, &tmp, dir, off, target); + if (ret > 0) + return CTX_ACT_OK; + if (ret < 0) + return ret; + + return dir == NAT_DIR_EGRESS ? + snat_v4_rewrite_egress(ctx, &tuple, state, off, ipv4_has_l4_header(ip4)) : + snat_v4_rewrite_ingress(ctx, &tuple, state, off); +} +#else +static __always_inline __maybe_unused +int snat_v4_process(struct __ctx_buff *ctx __maybe_unused, + int dir __maybe_unused, + const struct ipv4_nat_target *target __maybe_unused, + bool from_endpoint __maybe_unused) +{ + return CTX_ACT_OK; +} + +static __always_inline __maybe_unused +void snat_v4_delete_tuples(struct ipv4_ct_tuple *tuple __maybe_unused) +{ +} +#endif + +struct ipv6_nat_entry { + struct nat_entry common; + union { + struct { + union v6addr to_saddr; + __be16 to_sport; + }; + struct { + union v6addr to_daddr; + __be16 to_dport; + }; + }; +}; + +struct ipv6_nat_target { + union v6addr addr; + const __u16 min_port; /* host endianness */ + const __u16 max_port; /* host endianness */ + bool src_from_world; +}; + +#if defined(ENABLE_IPV6) && defined(ENABLE_NODEPORT) +struct bpf_elf_map __section_maps SNAT_MAPPING_IPV6 = { + .type = NAT_MAP_TYPE, + .size_key = sizeof(struct ipv6_ct_tuple), + .size_value = sizeof(struct ipv6_nat_entry), + .pinning = PIN_GLOBAL_NS, + .max_elem = SNAT_MAPPING_IPV6_SIZE, +#ifndef HAVE_LRU_HASH_MAP_TYPE + .flags = CONDITIONAL_PREALLOC, +#endif +}; + +static __always_inline +struct ipv6_nat_entry *snat_v6_lookup(struct ipv6_ct_tuple *tuple) +{ + return __snat_lookup(&SNAT_MAPPING_IPV6, tuple); +} + +static __always_inline int snat_v6_update(struct ipv6_ct_tuple *otuple, + struct ipv6_nat_entry *ostate, + struct ipv6_ct_tuple *rtuple, + struct ipv6_nat_entry *rstate) +{ + return __snat_update(&SNAT_MAPPING_IPV6, otuple, ostate, + rtuple, rstate); +} + +static __always_inline void snat_v6_delete(const struct ipv6_ct_tuple *otuple, + const struct ipv6_ct_tuple *rtuple) +{ + __snat_delete(&SNAT_MAPPING_IPV6, otuple, rtuple); +} + +static __always_inline void snat_v6_swap_tuple(const struct ipv6_ct_tuple *otuple, + struct ipv6_ct_tuple *rtuple) +{ + memset(rtuple, 0, sizeof(*rtuple)); + rtuple->nexthdr = otuple->nexthdr; + rtuple->daddr = otuple->saddr; + rtuple->saddr = otuple->daddr; + rtuple->dport = otuple->sport; + rtuple->sport = otuple->dport; + rtuple->flags = otuple->flags == NAT_DIR_EGRESS ? + NAT_DIR_INGRESS : NAT_DIR_EGRESS; +} + +static __always_inline int snat_v6_reverse_tuple(struct ipv6_ct_tuple *otuple, + struct ipv6_ct_tuple *rtuple) +{ + struct ipv6_nat_entry *ostate; + + ostate = snat_v6_lookup(otuple); + if (ostate) { + snat_v6_swap_tuple(otuple, rtuple); + rtuple->daddr = ostate->to_saddr; + rtuple->dport = ostate->to_sport; + } + + return ostate ? 0 : -1; +} + +static __always_inline void snat_v6_ct_canonicalize(struct ipv6_ct_tuple *otuple) +{ + union v6addr addr = {}; + + otuple->flags = NAT_DIR_EGRESS; + /* Workaround #5848. */ + ipv6_addr_copy(&addr, &otuple->saddr); + ipv6_addr_copy(&otuple->saddr, &otuple->daddr); + ipv6_addr_copy(&otuple->daddr, &addr); +} + +static __always_inline void snat_v6_delete_tuples(struct ipv6_ct_tuple *otuple) +{ + struct ipv6_ct_tuple rtuple; + + if (otuple->flags & TUPLE_F_IN) + return; + snat_v6_ct_canonicalize(otuple); + if (!snat_v6_reverse_tuple(otuple, &rtuple)) + snat_v6_delete(otuple, &rtuple); +} + +static __always_inline int snat_v6_new_mapping(struct __ctx_buff *ctx, + struct ipv6_ct_tuple *otuple, + struct ipv6_nat_entry *ostate, + const struct ipv6_nat_target *target) +{ + int ret = DROP_NAT_NO_MAPPING, retries; + struct ipv6_nat_entry rstate; + struct ipv6_ct_tuple rtuple; + __u16 port; + + memset(&rstate, 0, sizeof(rstate)); + memset(ostate, 0, sizeof(*ostate)); + + rstate.to_daddr = otuple->saddr; + rstate.to_dport = otuple->sport; + + ostate->to_saddr = target->addr; + + snat_v6_swap_tuple(otuple, &rtuple); + port = __snat_try_keep_port(target->min_port, + target->max_port, + bpf_ntohs(otuple->sport)); + + rtuple.dport = ostate->to_sport = bpf_htons(port); + rtuple.daddr = target->addr; + + if (!ipv6_addrcmp(&otuple->saddr, &rtuple.daddr)) { + ostate->common.host_local = 1; + rstate.common.host_local = ostate->common.host_local; + } + +#pragma unroll + for (retries = 0; retries < SNAT_COLLISION_RETRIES; retries++) { + if (!snat_v6_lookup(&rtuple)) { + ostate->common.created = bpf_mono_now(); + rstate.common.created = ostate->common.created; + + ret = snat_v6_update(otuple, ostate, &rtuple, &rstate); + if (!ret) + break; + } + + port = __snat_clamp_port_range(target->min_port, + target->max_port, + retries ? port + 1 : + get_prandom_u32()); + rtuple.dport = ostate->to_sport = bpf_htons(port); + } + + if (retries > SNAT_SIGNAL_THRES) + send_signal_nat_fill_up(ctx, SIGNAL_PROTO_V6); + return !ret ? 0 : DROP_NAT_NO_MAPPING; +} + +static __always_inline int snat_v6_track_local(struct __ctx_buff *ctx, + struct ipv6_ct_tuple *tuple, + const struct ipv6_nat_entry *state, + int dir, __u32 off, + const struct ipv6_nat_target *target) +{ + struct ct_state ct_state; + struct ipv6_ct_tuple tmp; + bool needs_ct = false; + __u32 monitor = 0; + int ret, where; + + if (state && state->common.host_local) { + needs_ct = true; + } else if (!state && dir == NAT_DIR_EGRESS) { + if (!ipv6_addrcmp(&tuple->saddr, (void *)&target->addr)) + needs_ct = true; + } + if (!needs_ct) + return 0; + + memset(&ct_state, 0, sizeof(ct_state)); + memcpy(&tmp, tuple, sizeof(tmp)); + + where = dir == NAT_DIR_INGRESS ? CT_INGRESS : CT_EGRESS; + + ret = ct_lookup6(get_ct_map6(&tmp), &tmp, ctx, off, where, + &ct_state, &monitor); + if (ret < 0) { + return ret; + } else if (ret == CT_NEW) { + ret = ct_create6(get_ct_map6(&tmp), NULL, &tmp, ctx, where, + &ct_state, false); + if (IS_ERR(ret)) + return ret; + } + + return 0; +} + +static __always_inline int snat_v6_handle_mapping(struct __ctx_buff *ctx, + struct ipv6_ct_tuple *tuple, + struct ipv6_nat_entry **state, + struct ipv6_nat_entry *tmp, + int dir, __u32 off, + const struct ipv6_nat_target *target) +{ + int ret; + + *state = snat_v6_lookup(tuple); + ret = snat_v6_track_local(ctx, tuple, *state, dir, off, target); + if (ret < 0) + return ret; + else if (*state) + return NAT_CONTINUE_XLATE; + else if (dir == NAT_DIR_INGRESS) + return tuple->nexthdr != IPPROTO_ICMPV6 && + bpf_ntohs(tuple->dport) < target->min_port ? + NAT_PUNT_TO_STACK : DROP_NAT_NO_MAPPING; + else + return snat_v6_new_mapping(ctx, tuple, (*state = tmp), target); +} + +static __always_inline int snat_v6_rewrite_egress(struct __ctx_buff *ctx, + struct ipv6_ct_tuple *tuple, + struct ipv6_nat_entry *state, + __u32 off) +{ + struct csum_offset csum = {}; + __be32 sum; + int ret; + + if (!ipv6_addrcmp(&state->to_saddr, &tuple->saddr) && + state->to_sport == tuple->sport) + return 0; + sum = csum_diff(&tuple->saddr, 16, &state->to_saddr, 16, 0); + csum_l4_offset_and_flags(tuple->nexthdr, &csum); + if (state->to_sport != tuple->sport) { + switch (tuple->nexthdr) { + case IPPROTO_TCP: + case IPPROTO_UDP: + ret = l4_modify_port(ctx, off, offsetof(struct tcphdr, source), + &csum, state->to_sport, tuple->sport); + if (ret < 0) + return ret; + break; + case IPPROTO_ICMPV6: { + __be32 from, to; + + if (ctx_store_bytes(ctx, off + + offsetof(struct icmp6hdr, + icmp6_dataun.u_echo.identifier), + &state->to_sport, + sizeof(state->to_sport), 0) < 0) + return DROP_WRITE_ERROR; + from = tuple->sport; + to = state->to_sport; + sum = csum_diff(&from, 4, &to, 4, sum); + break; + }} + } + if (ctx_store_bytes(ctx, ETH_HLEN + offsetof(struct ipv6hdr, saddr), + &state->to_saddr, 16, 0) < 0) + return DROP_WRITE_ERROR; + if (csum.offset && + csum_l4_replace(ctx, off, &csum, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + return 0; +} + +static __always_inline int snat_v6_rewrite_ingress(struct __ctx_buff *ctx, + struct ipv6_ct_tuple *tuple, + struct ipv6_nat_entry *state, + __u32 off) +{ + struct csum_offset csum = {}; + __be32 sum; + int ret; + + if (!ipv6_addrcmp(&state->to_daddr, &tuple->daddr) && + state->to_dport == tuple->dport) + return 0; + sum = csum_diff(&tuple->daddr, 16, &state->to_daddr, 16, 0); + csum_l4_offset_and_flags(tuple->nexthdr, &csum); + if (state->to_dport != tuple->dport) { + switch (tuple->nexthdr) { + case IPPROTO_TCP: + case IPPROTO_UDP: + ret = l4_modify_port(ctx, off, + offsetof(struct tcphdr, dest), + &csum, state->to_dport, + tuple->dport); + if (ret < 0) + return ret; + break; + case IPPROTO_ICMPV6: { + __be32 from, to; + + if (ctx_store_bytes(ctx, off + + offsetof(struct icmp6hdr, + icmp6_dataun.u_echo.identifier), + &state->to_dport, + sizeof(state->to_dport), 0) < 0) + return DROP_WRITE_ERROR; + from = tuple->dport; + to = state->to_dport; + sum = csum_diff(&from, 4, &to, 4, sum); + break; + }} + } + if (ctx_store_bytes(ctx, ETH_HLEN + offsetof(struct ipv6hdr, daddr), + &state->to_daddr, 16, 0) < 0) + return DROP_WRITE_ERROR; + if (csum.offset && + csum_l4_replace(ctx, off, &csum, 0, sum, BPF_F_PSEUDO_HDR) < 0) + return DROP_CSUM_L4; + return 0; +} + +static __always_inline bool snat_v6_can_skip(const struct ipv6_nat_target *target, + const struct ipv6_ct_tuple *tuple, int dir, + bool icmp_echoreply) +{ + __u16 dport = bpf_ntohs(tuple->dport), sport = bpf_ntohs(tuple->sport); + + if (dir == NAT_DIR_EGRESS && + ((!target->src_from_world && sport < NAT_MIN_EGRESS) || + icmp_echoreply)) + return true; + if (dir == NAT_DIR_INGRESS && (dport < target->min_port || dport > target->max_port)) + return true; + return false; +} + +static __always_inline __maybe_unused int snat_v6_create_dsr(struct __ctx_buff *ctx, + union v6addr *to_saddr, + __be16 to_sport) +{ + void *data, *data_end; + struct ipv6_ct_tuple tuple = {}; + struct ipv6_nat_entry state = {}; + struct ipv6hdr *ip6; + struct { + __be16 sport; + __be16 dport; + } l4hdr; + int ret, hdrlen; + __u32 off; + + build_bug_on(sizeof(struct ipv6_nat_entry) > 64); + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return DROP_INVALID; + + tuple.nexthdr = ip6->nexthdr; + hdrlen = ipv6_hdrlen(ctx, ETH_HLEN, &tuple.nexthdr); + if (hdrlen < 0) + return hdrlen; + + ipv6_addr_copy(&tuple.daddr, (union v6addr *)&ip6->saddr); + ipv6_addr_copy(&tuple.saddr, (union v6addr *)&ip6->daddr); + tuple.flags = NAT_DIR_EGRESS; + + off = ((void *)ip6 - data) + hdrlen; + + switch (tuple.nexthdr) { + case IPPROTO_TCP: + case IPPROTO_UDP: + if (ctx_load_bytes(ctx, off, &l4hdr, sizeof(l4hdr)) < 0) + return DROP_INVALID; + tuple.dport = l4hdr.sport; + tuple.sport = l4hdr.dport; + break; + default: + /* NodePort svc can be reached only via TCP or UDP, so + * drop the rest. + */ + return DROP_NAT_UNSUPP_PROTO; + } + + state.common.created = bpf_mono_now(); + ipv6_addr_copy(&state.to_saddr, to_saddr); + state.to_sport = to_sport; + + ret = map_update_elem(&SNAT_MAPPING_IPV6, &tuple, &state, 0); + if (ret) + return ret; + + return CTX_ACT_OK; +} + +static __always_inline __maybe_unused int snat_v6_process(struct __ctx_buff *ctx, int dir, + const struct ipv6_nat_target *target) +{ + struct icmp6hdr icmp6hdr __align_stack_8; + struct ipv6_nat_entry *state, tmp; + struct ipv6_ct_tuple tuple = {}; + void *data, *data_end; + struct ipv6hdr *ip6; + int ret, hdrlen; + struct { + __be16 sport; + __be16 dport; + } l4hdr; + __u8 nexthdr; + __u32 off; + bool icmp_echoreply = false; + + build_bug_on(sizeof(struct ipv6_nat_entry) > 64); + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return DROP_INVALID; + + nexthdr = ip6->nexthdr; + hdrlen = ipv6_hdrlen(ctx, ETH_HLEN, &nexthdr); + if (hdrlen < 0) + return hdrlen; + + tuple.nexthdr = nexthdr; + ipv6_addr_copy(&tuple.daddr, (union v6addr *)&ip6->daddr); + ipv6_addr_copy(&tuple.saddr, (union v6addr *)&ip6->saddr); + tuple.flags = dir; + off = ((void *)ip6 - data) + hdrlen; + switch (tuple.nexthdr) { + case IPPROTO_TCP: + case IPPROTO_UDP: + if (ctx_load_bytes(ctx, off, &l4hdr, sizeof(l4hdr)) < 0) + return DROP_INVALID; + tuple.dport = l4hdr.dport; + tuple.sport = l4hdr.sport; + break; + case IPPROTO_ICMPV6: + if (ctx_load_bytes(ctx, off, &icmp6hdr, sizeof(icmp6hdr)) < 0) + return DROP_INVALID; + /* Letting neighbor solicitation / advertisement pass through. */ + if (icmp6hdr.icmp6_type == ICMP6_NS_MSG_TYPE || + icmp6hdr.icmp6_type == ICMP6_NA_MSG_TYPE) + return CTX_ACT_OK; + if (icmp6hdr.icmp6_type != ICMPV6_ECHO_REQUEST && + icmp6hdr.icmp6_type != ICMPV6_ECHO_REPLY) + return DROP_NAT_UNSUPP_PROTO; + if (icmp6hdr.icmp6_type == ICMPV6_ECHO_REQUEST) { + tuple.dport = 0; + tuple.sport = icmp6hdr.icmp6_dataun.u_echo.identifier; + } else { + tuple.dport = icmp6hdr.icmp6_dataun.u_echo.identifier; + tuple.sport = 0; + icmp_echoreply = true; + } + break; + default: + return NAT_PUNT_TO_STACK; + }; + + if (snat_v6_can_skip(target, &tuple, dir, icmp_echoreply)) + return NAT_PUNT_TO_STACK; + ret = snat_v6_handle_mapping(ctx, &tuple, &state, &tmp, dir, off, target); + if (ret > 0) + return CTX_ACT_OK; + if (ret < 0) + return ret; + + return dir == NAT_DIR_EGRESS ? + snat_v6_rewrite_egress(ctx, &tuple, state, off) : + snat_v6_rewrite_ingress(ctx, &tuple, state, off); +} +#else +static __always_inline __maybe_unused +int snat_v6_process(struct __ctx_buff *ctx __maybe_unused, + int dir __maybe_unused, + const struct ipv6_nat_target *target __maybe_unused) +{ + return CTX_ACT_OK; +} + +static __always_inline __maybe_unused +void snat_v6_delete_tuples(struct ipv6_ct_tuple *tuple __maybe_unused) +{ +} +#endif + +#ifdef CONNTRACK +static __always_inline __maybe_unused void +ct_delete4(const void *map, struct ipv4_ct_tuple *tuple, struct __ctx_buff *ctx) +{ + int err; + + err = map_delete_elem(map, tuple); + if (err < 0) + cilium_dbg(ctx, DBG_ERROR_RET, BPF_FUNC_map_delete_elem, err); + else + snat_v4_delete_tuples(tuple); +} + +static __always_inline __maybe_unused void +ct_delete6(const void *map, struct ipv6_ct_tuple *tuple, struct __ctx_buff *ctx) +{ + int err; + + err = map_delete_elem(map, tuple); + if (err < 0) + cilium_dbg(ctx, DBG_ERROR_RET, BPF_FUNC_map_delete_elem, err); + else + snat_v6_delete_tuples(tuple); +} +#else +static __always_inline __maybe_unused void +ct_delete4(const void *map __maybe_unused, + struct ipv4_ct_tuple *tuple __maybe_unused, + struct __ctx_buff *ctx __maybe_unused) +{ +} + +static __always_inline __maybe_unused void +ct_delete6(const void *map __maybe_unused, + struct ipv6_ct_tuple *tuple __maybe_unused, + struct __ctx_buff *ctx __maybe_unused) +{ +} +#endif + +#endif /* __LIB_NAT__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/nat46.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/nat46.h new file mode 100644 index 000000000..7230d3465 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/nat46.h @@ -0,0 +1,398 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_NAT46__ +#define __LIB_NAT46__ + +#include +#include +#include +#include "common.h" +#include "ipv4.h" +#include "ipv6.h" +#include "eth.h" +#include "dbg.h" + +#if defined(ENABLE_NAT46) && \ + (!defined(ENABLE_IPV4) || !defined(ENABLE_IPV6) || \ + !defined(CONNTRACK) || !defined(ENABLE_HOST_REDIRECT)) +#error "ENABLE_NAT46 requisite options are not configured, see lib/nat46.h." +#endif + +static __always_inline int get_csum_offset(__u8 protocol) +{ + int csum_off; + + switch (protocol) { + case IPPROTO_TCP: + csum_off = TCP_CSUM_OFF; + break; + case IPPROTO_UDP: + csum_off = UDP_CSUM_OFF; + break; + case IPPROTO_ICMP: + csum_off = (offsetof(struct icmphdr, checksum)); + break; + case IPPROTO_ICMPV6: + csum_off = (offsetof(struct icmp6hdr, icmp6_cksum)); + break; + default: + return DROP_UNKNOWN_L4; + } + + return csum_off; +} + +static __always_inline int icmp4_to_icmp6(struct __ctx_buff *ctx, int nh_off) +{ + struct icmphdr icmp4 __align_stack_8; + struct icmp6hdr icmp6 __align_stack_8 = {}; + + if (ctx_load_bytes(ctx, nh_off, &icmp4, sizeof(icmp4)) < 0) + return DROP_INVALID; + + icmp6.icmp6_cksum = icmp4.checksum; + + switch (icmp4.type) { + case ICMP_ECHO: + icmp6.icmp6_type = ICMPV6_ECHO_REQUEST; + icmp6.icmp6_identifier = icmp4.un.echo.id; + icmp6.icmp6_sequence = icmp4.un.echo.sequence; + break; + case ICMP_ECHOREPLY: + icmp6.icmp6_type = ICMPV6_ECHO_REPLY; + icmp6.icmp6_identifier = icmp4.un.echo.id; + icmp6.icmp6_sequence = icmp4.un.echo.sequence; + break; + case ICMP_DEST_UNREACH: + icmp6.icmp6_type = ICMPV6_DEST_UNREACH; + switch (icmp4.code) { + case ICMP_NET_UNREACH: + case ICMP_HOST_UNREACH: + icmp6.icmp6_code = ICMPV6_NOROUTE; + break; + case ICMP_PROT_UNREACH: + icmp6.icmp6_type = ICMPV6_PARAMPROB; + icmp6.icmp6_code = ICMPV6_UNK_NEXTHDR; + icmp6.icmp6_pointer = 6; + break; + case ICMP_PORT_UNREACH: + icmp6.icmp6_code = ICMPV6_PORT_UNREACH; + break; + case ICMP_FRAG_NEEDED: + icmp6.icmp6_type = ICMPV6_PKT_TOOBIG; + icmp6.icmp6_code = 0; + /* FIXME */ + if (icmp4.un.frag.mtu) + icmp6.icmp6_mtu = bpf_htonl(bpf_ntohs(icmp4.un.frag.mtu)); + else + icmp6.icmp6_mtu = bpf_htonl(1500); + break; + case ICMP_SR_FAILED: + icmp6.icmp6_code = ICMPV6_NOROUTE; + break; + case ICMP_NET_UNKNOWN: + case ICMP_HOST_UNKNOWN: + case ICMP_HOST_ISOLATED: + case ICMP_NET_UNR_TOS: + case ICMP_HOST_UNR_TOS: + icmp6.icmp6_code = 0; + break; + case ICMP_NET_ANO: + case ICMP_HOST_ANO: + case ICMP_PKT_FILTERED: + icmp6.icmp6_code = ICMPV6_ADM_PROHIBITED; + break; + default: + return DROP_UNKNOWN_ICMP_CODE; + } + break; + case ICMP_TIME_EXCEEDED: + icmp6.icmp6_type = ICMPV6_TIME_EXCEED; + break; + case ICMP_PARAMETERPROB: + icmp6.icmp6_type = ICMPV6_PARAMPROB; + /* FIXME */ + icmp6.icmp6_pointer = 6; + break; + default: + return DROP_UNKNOWN_ICMP_TYPE; + } + + if (ctx_store_bytes(ctx, nh_off, &icmp6, sizeof(icmp6), 0) < 0) + return DROP_WRITE_ERROR; + + icmp4.checksum = 0; + icmp6.icmp6_cksum = 0; + return csum_diff(&icmp4, sizeof(icmp4), &icmp6, sizeof(icmp6), 0); +} + +static __always_inline int icmp6_to_icmp4(struct __ctx_buff *ctx, int nh_off) +{ + struct icmphdr icmp4 __align_stack_8 = {}; + struct icmp6hdr icmp6 __align_stack_8; + + if (ctx_load_bytes(ctx, nh_off, &icmp6, sizeof(icmp6)) < 0) + return DROP_INVALID; + + icmp4.checksum = icmp6.icmp6_cksum; + + switch (icmp6.icmp6_type) { + case ICMPV6_ECHO_REQUEST: + icmp4.type = ICMP_ECHO; + icmp4.un.echo.id = icmp6.icmp6_identifier; + icmp4.un.echo.sequence = icmp6.icmp6_sequence; + break; + case ICMPV6_ECHO_REPLY: + icmp4.type = ICMP_ECHOREPLY; + icmp4.un.echo.id = icmp6.icmp6_identifier; + icmp4.un.echo.sequence = icmp6.icmp6_sequence; + break; + case ICMPV6_DEST_UNREACH: + icmp4.type = ICMP_DEST_UNREACH; + switch (icmp6.icmp6_code) { + case ICMPV6_NOROUTE: + case ICMPV6_NOT_NEIGHBOUR: + case ICMPV6_ADDR_UNREACH: + icmp4.code = ICMP_HOST_UNREACH; + break; + case ICMPV6_ADM_PROHIBITED: + icmp4.code = ICMP_HOST_ANO; + break; + case ICMPV6_PORT_UNREACH: + icmp4.code = ICMP_PORT_UNREACH; + break; + default: + return DROP_UNKNOWN_ICMP6_CODE; + } + break; + case ICMPV6_PKT_TOOBIG: + icmp4.type = ICMP_DEST_UNREACH; + icmp4.code = ICMP_FRAG_NEEDED; + /* FIXME */ + if (icmp6.icmp6_mtu) + icmp4.un.frag.mtu = bpf_htons(bpf_ntohl(icmp6.icmp6_mtu)); + else + icmp4.un.frag.mtu = bpf_htons(1500); + break; + case ICMPV6_TIME_EXCEED: + icmp4.type = ICMP_TIME_EXCEEDED; + icmp4.code = icmp6.icmp6_code; + break; + case ICMPV6_PARAMPROB: + switch (icmp6.icmp6_code) { + case ICMPV6_HDR_FIELD: + icmp4.type = ICMP_PARAMETERPROB; + icmp4.code = 0; + break; + case ICMPV6_UNK_NEXTHDR: + icmp4.type = ICMP_DEST_UNREACH; + icmp4.code = ICMP_PROT_UNREACH; + break; + default: + return DROP_UNKNOWN_ICMP6_CODE; + } + break; + default: + return DROP_UNKNOWN_ICMP6_TYPE; + } + + if (ctx_store_bytes(ctx, nh_off, &icmp4, sizeof(icmp4), 0) < 0) + return DROP_WRITE_ERROR; + + icmp4.checksum = 0; + icmp6.icmp6_cksum = 0; + return csum_diff(&icmp6, sizeof(icmp6), &icmp4, sizeof(icmp4), 0); +} + +static __always_inline int ipv6_prefix_match(const struct in6_addr *addr, + const union v6addr *v6prefix) +{ + if (addr->in6_u.u6_addr32[0] == v6prefix->p1 && + addr->in6_u.u6_addr32[1] == v6prefix->p2 && + addr->in6_u.u6_addr32[2] == v6prefix->p3) + return 1; + else + return 0; +} + +/* + * ipv4 to ipv6 stateless nat + * (s4,d4) -> (s6,d6) + * s6 = nat46_prefix + * d6 = nat46_prefix or v6_dst if non null + */ +static __always_inline int ipv4_to_ipv6(struct __ctx_buff *ctx, struct iphdr *ip4, + int nh_off, + const union v6addr *v6_dst) +{ + struct ipv6hdr v6 = {}; + struct iphdr v4; + int csum_off; + __be32 csum; + __be16 v4hdr_len; + __be16 protocol = bpf_htons(ETH_P_IPV6); + __u64 csum_flags = BPF_F_PSEUDO_HDR; + union v6addr nat46_prefix = NAT46_PREFIX; + + if (ctx_load_bytes(ctx, nh_off, &v4, sizeof(v4)) < 0) + return DROP_INVALID; + + if (ipv4_hdrlen(ip4) != sizeof(v4)) + return DROP_INVALID_EXTHDR; + + /* build v6 header */ + v6.version = 0x6; + v6.saddr.in6_u.u6_addr32[0] = nat46_prefix.p1; + v6.saddr.in6_u.u6_addr32[1] = nat46_prefix.p2; + v6.saddr.in6_u.u6_addr32[2] = nat46_prefix.p3; + v6.saddr.in6_u.u6_addr32[3] = v4.saddr; + + if (v6_dst) { + v6.daddr.in6_u.u6_addr32[0] = v6_dst->p1; + v6.daddr.in6_u.u6_addr32[1] = v6_dst->p2; + v6.daddr.in6_u.u6_addr32[2] = v6_dst->p3; + v6.daddr.in6_u.u6_addr32[3] = v6_dst->p4; + } else { + v6.daddr.in6_u.u6_addr32[0] = nat46_prefix.p1; + v6.daddr.in6_u.u6_addr32[1] = nat46_prefix.p2; + v6.daddr.in6_u.u6_addr32[2] = nat46_prefix.p3; + v6.daddr.in6_u.u6_addr32[3] = bpf_htonl((bpf_ntohl(nat46_prefix.p4) & 0xFFFF0000) | + (bpf_ntohl(v4.daddr) & 0xFFFF)); + } + + if (v4.protocol == IPPROTO_ICMP) + v6.nexthdr = IPPROTO_ICMPV6; + else + v6.nexthdr = v4.protocol; + v6.hop_limit = v4.ttl; + v4hdr_len = (v4.ihl << 2); + v6.payload_len = bpf_htons(bpf_ntohs(v4.tot_len) - v4hdr_len); + + if (ctx_change_proto(ctx, bpf_htons(ETH_P_IPV6), 0) < 0) { +#ifdef DEBUG_NAT46 + printk("v46 NAT: ctx_modify failed\n"); +#endif + return DROP_WRITE_ERROR; + } + + if (ctx_store_bytes(ctx, nh_off, &v6, sizeof(v6), 0) < 0 || + ctx_store_bytes(ctx, nh_off - 2, &protocol, 2, 0) < 0) + return DROP_WRITE_ERROR; + + if (v4.protocol == IPPROTO_ICMP) { + csum = icmp4_to_icmp6(ctx, nh_off + sizeof(v6)); + csum = ipv6_pseudohdr_checksum(&v6, IPPROTO_ICMPV6, + bpf_ntohs(v6.payload_len), csum); + } else { + csum = 0; + csum = csum_diff(&v4.saddr, 4, &v6.saddr, 16, csum); + csum = csum_diff(&v4.daddr, 4, &v6.daddr, 16, csum); + if (v4.protocol == IPPROTO_UDP) + csum_flags |= BPF_F_MARK_MANGLED_0; + } + + /* + * get checksum from inner header tcp / udp / icmp + * undo ipv4 pseudohdr checksum and + * add ipv6 pseudohdr checksum + */ + csum_off = get_csum_offset(v6.nexthdr); + if (csum_off < 0) + return csum_off; + csum_off += sizeof(struct ipv6hdr); + + if (l4_csum_replace(ctx, nh_off + csum_off, 0, csum, csum_flags) < 0) + return DROP_CSUM_L4; + +#ifdef DEBUG_NAT46 + printk("v46 NAT: nh_off %d, csum_off %d\n", nh_off, csum_off); +#endif + return 0; +} + +/* + * ipv6 to ipv4 stateless nat + * (s6,d6) -> (s4,d4) + * s4 = . + * d4 = d6[96 .. 127] + */ +static __always_inline int ipv6_to_ipv4(struct __ctx_buff *ctx, int nh_off, + __be32 saddr) +{ + struct ipv6hdr v6; + struct iphdr v4 = {}; + int csum_off; + __be32 csum = 0; + __be16 protocol = bpf_htons(ETH_P_IP); + __u64 csum_flags = BPF_F_PSEUDO_HDR; + + if (ctx_load_bytes(ctx, nh_off, &v6, sizeof(v6)) < 0) + return DROP_INVALID; + + /* Drop frames which carry extensions headers */ + if (ipv6_hdrlen(ctx, nh_off, &v6.nexthdr) != sizeof(v6)) + return DROP_INVALID_EXTHDR; + + /* build v4 header */ + v4.ihl = 0x5; + v4.version = 0x4; + v4.saddr = saddr; + v4.daddr = v6.daddr.in6_u.u6_addr32[3]; + if (v6.nexthdr == IPPROTO_ICMPV6) + v4.protocol = IPPROTO_ICMP; + else + v4.protocol = v6.nexthdr; + v4.ttl = v6.hop_limit; + v4.tot_len = bpf_htons(bpf_ntohs(v6.payload_len) + sizeof(v4)); + csum_off = offsetof(struct iphdr, check); + csum = csum_diff(NULL, 0, &v4, sizeof(v4), csum); + + if (ctx_change_proto(ctx, bpf_htons(ETH_P_IP), 0) < 0) { +#ifdef DEBUG_NAT46 + printk("v46 NAT: ctx_modify failed\n"); +#endif + return DROP_WRITE_ERROR; + } + + if (ctx_store_bytes(ctx, nh_off, &v4, sizeof(v4), 0) < 0 || + ctx_store_bytes(ctx, nh_off - 2, &protocol, 2, 0) < 0) + return DROP_WRITE_ERROR; + + if (l3_csum_replace(ctx, nh_off + csum_off, 0, csum, 0) < 0) + return DROP_CSUM_L3; + + if (v6.nexthdr == IPPROTO_ICMPV6) { + __be32 csum1 = 0; + + csum = icmp6_to_icmp4(ctx, nh_off + sizeof(v4)); + csum1 = ipv6_pseudohdr_checksum(&v6, IPPROTO_ICMPV6, + bpf_ntohs(v6.payload_len), 0); + csum = csum - csum1; + } else { + csum = 0; + csum = csum_diff(&v6.saddr, 16, &v4.saddr, 4, csum); + csum = csum_diff(&v6.daddr, 16, &v4.daddr, 4, csum); + if (v4.protocol == IPPROTO_UDP) + csum_flags |= BPF_F_MARK_MANGLED_0; + } + /* + * get checksum from inner header tcp / udp / icmp + * undo ipv6 pseudohdr checksum and + * add ipv4 pseudohdr checksum + */ + csum_off = get_csum_offset(v4.protocol); + if (csum_off < 0) + return csum_off; + csum_off += sizeof(struct iphdr); + + if (l4_csum_replace(ctx, nh_off + csum_off, 0, csum, csum_flags) < 0) + return DROP_CSUM_L4; + +#ifdef DEBUG_NAT46 + printk("v64 NAT: nh_off %d, csum_off %d\n", nh_off, csum_off); +#endif + + return 0; +} +#endif /* __LIB_NAT46__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/nodeport.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/nodeport.h new file mode 100644 index 000000000..2159fec71 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/nodeport.h @@ -0,0 +1,2204 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2019-2020 Authors of Cilium */ + +#ifndef __NODEPORT_H_ +#define __NODEPORT_H_ + +#include +#include + +#include "tailcall.h" +#include "nat.h" +#include "edt.h" +#include "lb.h" +#include "common.h" +#include "overloadable.h" +#include "eps.h" +#include "conntrack.h" +#include "csum.h" +#include "encap.h" +#include "trace.h" +#include "ghash.h" +#include "pcap.h" +#include "host_firewall.h" + +#define CB_SRC_IDENTITY 0 + +#ifdef ENABLE_NODEPORT + /* Define dummy values to make bpf_{lxc,overlay}.c to compile */ +#ifndef NATIVE_DEV_IFINDEX +#define NATIVE_DEV_IFINDEX 0 +#endif +#ifndef DSR_ENCAP_MODE +#define DSR_ENCAP_MODE 0 +#define DSR_ENCAP_IPIP 2 +#endif +#if defined(ENABLE_IPV4) && defined(ENABLE_MASQUERADE) && !defined(IPV4_MASQUERADE) +#define IPV4_MASQUERADE 0 +#endif + +#endif /* ENABLE_NODEPORT */ + +static __always_inline __maybe_unused void +bpf_skip_nodeport_clear(struct __ctx_buff *ctx) +{ + ctx_skip_nodeport_clear(ctx); +} + +static __always_inline __maybe_unused void +bpf_skip_nodeport_set(struct __ctx_buff *ctx) +{ + ctx_skip_nodeport_set(ctx); +} + +static __always_inline __maybe_unused bool +bpf_skip_nodeport(struct __ctx_buff *ctx) +{ + return ctx_skip_nodeport(ctx); +} + +#ifdef ENABLE_NODEPORT +#ifdef ENABLE_IPV4 +struct bpf_elf_map __section_maps NODEPORT_NEIGH4 = { + .type = BPF_MAP_TYPE_LRU_HASH, + .size_key = sizeof(__be32), /* ipv4 addr */ + .size_value = sizeof(union macaddr), /* hw addr */ + .pinning = PIN_GLOBAL_NS, + .max_elem = NODEPORT_NEIGH4_SIZE, +}; +#endif /* ENABLE_IPV4 */ + +#ifdef ENABLE_IPV6 +struct bpf_elf_map __section_maps NODEPORT_NEIGH6 = { + .type = BPF_MAP_TYPE_LRU_HASH, + .size_key = sizeof(union v6addr), /* ipv6 addr */ + .size_value = sizeof(union macaddr), /* hw addr */ + .pinning = PIN_GLOBAL_NS, + .max_elem = NODEPORT_NEIGH6_SIZE, +}; + +/* The IPv6 extension should be 8-bytes aligned */ +struct dsr_opt_v6 { + __u8 nexthdr; + __u8 len; + __u8 opt_type; + __u8 opt_len; + union v6addr addr; + __be32 port; +}; +#endif /* ENABLE_IPV6 */ + +static __always_inline bool nodeport_uses_dsr(__u8 nexthdr __maybe_unused) +{ +# if defined(ENABLE_DSR) && !defined(ENABLE_DSR_HYBRID) + return true; +# elif defined(ENABLE_DSR) && defined(ENABLE_DSR_HYBRID) + if (nexthdr == IPPROTO_TCP) + return true; + return false; +# else + return false; +# endif +} + +static __always_inline bool nodeport_lb_hairpin(void) +{ + return is_defined(ENABLE_NODEPORT_HAIRPIN); +} + +static __always_inline bool fib_lookup_bypass(void) +{ + return is_defined(ENABLE_FIB_LOOKUP_BYPASS); +} + +static __always_inline void +bpf_mark_snat_done(struct __ctx_buff *ctx __maybe_unused) +{ + /* From XDP layer, we do not go through an egress hook from + * here, hence nothing to be done. + */ +#if __ctx_is == __ctx_skb + ctx->mark |= MARK_MAGIC_SNAT_DONE; +#endif +} + +static __always_inline bool +bpf_skip_recirculation(const struct __ctx_buff *ctx __maybe_unused) +{ + /* From XDP layer, we do not go through an egress hook from + * here, hence nothing to be skipped. + */ +#if __ctx_is == __ctx_skb + return ctx->tc_index & TC_INDEX_F_SKIP_RECIRCULATION; +#else + return false; +#endif +} + +static __always_inline __u64 ctx_adjust_hroom_dsr_flags(void) +{ +#ifdef BPF_HAVE_CSUM_LEVEL + return BPF_F_ADJ_ROOM_NO_CSUM_RESET; +#else + return 0; +#endif +} + +static __always_inline bool dsr_fail_needs_reply(int code __maybe_unused) +{ +#ifdef ENABLE_DSR_ICMP_ERRORS + if (code == DROP_FRAG_NEEDED) + return true; +#endif + return false; +} + +static __always_inline bool dsr_is_too_big(struct __ctx_buff *ctx __maybe_unused, + __u16 expanded_len __maybe_unused) +{ +#ifdef ENABLE_DSR_ICMP_ERRORS + if (expanded_len > THIS_MTU) + return true; +#endif + return false; +} + +static __always_inline int +maybe_add_l2_hdr(struct __ctx_buff *ctx __maybe_unused, + __u32 ifindex __maybe_unused, + bool *l2_hdr_required __maybe_unused) +{ + if (IS_L3_DEV(ifindex)) + /* NodePort request is going to be redirected to L3 dev, so skip + * L2 addr settings. + */ + *l2_hdr_required = false; + else if (ETH_HLEN == 0) { + /* NodePort request is going to be redirected from L3 to L2 dev, + * so we need to create L2 hdr first. + */ + __u16 proto = ctx_get_protocol(ctx); + + if (ctx_change_head(ctx, __ETH_HLEN, 0)) + return DROP_INVALID; + + if (eth_store_proto(ctx, proto, 0) < 0) + return DROP_WRITE_ERROR; + } + + return 0; +} + +#ifdef ENABLE_IPV6 +static __always_inline bool nodeport_uses_dsr6(const struct ipv6_ct_tuple *tuple) +{ + return nodeport_uses_dsr(tuple->nexthdr); +} + +/* TODO(brb): after GH#6320, we can move snat_v{4,6}_needed() to lib/nat.h, as + * then the helper function won't depend the dsr checks. + */ +static __always_inline bool snat_v6_needed(struct __ctx_buff *ctx, + union v6addr *addr) +{ + void *data, *data_end; + struct ipv6hdr *ip6; + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return false; +#ifdef ENABLE_DSR_HYBRID + { + __u8 nexthdr = ip6->nexthdr; + int ret; + + ret = ipv6_hdrlen(ctx, ETH_HLEN, &nexthdr); + if (ret > 0) { + if (nodeport_uses_dsr(nexthdr)) + return false; + } + } +#endif /* ENABLE_DSR_HYBRID */ + /* See snat_v4_needed(). */ + return !ipv6_addrcmp((union v6addr *)&ip6->saddr, addr); +} + +static __always_inline int nodeport_nat_ipv6_fwd(struct __ctx_buff *ctx, + union v6addr *addr) +{ + struct ipv6_nat_target target = { + .min_port = NODEPORT_PORT_MIN_NAT, + .max_port = NODEPORT_PORT_MAX_NAT, + }; + int ret; + + ipv6_addr_copy(&target.addr, addr); + + ret = snat_v6_needed(ctx, addr) ? + snat_v6_process(ctx, NAT_DIR_EGRESS, &target) : CTX_ACT_OK; + if (ret == NAT_PUNT_TO_STACK) + ret = CTX_ACT_OK; + return ret; +} + +#ifdef ENABLE_DSR +#if DSR_ENCAP_MODE == DSR_ENCAP_IPIP +static __always_inline void rss_gen_src6(union v6addr *src, + const union v6addr *client, + __be32 l4_hint) +{ + __u32 bits = 128 - IPV6_RSS_PREFIX_BITS; + + *src = (union v6addr)IPV6_RSS_PREFIX; + if (bits) { + __u32 todo; + + if (bits > 96) { + todo = bits - 96; + src->p1 |= bpf_htonl(hash_32(client->p1 ^ l4_hint, todo)); + bits -= todo; + } + if (bits > 64) { + todo = bits - 64; + src->p2 |= bpf_htonl(hash_32(client->p2 ^ l4_hint, todo)); + bits -= todo; + } + if (bits > 32) { + todo = bits - 32; + src->p3 |= bpf_htonl(hash_32(client->p3 ^ l4_hint, todo)); + bits -= todo; + } + src->p4 |= bpf_htonl(hash_32(client->p4 ^ l4_hint, bits)); + } +} + +static __always_inline int dsr_set_ipip6(struct __ctx_buff *ctx, + const struct ipv6hdr *ip6, + union v6addr *backend_addr, + __be32 l4_hint, int *ohead) +{ + __u16 payload_len = bpf_ntohs(ip6->payload_len) + sizeof(*ip6); + const int l3_off = ETH_HLEN; + union v6addr saddr; + struct { + __be16 payload_len; + __u8 nexthdr; + __u8 hop_limit; + } tp_new = { + .payload_len = bpf_htons(payload_len), + .nexthdr = IPPROTO_IPV6, + .hop_limit = IPDEFTTL, + }; + + if (dsr_is_too_big(ctx, payload_len + sizeof(*ip6))) { + *ohead = sizeof(*ip6); + return DROP_FRAG_NEEDED; + } + + rss_gen_src6(&saddr, (union v6addr *)&ip6->saddr, l4_hint); + + if (ctx_adjust_hroom(ctx, sizeof(*ip6), BPF_ADJ_ROOM_NET, + ctx_adjust_hroom_dsr_flags())) + return DROP_INVALID; + if (ctx_store_bytes(ctx, l3_off + offsetof(struct ipv6hdr, payload_len), + &tp_new.payload_len, 4, 0) < 0) + return DROP_WRITE_ERROR; + if (ctx_store_bytes(ctx, l3_off + offsetof(struct ipv6hdr, daddr), + backend_addr, sizeof(ip6->daddr), 0) < 0) + return DROP_WRITE_ERROR; + if (ctx_store_bytes(ctx, l3_off + offsetof(struct ipv6hdr, saddr), + &saddr, sizeof(ip6->saddr), 0) < 0) + return DROP_WRITE_ERROR; + return 0; +} +#elif DSR_ENCAP_MODE == DSR_ENCAP_NONE +static __always_inline int dsr_set_ext6(struct __ctx_buff *ctx, + struct ipv6hdr *ip6, + union v6addr *svc_addr, + __be32 svc_port, int *ohead) +{ + struct dsr_opt_v6 opt __align_stack_8 = {}; + __u16 payload_len = bpf_ntohs(ip6->payload_len) + sizeof(opt); + + if (dsr_is_too_big(ctx, payload_len)) { + *ohead = sizeof(opt); + return DROP_FRAG_NEEDED; + } + + opt.nexthdr = ip6->nexthdr; + ip6->nexthdr = NEXTHDR_DEST; + ip6->payload_len = bpf_htons(payload_len); + + opt.len = DSR_IPV6_EXT_LEN; + opt.opt_type = DSR_IPV6_OPT_TYPE; + opt.opt_len = DSR_IPV6_OPT_LEN; + ipv6_addr_copy(&opt.addr, svc_addr); + opt.port = svc_port; + + if (ctx_adjust_hroom(ctx, sizeof(opt), BPF_ADJ_ROOM_NET, + ctx_adjust_hroom_dsr_flags())) + return DROP_INVALID; + if (ctx_store_bytes(ctx, ETH_HLEN + sizeof(*ip6), &opt, + sizeof(opt), 0) < 0) + return DROP_INVALID; + return 0; +} +#endif /* DSR_ENCAP_MODE */ + +static __always_inline int find_dsr_v6(struct __ctx_buff *ctx, __u8 nexthdr, + struct dsr_opt_v6 *dsr_opt, bool *found) +{ + struct ipv6_opt_hdr opthdr __align_stack_8; + int i, len = sizeof(struct ipv6hdr); + __u8 nh = nexthdr; + +#pragma unroll + for (i = 0; i < IPV6_MAX_HEADERS; i++) { + switch (nh) { + case NEXTHDR_NONE: + return DROP_INVALID_EXTHDR; + + case NEXTHDR_FRAGMENT: + return DROP_FRAG_NOSUPPORT; + + case NEXTHDR_HOP: + case NEXTHDR_ROUTING: + case NEXTHDR_AUTH: + case NEXTHDR_DEST: + if (ctx_load_bytes(ctx, ETH_HLEN + len, &opthdr, sizeof(opthdr)) < 0) + return DROP_INVALID; + + if (nh == NEXTHDR_DEST && opthdr.hdrlen == DSR_IPV6_EXT_LEN) { + if (ctx_load_bytes(ctx, ETH_HLEN + len, dsr_opt, + sizeof(*dsr_opt)) < 0) + return DROP_INVALID; + if (dsr_opt->opt_type == DSR_IPV6_OPT_TYPE && + dsr_opt->opt_len == DSR_IPV6_OPT_LEN) { + *found = true; + return 0; + } + } + + nh = opthdr.nexthdr; + if (nh == NEXTHDR_AUTH) + len += ipv6_authlen(&opthdr); + else + len += ipv6_optlen(&opthdr); + break; + + default: + return 0; + } + } + + /* Reached limit of supported extension headers */ + return DROP_INVALID_EXTHDR; +} + +static __always_inline int handle_dsr_v6(struct __ctx_buff *ctx, bool *dsr) +{ + struct dsr_opt_v6 opt __align_stack_8 = {}; + void *data, *data_end; + struct ipv6hdr *ip6; + int ret; + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return DROP_INVALID; + + ret = find_dsr_v6(ctx, ip6->nexthdr, &opt, dsr); + if (ret != 0) + return ret; + + if (*dsr) { + if (snat_v6_create_dsr(ctx, &opt.addr, opt.port) < 0) + return DROP_INVALID; + } + + return 0; +} + +static __always_inline int xlate_dsr_v6(struct __ctx_buff *ctx, + const struct ipv6_ct_tuple *tuple, + int l4_off) +{ + struct ipv6_ct_tuple nat_tup = *tuple; + struct ipv6_nat_entry *entry; + int ret = 0; + + nat_tup.flags = NAT_DIR_EGRESS; + nat_tup.sport = tuple->dport; + nat_tup.dport = tuple->sport; + + entry = snat_v6_lookup(&nat_tup); + if (entry) + ret = snat_v6_rewrite_egress(ctx, &nat_tup, entry, l4_off); + return ret; +} + +static __always_inline int dsr_reply_icmp6(struct __ctx_buff *ctx, + struct ipv6hdr *ip6 __maybe_unused, + int code, int ohead __maybe_unused) +{ +#ifdef ENABLE_DSR_ICMP_ERRORS + const __s32 orig_dgram = 64, off = ETH_HLEN; + const __u32 l3_max = sizeof(*ip6) + orig_dgram; + __be16 type = bpf_htons(ETH_P_IPV6); + __u64 len_new = off + sizeof(*ip6) + orig_dgram; + __u64 len_old = ctx_full_len(ctx); + void *data_end = ctx_data_end(ctx); + void *data = ctx_data(ctx); + __wsum wsum; + union macaddr smac, dmac; + struct icmp6hdr icmp __align_stack_8 = { + .icmp6_type = ICMPV6_PKT_TOOBIG, + .icmp6_mtu = bpf_htonl(THIS_MTU - ohead), + }; + struct ipv6hdr ip __align_stack_8 = { + .version = 6, + .priority = ip6->priority, + .flow_lbl[0] = ip6->flow_lbl[0], + .flow_lbl[1] = ip6->flow_lbl[1], + .flow_lbl[2] = ip6->flow_lbl[2], + .nexthdr = IPPROTO_ICMPV6, + .hop_limit = IPDEFTTL, + .saddr = ip6->daddr, + .daddr = ip6->saddr, + .payload_len = bpf_htons(sizeof(icmp) + len_new - off), + }; + + update_metrics(ctx_full_len(ctx), METRIC_EGRESS, -code); + + if (eth_load_saddr(ctx, smac.addr, 0) < 0) + goto drop_err; + if (eth_load_daddr(ctx, dmac.addr, 0) < 0) + goto drop_err; + if (unlikely(data + len_new > data_end)) + goto drop_err; + + wsum = ipv6_pseudohdr_checksum(&ip, IPPROTO_ICMPV6, + bpf_ntohs(ip.payload_len), 0); + icmp.icmp6_cksum = csum_fold(csum_diff(NULL, 0, data + off, l3_max, + csum_diff(NULL, 0, &icmp, + sizeof(icmp), wsum))); + + if (ctx_adjust_troom(ctx, -(len_old - len_new)) < 0) + goto drop_err; + if (ctx_adjust_hroom(ctx, sizeof(ip) + sizeof(icmp), + BPF_ADJ_ROOM_NET, + ctx_adjust_hroom_dsr_flags()) < 0) + goto drop_err; + + if (eth_store_daddr(ctx, smac.addr, 0) < 0) + goto drop_err; + if (eth_store_saddr(ctx, dmac.addr, 0) < 0) + goto drop_err; + if (ctx_store_bytes(ctx, ETH_ALEN * 2, &type, sizeof(type), 0) < 0) + goto drop_err; + if (ctx_store_bytes(ctx, off, &ip, sizeof(ip), 0) < 0) + goto drop_err; + if (ctx_store_bytes(ctx, off + sizeof(ip), &icmp, + sizeof(icmp), 0) < 0) + goto drop_err; + + return ctx_redirect(ctx, ctx_get_ifindex(ctx), 0); +drop_err: +#endif + return send_drop_notify_error(ctx, 0, code, CTX_ACT_DROP, + METRIC_EGRESS); +} + +__section_tail(CILIUM_MAP_CALLS, CILIUM_CALL_IPV6_NODEPORT_DSR) +int tail_nodeport_ipv6_dsr(struct __ctx_buff *ctx) +{ + struct bpf_fib_lookup_padded fib_params = { + .l = { + .family = AF_INET6, + .ifindex = DIRECT_ROUTING_DEV_IFINDEX, + }, + }; + union macaddr *dmac = NULL; + void *data, *data_end; + struct ipv6hdr *ip6; + union v6addr addr; + int ret, ohead = 0; + bool l2_hdr_required = true; + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) { + ret = DROP_INVALID; + goto drop_err; + } + + addr.p1 = ctx_load_meta(ctx, CB_ADDR_V6_1); + addr.p2 = ctx_load_meta(ctx, CB_ADDR_V6_2); + addr.p3 = ctx_load_meta(ctx, CB_ADDR_V6_3); + addr.p4 = ctx_load_meta(ctx, CB_ADDR_V6_4); + +#if DSR_ENCAP_MODE == DSR_ENCAP_IPIP + ret = dsr_set_ipip6(ctx, ip6, &addr, + ctx_load_meta(ctx, CB_HINT), &ohead); +#elif DSR_ENCAP_MODE == DSR_ENCAP_NONE + ret = dsr_set_ext6(ctx, ip6, &addr, + ctx_load_meta(ctx, CB_PORT), &ohead); +#else +# error "Invalid load balancer DSR encapsulation mode!" +#endif + if (unlikely(ret)) { + if (dsr_fail_needs_reply(ret)) + return dsr_reply_icmp6(ctx, ip6, ret, ohead); + goto drop_err; + } + if (!revalidate_data(ctx, &data, &data_end, &ip6)) { + ret = DROP_INVALID; + goto drop_err; + } + + ret = maybe_add_l2_hdr(ctx, DIRECT_ROUTING_DEV_IFINDEX, + &l2_hdr_required); + if (ret != 0) + goto drop_err; + if (!l2_hdr_required) + goto out_send; + else if (!revalidate_data_with_eth_hlen(ctx, &data, &data_end, &ip6, + __ETH_HLEN)) + return DROP_INVALID; + + if (nodeport_lb_hairpin()) + dmac = map_lookup_elem(&NODEPORT_NEIGH6, &ip6->daddr); + if (dmac) { + union macaddr mac = NATIVE_DEV_MAC_BY_IFINDEX(fib_params.l.ifindex); + + if (eth_store_daddr_aligned(ctx, dmac->addr, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + if (eth_store_saddr_aligned(ctx, mac.addr, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + } else { + ipv6_addr_copy((union v6addr *) &fib_params.l.ipv6_src, + (union v6addr *) &ip6->saddr); + ipv6_addr_copy((union v6addr *) &fib_params.l.ipv6_dst, + (union v6addr *) &ip6->daddr); + + ret = fib_lookup(ctx, &fib_params.l, sizeof(fib_params), + BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT); + if (ret != 0) { + ret = DROP_NO_FIB; + goto drop_err; + } + if (nodeport_lb_hairpin()) + map_update_elem(&NODEPORT_NEIGH6, &ip6->daddr, + fib_params.l.dmac, 0); + if (eth_store_daddr(ctx, fib_params.l.dmac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + if (eth_store_saddr(ctx, fib_params.l.smac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + } + +out_send: + cilium_capture_out(ctx); + return ctx_redirect(ctx, fib_params.l.ifindex, 0); +drop_err: + return send_drop_notify_error(ctx, 0, ret, CTX_ACT_DROP, METRIC_EGRESS); +} +#endif /* ENABLE_DSR */ + +__section_tail(CILIUM_MAP_CALLS, CILIUM_CALL_IPV6_NODEPORT_NAT) +int tail_nodeport_nat_ipv6(struct __ctx_buff *ctx) +{ + int ret, dir = ctx_load_meta(ctx, CB_NAT); + union v6addr tmp = IPV6_DIRECT_ROUTING; + struct bpf_fib_lookup_padded fib_params = { + .l = { + .family = AF_INET6, + .ifindex = DIRECT_ROUTING_DEV_IFINDEX, + }, + }; + struct ipv6_nat_target target = { + .min_port = NODEPORT_PORT_MIN_NAT, + .max_port = NODEPORT_PORT_MAX_NAT, + .src_from_world = true, + }; + union macaddr *dmac = NULL; + void *data, *data_end; + struct ipv6hdr *ip6; + bool l2_hdr_required = true; + + target.addr = tmp; +#ifdef TUNNEL_MODE + if (dir == NAT_DIR_EGRESS) { + struct remote_endpoint_info *info; + union v6addr *dst; + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) { + ret = DROP_INVALID; + goto drop_err; + } + + dst = (union v6addr *)&ip6->daddr; + info = ipcache_lookup6(&IPCACHE_MAP, dst, V6_CACHE_KEY_LEN); + if (info != NULL && info->tunnel_endpoint != 0) { + ret = __encap_with_nodeid(ctx, info->tunnel_endpoint, + SECLABEL, TRACE_PAYLOAD_LEN); + if (ret) + goto drop_err; + + BPF_V6(target.addr, ROUTER_IP); + fib_params.l.ifindex = ENCAP_IFINDEX; + + /* fib lookup not necessary when going over tunnel. */ + if (eth_store_daddr(ctx, fib_params.l.dmac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + if (eth_store_saddr(ctx, fib_params.l.smac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + } + } +#endif + ret = snat_v6_process(ctx, dir, &target); + if (IS_ERR(ret)) { + /* In case of no mapping, recircle back to main path. SNAT is very + * expensive in terms of instructions (since we don't have BPF to + * BPF calls as we use tail calls) and complexity, hence this is + * done inside a tail call here. + */ + if (dir == NAT_DIR_INGRESS) { + bpf_skip_nodeport_set(ctx); + ep_tail_call(ctx, CILIUM_CALL_IPV6_FROM_LXC); + ret = DROP_MISSED_TAIL_CALL; + goto drop_err; + } + if (ret != NAT_PUNT_TO_STACK) + goto drop_err; + } + + bpf_mark_snat_done(ctx); + + if (dir == NAT_DIR_INGRESS) { + ep_tail_call(ctx, CILIUM_CALL_IPV6_NODEPORT_REVNAT); + ret = DROP_MISSED_TAIL_CALL; + goto drop_err; + } +#ifdef TUNNEL_MODE + if (fib_params.l.ifindex == ENCAP_IFINDEX) + goto out_send; +#endif + if (!revalidate_data(ctx, &data, &data_end, &ip6)) { + ret = DROP_INVALID; + goto drop_err; + } + + ret = maybe_add_l2_hdr(ctx, DIRECT_ROUTING_DEV_IFINDEX, + &l2_hdr_required); + if (ret != 0) + goto drop_err; + if (!l2_hdr_required) + goto out_send; + else if (!revalidate_data_with_eth_hlen(ctx, &data, &data_end, &ip6, + __ETH_HLEN)) + return DROP_INVALID; + + if (nodeport_lb_hairpin()) + dmac = map_lookup_elem(&NODEPORT_NEIGH6, &ip6->daddr); + if (dmac) { + union macaddr mac = NATIVE_DEV_MAC_BY_IFINDEX(fib_params.l.ifindex); + + if (eth_store_daddr_aligned(ctx, dmac->addr, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + if (eth_store_saddr_aligned(ctx, mac.addr, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + } else { + ipv6_addr_copy((union v6addr *) &fib_params.l.ipv6_src, + (union v6addr *) &ip6->saddr); + ipv6_addr_copy((union v6addr *) &fib_params.l.ipv6_dst, + (union v6addr *) &ip6->daddr); + + ret = fib_lookup(ctx, &fib_params.l, sizeof(fib_params), + BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT); + if (ret != 0) { + ret = DROP_NO_FIB; + goto drop_err; + } + if (nodeport_lb_hairpin()) + map_update_elem(&NODEPORT_NEIGH6, &ip6->daddr, + fib_params.l.dmac, 0); + + if (eth_store_daddr(ctx, fib_params.l.dmac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + if (eth_store_saddr(ctx, fib_params.l.smac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + } +out_send: + cilium_capture_out(ctx); + return ctx_redirect(ctx, fib_params.l.ifindex, 0); +drop_err: + return send_drop_notify_error(ctx, 0, ret, CTX_ACT_DROP, + dir == NAT_DIR_INGRESS ? + METRIC_INGRESS : METRIC_EGRESS); +} + +/* See nodeport_lb4(). */ +static __always_inline int nodeport_lb6(struct __ctx_buff *ctx, + __u32 src_identity) +{ + int ret, l3_off = ETH_HLEN, l4_off, hdrlen; + struct ipv6_ct_tuple tuple = {}; + void *data, *data_end; + struct ipv6hdr *ip6; + struct csum_offset csum_off = {}; + struct lb6_service *svc; + struct lb6_key key = {}; + struct ct_state ct_state_new = {}; + union macaddr smac, *mac; + bool backend_local; + __u32 monitor = 0; + + cilium_capture_in(ctx); + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return DROP_INVALID; + + tuple.nexthdr = ip6->nexthdr; + ipv6_addr_copy(&tuple.daddr, (union v6addr *) &ip6->daddr); + ipv6_addr_copy(&tuple.saddr, (union v6addr *) &ip6->saddr); + + hdrlen = ipv6_hdrlen(ctx, l3_off, &tuple.nexthdr); + if (hdrlen < 0) + return hdrlen; + + l4_off = l3_off + hdrlen; + + ret = lb6_extract_key(ctx, &tuple, l4_off, &key, &csum_off, CT_EGRESS); + if (IS_ERR(ret)) { + if (ret == DROP_NO_SERVICE) + goto skip_service_lookup; + else if (ret == DROP_UNKNOWN_L4) + return CTX_ACT_OK; + else + return ret; + } + + svc = lb6_lookup_service(&key, false); + if (svc) { + const bool skip_l3_xlate = DSR_ENCAP_MODE == DSR_ENCAP_IPIP; + + if (!lb6_src_range_ok(svc, (union v6addr *)&ip6->saddr)) + return DROP_NOT_IN_SRC_RANGE; + + ret = lb6_local(get_ct_map6(&tuple), ctx, l3_off, l4_off, + &csum_off, &key, &tuple, svc, &ct_state_new, + skip_l3_xlate); + if (IS_ERR(ret)) + return ret; + } + + if (!svc || !lb6_svc_is_routable(svc)) { + if (svc) + return DROP_IS_CLUSTER_IP; + +skip_service_lookup: + ctx_set_xfer(ctx, XFER_PKT_NO_SVC); + + if (nodeport_uses_dsr6(&tuple)) + return CTX_ACT_OK; + + ctx_store_meta(ctx, CB_NAT, NAT_DIR_INGRESS); + ctx_store_meta(ctx, CB_SRC_IDENTITY, src_identity); + ep_tail_call(ctx, CILIUM_CALL_IPV6_NODEPORT_NAT); + return DROP_MISSED_TAIL_CALL; + } + + backend_local = __lookup_ip6_endpoint(&tuple.daddr); + if (!backend_local && lb6_svc_is_hostport(svc)) + return DROP_INVALID; + + if (backend_local || !nodeport_uses_dsr6(&tuple)) { + struct ct_state ct_state = {}; + + ret = ct_lookup6(get_ct_map6(&tuple), &tuple, ctx, l4_off, + CT_EGRESS, &ct_state, &monitor); + switch (ret) { + case CT_NEW: +redo_all: + ct_state_new.src_sec_id = SECLABEL; + ct_state_new.node_port = 1; + ct_state_new.ifindex = NATIVE_DEV_IFINDEX; + ret = ct_create6(get_ct_map6(&tuple), NULL, &tuple, ctx, + CT_EGRESS, &ct_state_new, false); + if (IS_ERR(ret)) + return ret; + if (backend_local) { + ct_flip_tuple_dir6(&tuple); +redo_local: + ct_state_new.rev_nat_index = 0; + ret = ct_create6(get_ct_map6(&tuple), NULL, + &tuple, ctx, CT_INGRESS, + &ct_state_new, false); + if (IS_ERR(ret)) + return ret; + } + break; + case CT_REOPENED: + case CT_ESTABLISHED: + case CT_REPLY: + if (unlikely(ct_state.rev_nat_index != + svc->rev_nat_index)) + goto redo_all; + if (backend_local) { + ct_flip_tuple_dir6(&tuple); + if (!__ct_entry_keep_alive(get_ct_map6(&tuple), + &tuple)) { + ct_state_new.src_sec_id = SECLABEL; + ct_state_new.node_port = 1; + ct_state_new.ifindex = NATIVE_DEV_IFINDEX; + goto redo_local; + } + } + break; + default: + return DROP_UNKNOWN_CT; + } + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return DROP_INVALID; + if (eth_load_saddr(ctx, smac.addr, 0) < 0) + return DROP_INVALID; + + mac = map_lookup_elem(&NODEPORT_NEIGH6, &ip6->saddr); + if (!mac || eth_addrcmp(mac, &smac)) { + ret = map_update_elem(&NODEPORT_NEIGH6, &ip6->saddr, + &smac, 0); + if (ret < 0) + return ret; + } + } + + if (!backend_local) { + edt_set_aggregate(ctx, 0); + if (nodeport_uses_dsr6(&tuple)) { +#if DSR_ENCAP_MODE == DSR_ENCAP_IPIP + ctx_store_meta(ctx, CB_HINT, + ((__u32)tuple.sport << 16) | tuple.dport); + ctx_store_meta(ctx, CB_ADDR_V6_1, tuple.daddr.p1); + ctx_store_meta(ctx, CB_ADDR_V6_2, tuple.daddr.p2); + ctx_store_meta(ctx, CB_ADDR_V6_3, tuple.daddr.p3); + ctx_store_meta(ctx, CB_ADDR_V6_4, tuple.daddr.p4); +#elif DSR_ENCAP_MODE == DSR_ENCAP_NONE + ctx_store_meta(ctx, CB_PORT, key.dport); + ctx_store_meta(ctx, CB_ADDR_V6_1, key.address.p1); + ctx_store_meta(ctx, CB_ADDR_V6_2, key.address.p2); + ctx_store_meta(ctx, CB_ADDR_V6_3, key.address.p3); + ctx_store_meta(ctx, CB_ADDR_V6_4, key.address.p4); +#endif /* DSR_ENCAP_MODE */ + ep_tail_call(ctx, CILIUM_CALL_IPV6_NODEPORT_DSR); + } else { + ctx_store_meta(ctx, CB_NAT, NAT_DIR_EGRESS); + ep_tail_call(ctx, CILIUM_CALL_IPV6_NODEPORT_NAT); + } + return DROP_MISSED_TAIL_CALL; + } + + ctx_set_xfer(ctx, XFER_PKT_NO_SVC); + + return CTX_ACT_OK; +} + +/* See comment in tail_rev_nodeport_lb4(). */ +static __always_inline int rev_nodeport_lb6(struct __ctx_buff *ctx, int *ifindex) +{ + int ret, ret2, l3_off = ETH_HLEN, l4_off, hdrlen; + struct ipv6_ct_tuple tuple = {}; + void *data, *data_end; + struct ipv6hdr *ip6; + struct csum_offset csum_off = {}; + struct ct_state ct_state = {}; + struct bpf_fib_lookup fib_params = {}; + union macaddr *dmac = NULL; + __u32 monitor = 0; + bool l2_hdr_required = true; + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return DROP_INVALID; + + tuple.nexthdr = ip6->nexthdr; + ipv6_addr_copy(&tuple.daddr, (union v6addr *) &ip6->daddr); + ipv6_addr_copy(&tuple.saddr, (union v6addr *) &ip6->saddr); + + hdrlen = ipv6_hdrlen(ctx, l3_off, &tuple.nexthdr); + if (hdrlen < 0) + return hdrlen; + + l4_off = l3_off + hdrlen; + csum_l4_offset_and_flags(tuple.nexthdr, &csum_off); + + ret = ct_lookup6(get_ct_map6(&tuple), &tuple, ctx, l4_off, CT_INGRESS, &ct_state, + &monitor); + + if (ret == CT_REPLY && ct_state.node_port == 1 && ct_state.rev_nat_index != 0) { + ret2 = lb6_rev_nat(ctx, l4_off, &csum_off, ct_state.rev_nat_index, + &tuple, REV_NAT_F_TUPLE_SADDR); + if (IS_ERR(ret2)) + return ret2; + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return DROP_INVALID; + + bpf_mark_snat_done(ctx); + + *ifindex = ct_state.ifindex; +#ifdef TUNNEL_MODE + { + union v6addr *dst = (union v6addr *)&ip6->daddr; + struct remote_endpoint_info *info; + + info = ipcache_lookup6(&IPCACHE_MAP, dst, V6_CACHE_KEY_LEN); + if (info != NULL && info->tunnel_endpoint != 0) { + ret = __encap_with_nodeid(ctx, info->tunnel_endpoint, + SECLABEL, TRACE_PAYLOAD_LEN); + if (ret) + return ret; + + *ifindex = ENCAP_IFINDEX; + + /* fib lookup not necessary when going over tunnel. */ + if (eth_store_daddr(ctx, fib_params.dmac, 0) < 0) + return DROP_WRITE_ERROR; + if (eth_store_saddr(ctx, fib_params.smac, 0) < 0) + return DROP_WRITE_ERROR; + + return CTX_ACT_OK; + } + } +#endif + + ret = maybe_add_l2_hdr(ctx, *ifindex, &l2_hdr_required); + if (ret != 0) + return ret; + if (!l2_hdr_required) + return CTX_ACT_OK; + else if (!revalidate_data_with_eth_hlen(ctx, &data, &data_end, + &ip6, __ETH_HLEN)) + return DROP_INVALID; + + if (fib_lookup_bypass()) + dmac = map_lookup_elem(&NODEPORT_NEIGH6, &tuple.daddr); + if (dmac) { + union macaddr mac = NATIVE_DEV_MAC_BY_IFINDEX(*ifindex); + + if (eth_store_daddr_aligned(ctx, dmac->addr, 0) < 0) + return DROP_WRITE_ERROR; + if (eth_store_saddr_aligned(ctx, mac.addr, 0) < 0) + return DROP_WRITE_ERROR; + } else { + fib_params.family = AF_INET6; + fib_params.ifindex = *ifindex; + + ipv6_addr_copy((union v6addr *) &fib_params.ipv6_src, &tuple.saddr); + ipv6_addr_copy((union v6addr *) &fib_params.ipv6_dst, &tuple.daddr); + + ret = fib_lookup(ctx, &fib_params, sizeof(fib_params), + BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT); + if (ret != 0) + return DROP_NO_FIB; + + if (eth_store_daddr(ctx, fib_params.dmac, 0) < 0) + return DROP_WRITE_ERROR; + if (eth_store_saddr(ctx, fib_params.smac, 0) < 0) + return DROP_WRITE_ERROR; + } + } else { + if (!bpf_skip_recirculation(ctx)) { + bpf_skip_nodeport_set(ctx); + ep_tail_call(ctx, CILIUM_CALL_IPV6_FROM_LXC); + return DROP_MISSED_TAIL_CALL; + } + } + + return CTX_ACT_OK; +} + +__section_tail(CILIUM_MAP_CALLS, CILIUM_CALL_IPV6_NODEPORT_REVNAT) +int tail_rev_nodeport_lb6(struct __ctx_buff *ctx) +{ + int ifindex = 0; + int ret = 0; +#if defined(ENABLE_HOST_FIREWALL) && defined(IS_BPF_HOST) + /* We only enforce the host policies if nodeport.h is included from + * bpf_host. + */ + __u32 src_id = 0; + + ret = ipv6_host_policy_ingress(ctx, &src_id); + if (IS_ERR(ret)) + return send_drop_notify_error(ctx, src_id, ret, CTX_ACT_DROP, + METRIC_INGRESS); + /* We don't want to enforce host policies a second time if we jump back to + * bpf_host's handle_ipv6. + */ + ctx_skip_host_fw_set(ctx); +#endif + ret = rev_nodeport_lb6(ctx, &ifindex); + if (IS_ERR(ret)) + return send_drop_notify_error(ctx, 0, ret, CTX_ACT_DROP, METRIC_EGRESS); + + edt_set_aggregate(ctx, 0); + cilium_capture_out(ctx); + + return ctx_redirect(ctx, ifindex, 0); +} + +declare_tailcall_if(__or(__and(is_defined(ENABLE_IPV4), + is_defined(ENABLE_IPV6)), + __and(is_defined(ENABLE_HOST_FIREWALL), + is_defined(IS_BPF_HOST))), + CILIUM_CALL_IPV6_ENCAP_NODEPORT_NAT) +int tail_handle_nat_fwd_ipv6(struct __ctx_buff *ctx) +{ +#if defined(TUNNEL_MODE) && defined(IS_BPF_OVERLAY) + union v6addr addr = { .p1 = 0 }; + BPF_V6(addr, ROUTER_IP); +#else + union v6addr addr = IPV6_DIRECT_ROUTING; +#endif + return nodeport_nat_ipv6_fwd(ctx, &addr); +} +#endif /* ENABLE_IPV6 */ + +#ifdef ENABLE_IPV4 +static __always_inline bool nodeport_uses_dsr4(const struct ipv4_ct_tuple *tuple) +{ + return nodeport_uses_dsr(tuple->nexthdr); +} + +/* Returns true if the packet must be SNAT-ed. In addition, sets "addr" to + * SNAT IP addr, and if a packet is sent from an endpoint, sets "from_endpoint" + * to true. + */ +static __always_inline bool snat_v4_needed(struct __ctx_buff *ctx, __be32 *addr, + bool *from_endpoint __maybe_unused) +{ + struct endpoint_info *ep __maybe_unused; + void *data, *data_end; + struct iphdr *ip4; + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return false; + +#if defined(ENABLE_EGRESS_GATEWAY) + /* Check if SNAT needs to be applied to the packet. Apply SNAT if there + * is an egress rule in ebpf map, and the packet is not coming out from + * overlay interface. If the packet is coming from an overlay interface + * it means it is forwarded to another node, instead of leaving the + * cluster. + */ + if (1) { + struct egress_info *info; + + info = lookup_ip4_egress_endpoint(ip4->saddr, ip4->daddr); + if (info && ctx->ifindex != ENCAP_IFINDEX) { + *addr = info->egress_ip; + *from_endpoint = true; + return true; + } + } +#endif + + /* Basic minimum is to only NAT when there is a potential of + * overlapping tuples, e.g. applications in hostns reusing + * source IPs we SNAT in NodePort and BPF-masq. + */ +#if defined(TUNNEL_MODE) && defined(IS_BPF_OVERLAY) + if (ip4->saddr == IPV4_GATEWAY) { + *addr = IPV4_GATEWAY; + return true; + } +#else + /* NATIVE_DEV_IFINDEX == DIRECT_ROUTING_DEV_IFINDEX cannot be moved into + * preprocessor, as the former is known only during load time (templating). + * This checks whether bpf_host is running on the direct routing device. + */ + if (DIRECT_ROUTING_DEV_IFINDEX == NATIVE_DEV_IFINDEX && + ip4->saddr == IPV4_DIRECT_ROUTING) { + *addr = IPV4_DIRECT_ROUTING; + return true; + } +# ifdef ENABLE_MASQUERADE + if (ip4->saddr == IPV4_MASQUERADE) { + *addr = IPV4_MASQUERADE; + return true; + } +# endif +#endif /* defined(TUNNEL_MODE) && defined(IS_BPF_OVERLAY) */ + + +#ifdef ENABLE_MASQUERADE /* SNAT local pod to world packets */ +# ifdef IS_BPF_OVERLAY + /* Do not MASQ when this function is executed from bpf_overlay + * (IS_BPF_OVERLAY denotes this fact). Otherwise, a packet will + * be SNAT'd to cilium_host IP addr. + */ + return false; +# endif +#ifdef IPV4_SNAT_EXCLUSION_DST_CIDR + /* Do not MASQ if a dst IP belongs to a pods CIDR + * (native-routing-cidr if specified, otherwise local pod CIDR). + * The check is performed before we determine that a packet is + * sent from a local pod, as this check is cheaper than + * the map lookup done in the latter check. + */ + if (ipv4_is_in_subnet(ip4->daddr, IPV4_SNAT_EXCLUSION_DST_CIDR, + IPV4_SNAT_EXCLUSION_DST_CIDR_LEN)) + return false; +#endif + + ep = __lookup_ip4_endpoint(ip4->saddr); + if (ep && !(ep->flags & ENDPOINT_F_HOST)) { + struct remote_endpoint_info *info; + *from_endpoint = true; + + info = ipcache_lookup4(&IPCACHE_MAP, ip4->daddr, + V4_CACHE_KEY_LEN); + if (info) { +#ifdef ENABLE_IP_MASQ_AGENT + /* Do not SNAT if dst belongs to any ip-masq-agent + * subnet. + */ + struct lpm_v4_key pfx; + + pfx.lpm.prefixlen = 32; + memcpy(pfx.lpm.data, &ip4->daddr, sizeof(pfx.addr)); + if (map_lookup_elem(&IP_MASQ_AGENT_IPV4, &pfx)) + return false; +#endif +#ifndef TUNNEL_MODE + /* In the tunnel mode, a packet from a local ep + * to a remote node is not encap'd, and is sent + * via a native dev. Therefore, such packet has + * to be MASQ'd. Otherwise, it might be dropped + * either by underlying network (e.g. AWS drops + * packets by default from unknown subnets) or + * by the remote node if its native dev's + * rp_filter=1. + */ + if (info->sec_label == REMOTE_NODE_ID) + return false; +#endif + + *addr = IPV4_MASQUERADE; + return true; + } + } +#endif /*ENABLE_MASQUERADE */ + + return false; +} + +static __always_inline int nodeport_nat_ipv4_fwd(struct __ctx_buff *ctx) +{ + bool from_endpoint = false; + struct ipv4_nat_target target = { + .min_port = NODEPORT_PORT_MIN_NAT, + .max_port = NODEPORT_PORT_MAX_NAT, + .addr = 0, + }; + int ret = CTX_ACT_OK; + + if (snat_v4_needed(ctx, &target.addr, &from_endpoint)) + ret = snat_v4_process(ctx, NAT_DIR_EGRESS, &target, + from_endpoint); + if (ret == NAT_PUNT_TO_STACK) + ret = CTX_ACT_OK; + + return ret; +} + +#ifdef ENABLE_DSR +#if DSR_ENCAP_MODE == DSR_ENCAP_IPIP +static __always_inline __be32 rss_gen_src4(__be32 client, __be32 l4_hint) +{ + const __u32 bits = 32 - IPV4_RSS_PREFIX_BITS; + __be32 src = IPV4_RSS_PREFIX; + + if (bits) + src |= bpf_htonl(hash_32(client ^ l4_hint, bits)); + return src; +} + +/* + * Original packet: [clientIP:clientPort -> serviceIP:servicePort] } IP/L4 + * + * After DSR IPIP: [rssSrcIP -> backendIP] } IP + * [clientIP:clientPort -> serviceIP:servicePort] } IP/L4 + */ +static __always_inline int dsr_set_ipip4(struct __ctx_buff *ctx, + const struct iphdr *ip4, + __be32 backend_addr, + __be32 l4_hint, int *ohead) +{ + __u16 tot_len = bpf_ntohs(ip4->tot_len) + sizeof(*ip4); + const int l3_off = ETH_HLEN; + __be32 sum; + struct { + __be16 tot_len; + __be16 id; + __be16 frag_off; + __u8 ttl; + __u8 protocol; + __be32 saddr; + __be32 daddr; + } tp_old = { + .tot_len = ip4->tot_len, + .ttl = ip4->ttl, + .protocol = ip4->protocol, + .saddr = ip4->saddr, + .daddr = ip4->daddr, + }, tp_new = { + .tot_len = bpf_htons(tot_len), + .ttl = IPDEFTTL, + .protocol = IPPROTO_IPIP, + .saddr = rss_gen_src4(ip4->saddr, l4_hint), + .daddr = backend_addr, + }; + + if (dsr_is_too_big(ctx, tot_len)) { + *ohead = sizeof(*ip4); + return DROP_FRAG_NEEDED; + } + + if (ctx_adjust_hroom(ctx, sizeof(*ip4), BPF_ADJ_ROOM_NET, + ctx_adjust_hroom_dsr_flags())) + return DROP_INVALID; + sum = csum_diff(&tp_old, 16, &tp_new, 16, 0); + if (ctx_store_bytes(ctx, l3_off + offsetof(struct iphdr, tot_len), + &tp_new.tot_len, 2, 0) < 0) + return DROP_WRITE_ERROR; + if (ctx_store_bytes(ctx, l3_off + offsetof(struct iphdr, ttl), + &tp_new.ttl, 2, 0) < 0) + return DROP_WRITE_ERROR; + if (ctx_store_bytes(ctx, l3_off + offsetof(struct iphdr, saddr), + &tp_new.saddr, 8, 0) < 0) + return DROP_WRITE_ERROR; + if (l3_csum_replace(ctx, l3_off + offsetof(struct iphdr, check), + 0, sum, 0) < 0) + return DROP_CSUM_L3; + return 0; +} +#elif DSR_ENCAP_MODE == DSR_ENCAP_NONE +static __always_inline int dsr_set_opt4(struct __ctx_buff *ctx, + struct iphdr *ip4, __be32 svc_addr, + __be32 svc_port, int *ohead) +{ + __u32 iph_old, iph_new, opt[2]; + __u16 tot_len = bpf_ntohs(ip4->tot_len) + sizeof(opt); + __be32 sum; + + if (ip4->protocol == IPPROTO_TCP) { + union tcp_flags tcp_flags = { .value = 0 }; + + if (ctx_load_bytes(ctx, ETH_HLEN + sizeof(*ip4) + 12, + &tcp_flags, 2) < 0) + return DROP_CT_INVALID_HDR; + + /* Setting the option is required only for the first packet + * (SYN), in the case of TCP, as for further packets of the + * same connection a remote node will use a NAT entry to + * reverse xlate a reply. + */ + if (!(tcp_flags.value & (TCP_FLAG_SYN))) + return 0; + } + + if (dsr_is_too_big(ctx, tot_len)) { + *ohead = sizeof(opt); + return DROP_FRAG_NEEDED; + } + + iph_old = *(__u32 *)ip4; + ip4->ihl += sizeof(opt) >> 2; + ip4->tot_len = bpf_htons(tot_len); + iph_new = *(__u32 *)ip4; + + opt[0] = bpf_htonl(DSR_IPV4_OPT_32 | svc_port); + opt[1] = bpf_htonl(svc_addr); + + sum = csum_diff(&iph_old, 4, &iph_new, 4, 0); + sum = csum_diff(NULL, 0, &opt, sizeof(opt), sum); + + if (ctx_adjust_hroom(ctx, sizeof(opt), BPF_ADJ_ROOM_NET, + ctx_adjust_hroom_dsr_flags())) + return DROP_INVALID; + + if (ctx_store_bytes(ctx, ETH_HLEN + sizeof(*ip4), + &opt, sizeof(opt), 0) < 0) + return DROP_INVALID; + if (l3_csum_replace(ctx, ETH_HLEN + offsetof(struct iphdr, check), + 0, sum, 0) < 0) + return DROP_CSUM_L3; + + return 0; +} +#endif /* DSR_ENCAP_MODE */ + +static __always_inline int handle_dsr_v4(struct __ctx_buff *ctx, bool *dsr) +{ + void *data, *data_end; + struct iphdr *ip4; + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + /* Check whether IPv4 header contains a 64-bit option (IPv4 header + * w/o option (5 x 32-bit words) + the DSR option (2 x 32-bit words)). + */ + if (ip4->ihl == 0x7) { + __u32 opt1 = 0, opt2 = 0; + __be32 address, dport; + + if (ctx_load_bytes(ctx, ETH_HLEN + sizeof(struct iphdr), + &opt1, sizeof(opt1)) < 0) + return DROP_INVALID; + + opt1 = bpf_ntohl(opt1); + if ((opt1 & DSR_IPV4_OPT_MASK) == DSR_IPV4_OPT_32) { + if (ctx_load_bytes(ctx, ETH_HLEN + + sizeof(struct iphdr) + + sizeof(opt1), + &opt2, sizeof(opt2)) < 0) + return DROP_INVALID; + + opt2 = bpf_ntohl(opt2); + dport = opt1 & DSR_IPV4_DPORT_MASK; + address = opt2; + *dsr = true; + + if (snat_v4_create_dsr(ctx, address, dport) < 0) + return DROP_INVALID; + } + } + + return 0; +} + +static __always_inline int xlate_dsr_v4(struct __ctx_buff *ctx, + const struct ipv4_ct_tuple *tuple, + int l4_off, bool has_l4_header) +{ + struct ipv4_ct_tuple nat_tup = *tuple; + struct ipv4_nat_entry *entry; + int ret = 0; + + nat_tup.flags = NAT_DIR_EGRESS; + nat_tup.sport = tuple->dport; + nat_tup.dport = tuple->sport; + + entry = snat_v4_lookup(&nat_tup); + if (entry) + ret = snat_v4_rewrite_egress(ctx, &nat_tup, entry, l4_off, has_l4_header); + return ret; +} + +static __always_inline int dsr_reply_icmp4(struct __ctx_buff *ctx, + struct iphdr *ip4 __maybe_unused, + int code, int ohead __maybe_unused) +{ +#ifdef ENABLE_DSR_ICMP_ERRORS + const __s32 orig_dgram = 8, off = ETH_HLEN; + const __u32 l3_max = MAX_IPOPTLEN + sizeof(*ip4) + orig_dgram; + __be16 type = bpf_htons(ETH_P_IP); + __s32 len_new = off + ipv4_hdrlen(ip4) + orig_dgram; + __s32 len_old = ctx_full_len(ctx); + __u8 tmp[l3_max]; + union macaddr smac, dmac; + struct icmphdr icmp __align_stack_8 = { + .type = ICMP_DEST_UNREACH, + .code = ICMP_FRAG_NEEDED, + .un = { + .frag = { + .mtu = bpf_htons(THIS_MTU - ohead), + }, + }, + }; + struct iphdr ip __align_stack_8 = { + .ihl = sizeof(ip) >> 2, + .version = IPVERSION, + .ttl = IPDEFTTL, + .tos = ip4->tos, + .id = ip4->id, + .protocol = IPPROTO_ICMP, + .saddr = ip4->daddr, + .daddr = ip4->saddr, + .frag_off = bpf_htons(IP_DF), + .tot_len = bpf_htons(sizeof(ip) + sizeof(icmp) + + len_new - off), + }; + + update_metrics(ctx_full_len(ctx), METRIC_EGRESS, -code); + + if (eth_load_saddr(ctx, smac.addr, 0) < 0) + goto drop_err; + if (eth_load_daddr(ctx, dmac.addr, 0) < 0) + goto drop_err; + + ip.check = csum_fold(csum_diff(NULL, 0, &ip, sizeof(ip), 0)); + + /* We use a workaround here in that we push zero-bytes into the + * payload in order to support dynamic IPv4 header size. This + * works given one's complement sum does not change. + */ + memset(tmp, 0, MAX_IPOPTLEN); + if (ctx_store_bytes(ctx, len_new, tmp, MAX_IPOPTLEN, 0) < 0) + goto drop_err; + if (ctx_load_bytes(ctx, off, tmp, sizeof(tmp)) < 0) + goto drop_err; + + icmp.checksum = csum_fold(csum_diff(NULL, 0, tmp, sizeof(tmp), + csum_diff(NULL, 0, &icmp, + sizeof(icmp), 0))); + + if (ctx_adjust_troom(ctx, -(len_old - len_new)) < 0) + goto drop_err; + if (ctx_adjust_hroom(ctx, sizeof(ip) + sizeof(icmp), + BPF_ADJ_ROOM_NET, + ctx_adjust_hroom_dsr_flags()) < 0) + goto drop_err; + + if (eth_store_daddr(ctx, smac.addr, 0) < 0) + goto drop_err; + if (eth_store_saddr(ctx, dmac.addr, 0) < 0) + goto drop_err; + if (ctx_store_bytes(ctx, ETH_ALEN * 2, &type, sizeof(type), 0) < 0) + goto drop_err; + if (ctx_store_bytes(ctx, off, &ip, sizeof(ip), 0) < 0) + goto drop_err; + if (ctx_store_bytes(ctx, off + sizeof(ip), &icmp, + sizeof(icmp), 0) < 0) + goto drop_err; + + return ctx_redirect(ctx, ctx_get_ifindex(ctx), 0); +drop_err: +#endif + return send_drop_notify_error(ctx, 0, code, CTX_ACT_DROP, + METRIC_EGRESS); +} + +__section_tail(CILIUM_MAP_CALLS, CILIUM_CALL_IPV4_NODEPORT_DSR) +int tail_nodeport_ipv4_dsr(struct __ctx_buff *ctx) +{ + struct bpf_fib_lookup_padded fib_params = { + .l = { + .family = AF_INET, + .ifindex = DIRECT_ROUTING_DEV_IFINDEX, + }, + }; + union macaddr *dmac = NULL; + void *data, *data_end; + int ret, ohead = 0; + struct iphdr *ip4; + bool l2_hdr_required = true; + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) { + ret = DROP_INVALID; + goto drop_err; + } + +#if DSR_ENCAP_MODE == DSR_ENCAP_IPIP + ret = dsr_set_ipip4(ctx, ip4, + ctx_load_meta(ctx, CB_ADDR_V4), + ctx_load_meta(ctx, CB_HINT), &ohead); +#elif DSR_ENCAP_MODE == DSR_ENCAP_NONE + ret = dsr_set_opt4(ctx, ip4, + ctx_load_meta(ctx, CB_ADDR_V4), + ctx_load_meta(ctx, CB_PORT), &ohead); +#else +# error "Invalid load balancer DSR encapsulation mode!" +#endif + if (unlikely(ret)) { + if (dsr_fail_needs_reply(ret)) + return dsr_reply_icmp4(ctx, ip4, ret, ohead); + goto drop_err; + } + if (!revalidate_data(ctx, &data, &data_end, &ip4)) { + ret = DROP_INVALID; + goto drop_err; + } + + ret = maybe_add_l2_hdr(ctx, DIRECT_ROUTING_DEV_IFINDEX, + &l2_hdr_required); + if (ret != 0) + goto drop_err; + if (!l2_hdr_required) + goto out_send; + else if (!revalidate_data_with_eth_hlen(ctx, &data, &data_end, &ip4, + __ETH_HLEN)) + return DROP_INVALID; + + if (nodeport_lb_hairpin()) + dmac = map_lookup_elem(&NODEPORT_NEIGH4, &ip4->daddr); + if (dmac) { + union macaddr mac = NATIVE_DEV_MAC_BY_IFINDEX(fib_params.l.ifindex); + + if (eth_store_daddr_aligned(ctx, dmac->addr, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + if (eth_store_saddr_aligned(ctx, mac.addr, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + } else { + fib_params.l.ipv4_src = ip4->saddr; + fib_params.l.ipv4_dst = ip4->daddr; + + ret = fib_lookup(ctx, &fib_params.l, sizeof(fib_params), + BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT); + if (ret != 0) { + ret = DROP_NO_FIB; + goto drop_err; + } + if (nodeport_lb_hairpin()) + map_update_elem(&NODEPORT_NEIGH4, &ip4->daddr, + fib_params.l.dmac, 0); + if (eth_store_daddr(ctx, fib_params.l.dmac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + if (eth_store_saddr(ctx, fib_params.l.smac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + } + +out_send: + cilium_capture_out(ctx); + return ctx_redirect(ctx, fib_params.l.ifindex, 0); +drop_err: + return send_drop_notify_error(ctx, 0, ret, CTX_ACT_DROP, METRIC_EGRESS); +} +#endif /* ENABLE_DSR */ + +__section_tail(CILIUM_MAP_CALLS, CILIUM_CALL_IPV4_NODEPORT_NAT) +int tail_nodeport_nat_ipv4(struct __ctx_buff *ctx) +{ + int ret, dir = ctx_load_meta(ctx, CB_NAT); + struct bpf_fib_lookup_padded fib_params = { + .l = { + .family = AF_INET, + .ifindex = DIRECT_ROUTING_DEV_IFINDEX, + }, + }; + struct ipv4_nat_target target = { + .min_port = NODEPORT_PORT_MIN_NAT, + .max_port = NODEPORT_PORT_MAX_NAT, + .src_from_world = true, + }; + union macaddr *dmac = NULL; + void *data, *data_end; + struct iphdr *ip4; + bool l2_hdr_required = true; + + target.addr = IPV4_DIRECT_ROUTING; +#ifdef TUNNEL_MODE + if (dir == NAT_DIR_EGRESS) { + struct remote_endpoint_info *info; + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) { + ret = DROP_INVALID; + goto drop_err; + } + + info = ipcache_lookup4(&IPCACHE_MAP, ip4->daddr, V4_CACHE_KEY_LEN); + if (info != NULL && info->tunnel_endpoint != 0) { + ret = __encap_with_nodeid(ctx, info->tunnel_endpoint, + SECLABEL, TRACE_PAYLOAD_LEN); + if (ret) + goto drop_err; + + target.addr = IPV4_GATEWAY; + fib_params.l.ifindex = ENCAP_IFINDEX; + + /* fib lookup not necessary when going over tunnel. */ + if (eth_store_daddr(ctx, fib_params.l.dmac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + if (eth_store_saddr(ctx, fib_params.l.smac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + } + } +#endif + /* Handles SNAT on NAT_DIR_EGRESS and reverse SNAT for reply packets + * from remote backends on NAT_DIR_INGRESS. + */ + ret = snat_v4_process(ctx, dir, &target, false); + if (IS_ERR(ret)) { + /* In case of no mapping, recircle back to main path. SNAT is very + * expensive in terms of instructions (since we don't have BPF to + * BPF calls as we use tail calls) and complexity, hence this is + * done inside a tail call here. + */ + if (dir == NAT_DIR_INGRESS) { + bpf_skip_nodeport_set(ctx); + ep_tail_call(ctx, CILIUM_CALL_IPV4_FROM_LXC); + ret = DROP_MISSED_TAIL_CALL; + goto drop_err; + } + if (ret != NAT_PUNT_TO_STACK) + goto drop_err; + } + + bpf_mark_snat_done(ctx); + + if (dir == NAT_DIR_INGRESS) { + /* Handle reverse DNAT for reply packets from remote backends. */ + ep_tail_call(ctx, CILIUM_CALL_IPV4_NODEPORT_REVNAT); + ret = DROP_MISSED_TAIL_CALL; + goto drop_err; + } +#ifdef TUNNEL_MODE + if (fib_params.l.ifindex == ENCAP_IFINDEX) + goto out_send; +#endif + if (!revalidate_data(ctx, &data, &data_end, &ip4)) { + ret = DROP_INVALID; + goto drop_err; + } + + ret = maybe_add_l2_hdr(ctx, DIRECT_ROUTING_DEV_IFINDEX, + &l2_hdr_required); + if (ret != 0) + goto drop_err; + if (!l2_hdr_required) + goto out_send; + else if (!revalidate_data_with_eth_hlen(ctx, &data, &data_end, &ip4, + __ETH_HLEN)) + return DROP_INVALID; + + if (nodeport_lb_hairpin()) + dmac = map_lookup_elem(&NODEPORT_NEIGH4, &ip4->daddr); + if (dmac) { + union macaddr mac = NATIVE_DEV_MAC_BY_IFINDEX(fib_params.l.ifindex); + + if (eth_store_daddr_aligned(ctx, dmac->addr, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + if (eth_store_saddr_aligned(ctx, mac.addr, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + } else { + fib_params.l.ipv4_src = ip4->saddr; + fib_params.l.ipv4_dst = ip4->daddr; + + ret = fib_lookup(ctx, &fib_params.l, sizeof(fib_params), + BPF_FIB_LOOKUP_DIRECT | BPF_FIB_LOOKUP_OUTPUT); + if (ret != 0) { + ret = DROP_NO_FIB; + goto drop_err; + } + if (nodeport_lb_hairpin()) + map_update_elem(&NODEPORT_NEIGH4, &ip4->daddr, + fib_params.l.dmac, 0); + + if (eth_store_daddr(ctx, fib_params.l.dmac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + if (eth_store_saddr(ctx, fib_params.l.smac, 0) < 0) { + ret = DROP_WRITE_ERROR; + goto drop_err; + } + } +out_send: + cilium_capture_out(ctx); + return ctx_redirect(ctx, fib_params.l.ifindex, 0); +drop_err: + return send_drop_notify_error(ctx, 0, ret, CTX_ACT_DROP, + dir == NAT_DIR_INGRESS ? + METRIC_INGRESS : METRIC_EGRESS); +} + +/* Main node-port entry point for host-external ingressing node-port traffic + * which handles the case of: i) backend is local EP, ii) backend is remote EP, + * iii) reply from remote backend EP. + */ +static __always_inline int nodeport_lb4(struct __ctx_buff *ctx, + __u32 src_identity) +{ + struct ipv4_ct_tuple tuple = {}; + void *data, *data_end; + struct iphdr *ip4; + int ret, l3_off = ETH_HLEN, l4_off; + struct csum_offset csum_off = {}; + struct lb4_service *svc; + struct lb4_key key = {}; + struct ct_state ct_state_new = {}; + union macaddr smac, *mac; + bool backend_local; + __u32 monitor = 0; + + cilium_capture_in(ctx); + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + tuple.nexthdr = ip4->protocol; + tuple.daddr = ip4->daddr; + tuple.saddr = ip4->saddr; + + l4_off = l3_off + ipv4_hdrlen(ip4); + + ret = lb4_extract_key(ctx, ip4, l4_off, &key, &csum_off, CT_EGRESS); + if (IS_ERR(ret)) { + if (ret == DROP_NO_SERVICE) + goto skip_service_lookup; + else if (ret == DROP_UNKNOWN_L4) + return CTX_ACT_OK; + else + return ret; + } + + svc = lb4_lookup_service(&key, false); + if (svc) { + const bool skip_l3_xlate = DSR_ENCAP_MODE == DSR_ENCAP_IPIP; + + if (!lb4_src_range_ok(svc, ip4->saddr)) + return DROP_NOT_IN_SRC_RANGE; + + ret = lb4_local(get_ct_map4(&tuple), ctx, l3_off, l4_off, + &csum_off, &key, &tuple, svc, &ct_state_new, + ip4->saddr, ipv4_has_l4_header(ip4), + skip_l3_xlate); + if (IS_ERR(ret)) + return ret; + } + + if (!svc || !lb4_svc_is_routable(svc)) { + if (svc) + return DROP_IS_CLUSTER_IP; + + /* The packet is not destined to a service but it can be a reply + * packet from a remote backend, in which case we need to perform + * the reverse NAT. + */ +skip_service_lookup: + ctx_set_xfer(ctx, XFER_PKT_NO_SVC); + +#ifndef ENABLE_MASQUERADE + if (nodeport_uses_dsr4(&tuple)) + return CTX_ACT_OK; +#endif + + ctx_store_meta(ctx, CB_NAT, NAT_DIR_INGRESS); + ctx_store_meta(ctx, CB_SRC_IDENTITY, src_identity); + ep_tail_call(ctx, CILIUM_CALL_IPV4_NODEPORT_NAT); + return DROP_MISSED_TAIL_CALL; + } + + backend_local = __lookup_ip4_endpoint(tuple.daddr); + if (!backend_local && lb4_svc_is_hostport(svc)) + return DROP_INVALID; + + /* Reply from DSR packet is never seen on this node again hence no + * need to track in here. + */ + if (backend_local || !nodeport_uses_dsr4(&tuple)) { + struct ct_state ct_state = {}; + + ret = ct_lookup4(get_ct_map4(&tuple), &tuple, ctx, l4_off, + CT_EGRESS, &ct_state, &monitor); + switch (ret) { + case CT_NEW: +redo_all: + ct_state_new.src_sec_id = SECLABEL; + ct_state_new.node_port = 1; + ct_state_new.ifindex = NATIVE_DEV_IFINDEX; + ret = ct_create4(get_ct_map4(&tuple), NULL, &tuple, ctx, + CT_EGRESS, &ct_state_new, false); + if (IS_ERR(ret)) + return ret; + if (backend_local) { + ct_flip_tuple_dir4(&tuple); +redo_local: + /* Reset rev_nat_index, otherwise ipv4_policy() + * in bpf_lxc will do invalid xlation. + */ + ct_state_new.rev_nat_index = 0; + ret = ct_create4(get_ct_map4(&tuple), NULL, + &tuple, ctx, CT_INGRESS, + &ct_state_new, false); + if (IS_ERR(ret)) + return ret; + } + break; + case CT_REOPENED: + case CT_ESTABLISHED: + case CT_REPLY: + /* Recreate CT entries, as the existing one is stale and + * belongs to a flow which target a different svc. + */ + if (unlikely(ct_state.rev_nat_index != + svc->rev_nat_index)) + goto redo_all; + if (backend_local) { + ct_flip_tuple_dir4(&tuple); + if (!__ct_entry_keep_alive(get_ct_map4(&tuple), + &tuple)) { + ct_state_new.src_sec_id = SECLABEL; + ct_state_new.node_port = 1; + ct_state_new.ifindex = NATIVE_DEV_IFINDEX; + goto redo_local; + } + } + break; + default: + return DROP_UNKNOWN_CT; + } + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + if (eth_load_saddr(ctx, smac.addr, 0) < 0) + return DROP_INVALID; + + mac = map_lookup_elem(&NODEPORT_NEIGH4, &ip4->saddr); + if (!mac || eth_addrcmp(mac, &smac)) { + ret = map_update_elem(&NODEPORT_NEIGH4, &ip4->saddr, + &smac, 0); + if (ret < 0) + return ret; + } + } + + if (!backend_local) { + edt_set_aggregate(ctx, 0); + if (nodeport_uses_dsr4(&tuple)) { +#if DSR_ENCAP_MODE == DSR_ENCAP_IPIP + ctx_store_meta(ctx, CB_HINT, + ((__u32)tuple.sport << 16) | tuple.dport); + ctx_store_meta(ctx, CB_ADDR_V4, tuple.daddr); +#elif DSR_ENCAP_MODE == DSR_ENCAP_NONE + ctx_store_meta(ctx, CB_PORT, key.dport); + ctx_store_meta(ctx, CB_ADDR_V4, key.address); +#endif /* DSR_ENCAP_MODE */ + ep_tail_call(ctx, CILIUM_CALL_IPV4_NODEPORT_DSR); + } else { + ctx_store_meta(ctx, CB_NAT, NAT_DIR_EGRESS); + ep_tail_call(ctx, CILIUM_CALL_IPV4_NODEPORT_NAT); + } + return DROP_MISSED_TAIL_CALL; + } + + ctx_set_xfer(ctx, XFER_PKT_NO_SVC); + + return CTX_ACT_OK; +} + +/* Reverse NAT handling of node-port traffic for the case where the + * backend i) was a local EP and bpf_lxc redirected to us, ii) was + * a remote backend and we got here after reverse SNAT from the + * tail_nodeport_nat_ipv4(). + * + * CILIUM_CALL_IPV{4,6}_NODEPORT_REVNAT is plugged into CILIUM_MAP_CALLS + * of the bpf_host, bpf_overlay and of the bpf_lxc. + */ +static __always_inline int rev_nodeport_lb4(struct __ctx_buff *ctx, int *ifindex) +{ + struct ipv4_ct_tuple tuple = {}; + void *data, *data_end; + struct iphdr *ip4; + struct csum_offset csum_off = {}; + int ret, ret2, l3_off = ETH_HLEN, l4_off; + struct ct_state ct_state = {}; + struct bpf_fib_lookup fib_params = {}; + union macaddr *dmac = NULL; + __u32 monitor = 0; + bool l2_hdr_required = true; + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + tuple.nexthdr = ip4->protocol; + tuple.daddr = ip4->daddr; + tuple.saddr = ip4->saddr; + + l4_off = l3_off + ipv4_hdrlen(ip4); + csum_l4_offset_and_flags(tuple.nexthdr, &csum_off); + + ret = ct_lookup4(get_ct_map4(&tuple), &tuple, ctx, l4_off, CT_INGRESS, &ct_state, + &monitor); + + if (ret == CT_REPLY && ct_state.node_port == 1 && ct_state.rev_nat_index != 0) { + ret2 = lb4_rev_nat(ctx, l3_off, l4_off, &csum_off, + &ct_state, &tuple, + REV_NAT_F_TUPLE_SADDR, ipv4_has_l4_header(ip4)); + if (IS_ERR(ret2)) + return ret2; + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + bpf_mark_snat_done(ctx); + + *ifindex = ct_state.ifindex; +#ifdef TUNNEL_MODE + { + struct remote_endpoint_info *info; + + info = ipcache_lookup4(&IPCACHE_MAP, ip4->daddr, V4_CACHE_KEY_LEN); + if (info != NULL && info->tunnel_endpoint != 0) { + ret = __encap_with_nodeid(ctx, info->tunnel_endpoint, + SECLABEL, TRACE_PAYLOAD_LEN); + if (ret) + return ret; + + *ifindex = ENCAP_IFINDEX; + + /* fib lookup not necessary when going over tunnel. */ + if (eth_store_daddr(ctx, fib_params.dmac, 0) < 0) + return DROP_WRITE_ERROR; + if (eth_store_saddr(ctx, fib_params.smac, 0) < 0) + return DROP_WRITE_ERROR; + + return CTX_ACT_OK; + } + } +#endif + + ret = maybe_add_l2_hdr(ctx, *ifindex, &l2_hdr_required); + if (ret != 0) + return ret; + if (!l2_hdr_required) + return CTX_ACT_OK; + else if (!revalidate_data_with_eth_hlen(ctx, &data, &data_end, + &ip4, __ETH_HLEN)) + return DROP_INVALID; + + if (fib_lookup_bypass()) + dmac = map_lookup_elem(&NODEPORT_NEIGH4, &ip4->daddr); + if (dmac) { + union macaddr mac = NATIVE_DEV_MAC_BY_IFINDEX(*ifindex); + + if (eth_store_daddr_aligned(ctx, dmac->addr, 0) < 0) + return DROP_WRITE_ERROR; + if (eth_store_saddr_aligned(ctx, mac.addr, 0) < 0) + return DROP_WRITE_ERROR; + } else { + fib_params.family = AF_INET; + fib_params.ifindex = *ifindex; + + fib_params.ipv4_src = ip4->saddr; + fib_params.ipv4_dst = ip4->daddr; + + ret = fib_lookup(ctx, &fib_params, sizeof(fib_params), + BPF_FIB_LOOKUP_DIRECT | + BPF_FIB_LOOKUP_OUTPUT); + if (ret != 0) + return DROP_NO_FIB; + + if (eth_store_daddr(ctx, fib_params.dmac, 0) < 0) + return DROP_WRITE_ERROR; + if (eth_store_saddr(ctx, fib_params.smac, 0) < 0) + return DROP_WRITE_ERROR; + } + } else { + if (!bpf_skip_recirculation(ctx)) { + bpf_skip_nodeport_set(ctx); + ep_tail_call(ctx, CILIUM_CALL_IPV4_FROM_LXC); + return DROP_MISSED_TAIL_CALL; + } + } + + return CTX_ACT_OK; +} + +__section_tail(CILIUM_MAP_CALLS, CILIUM_CALL_IPV4_NODEPORT_REVNAT) +int tail_rev_nodeport_lb4(struct __ctx_buff *ctx) +{ + int ifindex = 0; + int ret = 0; +#if defined(ENABLE_HOST_FIREWALL) && defined(IS_BPF_HOST) + /* We only enforce the host policies if nodeport.h is included from + * bpf_host. + */ + __u32 src_id = 0; + + ret = ipv4_host_policy_ingress(ctx, &src_id); + if (IS_ERR(ret)) + return send_drop_notify_error(ctx, src_id, ret, CTX_ACT_DROP, + METRIC_INGRESS); + /* We don't want to enforce host policies a second time if we jump back to + * bpf_host's handle_ipv6. + */ + ctx_skip_host_fw_set(ctx); +#endif + ret = rev_nodeport_lb4(ctx, &ifindex); + if (IS_ERR(ret)) + return send_drop_notify_error(ctx, 0, ret, CTX_ACT_DROP, METRIC_EGRESS); + + edt_set_aggregate(ctx, 0); + cilium_capture_out(ctx); + + return ctx_redirect(ctx, ifindex, 0); +} + +declare_tailcall_if(__or3(__and(is_defined(ENABLE_IPV4), + is_defined(ENABLE_IPV6)), + __and(is_defined(ENABLE_HOST_FIREWALL), + is_defined(IS_BPF_HOST)), + is_defined(ENABLE_EGRESS_GATEWAY)), + CILIUM_CALL_IPV4_ENCAP_NODEPORT_NAT) +int tail_handle_nat_fwd_ipv4(struct __ctx_buff *ctx) +{ + return nodeport_nat_ipv4_fwd(ctx); +} +#endif /* ENABLE_IPV4 */ + +#ifdef ENABLE_HEALTH_CHECK +static __always_inline int +health_encap_v4(struct __ctx_buff *ctx, __u32 tunnel_ep, + __u32 seclabel) +{ + struct bpf_tunnel_key key; + + /* When encapsulating, a packet originating from the local + * host is being considered as a packet from a remote node + * as it is being received. + */ + memset(&key, 0, sizeof(key)); + key.tunnel_id = seclabel == HOST_ID ? LOCAL_NODE_ID : seclabel; + key.remote_ipv4 = bpf_htonl(tunnel_ep); + key.tunnel_ttl = 64; + + if (unlikely(ctx_set_tunnel_key(ctx, &key, sizeof(key), + BPF_F_ZERO_CSUM_TX) < 0)) + return DROP_WRITE_ERROR; + return 0; +} + +static __always_inline int +health_encap_v6(struct __ctx_buff *ctx, const union v6addr *tunnel_ep, + __u32 seclabel) +{ + struct bpf_tunnel_key key; + + memset(&key, 0, sizeof(key)); + key.tunnel_id = seclabel == HOST_ID ? LOCAL_NODE_ID : seclabel; + key.remote_ipv6[0] = tunnel_ep->p1; + key.remote_ipv6[1] = tunnel_ep->p2; + key.remote_ipv6[2] = tunnel_ep->p3; + key.remote_ipv6[3] = tunnel_ep->p4; + key.tunnel_ttl = 64; + + if (unlikely(ctx_set_tunnel_key(ctx, &key, sizeof(key), + BPF_F_ZERO_CSUM_TX | + BPF_F_TUNINFO_IPV6) < 0)) + return DROP_WRITE_ERROR; + return 0; +} + +static __always_inline int +lb_handle_health(struct __ctx_buff *ctx __maybe_unused) +{ + void *data __maybe_unused, *data_end __maybe_unused; + __sock_cookie key __maybe_unused; + int ret __maybe_unused; + __u16 proto = 0; + + if ((ctx->mark & MARK_MAGIC_HEALTH_IPIP_DONE) == + MARK_MAGIC_HEALTH_IPIP_DONE) + return CTX_ACT_OK; + validate_ethertype(ctx, &proto); + switch (proto) { +#if defined(ENABLE_IPV4) && DSR_ENCAP_MODE == DSR_ENCAP_IPIP + case bpf_htons(ETH_P_IP): { + struct lb4_health *val; + + key = get_socket_cookie(ctx); + val = map_lookup_elem(&LB4_HEALTH_MAP, &key); + if (!val) + return CTX_ACT_OK; + ret = health_encap_v4(ctx, val->peer.address, 0); + if (ret != 0) + return ret; + ctx->mark |= MARK_MAGIC_HEALTH_IPIP_DONE; + return redirect(ENCAP4_IFINDEX, 0); + } +#endif +#if defined(ENABLE_IPV6) && DSR_ENCAP_MODE == DSR_ENCAP_IPIP + case bpf_htons(ETH_P_IPV6): { + struct lb6_health *val; + + key = get_socket_cookie(ctx); + val = map_lookup_elem(&LB6_HEALTH_MAP, &key); + if (!val) + return CTX_ACT_OK; + ret = health_encap_v6(ctx, &val->peer.address, 0); + if (ret != 0) + return ret; + ctx->mark |= MARK_MAGIC_HEALTH_IPIP_DONE; + return redirect(ENCAP6_IFINDEX, 0); + } +#endif + default: + return CTX_ACT_OK; + } +} +#endif /* ENABLE_HEALTH_CHECK */ + +static __always_inline int handle_nat_fwd(struct __ctx_buff *ctx) +{ + int ret = CTX_ACT_OK; + __u16 proto; + + if (!validate_ethertype(ctx, &proto)) + return CTX_ACT_OK; + switch (proto) { +#ifdef ENABLE_IPV4 + case bpf_htons(ETH_P_IP): + invoke_tailcall_if(__or3(__and(is_defined(ENABLE_IPV4), + is_defined(ENABLE_IPV6)), + __and(is_defined(ENABLE_HOST_FIREWALL), + is_defined(IS_BPF_HOST)), + is_defined(ENABLE_EGRESS_GATEWAY)), + CILIUM_CALL_IPV4_ENCAP_NODEPORT_NAT, + tail_handle_nat_fwd_ipv4); + break; +#endif /* ENABLE_IPV4 */ +#ifdef ENABLE_IPV6 + case bpf_htons(ETH_P_IPV6): + invoke_tailcall_if(__or(__and(is_defined(ENABLE_IPV4), + is_defined(ENABLE_IPV6)), + __and(is_defined(ENABLE_HOST_FIREWALL), + is_defined(IS_BPF_HOST))), + CILIUM_CALL_IPV6_ENCAP_NODEPORT_NAT, + tail_handle_nat_fwd_ipv6); + break; +#endif /* ENABLE_IPV6 */ + default: + build_bug_on(!(NODEPORT_PORT_MIN_NAT < NODEPORT_PORT_MAX_NAT)); + build_bug_on(!(NODEPORT_PORT_MIN < NODEPORT_PORT_MAX)); + build_bug_on(!(NODEPORT_PORT_MAX < NODEPORT_PORT_MIN_NAT)); + break; + } + return ret; +} + +#endif /* ENABLE_NODEPORT */ +#endif /* __NODEPORT_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/overloadable.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/overloadable.h new file mode 100644 index 000000000..e62833c64 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/overloadable.h @@ -0,0 +1,16 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __LIB_OVERLOADABLE_H_ +#define __LIB_OVERLOADABLE_H_ + +#include +#include + +#if __ctx_is == __ctx_skb +# include "lib/overloadable_skb.h" +#else +# include "lib/overloadable_xdp.h" +#endif + +#endif /* __LIB_OVERLOADABLE_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/overloadable_skb.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/overloadable_skb.h new file mode 100644 index 000000000..90e822233 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/overloadable_skb.h @@ -0,0 +1,157 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __LIB_OVERLOADABLE_SKB_H_ +#define __LIB_OVERLOADABLE_SKB_H_ + +static __always_inline __maybe_unused void +bpf_clear_meta(struct __sk_buff *ctx) +{ + __u32 zero = 0; + + WRITE_ONCE(ctx->cb[0], zero); + WRITE_ONCE(ctx->cb[1], zero); + WRITE_ONCE(ctx->cb[2], zero); + WRITE_ONCE(ctx->cb[3], zero); + WRITE_ONCE(ctx->cb[4], zero); +} + +/** + * get_identity - returns source identity from the mark field + */ +static __always_inline __maybe_unused int +get_identity(const struct __sk_buff *ctx) +{ + return ((ctx->mark & 0xFF) << 16) | ctx->mark >> 16; +} + +static __always_inline __maybe_unused void +set_encrypt_dip(struct __sk_buff *ctx, __u32 ip_endpoint) +{ + ctx->cb[4] = ip_endpoint; +} + +/** + * set_identity_mark - pushes 24 bit identity into ctx mark value. + */ +static __always_inline __maybe_unused void +set_identity_mark(struct __sk_buff *ctx, __u32 identity) +{ + ctx->mark = ctx->mark & MARK_MAGIC_KEY_MASK; + ctx->mark |= ((identity & 0xFFFF) << 16) | ((identity & 0xFF0000) >> 16); +} + +static __always_inline __maybe_unused void +set_identity_meta(struct __sk_buff *ctx, __u32 identity) +{ + ctx->cb[1] = identity; +} + +/** + * set_encrypt_key - pushes 8 bit key and encryption marker into ctx mark value. + */ +static __always_inline __maybe_unused void +set_encrypt_key_mark(struct __sk_buff *ctx, __u8 key) +{ + ctx->mark = or_encrypt_key(key); +} + +static __always_inline __maybe_unused void +set_encrypt_key_meta(struct __sk_buff *ctx, __u8 key) +{ + ctx->cb[0] = or_encrypt_key(key); +} + +/** + * set_encrypt_mark - sets the encryption mark to make skb to match ip rule + * used to steer packet into Wireguard tunnel device (cilium_wg0) in order to + * encrypt it. + */ +static __always_inline __maybe_unused void +set_encrypt_mark(struct __sk_buff *ctx) +{ + ctx->mark |= MARK_MAGIC_ENCRYPT; +} + +static __always_inline __maybe_unused int +redirect_self(const struct __sk_buff *ctx) +{ + /* Looping back the packet into the originating netns. In + * case of veth, it's xmit'ing into the hosts' veth device + * such that we end up on ingress in the peer. For ipvlan + * slave it's redirect to ingress as we are attached on the + * slave in netns already. + */ +#ifdef ENABLE_HOST_REDIRECT + return redirect(ctx->ifindex, 0); +#else + return redirect(ctx->ifindex, BPF_F_INGRESS); +#endif +} + +static __always_inline __maybe_unused void +ctx_skip_nodeport_clear(struct __sk_buff *ctx __maybe_unused) +{ +#ifdef ENABLE_NODEPORT + ctx->tc_index &= ~TC_INDEX_F_SKIP_NODEPORT; +#endif +} + +static __always_inline __maybe_unused void +ctx_skip_nodeport_set(struct __sk_buff *ctx __maybe_unused) +{ +#ifdef ENABLE_NODEPORT + ctx->tc_index |= TC_INDEX_F_SKIP_NODEPORT; +#endif +} + +static __always_inline __maybe_unused bool +ctx_skip_nodeport(struct __sk_buff *ctx __maybe_unused) +{ +#ifdef ENABLE_NODEPORT + volatile __u32 tc_index = ctx->tc_index; + ctx->tc_index &= ~TC_INDEX_F_SKIP_NODEPORT; + return tc_index & TC_INDEX_F_SKIP_NODEPORT; +#else + return true; +#endif +} + +#ifdef ENABLE_HOST_FIREWALL +static __always_inline void +ctx_skip_host_fw_set(struct __sk_buff *ctx) +{ + ctx->tc_index |= TC_INDEX_F_SKIP_HOST_FIREWALL; +} + +static __always_inline bool +ctx_skip_host_fw(struct __sk_buff *ctx) +{ + volatile __u32 tc_index = ctx->tc_index; + + ctx->tc_index &= ~TC_INDEX_F_SKIP_HOST_FIREWALL; + return tc_index & TC_INDEX_F_SKIP_HOST_FIREWALL; +} +#endif /* ENABLE_HOST_FIREWALL */ + +static __always_inline __maybe_unused __u32 ctx_get_xfer(struct __sk_buff *ctx) +{ + __u32 *data_meta = ctx_data_meta(ctx); + void *data = ctx_data(ctx); + + return !ctx_no_room(data_meta + 1, data) ? data_meta[0] : 0; +} + +static __always_inline __maybe_unused void +ctx_set_xfer(struct __sk_buff *ctx __maybe_unused, __u32 meta __maybe_unused) +{ + /* Only possible from XDP -> SKB. */ +} + +static __always_inline __maybe_unused int +ctx_change_head(struct __sk_buff *ctx, __u32 head_room, __u64 flags) +{ + return skb_change_head(ctx, head_room, flags); +} + +#endif /* __LIB_OVERLOADABLE_SKB_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/overloadable_xdp.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/overloadable_xdp.h new file mode 100644 index 000000000..3d871bd4b --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/overloadable_xdp.h @@ -0,0 +1,104 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2020 Authors of Cilium */ + +#ifndef __LIB_OVERLOADABLE_XDP_H_ +#define __LIB_OVERLOADABLE_XDP_H_ + +static __always_inline __maybe_unused void +bpf_clear_meta(struct xdp_md *ctx __maybe_unused) +{ +} + +static __always_inline __maybe_unused int +get_identity(struct xdp_md *ctx __maybe_unused) +{ + return 0; +} + +static __always_inline __maybe_unused void +set_encrypt_dip(struct xdp_md *ctx __maybe_unused, + __u32 ip_endpoint __maybe_unused) +{ +} + +static __always_inline __maybe_unused void +set_identity_mark(struct xdp_md *ctx __maybe_unused, __u32 identity __maybe_unused) +{ +} + +static __always_inline __maybe_unused void +set_identity_meta(struct xdp_md *ctx __maybe_unused, + __u32 identity __maybe_unused) +{ +} + +static __always_inline __maybe_unused void +set_encrypt_key_mark(struct xdp_md *ctx __maybe_unused, __u8 key __maybe_unused) +{ +} + +static __always_inline __maybe_unused void +set_encrypt_key_meta(struct xdp_md *ctx __maybe_unused, __u8 key __maybe_unused) +{ +} + +static __always_inline __maybe_unused int +redirect_self(struct xdp_md *ctx __maybe_unused) +{ +#ifdef ENABLE_HOST_REDIRECT + return XDP_TX; +#else + return -ENOTSUP; +#endif +} + +#define RECIRC_MARKER 5 /* tail call recirculation */ +#define XFER_MARKER 6 /* xdp -> skb meta transfer */ + +static __always_inline __maybe_unused void +ctx_skip_nodeport_clear(struct xdp_md *ctx __maybe_unused) +{ +#ifdef ENABLE_NODEPORT + ctx_store_meta(ctx, RECIRC_MARKER, 0); +#endif +} + +static __always_inline __maybe_unused void +ctx_skip_nodeport_set(struct xdp_md *ctx __maybe_unused) +{ +#ifdef ENABLE_NODEPORT + ctx_store_meta(ctx, RECIRC_MARKER, 1); +#endif +} + +static __always_inline __maybe_unused bool +ctx_skip_nodeport(struct xdp_md *ctx __maybe_unused) +{ +#ifdef ENABLE_NODEPORT + return ctx_load_meta(ctx, RECIRC_MARKER); +#else + return true; +#endif +} + +static __always_inline __maybe_unused __u32 +ctx_get_xfer(struct xdp_md *ctx __maybe_unused) +{ + return 0; /* Only intended for SKB context. */ +} + +static __always_inline __maybe_unused void ctx_set_xfer(struct xdp_md *ctx, + __u32 meta) +{ + ctx_store_meta(ctx, XFER_MARKER, meta); +} + +static __always_inline __maybe_unused int +ctx_change_head(struct xdp_md *ctx __maybe_unused, + __u32 head_room __maybe_unused, + __u64 flags __maybe_unused) +{ + return 0; /* Only intended for SKB context. */ +} + +#endif /* __LIB_OVERLOADABLE_XDP_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/pcap.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/pcap.h new file mode 100644 index 000000000..33d6ec1ef --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/pcap.h @@ -0,0 +1,483 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2021 Authors of Cilium */ + +#ifndef __LIB_PCAP_H_ +#define __LIB_PCAP_H_ + +#include +#include + +#include "common.h" +#include "lb.h" + +struct pcap_timeval { + __u32 tv_sec; + __u32 tv_usec; +}; + +struct pcap_timeoff { + __u64 tv_boot; +}; + +struct pcap_pkthdr { + union { + /* User space needs to perform inline conversion from + * boot offset to time of day before writing out to + * an external file. + */ + struct pcap_timeval ts; + struct pcap_timeoff to; + }; + __u32 caplen; + __u32 len; +}; + +struct capture_msg { + /* The hash is reserved and always zero for allowing different + * header extensions in future. + */ + NOTIFY_COMMON_HDR + /* The pcap hdr must be the last member so that the placement + * inside the perf RB is linear: pcap hdr + packet payload. + */ + struct pcap_pkthdr hdr; +}; + +static __always_inline void cilium_capture(struct __ctx_buff *ctx, + const __u8 subtype, + const __u16 rule_id, + const __u64 tstamp, + __u64 __cap_len) +{ + __u64 ctx_len = ctx_full_len(ctx); + __u64 cap_len = (!__cap_len || ctx_len < __cap_len) ? + ctx_len : __cap_len; + /* rule_id is the demuxer for the target pcap file when there are + * multiple capturing rules present. + */ + struct capture_msg msg = { + .type = CILIUM_NOTIFY_CAPTURE, + .subtype = subtype, + .source = rule_id, + .hdr = { + .to = { + .tv_boot = tstamp, + }, + .caplen = cap_len, + .len = ctx_len, + }, + }; + + ctx_event_output(ctx, &EVENTS_MAP, (cap_len << 32) | BPF_F_CURRENT_CPU, + &msg, sizeof(msg)); +} + +static __always_inline void __cilium_capture_in(struct __ctx_buff *ctx, + __u16 rule_id, __u32 cap_len) +{ + /* For later pcap file generation, we export boot time to the RB + * such that user space can later reconstruct a real time of day + * timestamp in-place. + */ + cilium_capture(ctx, CAPTURE_INGRESS, rule_id, + bpf_ktime_cache_set(boot_ns), cap_len); +} + +static __always_inline void __cilium_capture_out(struct __ctx_buff *ctx, + __u16 rule_id, __u32 cap_len) +{ + cilium_capture(ctx, CAPTURE_EGRESS, rule_id, + bpf_ktime_cache_get(), cap_len); +} + +/* The capture_enabled integer ({0,1}) is enabled/disabled via BPF based ELF + * templating. Meaning, when disabled, the verifier's dead code elimination + * will ensure that there is no overhead when the facility is not used. The + * below is a fallback definition for when the templating var is not defined. + */ +#ifndef capture_enabled +# define capture_enabled (__ctx_is == __ctx_xdp) +#endif /* capture_enabled */ + +struct capture_cache { + bool rule_seen; + __u16 rule_id; + __u16 cap_len; +}; + +struct bpf_elf_map __section_maps cilium_capture_cache = { + .type = BPF_MAP_TYPE_PERCPU_ARRAY, + .size_key = sizeof(__u32), + .size_value = sizeof(struct capture_cache), + .pinning = PIN_GLOBAL_NS, + .max_elem = 1, +}; + +struct capture_rule { + __u16 rule_id; + __u16 reserved; + __u32 cap_len; +}; + +/* 5-tuple wildcard key / mask. */ +struct capture4_wcard { + __be32 saddr; /* masking: prefix */ + __be32 daddr; /* masking: prefix */ + __be16 sport; /* masking: 0 or 0xffff */ + __be16 dport; /* masking: 0 or 0xffff */ + __u8 nexthdr; /* masking: 0 or 0xff */ + __u8 smask; /* prefix len: saddr */ + __u8 dmask; /* prefix len: daddr */ + __u8 flags; /* reserved: 0 */ +}; + +/* 5-tuple wildcard key / mask. */ +struct capture6_wcard { + union v6addr saddr; /* masking: prefix */ + union v6addr daddr; /* masking: prefix */ + __be16 sport; /* masking: 0 or 0xffff */ + __be16 dport; /* masking: 0 or 0xffff */ + __u8 nexthdr; /* masking: 0 or 0xff */ + __u8 smask; /* prefix len: saddr */ + __u8 dmask; /* prefix len: daddr */ + __u8 flags; /* reserved: 0 */ +}; + +#if defined(ENABLE_IPV4) && defined(ENABLE_CAPTURE) +struct bpf_elf_map __section_maps CAPTURE4_RULES = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(struct capture4_wcard), + .size_value = sizeof(struct capture_rule), + .pinning = PIN_GLOBAL_NS, + .max_elem = CAPTURE4_SIZE, + .flags = BPF_F_NO_PREALLOC, +}; + +static __always_inline void +cilium_capture4_masked_key(const struct capture4_wcard *orig, + const struct capture4_wcard *mask, + struct capture4_wcard *out) +{ + out->daddr = orig->daddr & mask->daddr; + out->saddr = orig->saddr & mask->saddr; + out->dport = orig->dport & mask->dport; + out->sport = orig->sport & mask->sport; + out->nexthdr = orig->nexthdr & mask->nexthdr; + out->dmask = mask->dmask; + out->smask = mask->smask; +} + +/* The agent is generating and emitting the PREFIX_MASKS4 and regenerating + * if a mask was added or removed. The cilium_capture4_rules can have n + * entries with m different PREFIX_MASKS4 where n >> m. Lookup performance + * depends mainly on m. Below is a fallback / example definition mainly for + * compile testing given agent typically emits this instead. Ordering of + * masks from agent side can f.e. be based on # of 1s from high to low. + */ +#ifndef PREFIX_MASKS4 +# define PREFIX_MASKS4 \ + { \ + /* rule_id 1: \ + * srcIP/32, dstIP/32, dport, nexthdr \ + */ \ + .daddr = 0xffffffff, \ + .dmask = 32, \ + .saddr = 0xffffffff, \ + .smask = 32, \ + .dport = 0xffff, \ + .sport = 0, \ + .nexthdr = 0xff, \ + }, { \ + /* rule_id 2 (1st mask): \ + * srcIP/32 or dstIP/32 \ + */ \ + .daddr = 0xffffffff, \ + .dmask = 32, \ + .saddr = 0, \ + .smask = 0, \ + .dport = 0, \ + .sport = 0, \ + .nexthdr = 0, \ + }, { \ + /* rule_id 2 (2nd mask): \ + * srcIP/32 or dstIP/32 \ + */ \ + .daddr = 0, \ + .dmask = 0, \ + .saddr = 0xffffffff, \ + .smask = 32, \ + .dport = 0, \ + .sport = 0, \ + .nexthdr = 0, \ + }, +#endif /* PREFIX_MASKS4 */ + +static __always_inline struct capture_rule * +cilium_capture4_classify_wcard(struct __ctx_buff *ctx) +{ + struct capture4_wcard prefix_masks[] = { PREFIX_MASKS4 }; + struct capture4_wcard okey, lkey; + struct capture_rule *match; + void *data, *data_end; + struct iphdr *ip4; + int i; + const int size = sizeof(prefix_masks) / + sizeof(prefix_masks[0]); + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return NULL; + + okey.daddr = ip4->daddr; + okey.dmask = 32; + okey.saddr = ip4->saddr; + okey.smask = 32; + okey.nexthdr = ip4->protocol; + + if (ip4->protocol != IPPROTO_TCP && + ip4->protocol != IPPROTO_UDP) + return NULL; + if (ctx_load_bytes(ctx, ETH_HLEN + ipv4_hdrlen(ip4), + &okey.sport, 4) < 0) + return NULL; + + okey.flags = 0; + lkey.flags = 0; + +_Pragma("unroll") + for (i = 0; i < size; i++) { + cilium_capture4_masked_key(&okey, &prefix_masks[i], &lkey); + match = map_lookup_elem(&cilium_capture4_rules, &lkey); + if (match) + return match; + } + + return NULL; +} +#endif /* ENABLE_IPV4 && ENABLE_CAPTURE */ + +#if defined(ENABLE_IPV6) && defined(ENABLE_CAPTURE) +struct bpf_elf_map __section_maps CAPTURE6_RULES = { + .type = BPF_MAP_TYPE_HASH, + .size_key = sizeof(struct capture6_wcard), + .size_value = sizeof(struct capture_rule), + .pinning = PIN_GLOBAL_NS, + .max_elem = CAPTURE6_SIZE, + .flags = BPF_F_NO_PREALLOC, +}; + +static __always_inline void +cilium_capture6_masked_key(const struct capture6_wcard *orig, + const struct capture6_wcard *mask, + struct capture6_wcard *out) +{ + out->daddr.d1 = orig->daddr.d1 & mask->daddr.d1; + out->daddr.d2 = orig->daddr.d2 & mask->daddr.d2; + out->saddr.d1 = orig->saddr.d1 & mask->saddr.d1; + out->saddr.d2 = orig->saddr.d2 & mask->saddr.d2; + out->dport = orig->dport & mask->dport; + out->sport = orig->sport & mask->sport; + out->nexthdr = orig->nexthdr & mask->nexthdr; + out->dmask = mask->dmask; + out->smask = mask->smask; +} + +/* The agent is generating and emitting the PREFIX_MASKS6 and regenerating + * if a mask was added or removed. Example for compile testing: + */ +#ifndef PREFIX_MASKS6 +# define PREFIX_MASKS6 \ + { \ + /* rule_id 1: \ + * srcIP/128, dstIP/128, dport, nexthdr \ + */ \ + .daddr = { \ + .d1 = 0xffffffff, \ + .d2 = 0xffffffff, \ + }, \ + .dmask = 128, \ + .saddr = { \ + .d1 = 0xffffffff, \ + .d2 = 0xffffffff, \ + }, \ + .smask = 128, \ + .dport = 0xffff, \ + .sport = 0, \ + .nexthdr = 0xff, \ + }, { \ + /* rule_id 2 (1st mask): \ + * srcIP/128 or dstIP/128 \ + */ \ + .daddr = { \ + .d1 = 0xffffffff, \ + .d2 = 0xffffffff, \ + }, \ + .dmask = 128, \ + .saddr = {}, \ + .smask = 0, \ + .dport = 0, \ + .sport = 0, \ + .nexthdr = 0, \ + }, { \ + /* rule_id 2 (2nd mask): \ + * srcIP/128 or dstIP/128 \ + */ \ + .daddr = {}, \ + .dmask = 0, \ + .saddr = { \ + .d1 = 0xffffffff, \ + .d2 = 0xffffffff, \ + }, \ + .smask = 128, \ + .dport = 0, \ + .sport = 0, \ + .nexthdr = 0, \ + }, +#endif /* PREFIX_MASKS6 */ + +static __always_inline struct capture_rule * +cilium_capture6_classify_wcard(struct __ctx_buff *ctx) +{ + struct capture6_wcard prefix_masks[] = { PREFIX_MASKS6 }; + struct capture6_wcard okey, lkey; + struct capture_rule *match; + void *data, *data_end; + struct ipv6hdr *ip6; + int i, ret, l3_off = ETH_HLEN; + const int size = sizeof(prefix_masks) / + sizeof(prefix_masks[0]); + + if (!revalidate_data(ctx, &data, &data_end, &ip6)) + return NULL; + + ipv6_addr_copy(&okey.daddr, (union v6addr *)&ip6->daddr); + okey.dmask = 128; + ipv6_addr_copy(&okey.saddr, (union v6addr *)&ip6->saddr); + okey.smask = 128; + okey.nexthdr = ip6->nexthdr; + + ret = ipv6_hdrlen(ctx, l3_off, &okey.nexthdr); + if (ret < 0) + return NULL; + if (okey.nexthdr != IPPROTO_TCP && + okey.nexthdr != IPPROTO_UDP) + return NULL; + if (ctx_load_bytes(ctx, l3_off + ret, + &okey.sport, 4) < 0) + return NULL; + + okey.flags = 0; + lkey.flags = 0; + +_Pragma("unroll") + for (i = 0; i < size; i++) { + cilium_capture6_masked_key(&okey, &prefix_masks[i], &lkey); + match = map_lookup_elem(&cilium_capture6_rules, &lkey); + if (match) + return match; + } + + return NULL; +} +#endif /* ENABLE_IPV6 && ENABLE_CAPTURE */ + +static __always_inline struct capture_rule * +cilium_capture_classify_wcard(struct __ctx_buff *ctx) +{ + struct capture_rule *ret = NULL; + __u16 proto; + + if (!validate_ethertype(ctx, &proto)) + return ret; + switch (proto) { +#if defined(ENABLE_IPV4) && defined(ENABLE_CAPTURE) + case bpf_htons(ETH_P_IP): + ret = cilium_capture4_classify_wcard(ctx); + break; +#endif /* ENABLE_IPV4 && ENABLE_CAPTURE */ +#if defined(ENABLE_IPV6) && defined(ENABLE_CAPTURE) + case bpf_htons(ETH_P_IPV6): + ret = cilium_capture6_classify_wcard(ctx); + break; +#endif /* ENABLE_IPV6 && ENABLE_CAPTURE */ + default: + break; + } + return ret; +} + +static __always_inline bool +cilium_capture_candidate(struct __ctx_buff *ctx __maybe_unused, + __u16 *rule_id __maybe_unused, + __u32 *cap_len __maybe_unused) +{ + if (capture_enabled) { + struct capture_cache *c; + struct capture_rule *r; + __u32 zero = 0; + + c = map_lookup_elem(&cilium_capture_cache, &zero); + if (always_succeeds(c)) { + r = cilium_capture_classify_wcard(ctx); + c->rule_seen = r; + if (r) { + c->cap_len = *cap_len = r->cap_len; + c->rule_id = *rule_id = r->rule_id; + return true; + } + } + } + return false; +} + +static __always_inline bool +cilium_capture_cached(struct __ctx_buff *ctx __maybe_unused, + __u16 *rule_id __maybe_unused, + __u32 *cap_len __maybe_unused) +{ + if (capture_enabled) { + struct capture_cache *c; + __u32 zero = 0; + + /* Avoid full classification a 2nd time due to i) overhead but + * also since ii) we might have pushed an encap header in front + * where we don't want to dissect everything again. + */ + c = map_lookup_elem(&cilium_capture_cache, &zero); + if (always_succeeds(c) && c->rule_seen) { + *cap_len = c->cap_len; + *rule_id = c->rule_id; + return true; + } + } + return false; +} + +static __always_inline void +cilium_capture_in(struct __ctx_buff *ctx __maybe_unused) +{ +#ifdef ENABLE_CAPTURE + __u32 cap_len; + __u16 rule_id; + + if (cilium_capture_candidate(ctx, &rule_id, &cap_len)) + __cilium_capture_in(ctx, rule_id, cap_len); +#endif /* ENABLE_CAPTURE */ +} + +static __always_inline void +cilium_capture_out(struct __ctx_buff *ctx __maybe_unused) +{ +#ifdef ENABLE_CAPTURE + __u32 cap_len; + __u16 rule_id; + + /* cilium_capture_out() is always paired with cilium_capture_in(), so + * we can rely on previous cached result on whether to push the pkt + * to the RB or not. + */ + if (cilium_capture_cached(ctx, &rule_id, &cap_len)) + __cilium_capture_out(ctx, rule_id, cap_len); +#endif /* ENABLE_CAPTURE */ +} + +#endif /* __LIB_PCAP_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/policy.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/policy.h new file mode 100644 index 000000000..cf80bed8c --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/policy.h @@ -0,0 +1,298 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_POLICY_H_ +#define __LIB_POLICY_H_ + +#include + +#include "drop.h" +#include "dbg.h" +#include "eps.h" +#include "maps.h" + +#ifdef SOCKMAP +static __always_inline int +policy_sk_egress(__u32 identity, __u32 ip, __u16 dport) +{ + void *map = lookup_ip4_endpoint_policy_map(ip); + int dir = CT_EGRESS; + __u8 proto = IPPROTO_TCP; + struct policy_entry *policy; + struct policy_key key = { + .sec_label = identity, + .dport = dport, + .protocol = proto, + .egress = !dir, + .pad = 0, + }; + + if (!map) + return CTX_ACT_OK; + + /* Start with L3/L4 lookup. */ + policy = map_lookup_elem(map, &key); + if (likely(policy)) { + /* FIXME: Need byte counter */ + __sync_fetch_and_add(&policy->packets, 1); + if (unlikely(policy->deny)) + return DROP_POLICY_DENY; + return policy->proxy_port; + } + + /* L4-only lookup. */ + key.sec_label = 0; + policy = map_lookup_elem(map, &key); + if (likely(policy)) { + /* FIXME: Need byte counter */ + __sync_fetch_and_add(&policy->packets, 1); + if (unlikely(policy->deny)) + return DROP_POLICY_DENY; + return policy->proxy_port; + } + key.sec_label = identity; + + /* If L4 policy check misses, fall back to L3. */ + key.dport = 0; + key.protocol = 0; + policy = map_lookup_elem(map, &key); + if (likely(policy)) { + /* FIXME: Need byte counter */ + __sync_fetch_and_add(&policy->packets, 1); + if (unlikely(policy->deny)) + return DROP_POLICY_DENY; + return CTX_ACT_OK; + } + + /* Final fallback if allow-all policy is in place. */ + key.sec_label = 0; + policy = map_lookup_elem(map, &key); + if (likely(policy)) { + /* FIXME: Need byte counter */ + __sync_fetch_and_add(&policy->packets, 1); + if (unlikely(policy->deny)) + return DROP_POLICY_DENY; + return CTX_ACT_OK; + } + + return DROP_POLICY; +} +#else +static __always_inline void +account(struct __ctx_buff *ctx, struct policy_entry *policy) +{ + /* FIXME: Use per cpu counters */ + __sync_fetch_and_add(&policy->packets, 1); + __sync_fetch_and_add(&policy->bytes, ctx_full_len(ctx)); +} + +static __always_inline int +__policy_can_access(const void *map, struct __ctx_buff *ctx, __u32 localID, + __u32 remoteID, __u16 dport, __u8 proto, int dir, + bool is_untracked_fragment, __u8 *match_type) +{ + struct policy_entry *policy; + struct policy_key key = { + .sec_label = remoteID, + .dport = dport, + .protocol = proto, + .egress = !dir, + .pad = 0, + }; + +#ifdef ALLOW_ICMP_FRAG_NEEDED + /* When ALLOW_ICMP_FRAG_NEEDED is defined we allow all packets + * of ICMP type 3 code 4 - Fragmentation Needed. + */ + if (proto == IPPROTO_ICMP) { + void *data, *data_end; + struct icmphdr icmphdr __align_stack_8; + struct iphdr *ip4; + __u32 off; + + if (!revalidate_data(ctx, &data, &data_end, &ip4)) + return DROP_INVALID; + + off = ((void *)ip4 - data) + ipv4_hdrlen(ip4); + if (ctx_load_bytes(ctx, off, &icmphdr, sizeof(icmphdr)) < 0) + return DROP_INVALID; + + if (icmphdr.type == ICMP_DEST_UNREACH && + icmphdr.code == ICMP_FRAG_NEEDED) + return CTX_ACT_OK; + } +#endif /* ALLOW_ICMP_FRAG_NEEDED */ + + /* L4 lookup can't be done on untracked fragments. */ + if (!is_untracked_fragment) { + /* Start with L3/L4 lookup. */ + policy = map_lookup_elem(map, &key); + if (likely(policy)) { + cilium_dbg3(ctx, DBG_L4_CREATE, remoteID, localID, + dport << 16 | proto); + + account(ctx, policy); + *match_type = POLICY_MATCH_L3_L4; + if (unlikely(policy->deny)) + return DROP_POLICY_DENY; + return policy->proxy_port; + } + + /* L4-only lookup. */ + key.sec_label = 0; + policy = map_lookup_elem(map, &key); + if (likely(policy)) { + account(ctx, policy); + *match_type = POLICY_MATCH_L4_ONLY; + if (unlikely(policy->deny)) + return DROP_POLICY_DENY; + return policy->proxy_port; + } + key.sec_label = remoteID; + } + + /* If L4 policy check misses, fall back to L3. */ + key.dport = 0; + key.protocol = 0; + policy = map_lookup_elem(map, &key); + if (likely(policy)) { + account(ctx, policy); + *match_type = POLICY_MATCH_L3_ONLY; + if (unlikely(policy->deny)) + return DROP_POLICY_DENY; + return CTX_ACT_OK; + } + + /* Final fallback if allow-all policy is in place. */ + key.sec_label = 0; + policy = map_lookup_elem(map, &key); + if (policy) { + account(ctx, policy); + *match_type = POLICY_MATCH_ALL; + if (unlikely(policy->deny)) + return DROP_POLICY_DENY; + return CTX_ACT_OK; + } + + if (ctx_load_meta(ctx, CB_POLICY)) + return CTX_ACT_OK; + + if (is_untracked_fragment) + return DROP_FRAG_NOSUPPORT; + + return DROP_POLICY; +} + +/** + * Determine whether the policy allows this traffic on ingress. + * @arg ctx Packet to allow or deny + * @arg srcID Source security identity for this packet + * @arg dstID Destination security identity for this packet + * @arg dport Destination port of this packet + * @arg proto L3 Protocol of this packet + * @arg is_untracked_fragment True if packet is a TCP/UDP datagram fragment + * AND IPv4 fragment tracking is disabled + * @arg match_type Pointer to store layers used for policy match + * + * Returns: + * - Positive integer indicating the proxy_port to handle this traffic + * - CTX_ACT_OK if the policy allows this traffic based only on labels/L3/L4 + * - Negative error code if the packet should be dropped + */ +static __always_inline int +policy_can_access_ingress(struct __ctx_buff *ctx, __u32 srcID, __u32 dstID, + __u16 dport, __u8 proto, bool is_untracked_fragment, + __u8 *match_type, __u8 *audited) +{ + int ret; + + ret = __policy_can_access(&POLICY_MAP, ctx, dstID, srcID, dport, + proto, CT_INGRESS, is_untracked_fragment, + match_type); + if (ret >= CTX_ACT_OK) + return ret; + + cilium_dbg(ctx, DBG_POLICY_DENIED, srcID, dstID); + + *audited = 0; +#ifdef POLICY_AUDIT_MODE + if (IS_ERR(ret)) { + ret = CTX_ACT_OK; + *audited = 1; + } +#endif + + return ret; +} + +#ifdef ENCAP_IFINDEX +static __always_inline bool is_encap(__u16 dport, __u8 proto) +{ + return proto == IPPROTO_UDP && + (dport == bpf_htons(PORT_UDP_VXLAN) || + dport == bpf_htons(PORT_UDP_GENEVE) || + dport == bpf_htons(PORT_UDP_VXLAN_LINUX)); +} +#endif + +static __always_inline int +policy_can_egress(struct __ctx_buff *ctx, __u32 srcID, __u32 dstID, + __u16 dport, __u8 proto, __u8 *match_type, __u8 *audited) +{ + int ret; + +#ifdef ENCAP_IFINDEX + if (srcID != HOST_ID && is_encap(dport, proto)) + return DROP_ENCAP_PROHIBITED; +#endif + ret = __policy_can_access(&POLICY_MAP, ctx, srcID, dstID, dport, proto, + CT_EGRESS, false, match_type); + if (ret >= 0) + return ret; + cilium_dbg(ctx, DBG_POLICY_DENIED, srcID, dstID); + *audited = 0; +#ifdef POLICY_AUDIT_MODE + if (IS_ERR(ret)) { + ret = CTX_ACT_OK; + *audited = 1; + } +#endif + return ret; +} + +static __always_inline int policy_can_egress6(struct __ctx_buff *ctx, + const struct ipv6_ct_tuple *tuple, + __u32 srcID, __u32 dstID, + __u8 *match_type, __u8 *audited) +{ + return policy_can_egress(ctx, srcID, dstID, tuple->dport, + tuple->nexthdr, match_type, audited); +} + +static __always_inline int policy_can_egress4(struct __ctx_buff *ctx, + const struct ipv4_ct_tuple *tuple, + __u32 srcID, __u32 dstID, + __u8 *match_type, __u8 *audited) +{ + return policy_can_egress(ctx, srcID, dstID, tuple->dport, + tuple->nexthdr, match_type, audited); +} + +/** + * Mark ctx to skip policy enforcement + * @arg ctx packet + * + * Will cause the packet to ignore the policy enforcement layer and + * be considered accepted despite of the policy outcome. + */ +static __always_inline void policy_mark_skip(struct __ctx_buff *ctx) +{ + ctx_store_meta(ctx, CB_POLICY, 1); +} + +static __always_inline void policy_clear_mark(struct __ctx_buff *ctx) +{ + ctx_store_meta(ctx, CB_POLICY, 0); +} +#endif /* SOCKMAP */ +#endif diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/policy_log.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/policy_log.h new file mode 100644 index 000000000..5e9ba5e41 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/policy_log.h @@ -0,0 +1,88 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +/* + * Policy verdict notification via perf event ring buffer. + * + * API: + * void send_policy_verdict_notify(ctx, remote_label, dst_port, proto, dir, + * is_ipv6, verdict, match_type) + * + * If POLICY_VERDICT_NOTIFY is not defined, the API will be a non-op. + */ +#ifndef __LIB_POLICY_LOG__ +#define __LIB_POLICY_LOG__ + +#include "common.h" + +#ifdef POLICY_VERDICT_NOTIFY + +#ifndef POLICY_VERDICT_LOG_FILTER +DEFINE_U32(POLICY_VERDICT_LOG_FILTER, 0xffff); +#define POLICY_VERDICT_LOG_FILTER fetch_u32(POLICY_VERDICT_LOG_FILTER) +#endif + +struct policy_verdict_notify { + NOTIFY_CAPTURE_HDR + __u32 remote_label; + __s32 verdict; + __u16 dst_port; + __u8 proto; + __u8 dir:2, + ipv6:1, + match_type:3, + audited:1, + pad0:1; + __u32 pad1; /* align with 64 bits */ +}; + +static __always_inline bool policy_verdict_filter_allow(__u32 filter, __u8 dir) +{ + /* Make dir being volatile to avoid compiler optimizing out + * filter (thinking it to be zero). + */ + volatile __u8 d = dir; + + return ((filter & d) > 0); +} + +static __always_inline void +send_policy_verdict_notify(struct __ctx_buff *ctx, __u32 remote_label, __u16 dst_port, + __u8 proto, __u8 dir, __u8 is_ipv6, int verdict, + __u8 match_type, __u8 is_audited) +{ + __u64 ctx_len = ctx_full_len(ctx); + __u64 cap_len = min_t(__u64, TRACE_PAYLOAD_LEN, ctx_len); + struct policy_verdict_notify msg; + + if (!policy_verdict_filter_allow(POLICY_VERDICT_LOG_FILTER, dir)) + return; + + msg = (typeof(msg)) { + __notify_common_hdr(CILIUM_NOTIFY_POLICY_VERDICT, 0), + __notify_pktcap_hdr(ctx_len, cap_len), + .remote_label = remote_label, + .verdict = verdict, + .dst_port = bpf_ntohs(dst_port), + .match_type = match_type, + .proto = proto, + .dir = dir, + .ipv6 = is_ipv6, + .audited = is_audited, + }; + + ctx_event_output(ctx, &EVENTS_MAP, + (cap_len << 32) | BPF_F_CURRENT_CPU, + &msg, sizeof(msg)); +} +#else +static __always_inline void +send_policy_verdict_notify(struct __ctx_buff *ctx __maybe_unused, + __u32 remote_label __maybe_unused, __u16 dst_port __maybe_unused, + __u8 proto __maybe_unused, __u8 dir __maybe_unused, + __u8 is_ipv6 __maybe_unused, int verdict __maybe_unused, + __u8 match_type __maybe_unused, __u8 is_audited __maybe_unused) +{ +} +#endif /* POLICY_VERDICT_NOTIFY */ +#endif /* __LIB_POLICY_LOG__*/ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/proxy.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/proxy.h new file mode 100644 index 000000000..e76d1d7b8 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/proxy.h @@ -0,0 +1,366 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_PROXY_H_ +#define __LIB_PROXY_H_ + +#include "conntrack.h" + +#if !(__ctx_is == __ctx_skb) +#error "Proxy redirection is only supported from skb context" +#endif + +#ifdef ENABLE_TPROXY +static __always_inline int +assign_socket_tcp(struct __ctx_buff *ctx, + struct bpf_sock_tuple *tuple, __u32 len, bool established) +{ + int result = DROP_PROXY_LOOKUP_FAILED; + struct bpf_sock *sk; + __u16 dbg_ctx; + + sk = skc_lookup_tcp(ctx, tuple, len, BPF_F_CURRENT_NETNS, 0); + if (!sk) + goto out; + + if (established && sk->state == BPF_TCP_TIME_WAIT) + goto release; + if (established && sk->state == BPF_TCP_LISTEN) + goto release; + + dbg_ctx = sk->family << 16 | ctx->protocol; + result = sk_assign(ctx, sk, 0); + cilium_dbg(ctx, DBG_SK_ASSIGN, -result, dbg_ctx); + if (result == 0) + result = CTX_ACT_OK; + else + result = DROP_PROXY_SET_FAILED; +release: + sk_release(sk); +out: + return result; +} + +static __always_inline int +assign_socket_udp(struct __ctx_buff *ctx, + struct bpf_sock_tuple *tuple, __u32 len, + bool established __maybe_unused) +{ + int result = DROP_PROXY_LOOKUP_FAILED; + struct bpf_sock *sk; + __u16 dbg_ctx; + + sk = sk_lookup_udp(ctx, tuple, len, BPF_F_CURRENT_NETNS, 0); + if (!sk) + goto out; + + dbg_ctx = sk->family << 16 | ctx->protocol; + result = sk_assign(ctx, sk, 0); + cilium_dbg(ctx, DBG_SK_ASSIGN, -result, dbg_ctx); + if (result == 0) + result = CTX_ACT_OK; + else + result = DROP_PROXY_SET_FAILED; + sk_release(sk); +out: + return result; +} + +static __always_inline int +assign_socket(struct __ctx_buff *ctx, + struct bpf_sock_tuple *tuple, __u32 len, + __u8 nexthdr, bool established) +{ + /* Workaround: While the below functions are nearly identical in C + * implementation, the 'struct bpf_sock *' has a different verifier + * pointer type, which means we can't fold these implementations + * together. + */ + switch (nexthdr) { + case IPPROTO_TCP: + return assign_socket_tcp(ctx, tuple, len, established); + case IPPROTO_UDP: + return assign_socket_udp(ctx, tuple, len, established); + } + return DROP_PROXY_UNKNOWN_PROTO; +} + +/** + * combine_ports joins the specified ports in a manner consistent with + * pkg/monitor/dataapth_debug.go to report the ports ino monitor messages. + */ +static __always_inline __u32 +combine_ports(__u16 dport, __u16 sport) +{ + return (bpf_ntohs(dport) << 16) | bpf_ntohs(sport); +} + +#define CTX_REDIRECT_FN(NAME, CT_TUPLE_TYPE, SK_FIELD, \ + DBG_LOOKUP_CODE, DADDR_DBG, SADDR_DBG) \ +/** \ + * ctx_redirect_to_proxy_ingress4 / ctx_redirect_to_proxy_ingress6 \ + * @ctx pointer to program context \ + * @tuple pointer to *scratch buffer* with packet tuple \ + * @proxy_port port to redirect traffic towards \ + * \ + * Prefetch the proxy socket and associate with the ctx. Must be run on tc \ + * ingress. Will modify 'tuple'! \ + */ \ +static __always_inline int \ +NAME(struct __ctx_buff *ctx, CT_TUPLE_TYPE * ct_tuple, __be16 proxy_port) \ +{ \ + struct bpf_sock_tuple *tuple = (struct bpf_sock_tuple *)ct_tuple; \ + __u8 nexthdr = ct_tuple->nexthdr; \ + __u32 len = sizeof(tuple->SK_FIELD); \ + __u16 port; \ + int result; \ + \ + /* The provided 'ct_tuple' is in the internal Cilium format, which \ + * reverses the source/destination ports as compared with the actual \ + * packet contents. 'bpf_sock_tuple' in the eBPF API needs these to \ + * match normal packet ordering to successfully look up the \ + * corresponding socket. So, swap them here. \ + */ \ + port = tuple->SK_FIELD.sport; \ + tuple->SK_FIELD.sport = tuple->SK_FIELD.dport; \ + tuple->SK_FIELD.dport = port; \ + \ + /* Look for established socket locally first */ \ + cilium_dbg3(ctx, DBG_LOOKUP_CODE, \ + tuple->SK_FIELD.SADDR_DBG, tuple->SK_FIELD.DADDR_DBG, \ + combine_ports(tuple->SK_FIELD.dport, tuple->SK_FIELD.sport)); \ + result = assign_socket(ctx, tuple, len, nexthdr, true); \ + if (result == CTX_ACT_OK) \ + goto out; \ + \ + /* if there's no established connection, locate the tproxy socket */ \ + tuple->SK_FIELD.dport = proxy_port; \ + tuple->SK_FIELD.sport = 0; \ + memset(&tuple->SK_FIELD.daddr, 0, sizeof(tuple->SK_FIELD.daddr)); \ + memset(&tuple->SK_FIELD.saddr, 0, sizeof(tuple->SK_FIELD.saddr)); \ + cilium_dbg3(ctx, DBG_LOOKUP_CODE, \ + tuple->SK_FIELD.SADDR_DBG, tuple->SK_FIELD.DADDR_DBG, \ + combine_ports(tuple->SK_FIELD.dport, tuple->SK_FIELD.sport)); \ + result = assign_socket(ctx, tuple, len, nexthdr, false); \ + \ +out: \ + return result; \ +} + +#ifdef ENABLE_IPV4 +CTX_REDIRECT_FN(ctx_redirect_to_proxy_ingress4, struct ipv4_ct_tuple, ipv4, + DBG_SK_LOOKUP4, daddr, saddr) +#endif +#ifdef ENABLE_IPV6 +CTX_REDIRECT_FN(ctx_redirect_to_proxy_ingress6, struct ipv6_ct_tuple, ipv6, + DBG_SK_LOOKUP6, daddr[3], saddr[3]) +#endif +#undef CTX_REDIRECT_FN +#endif /* ENABLE_TPROXY */ + +/** + * __ctx_redirect_to_proxy configures the ctx with the proxy mark and proxy + * port number to ensure that the stack redirects the packet into the proxy. + * + * It is called from both ingress and egress side of endpoint devices. + * + * In regular veth mode: + * * To apply egress policy, the egressing endpoint configures the mark, + * which returns CTX_ACT_OK to pass the packet to the stack in the context + * of the source device (stack ingress). + * * To apply ingress policy, the egressing endpoint or netdev program tail + * calls into the policy program which configures the mark here, which + * returns CTX_ACT_OK to pass the packet to the stack in the context of the + * source device (netdev or egress endpoint device, stack ingress). + * + * In chaining mode with bridged endpoint devices: + * * To apply egress policy, the egressing endpoint configures the mark, + * which is propagated via ctx_store_meta() in the caller. The redirect() call + * here redirects the packet to the ingress TC filter configured on the bridge + * master device. + * * To apply ingress policy, the stack transmits the packet into the bridge + * master device which tail calls into the policy program for the ingress + * endpoint, which configures mark and cb[] as described for the egress path. + * The redirect() call here redirects the packet to the ingress TC filter + * configured on the bridge master device. + * * In both cases for bridged endpoint devices, the bridge master device has + * a BPF program configured upon ingress to transfer the cb[] to the mark + * before passing the traffic up to the stack towards the proxy. + */ +static __always_inline int +__ctx_redirect_to_proxy(struct __ctx_buff *ctx, void *tuple __maybe_unused, + __be16 proxy_port, bool from_host __maybe_unused, + bool ipv4 __maybe_unused) +{ + int result __maybe_unused = CTX_ACT_OK; + +#ifdef ENABLE_TPROXY + if (!from_host) + ctx->mark |= MARK_MAGIC_TO_PROXY; + else +#endif + ctx->mark = MARK_MAGIC_TO_PROXY | proxy_port << 16; + + cilium_dbg(ctx, DBG_CAPTURE_PROXY_PRE, proxy_port, 0); + +#ifdef ENABLE_TPROXY + if (proxy_port && !from_host) { +#ifdef ENABLE_IPV4 + if (ipv4) + result = ctx_redirect_to_proxy_ingress4(ctx, tuple, proxy_port); +#endif /* ENABLE_IPV4 */ +#ifdef ENABLE_IPV6 + if (!ipv4) + result = ctx_redirect_to_proxy_ingress6(ctx, tuple, proxy_port); +#endif /* ENABLE_IPV6 */ + } +#endif /* ENABLE_TPROXY */ + ctx_change_type(ctx, PACKET_HOST); /* Required for ingress packets from overlay */ + return result; +} + +#ifdef ENABLE_IPV4 +static __always_inline int +ctx_redirect_to_proxy4(struct __ctx_buff *ctx, void *tuple __maybe_unused, + __be16 proxy_port, bool from_host __maybe_unused) +{ + return __ctx_redirect_to_proxy(ctx, tuple, proxy_port, from_host, true); +} +#endif /* ENABLE_IPV4 */ + +#ifdef ENABLE_IPV6 +static __always_inline int +ctx_redirect_to_proxy6(struct __ctx_buff *ctx, void *tuple __maybe_unused, + __be16 proxy_port, bool from_host __maybe_unused) +{ + return __ctx_redirect_to_proxy(ctx, tuple, proxy_port, from_host, false); +} +#endif /* ENABLE_IPV6 */ + +#ifdef ENABLE_TPROXY +#define IP_TUPLE_EXTRACT_FN(NAME, PREFIX) \ +/** \ + * extract_tuple4 / extract_tuple6 \ + * \ + * Extracts the packet 5-tuple into 'tuple'. \ + * \ + * Note that it doesn't fully initialize 'tuple' as the directionality \ + * bit is unused in the proxy paths. \ + */ \ +static __always_inline int \ +NAME(struct __ctx_buff *ctx, struct PREFIX ## _ct_tuple *tuple) \ +{ \ + int err, l4_off; \ + \ + err = PREFIX ## _extract_tuple(ctx, tuple, &l4_off); \ + if (err != CTX_ACT_OK) \ + return err; \ + \ + if (ctx_load_bytes(ctx, l4_off, &tuple->dport, 4) < 0) \ + return DROP_CT_INVALID_HDR; \ + \ + __ ## PREFIX ## _ct_tuple_reverse(tuple); \ + \ + return CTX_ACT_OK; \ +} + +#ifdef ENABLE_IPV4 +IP_TUPLE_EXTRACT_FN(extract_tuple4, ipv4) +#endif /* ENABLE_IPV4 */ +#ifdef ENABLE_IPV6 +IP_TUPLE_EXTRACT_FN(extract_tuple6, ipv6) +#endif /* ENABLE_IPV6 */ +#endif /* ENABLE_TPROXY */ + +/** + * ctx_redirect_to_proxy_first() applies changes to the context to forward + * the packet towards the proxy. It is designed to run as the first function + * that accesses the context from the current BPF program. + */ +static __always_inline int +ctx_redirect_to_proxy_first(struct __ctx_buff *ctx, __be16 proxy_port) +{ + int ret = CTX_ACT_OK; +#if defined(ENABLE_TPROXY) + __u16 proto; + + /** + * For reply traffic to egress proxy for a local endpoint, we skip the + * policy & proxy_port lookup and just hairpin & rely on local stack + * routing via ctx->mark to ensure that the return traffic reaches the + * proxy. This is only relevant for endpoint-routes mode but we don't + * have a macro for this so the logic applies unconditionally here. + * See ct_state.proxy_redirect usage in bpf_lxc.c for more info. + */ + if (!proxy_port) + goto mark; + + if (!validate_ethertype(ctx, &proto)) + return DROP_UNSUPPORTED_L2; + + ret = DROP_UNKNOWN_L3; + switch (proto) { +#ifdef ENABLE_IPV6 + case bpf_htons(ETH_P_IPV6): { + struct ipv6_ct_tuple tuple; + + ret = extract_tuple6(ctx, &tuple); + if (ret < 0) + return ret; + ret = ctx_redirect_to_proxy_ingress6(ctx, &tuple, proxy_port); + break; + } +#endif /* ENABLE_IPV6 */ +#ifdef ENABLE_IPV4 + case bpf_htons(ETH_P_IP): { + struct ipv4_ct_tuple tuple; + + ret = extract_tuple4(ctx, &tuple); + if (ret < 0) + return ret; + ret = ctx_redirect_to_proxy_ingress4(ctx, &tuple, proxy_port); + break; + } +#endif /* ENABLE_IPV4 */ + default: + goto out; + } +#endif /* ENABLE_TPROXY */ + +mark: __maybe_unused + cilium_dbg(ctx, DBG_CAPTURE_PROXY_POST, proxy_port, 0); + ctx->mark = MARK_MAGIC_TO_PROXY | (proxy_port << 16); + ctx_change_type(ctx, PACKET_HOST); + +out: __maybe_unused + return ret; +} + +/** + * tc_index_skip_ingress_proxy - returns true if packet originates from ingress proxy + */ +static __always_inline bool tc_index_skip_ingress_proxy(struct __ctx_buff *ctx) +{ + volatile __u32 tc_index = ctx->tc_index; +#ifdef DEBUG + if (tc_index & TC_INDEX_F_SKIP_INGRESS_PROXY) + cilium_dbg(ctx, DBG_SKIP_PROXY, tc_index, 0); +#endif + + return tc_index & TC_INDEX_F_SKIP_INGRESS_PROXY; +} + +/** + * tc_index_skip_egress_proxy - returns true if packet originates from egress proxy + */ +static __always_inline bool tc_index_skip_egress_proxy(struct __ctx_buff *ctx) +{ + volatile __u32 tc_index = ctx->tc_index; +#ifdef DEBUG + if (tc_index & TC_INDEX_F_SKIP_EGRESS_PROXY) + cilium_dbg(ctx, DBG_SKIP_PROXY, tc_index, 0); +#endif + + return tc_index & TC_INDEX_F_SKIP_EGRESS_PROXY; +} +#endif /* __LIB_PROXY_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/signal.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/signal.h new file mode 100644 index 000000000..7563c5046 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/signal.h @@ -0,0 +1,65 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2019-2020 Authors of Cilium */ + +#ifndef __LIB_SIGNAL_H_ +#define __LIB_SIGNAL_H_ + +#include + +struct bpf_elf_map __section_maps SIGNAL_MAP = { + .type = BPF_MAP_TYPE_PERF_EVENT_ARRAY, + .size_key = sizeof(__u32), + .size_value = sizeof(__u32), + .pinning = PIN_GLOBAL_NS, + .max_elem = __NR_CPUS__, +}; + +enum { + SIGNAL_NAT_FILL_UP = 0, + SIGNAL_CT_FILL_UP, +}; + +enum { + SIGNAL_PROTO_V4 = 0, + SIGNAL_PROTO_V6, +}; + +struct signal_msg { + __u32 signal_nr; + union { + struct { + __u32 proto; + }; + }; +}; + +static __always_inline void send_signal(struct __ctx_buff *ctx, + struct signal_msg *msg) +{ + ctx_event_output(ctx, &SIGNAL_MAP, BPF_F_CURRENT_CPU, + msg, sizeof(*msg)); +} + +static __always_inline void send_signal_nat_fill_up(struct __ctx_buff *ctx, + __u32 proto) +{ + struct signal_msg msg = { + .signal_nr = SIGNAL_NAT_FILL_UP, + .proto = proto, + }; + + send_signal(ctx, &msg); +} + +static __always_inline void send_signal_ct_fill_up(struct __ctx_buff *ctx, + __u32 proto) +{ + struct signal_msg msg = { + .signal_nr = SIGNAL_CT_FILL_UP, + .proto = proto, + }; + + send_signal(ctx, &msg); +} + +#endif /* __LIB_SIGNAL_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/static_data.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/static_data.h new file mode 100644 index 000000000..8559acf61 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/static_data.h @@ -0,0 +1,32 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_STATIC_DATA_H_ +#define __LIB_STATIC_DATA_H_ + +#include +#include + +#include "endian.h" + +/* fetch_* macros assist in fetching variously sized static data */ +#define fetch_u32(x) __fetch(x) +#define fetch_u32_i(x, i) __fetch(x ## _ ## i) +#define fetch_ipv6(x) fetch_u32_i(x, 1), fetch_u32_i(x, 2), fetch_u32_i(x, 3), fetch_u32_i(x, 4) +#define fetch_mac(x) { { fetch_u32_i(x, 1), (__u16)fetch_u32_i(x, 2) } } + +/* DEFINE_* macros help to declare static data. */ +#define DEFINE_U32(NAME, value) volatile __u32 NAME = value +#define DEFINE_U32_I(NAME, i) volatile __u32 NAME ## _ ## i +#define DEFINE_IPV6(NAME, \ + a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16) \ +DEFINE_U32_I(NAME, 1) = bpf_htonl( (a1) << 24 | (a2) << 16 | (a3) << 8 | (a4)); \ +DEFINE_U32_I(NAME, 2) = bpf_htonl( (a5) << 24 | (a6) << 16 | (a7) << 8 | (a8)); \ +DEFINE_U32_I(NAME, 3) = bpf_htonl( (a9) << 24 | (a10) << 16 | (a11) << 8 | (a12)); \ +DEFINE_U32_I(NAME, 4) = bpf_htonl((a13) << 24 | (a14) << 16 | (a15) << 8 | (a16)) + +#define DEFINE_MAC(NAME, a1, a2, a3, a4, a5, a6) \ +DEFINE_U32_I(NAME, 1) = (a1) << 24 | (a2) << 16 | (a3) << 8 | (a4); \ +DEFINE_U32_I(NAME, 2) = (a5) << 8 | (a6) + +#endif /* __LIB_STATIC_DATA_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/tailcall.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/tailcall.h new file mode 100644 index 000000000..794d0bb85 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/tailcall.h @@ -0,0 +1,106 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2019-2020 Authors of Cilium */ +#ifndef TAILCALL_H +#define TAILCALL_H + +#include "config.h" + +#define __eval(x, ...) x ## __VA_ARGS__ + +#define __and_00 0 +#define __and_01 0 +#define __and_10 0 +#define __and_11 1 +#define __and_0(y) __eval(__and_0, y) +#define __and_1(y) __eval(__and_1, y) +#define __and(x, y) __eval(__and_, x)(y) + +#define __or_00 0 +#define __or_01 1 +#define __or_10 1 +#define __or_11 1 +#define __or_0(y) __eval(__or_0, y) +#define __or_1(y) __eval(__or_1, y) +#define __or(x, y) __eval(__or_, x)(y) + +#define __or3_1(y, z) 1 +#define __or3_0(y, z) __or(y, z) +#define __or3(x, y, z) __eval(__or3_, x)(y, z) + +/* declare_tailcall_if() and invoke_tailcall_if() is a pair + * of helpers which based on COND either selects to emit a + * tail call for the underlying function when true or emits + * it as inlined when false. COND can be selected by one or + * multiple compile time flags. + * + * Usage example: + * + * 1) Declaration: + * + * declare_tailcall_if(__and(is_defined(ENABLE_IPV4), is_defined(ENABLE_IPV6)), + * CILIUM_CALL_FOO) + * int foo_fn(struct __ctx_buff *ctx) + * { + * [...] + * } + * + * 2) Call-site: + * + * [...] + * invoke_tailcall_if(__and(is_defined(ENABLE_IPV4), is_defined(ENABLE_IPV6)), + * CILIUM_CALL_FOO, foo_fn); + * [...] + * + * 3) Compilation result: + * + * When compiled with -DENABLE_IPV4 and -DENABLE_IPV6 both + * set, then above emits a tail call as follows: + * + * __attribute__((section("2" "/" "10"), used)) + * int foo_fn(struct __ctx_buff *ctx) + * { + * [...] + * } + * + * [...] + * do { ep_tail_call(ctx, 10); ret = -140; } while (0); + * [...] + * + * The fall-through side sets DROP_MISSED_TAIL_CALL as ret. + * + * When only one of them is set in the above example or none + * of them, then the code emission looks like: + * + * static __inline __attribute__ ((__always_inline__)) + * int foo_fn(struct __ctx_buff *ctx) + * { + * [...] + * } + * + * [...] + * return foo_fn(ctx); + * [...] + * + * Selectors can be single is_defined(), or multiple ones + * combined with __and() or __or() macros. COND must be + * the same expression for declare_tailcall_if() and the + * invoke_tailcall_if() part. + */ +#define __declare_tailcall_if_0(NAME) \ + static __always_inline +#define __declare_tailcall_if_1(NAME) \ + __section_tail(CILIUM_MAP_CALLS, NAME) +#define declare_tailcall_if(COND, NAME) \ + __eval(__declare_tailcall_if_, COND)(NAME) + +#define __invoke_tailcall_if_0(NAME, FUNC) \ + return FUNC(ctx) +#define __invoke_tailcall_if_1(NAME, FUNC) \ + do { \ + ep_tail_call(ctx, NAME); \ + ret = DROP_MISSED_TAIL_CALL; \ + } while (0) +#define invoke_tailcall_if(COND, NAME, FUNC) \ + __eval(__invoke_tailcall_if_, COND)(NAME, FUNC) + +#endif /* TAILCALL_H */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/time.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/time.h new file mode 100644 index 000000000..f1fa289db --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/time.h @@ -0,0 +1,64 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_TIME_H_ +#define __LIB_TIME_H_ + +#include +#include + +#define NSEC_PER_SEC (1000ULL * 1000ULL * 1000UL) +#define NSEC_PER_MSEC (1000ULL * 1000ULL) +#define NSEC_PER_USEC (1000UL) + +/* Monotonic clock, scalar format. */ +#define bpf_ktime_get_sec() \ + ({ __u64 __x = ktime_get_ns() / NSEC_PER_SEC; __x; }) +#define bpf_ktime_get_msec() \ + ({ __u64 __x = ktime_get_ns() / NSEC_PER_MSEC; __x; }) +#define bpf_ktime_get_usec() \ + ({ __u64 __x = ktime_get_ns() / NSEC_PER_USEC; __x; }) +#define bpf_ktime_get_nsec() \ + ({ __u64 __x = ktime_get_ns(); __x; }) + +/* Jiffies */ +#define bpf_jiffies_to_sec(j) \ + ({ __u64 __x = (j) / KERNEL_HZ; __x; }) +#define bpf_sec_to_jiffies(s) \ + ({ __u64 __x = (s) * KERNEL_HZ; __x; }) + +/* Per-CPU ktime cache for faster clock access. */ +struct bpf_elf_map __section_maps cilium_ktime_cache = { + .type = BPF_MAP_TYPE_PERCPU_ARRAY, + .size_key = sizeof(__u32), + .size_value = sizeof(__u64), + .pinning = PIN_GLOBAL_NS, + .max_elem = 1, +}; + +/* Currently supported clock types: + * + * - bpf_ktime_cache_set(ns) -> CLOCK_MONOTONIC + * - bpf_ktime_cache_set(boot_ns) -> CLOCK_BOOTTIME + */ +#define bpf_ktime_cache_set(clock) \ + ({ \ + __u32 __z = 0; \ + __u64 *__cache = map_lookup_elem(&cilium_ktime_cache, &__z); \ + __u64 __ktime = ktime_get_##clock(); \ + if (always_succeeds(__cache)) \ + *__cache = __ktime; \ + __ktime; \ + }) + +#define bpf_ktime_cache_get() \ + ({ \ + __u32 __z = 0; \ + __u64 *__cache = map_lookup_elem(&cilium_ktime_cache, &__z); \ + __u64 __ktime = 0; \ + if (always_succeeds(__cache)) \ + __ktime = *__cache; \ + __ktime; \ + }) + +#endif /* __LIB_TIME_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/trace.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/trace.h new file mode 100644 index 000000000..eb1aa445d --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/trace.h @@ -0,0 +1,281 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +/* + * Packet forwarding notification via perf event ring buffer. + * + * API: + * void send_trace_notify(ctx, obs_point, src, dst, dst_id, ifindex, reason, monitor) + * + * If TRACE_NOTIFY is not defined, the API will be compiled in as a NOP. + */ +#ifndef __LIB_TRACE__ +#define __LIB_TRACE__ + +#include "dbg.h" +#include "events.h" +#include "common.h" +#include "utils.h" +#include "metrics.h" + +/* Available observation points. */ +enum { + TRACE_TO_LXC, + TRACE_TO_PROXY, + TRACE_TO_HOST, + TRACE_TO_STACK, + TRACE_TO_OVERLAY, + TRACE_FROM_LXC, + TRACE_FROM_PROXY, + TRACE_FROM_HOST, + TRACE_FROM_STACK, + TRACE_FROM_OVERLAY, + TRACE_FROM_NETWORK, + TRACE_TO_NETWORK, +}; + +/* Reasons for forwarding a packet. */ +enum { + TRACE_REASON_POLICY = CT_NEW, + TRACE_REASON_CT_ESTABLISHED = CT_ESTABLISHED, + TRACE_REASON_CT_REPLY = CT_REPLY, + TRACE_REASON_CT_RELATED = CT_RELATED, + TRACE_REASON_CT_REOPENED = CT_REOPENED, +}; + +#define TRACE_REASON_ENCRYPTED 0x80 + +/* Trace aggregation levels. */ +enum { + TRACE_AGGREGATE_NONE = 0, /* Trace every packet on rx & tx */ + TRACE_AGGREGATE_RX = 1, /* Hide trace on packet receive */ + TRACE_AGGREGATE_ACTIVE_CT = 3, /* Ratelimit active connection traces */ +}; + +#ifndef MONITOR_AGGREGATION +#define MONITOR_AGGREGATION TRACE_AGGREGATE_NONE +#endif + +/** + * update_trace_metrics + * @ctx: socket buffer + * @obs_point: observation point (TRACE_*) + * @reason: reason for forwarding the packet (TRACE_REASON_*) + * + * Update metrics based on a trace event + */ +static __always_inline void +update_trace_metrics(struct __ctx_buff *ctx, __u8 obs_point, __u8 reason) +{ + __u8 encrypted; + + switch (obs_point) { + case TRACE_TO_LXC: + update_metrics(ctx_full_len(ctx), METRIC_INGRESS, + REASON_FORWARDED); + break; + + /* TRACE_FROM_LXC, i.e endpoint-to-endpoint delivery is handled + * separately in ipv*_local_delivery() where we can bump an egress + * forward. It could still be dropped but it would show up later as an + * ingress drop, in that scenario. + * + * TRACE_TO_PROXY is not handled in datapath. This is because we have + * separate L7 proxy "forwarded" and "dropped" (ingress/egress) + * counters in the proxy layer to capture these metrics. + */ + case TRACE_TO_HOST: + case TRACE_TO_STACK: + case TRACE_TO_OVERLAY: + case TRACE_TO_NETWORK: + update_metrics(ctx_full_len(ctx), METRIC_EGRESS, + REASON_FORWARDED); + break; + case TRACE_FROM_OVERLAY: + case TRACE_FROM_NETWORK: + encrypted = reason & TRACE_REASON_ENCRYPTED; + if (!encrypted) + update_metrics(ctx_full_len(ctx), METRIC_INGRESS, + REASON_PLAINTEXT); + else + update_metrics(ctx_full_len(ctx), METRIC_INGRESS, + REASON_DECRYPT); + break; + } +} + +#ifdef TRACE_NOTIFY +struct trace_notify { + NOTIFY_CAPTURE_HDR + __u32 src_label; + __u32 dst_label; + __u16 dst_id; + __u8 reason; + __u8 ipv6:1; + __u8 pad:7; + __u32 ifindex; + union { + struct { + __be32 orig_ip4; + __u32 orig_pad1; + __u32 orig_pad2; + __u32 orig_pad3; + }; + union v6addr orig_ip6; + }; +}; + +static __always_inline bool emit_trace_notify(__u8 obs_point, __u32 monitor) +{ + if (MONITOR_AGGREGATION >= TRACE_AGGREGATE_RX) { + switch (obs_point) { + case TRACE_FROM_LXC: + case TRACE_FROM_PROXY: + case TRACE_FROM_HOST: + case TRACE_FROM_STACK: + case TRACE_FROM_OVERLAY: + case TRACE_FROM_NETWORK: + return false; + default: + break; + } + } + + /* + * Ignore sample when aggregation is enabled and 'monitor' is set to 0. + * Rate limiting (trace message aggregation) relies on connection tracking, + * so if there is no CT information available at the observation point, + * then 'monitor' will be set to 0 to avoid emitting trace notifications + * when aggregation is enabled (the default). + */ + if (MONITOR_AGGREGATION >= TRACE_AGGREGATE_ACTIVE_CT && !monitor) + return false; + + return true; +} + +static __always_inline void +send_trace_notify(struct __ctx_buff *ctx, __u8 obs_point, __u32 src, __u32 dst, + __u16 dst_id, __u32 ifindex, __u8 reason, __u32 monitor) +{ + __u64 ctx_len = ctx_full_len(ctx); + __u64 cap_len = min_t(__u64, monitor ? : TRACE_PAYLOAD_LEN, + ctx_len); + struct trace_notify msg __align_stack_8; + + update_trace_metrics(ctx, obs_point, reason); + + if (!emit_trace_notify(obs_point, monitor)) + return; + + msg = (typeof(msg)) { + __notify_common_hdr(CILIUM_NOTIFY_TRACE, obs_point), + __notify_pktcap_hdr(ctx_len, cap_len), + .src_label = src, + .dst_label = dst, + .dst_id = dst_id, + .reason = reason, + .ifindex = ifindex, + }; + memset(&msg.orig_ip6, 0, sizeof(union v6addr)); + + ctx_event_output(ctx, &EVENTS_MAP, + (cap_len << 32) | BPF_F_CURRENT_CPU, + &msg, sizeof(msg)); +} + +static __always_inline void +send_trace_notify4(struct __ctx_buff *ctx, __u8 obs_point, __u32 src, __u32 dst, + __be32 orig_addr, __u16 dst_id, __u32 ifindex, __u8 reason, + __u32 monitor) +{ + __u64 ctx_len = ctx_full_len(ctx); + __u64 cap_len = min_t(__u64, monitor ? : TRACE_PAYLOAD_LEN, + ctx_len); + struct trace_notify msg; + + update_trace_metrics(ctx, obs_point, reason); + + if (!emit_trace_notify(obs_point, monitor)) + return; + + msg = (typeof(msg)) { + __notify_common_hdr(CILIUM_NOTIFY_TRACE, obs_point), + __notify_pktcap_hdr(ctx_len, cap_len), + .src_label = src, + .dst_label = dst, + .dst_id = dst_id, + .reason = reason, + .ifindex = ifindex, + .ipv6 = 0, + .orig_ip4 = orig_addr, + }; + + ctx_event_output(ctx, &EVENTS_MAP, + (cap_len << 32) | BPF_F_CURRENT_CPU, + &msg, sizeof(msg)); +} + +static __always_inline void +send_trace_notify6(struct __ctx_buff *ctx, __u8 obs_point, __u32 src, __u32 dst, + union v6addr *orig_addr, __u16 dst_id, __u32 ifindex, + __u8 reason, __u32 monitor) +{ + __u64 ctx_len = ctx_full_len(ctx); + __u64 cap_len = min_t(__u64, monitor ? : TRACE_PAYLOAD_LEN, + ctx_len); + struct trace_notify msg; + + update_trace_metrics(ctx, obs_point, reason); + + if (!emit_trace_notify(obs_point, monitor)) + return; + + msg = (typeof(msg)) { + __notify_common_hdr(CILIUM_NOTIFY_TRACE, obs_point), + __notify_pktcap_hdr(ctx_len, cap_len), + .src_label = src, + .dst_label = dst, + .dst_id = dst_id, + .reason = reason, + .ifindex = ifindex, + .ipv6 = 1, + }; + + ipv6_addr_copy(&msg.orig_ip6, orig_addr); + + ctx_event_output(ctx, &EVENTS_MAP, + (cap_len << 32) | BPF_F_CURRENT_CPU, + &msg, sizeof(msg)); +} +#else +static __always_inline void +send_trace_notify(struct __ctx_buff *ctx, __u8 obs_point, + __u32 src __maybe_unused, __u32 dst __maybe_unused, + __u16 dst_id __maybe_unused, __u32 ifindex __maybe_unused, + __u8 reason, __u32 monitor __maybe_unused) +{ + update_trace_metrics(ctx, obs_point, reason); +} + +static __always_inline void +send_trace_notify4(struct __ctx_buff *ctx, __u8 obs_point, + __u32 src __maybe_unused, __u32 dst __maybe_unused, + __be32 orig_addr __maybe_unused, __u16 dst_id __maybe_unused, + __u32 ifindex __maybe_unused, __u8 reason, + __u32 monitor __maybe_unused) +{ + update_trace_metrics(ctx, obs_point, reason); +} + +static __always_inline void +send_trace_notify6(struct __ctx_buff *ctx, __u8 obs_point, + __u32 src __maybe_unused, __u32 dst __maybe_unused, + union v6addr *orig_addr __maybe_unused, + __u16 dst_id __maybe_unused, __u32 ifindex __maybe_unused, + __u8 reason, __u32 monitor __maybe_unused) +{ + update_trace_metrics(ctx, obs_point, reason); +} +#endif /* TRACE_NOTIFY */ +#endif /* __LIB_TRACE__ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/lib/utils.h b/eBPF_Supermarket/eBPF_TCP_Ping/lib/utils.h new file mode 100644 index 000000000..4d4303d28 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/lib/utils.h @@ -0,0 +1,42 @@ +/* SPDX-License-Identifier: GPL-2.0 */ +/* Copyright (C) 2016-2020 Authors of Cilium */ + +#ifndef __LIB_UTILS_H_ +#define __LIB_UTILS_H_ + +#include +#include + +#include "endian.h" +#include "time.h" +#include "static_data.h" + +#define __min(t_x, t_y, x, y) \ +({ \ + t_x _x = (x); \ + t_y _y = (y); \ + (void) (&_x == &_y); \ + _x < _y ? _x : _y; \ +}) + +#define __max(t_x, t_y, x, y) \ +({ \ + t_x _x = (x); \ + t_y _y = (y); \ + (void) (&_x == &_y); \ + _x > _y ? _x : _y; \ +}) + +#define min(x, y) \ + __min(typeof(x), typeof(y), x, y) + +#define max(x, y) \ + __max(typeof(x), typeof(y), x, y) + +#define min_t(t, x, y) \ + __min(t, t, x, y) + +#define max_t(t, x, y) \ + __max(t, t, x, y) + +#endif /* __LIB_UTILS_H_ */ diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/tcp_ping.go b/eBPF_Supermarket/eBPF_TCP_Ping/tcp_ping.go new file mode 100644 index 000000000..326c6c2c4 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/tcp_ping.go @@ -0,0 +1,251 @@ +package main + +import ( + "bytes" + "encoding/binary" + "flag" + "fmt" + "net" + "os" + "os/signal" + "strconv" + "strings" + "syscall" + "time" + + bpf "github.com/iovisor/gobpf/bcc" +) + +/* command line arguments */ +var ( + help bool + silent bool + duration int + connections int +) + +const pingPort = 65532 + +const source string = ` +#include +#include +#include +#include +#include + +typedef struct { + u64 ts_ns; +} tcp_start_info_t; + +typedef struct { + u64 daddr; + u64 delta_us; +} rtt_t; + +BPF_HASH(tcp_start_infos, struct sock *, tcp_start_info_t); +BPF_PERF_OUTPUT(ping_events); + +int kprobe__tcp_v4_connect(struct pt_regs *ctx, struct sock *skp) +{ + u64 pid = bpf_get_current_pid_tgid() >> 32; + if (pid != PID) + return 0; + + tcp_start_info_t info; + info.ts_ns = bpf_ktime_get_ns(); + tcp_start_infos.update(&skp, &info); + + return 0; +}; + +int kprobe__tcp_rcv_state_process(struct pt_regs *ctx, struct sock *sk, struct sk_buff *skb) +{ + tcp_start_info_t *info = tcp_start_infos.lookup(&sk); + if (unlikely(!info)) + return 0; + + u16 family = sk->__sk_common.skc_family; + u16 dport = bpf_ntohs(sk->__sk_common.skc_dport); + + struct tcphdr *tcp = (struct tcphdr *)(skb->head + skb->transport_header); + u16 tcpflags = *(u16 *)((u8 *)tcp + 12); + if (!(tcpflags & TCP_FLAG_RST)) + goto exit; + + if (likely(AF_INET == family && PINGPORT == dport)) { + u64 daddr = bpf_ntohl(sk->__sk_common.skc_daddr); + u64 ts = info->ts_ns; + u64 now = bpf_ktime_get_ns(); + u64 delta_us = (now - ts) / 1000ul; + + rtt_t rtt; + rtt.daddr = daddr; + rtt.delta_us = delta_us; + + ping_events.perf_submit(ctx, &rtt, sizeof(rtt)); + } + +exit: + tcp_start_infos.delete(&sk); + + return 0; +} +` + +type pingEventType struct { + Daddr uint64 + DeltaUs uint64 +} + +func loadKporbe(m *bpf.Module, name string) { + probe, err := m.LoadKprobe("kprobe__" + name) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to load %s: %s\n", name, err) + os.Exit(1) + } + + if err = m.AttachKprobe(name, probe, -1); err != nil { + fmt.Fprintf(os.Stderr, "Failed to attach %s: %s\n", name, err) + os.Exit(1) + } +} + +func cmdLineInit() { + flag.BoolVar(&help, "h", false, "Show help") + flag.BoolVar(&silent, "s", false, "Do not show information of each ping") + flag.IntVar(&duration, "d", 1000, "Ping `duration` ms") + flag.IntVar(&connections, "c", 1, "`Number` connections to keep ping") + + flag.Usage = usage +} + +func usage() { + fmt.Fprintf(os.Stderr, "tcp_ping version: 0.0.1\nUsage: tcp_ping 172.217.194.106 [-d 500] [-c 100] [-s]\n\nOptions:\n") + flag.PrintDefaults() +} + +func main() { + cmdLineInit() + + if len(os.Args) < 2 { + flag.Usage() + return + } + + host := os.Args[1] + if net.ParseIP(host) == nil { + flag.Usage() + return + } + + os.Args = os.Args[1:] + flag.Parse() + + if help || host == "" { + flag.Usage() + return + } + + m := bpf.NewModule(source, []string{ + "-w", + "-DPINGPORT=" + strconv.Itoa(pingPort), + "-DPID=" + strconv.Itoa(os.Getpid()), + }) + + defer m.Close() + + loadKporbe(m, "tcp_v4_connect") + loadKporbe(m, "tcp_rcv_state_process") + + pingEvent := bpf.NewTable(m.TableId("ping_events"), m) + pingEventCh := make(chan []byte) + perfMap, err := bpf.InitPerfMap(pingEvent, pingEventCh, nil) + if err != nil { + fmt.Fprintf(os.Stderr, "Failed to init perf map: %s\n", err) + os.Exit(1) + } + + fmt.Println("Runing ping program, hit Ctrl + C to stop and count the results") + + sig := make(chan os.Signal, 1) + signal.Notify(sig, os.Interrupt, os.Kill) + + closed := make(chan struct{}) + done := make(chan struct{}) + + var timeList []float64 + go func() { + var event pingEventType + for { + select { + case <-closed: + close(done) + return + case data := <-pingEventCh: + err := binary.Read(bytes.NewBuffer(data), binary.LittleEndian, &event) + if err != nil { + fmt.Printf("failed to decode received data: %s\n", err.Error()) + continue + } + + deltaMs := float64(event.DeltaUs) / 1000.0 + timeList = append(timeList, deltaMs) + + if !silent { + fmt.Printf("tcp RST from %s: time=%.3f ms\n", host, deltaMs) + } + + } + } + }() + + for i := 0; i < connections; i++ { + go func() { + ticker := time.NewTicker(time.Duration(duration) * time.Millisecond) + defer ticker.Stop() + + fd, err := syscall.Socket(syscall.AF_INET, syscall.SOCK_STREAM, 0) + if err != nil { + fmt.Printf("failed to create socket: %s\n", err.Error()) + sig <- os.Interrupt + return + } + defer syscall.Close(fd) + + saddr := &syscall.SockaddrInet4{Port: pingPort} + copy(saddr.Addr[:], net.ParseIP(host).To4()) + + for { + select { + case <-closed: + return + case <-ticker.C: + err = syscall.Connect(fd, saddr) + if err != nil { + errStr := err.Error() + if !strings.Contains(errStr, "connection refused") { + fmt.Printf("failed to call connect: %s\n", err.Error()) + sig <- os.Interrupt + } + } + } + } + }() + } + + perfMap.Start() + <-sig + perfMap.Stop() + + close(closed) + <-done + + times := len(timeList) + + var sumTimeMs float64 + for _, timeMs := range timeList { + sumTimeMs += timeMs + } + + fmt.Printf("\n\ntcp RST from %s: average time=%.3f ms\n", host, sumTimeMs/float64(times)) +} diff --git a/eBPF_Supermarket/eBPF_TCP_Ping/xdp_ping.c b/eBPF_Supermarket/eBPF_TCP_Ping/xdp_ping.c new file mode 100644 index 000000000..fb59a60b9 --- /dev/null +++ b/eBPF_Supermarket/eBPF_TCP_Ping/xdp_ping.c @@ -0,0 +1,155 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define PING_PORT 65532 + +#define ETH_HLEN __ETH_HLEN + +#define IP_HLEN sizeof(struct iphdr) +#define TCP_CSUM_OFFSET (ETH_HLEN + IP_HLEN + offsetof(struct tcphdr, check)) +#define ACK_SEQ_OFFSET (ETH_HLEN + IP_HLEN + offsetof(struct tcphdr, ack_seq)) + +#define TCP_FLAG_FIELD_OFFSET ( (__u64)&tcp_flag_word( (struct tcphdr *)0 ) ) +#define TCP_FLAG_OFFSET (ETH_HLEN + IP_HLEN + TCP_FLAG_FIELD_OFFSET) + +#define bpf_printk(fmt, ...) ({ \ + const char ____fmt[] = fmt; \ + trace_printk(____fmt, sizeof(____fmt), ##__VA_ARGS__); \ +}) + +struct vlanhdr { + __be16 h_vlan_TCI; + __be16 h_vlan_encapsulated_proto; +}; + +static inline void swap_mac(struct ethhdr *eth) +{ + __u8 tmp_mac[ETH_ALEN]; + + memcpy(tmp_mac, eth->h_dest, ETH_ALEN); + memcpy(eth->h_dest, eth->h_source, ETH_ALEN); + memcpy(eth->h_source, tmp_mac, ETH_ALEN); +} + +static inline void swap_ip(struct iphdr *ip) +{ + struct in_addr tmp_ip; + + memcpy(&tmp_ip, &ip->saddr, sizeof(tmp_ip)); + memcpy(&ip->saddr, &ip->daddr, sizeof(tmp_ip)); + memcpy(&ip->daddr, &tmp_ip, sizeof(tmp_ip)); +} + +static inline void swap_port(struct tcphdr *tcp) +{ + __u16 tmp_port; + + memcpy(&tmp_port, &tcp->source, sizeof(tmp_port)); + memcpy(&tcp->source, &tcp->dest, sizeof(tmp_port)); + memcpy(&tcp->dest, &tmp_port, sizeof(tmp_port)); +} + +__section("xdp-ping") +int xdp_ping(struct xdp_md *ctx) +{ + int ret = 0; + void *data_end = (void *)(long)ctx->data_end; + void *data = (void *)(long)ctx->data; + + /* eth */ + struct ethhdr *eth = data; + __u64 nh_off = sizeof(*eth); + if (unlikely(data + nh_off > data_end)) + return XDP_DROP; + + __be16 h_proto = eth->h_proto; + + /* vlan */ + __u64 vlanhdr_len = 0; + // handle double tags in ethernet frames + #pragma unroll + for (int i = 0; i < 2; i++) { + if (bpf_htons(ETH_P_8021Q) == h_proto || bpf_htons(ETH_P_8021AD) == h_proto) { + struct vlanhdr *vhdr = data + nh_off; + + nh_off += sizeof(*vhdr); + if (data + nh_off > data_end) + return XDP_DROP; + + vlanhdr_len += sizeof(*vhdr); + h_proto = vhdr->h_vlan_encapsulated_proto; + } + } + + /* ipv4 */ + if (bpf_htons(ETH_P_IP) != h_proto) + return XDP_PASS; + + struct iphdr *ip = data + nh_off; + if (unlikely((void *)ip + sizeof(*ip) > data_end)) + return XDP_DROP; + + /* tcp */ + if (IPPROTO_TCP != ip->protocol) + return XDP_PASS; + + struct tcphdr *tcp = (void *)ip + sizeof(*ip); + if (unlikely((void *)tcp + sizeof(*tcp) > data_end)) + return XDP_DROP; + + if (PING_PORT != bpf_ntohs(tcp->dest) || 1 != tcp->syn) + return XDP_PASS; + + /* main logic */ + + swap_mac(eth); + swap_ip(ip); + swap_port(tcp); + + __u16 *tcp_flag = (void *)tcp + TCP_FLAG_FIELD_OFFSET; + __u16 old_tcp_flag = *tcp_flag; + __u16 new_tcp_flag = *tcp_flag; + + /* clear syn bit */ + new_tcp_flag &= ~TCP_FLAG_SYN; + /* set rst bit */ + new_tcp_flag |= TCP_FLAG_RST; + /* set ack bit */ + new_tcp_flag |= TCP_FLAG_ACK; + + ret = l4_csum_replace(ctx, TCP_CSUM_OFFSET + vlanhdr_len, old_tcp_flag, new_tcp_flag, 0); + if (unlikely(ret)) { + bpf_printk("l4_csum_replace tcp_flag error\n"); + return XDP_DROP; + } + + memcpy(data + TCP_FLAG_OFFSET + vlanhdr_len, &new_tcp_flag, sizeof(new_tcp_flag)); + + /* calculate and set ack sequence */ + __be32 old_ack_seq = tcp->ack_seq; + __be32 new_ack_seq = bpf_htonl(bpf_ntohl(tcp->seq) + 1); + + ret = l4_csum_replace(ctx, TCP_CSUM_OFFSET + vlanhdr_len, old_ack_seq, new_ack_seq, 0); + if (unlikely(ret)) { + bpf_printk("l4_csum_replace ack_seq error\n"); + return XDP_DROP; + } + + memcpy(data + ACK_SEQ_OFFSET + vlanhdr_len, &new_ack_seq, sizeof(new_ack_seq)); + + return XDP_TX; +} + +BPF_LICENSE("GPL");