1 // SPDX-License-Identifier: GPL-2.0
2 #define KBUILD_MODNAME "foo"
3
4 #include "vmlinux.h"
5 #include "xdp_sample.bpf.h"
6 #include "xdp_sample_shared.h"
7
8 struct {
9 __uint(type, BPF_MAP_TYPE_DEVMAP_HASH);
10 __uint(key_size, sizeof(int));
11 __uint(value_size, sizeof(int));
12 __uint(max_entries, 32);
13 } forward_map_general SEC(".maps");
14
15 struct {
16 __uint(type, BPF_MAP_TYPE_DEVMAP_HASH);
17 __uint(key_size, sizeof(int));
18 __uint(value_size, sizeof(struct bpf_devmap_val));
19 __uint(max_entries, 32);
20 } forward_map_native SEC(".maps");
21
22 /* map to store egress interfaces mac addresses */
23 struct {
24 __uint(type, BPF_MAP_TYPE_HASH);
25 __type(key, u32);
26 __type(value, __be64);
27 __uint(max_entries, 32);
28 } mac_map SEC(".maps");
29
xdp_redirect_map(struct xdp_md * ctx,void * forward_map)30 static int xdp_redirect_map(struct xdp_md *ctx, void *forward_map)
31 {
32 u32 key = bpf_get_smp_processor_id();
33 struct datarec *rec;
34
35 rec = bpf_map_lookup_elem(&rx_cnt, &key);
36 if (!rec)
37 return XDP_PASS;
38 NO_TEAR_INC(rec->processed);
39
40 return bpf_redirect_map(forward_map, 0,
41 BPF_F_BROADCAST | BPF_F_EXCLUDE_INGRESS);
42 }
43
44 SEC("xdp")
xdp_redirect_map_general(struct xdp_md * ctx)45 int xdp_redirect_map_general(struct xdp_md *ctx)
46 {
47 return xdp_redirect_map(ctx, &forward_map_general);
48 }
49
50 SEC("xdp")
xdp_redirect_map_native(struct xdp_md * ctx)51 int xdp_redirect_map_native(struct xdp_md *ctx)
52 {
53 return xdp_redirect_map(ctx, &forward_map_native);
54 }
55
56 SEC("xdp/devmap")
xdp_devmap_prog(struct xdp_md * ctx)57 int xdp_devmap_prog(struct xdp_md *ctx)
58 {
59 void *data_end = (void *)(long)ctx->data_end;
60 void *data = (void *)(long)ctx->data;
61 u32 key = ctx->egress_ifindex;
62 struct ethhdr *eth = data;
63 __be64 *mac;
64 u64 nh_off;
65
66 nh_off = sizeof(*eth);
67 if (data + nh_off > data_end)
68 return XDP_DROP;
69
70 mac = bpf_map_lookup_elem(&mac_map, &key);
71 if (mac)
72 __builtin_memcpy(eth->h_source, mac, ETH_ALEN);
73
74 return XDP_PASS;
75 }
76
77 char _license[] SEC("license") = "GPL";
78