1 // SPDX-License-Identifier: GPL-2.0-only
2 /* Copyright (c) 2017 Facebook
7 #include <linux/if_ether.h>
8 #include <linux/if_packet.h>
10 #include <linux/ipv6.h>
12 #include <linux/tcp.h>
13 #include <linux/pkt_cls.h>
14 #include "bpf_helpers.h"
15 #include "bpf_endian.h"
17 #define barrier() __asm__ __volatile__("": : :"memory")
18 int _version SEC("version") = 1;
20 /* llvm will optimize both subprograms into exactly the same BPF assembly
22 * Disassembly of section .text:
24 * 0000000000000000 test_pkt_access_subprog1:
25 * ; return skb->len * 2;
26 * 0: 61 10 00 00 00 00 00 00 r0 = *(u32 *)(r1 + 0)
27 * 1: 64 00 00 00 01 00 00 00 w0 <<= 1
28 * 2: 95 00 00 00 00 00 00 00 exit
30 * 0000000000000018 test_pkt_access_subprog2:
31 * ; return skb->len * val;
32 * 3: 61 10 00 00 00 00 00 00 r0 = *(u32 *)(r1 + 0)
33 * 4: 64 00 00 00 01 00 00 00 w0 <<= 1
34 * 5: 95 00 00 00 00 00 00 00 exit
36 * Which makes it an interesting test for BTF-enabled verifier.
38 static __attribute__ ((noinline))
39 int test_pkt_access_subprog1(volatile struct __sk_buff *skb)
44 static __attribute__ ((noinline))
45 int test_pkt_access_subprog2(int val, volatile struct __sk_buff *skb)
47 return skb->len * val;
50 SEC("classifier/test_pkt_access")
51 int test_pkt_access(struct __sk_buff *skb)
53 void *data_end = (void *)(long)skb->data_end;
54 void *data = (void *)(long)skb->data;
55 struct ethhdr *eth = (struct ethhdr *)(data);
56 struct tcphdr *tcp = NULL;
60 if (eth + 1 > data_end)
63 if (eth->h_proto == bpf_htons(ETH_P_IP)) {
64 struct iphdr *iph = (struct iphdr *)(eth + 1);
66 if (iph + 1 > data_end)
68 ihl_len = iph->ihl * 4;
69 proto = iph->protocol;
70 tcp = (struct tcphdr *)((void *)(iph) + ihl_len);
71 } else if (eth->h_proto == bpf_htons(ETH_P_IPV6)) {
72 struct ipv6hdr *ip6h = (struct ipv6hdr *)(eth + 1);
74 if (ip6h + 1 > data_end)
76 ihl_len = sizeof(*ip6h);
77 proto = ip6h->nexthdr;
78 tcp = (struct tcphdr *)((void *)(ip6h) + ihl_len);
81 if (test_pkt_access_subprog1(skb) != skb->len * 2)
83 if (test_pkt_access_subprog2(2, skb) != skb->len * 2)
86 if (((void *)(tcp) + 20) > data_end || proto != 6)
88 barrier(); /* to force ordering of checks */
89 if (((void *)(tcp) + 18) > data_end)
91 if (tcp->urg_ptr == 123)