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/bpf_helpers.h>
15 #include <bpf/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 #define MAX_STACK (512 - 2 * 32)
52 __attribute__ ((noinline))
53 int get_skb_len(struct __sk_buff *skb)
55 volatile char buf[MAX_STACK] = {};
60 __attribute__ ((noinline))
61 int get_constant(long val)
66 int get_skb_ifindex(int, struct __sk_buff *skb, int);
68 __attribute__ ((noinline))
69 int test_pkt_access_subprog3(int val, struct __sk_buff *skb)
71 return get_skb_len(skb) * get_skb_ifindex(val, skb, get_constant(123));
74 __attribute__ ((noinline))
75 int get_skb_ifindex(int val, struct __sk_buff *skb, int var)
77 volatile char buf[MAX_STACK] = {};
79 return skb->ifindex * val * var;
82 SEC("classifier/test_pkt_access")
83 int test_pkt_access(struct __sk_buff *skb)
85 void *data_end = (void *)(long)skb->data_end;
86 void *data = (void *)(long)skb->data;
87 struct ethhdr *eth = (struct ethhdr *)(data);
88 struct tcphdr *tcp = NULL;
92 if (eth + 1 > data_end)
95 if (eth->h_proto == bpf_htons(ETH_P_IP)) {
96 struct iphdr *iph = (struct iphdr *)(eth + 1);
98 if (iph + 1 > data_end)
100 ihl_len = iph->ihl * 4;
101 proto = iph->protocol;
102 tcp = (struct tcphdr *)((void *)(iph) + ihl_len);
103 } else if (eth->h_proto == bpf_htons(ETH_P_IPV6)) {
104 struct ipv6hdr *ip6h = (struct ipv6hdr *)(eth + 1);
106 if (ip6h + 1 > data_end)
108 ihl_len = sizeof(*ip6h);
109 proto = ip6h->nexthdr;
110 tcp = (struct tcphdr *)((void *)(ip6h) + ihl_len);
113 if (test_pkt_access_subprog1(skb) != skb->len * 2)
115 if (test_pkt_access_subprog2(2, skb) != skb->len * 2)
117 if (test_pkt_access_subprog3(3, skb) != skb->len * 3 * skb->ifindex)
120 if (((void *)(tcp) + 20) > data_end || proto != 6)
122 barrier(); /* to force ordering of checks */
123 if (((void *)(tcp) + 18) > data_end)
125 if (tcp->urg_ptr == 123)
129 return TC_ACT_UNSPEC;