David S. Miller | bc1bafb | 2017-05-01 12:43:49 -0700 | [diff] [blame] | 1 | #ifndef __BPF_ENDIAN__ |
| 2 | #define __BPF_ENDIAN__ |
| 3 | |
Daniel Borkmann | 78a5a93 | 2017-06-08 19:06:25 +0200 | [diff] [blame] | 4 | #include <linux/swab.h> |
David S. Miller | bc1bafb | 2017-05-01 12:43:49 -0700 | [diff] [blame] | 5 | |
Daniel Borkmann | 78a5a93 | 2017-06-08 19:06:25 +0200 | [diff] [blame] | 6 | /* LLVM's BPF target selects the endianness of the CPU |
| 7 | * it compiles on, or the user specifies (bpfel/bpfeb), |
| 8 | * respectively. The used __BYTE_ORDER__ is defined by |
| 9 | * the compiler, we cannot rely on __BYTE_ORDER from |
| 10 | * libc headers, since it doesn't reflect the actual |
| 11 | * requested byte order. |
| 12 | * |
| 13 | * Note, LLVM's BPF target has different __builtin_bswapX() |
| 14 | * semantics. It does map to BPF_ALU | BPF_END | BPF_TO_BE |
| 15 | * in bpfel and bpfeb case, which means below, that we map |
| 16 | * to cpu_to_be16(). We could use it unconditionally in BPF |
| 17 | * case, but better not rely on it, so that this header here |
| 18 | * can be used from application and BPF program side, which |
| 19 | * use different targets. |
| 20 | */ |
| 21 | #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ |
| 22 | # define __bpf_ntohs(x) __builtin_bswap16(x) |
| 23 | # define __bpf_htons(x) __builtin_bswap16(x) |
| 24 | # define __bpf_constant_ntohs(x) ___constant_swab16(x) |
| 25 | # define __bpf_constant_htons(x) ___constant_swab16(x) |
| 26 | #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ |
| 27 | # define __bpf_ntohs(x) (x) |
| 28 | # define __bpf_htons(x) (x) |
| 29 | # define __bpf_constant_ntohs(x) (x) |
| 30 | # define __bpf_constant_htons(x) (x) |
David S. Miller | bc1bafb | 2017-05-01 12:43:49 -0700 | [diff] [blame] | 31 | #else |
Daniel Borkmann | 78a5a93 | 2017-06-08 19:06:25 +0200 | [diff] [blame] | 32 | # error "Fix your compiler's __BYTE_ORDER__?!" |
David S. Miller | bc1bafb | 2017-05-01 12:43:49 -0700 | [diff] [blame] | 33 | #endif |
| 34 | |
| 35 | #define bpf_htons(x) \ |
| 36 | (__builtin_constant_p(x) ? \ |
Daniel Borkmann | 78a5a93 | 2017-06-08 19:06:25 +0200 | [diff] [blame] | 37 | __bpf_constant_htons(x) : __bpf_htons(x)) |
David S. Miller | bc1bafb | 2017-05-01 12:43:49 -0700 | [diff] [blame] | 38 | #define bpf_ntohs(x) \ |
| 39 | (__builtin_constant_p(x) ? \ |
Daniel Borkmann | 78a5a93 | 2017-06-08 19:06:25 +0200 | [diff] [blame] | 40 | __bpf_constant_ntohs(x) : __bpf_ntohs(x)) |
David S. Miller | bc1bafb | 2017-05-01 12:43:49 -0700 | [diff] [blame] | 41 | |
Daniel Borkmann | 78a5a93 | 2017-06-08 19:06:25 +0200 | [diff] [blame] | 42 | #endif /* __BPF_ENDIAN__ */ |