1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2022 Intel */
3
4 #include <linux/bpf.h>
5 #include <bpf/bpf_helpers.h>
6 #include <linux/if_ether.h>
7 #include "xsk_xdp_common.h"
8
9 struct {
10 __uint(type, BPF_MAP_TYPE_XSKMAP);
11 __uint(max_entries, 2);
12 __uint(key_size, sizeof(int));
13 __uint(value_size, sizeof(int));
14 } xsk SEC(".maps");
15
16 static unsigned int idx;
17 int count = 0;
18
xsk_def_prog(struct xdp_md * xdp)19 SEC("xdp.frags") int xsk_def_prog(struct xdp_md *xdp)
20 {
21 return bpf_redirect_map(&xsk, 0, XDP_DROP);
22 }
23
xsk_xdp_drop(struct xdp_md * xdp)24 SEC("xdp.frags") int xsk_xdp_drop(struct xdp_md *xdp)
25 {
26 /* Drop every other packet */
27 if (idx++ % 2)
28 return XDP_DROP;
29
30 return bpf_redirect_map(&xsk, 0, XDP_DROP);
31 }
32
xsk_xdp_populate_metadata(struct xdp_md * xdp)33 SEC("xdp.frags") int xsk_xdp_populate_metadata(struct xdp_md *xdp)
34 {
35 void *data, *data_meta;
36 struct xdp_info *meta;
37 int err;
38
39 /* Reserve enough for all custom metadata. */
40 err = bpf_xdp_adjust_meta(xdp, -(int)sizeof(struct xdp_info));
41 if (err)
42 return XDP_DROP;
43
44 data = (void *)(long)xdp->data;
45 data_meta = (void *)(long)xdp->data_meta;
46
47 if (data_meta + sizeof(struct xdp_info) > data)
48 return XDP_DROP;
49
50 meta = data_meta;
51 meta->count = count++;
52
53 return bpf_redirect_map(&xsk, 0, XDP_DROP);
54 }
55
xsk_xdp_shared_umem(struct xdp_md * xdp)56 SEC("xdp") int xsk_xdp_shared_umem(struct xdp_md *xdp)
57 {
58 void *data = (void *)(long)xdp->data;
59 void *data_end = (void *)(long)xdp->data_end;
60 struct ethhdr *eth = data;
61
62 if (eth + 1 > data_end)
63 return XDP_DROP;
64
65 /* Redirecting packets based on the destination MAC address */
66 idx = ((unsigned int)(eth->h_dest[5])) / 2;
67 if (idx > MAX_SOCKETS)
68 return XDP_DROP;
69
70 return bpf_redirect_map(&xsk, idx, XDP_DROP);
71 }
72
73 char _license[] SEC("license") = "GPL";
74