1 // SPDX-License-Identifier: GPL-2.0
2 #define BPF_NO_KFUNC_PROTOTYPES
4 #include <bpf/bpf_helpers.h>
5 #include <bpf/bpf_endian.h>
7 #define ETH_P_IP 0x0800
8 #define ETH_P_IPV6 0x86dd
9 #define IP_MF 0x2000 /* "More Fragments" */
10 #define IP_OFFSET 0x1fff /* "Fragment Offset" */
14 struct bpf_flowtable_opts___local {
18 struct flow_offload_tuple_rhash *
19 bpf_xdp_flow_lookup(struct xdp_md *, struct bpf_fib_lookup *,
20 struct bpf_flowtable_opts___local *, u32) __ksym;
23 __uint(type, BPF_MAP_TYPE_ARRAY);
26 __uint(max_entries, 1);
29 static bool xdp_flowtable_offload_check_iphdr(struct iphdr *iph)
31 /* ip fragmented traffic */
32 if (iph->frag_off & bpf_htons(IP_MF | IP_OFFSET))
36 if (iph->ihl * 4 != sizeof(*iph))
45 static bool xdp_flowtable_offload_check_tcp_state(void *ports, void *data_end,
48 if (proto == IPPROTO_TCP) {
49 struct tcphdr *tcph = ports;
51 if (tcph + 1 > data_end)
54 if (tcph->fin || tcph->rst)
61 struct flow_ports___local {
63 } __attribute__((preserve_access_index));
66 int xdp_flowtable_do_lookup(struct xdp_md *ctx)
68 void *data_end = (void *)(long)ctx->data_end;
69 struct bpf_flowtable_opts___local opts = {};
70 struct flow_offload_tuple_rhash *tuplehash;
71 struct bpf_fib_lookup tuple = {
72 .ifindex = ctx->ingress_ifindex,
74 void *data = (void *)(long)ctx->data;
75 struct ethhdr *eth = data;
76 struct flow_ports___local *ports;
79 if (eth + 1 > data_end)
82 switch (eth->h_proto) {
83 case bpf_htons(ETH_P_IP): {
84 struct iphdr *iph = data + sizeof(*eth);
86 ports = (struct flow_ports___local *)(iph + 1);
87 if (ports + 1 > data_end)
90 /* sanity check on ip header */
91 if (!xdp_flowtable_offload_check_iphdr(iph))
94 if (!xdp_flowtable_offload_check_tcp_state(ports, data_end,
98 tuple.family = AF_INET;
100 tuple.l4_protocol = iph->protocol;
101 tuple.tot_len = bpf_ntohs(iph->tot_len);
102 tuple.ipv4_src = iph->saddr;
103 tuple.ipv4_dst = iph->daddr;
104 tuple.sport = ports->source;
105 tuple.dport = ports->dest;
108 case bpf_htons(ETH_P_IPV6): {
109 struct in6_addr *src = (struct in6_addr *)tuple.ipv6_src;
110 struct in6_addr *dst = (struct in6_addr *)tuple.ipv6_dst;
111 struct ipv6hdr *ip6h = data + sizeof(*eth);
113 ports = (struct flow_ports___local *)(ip6h + 1);
114 if (ports + 1 > data_end)
117 if (ip6h->hop_limit <= 1)
120 if (!xdp_flowtable_offload_check_tcp_state(ports, data_end,
124 tuple.family = AF_INET6;
125 tuple.l4_protocol = ip6h->nexthdr;
126 tuple.tot_len = bpf_ntohs(ip6h->payload_len);
129 tuple.sport = ports->source;
130 tuple.dport = ports->dest;
137 tuplehash = bpf_xdp_flow_lookup(ctx, &tuple, &opts, sizeof(opts));
141 val = bpf_map_lookup_elem(&stats, &key);
143 __sync_add_and_fetch(val, 1);
148 char _license[] SEC("license") = "GPL";