|
| 1 | +// SPDX-License-Identifier: GPL-2.0 |
| 2 | +#define KBUILD_MODNAME "foo" |
| 3 | +#include <uapi/linux/bpf.h> |
| 4 | +#include <linux/in.h> |
| 5 | +#include <linux/if_ether.h> |
| 6 | +#include <linux/ip.h> |
| 7 | +#include <linux/ipv6.h> |
| 8 | +#include <bpf/bpf_helpers.h> |
| 9 | + |
| 10 | +struct { |
| 11 | + __uint(type, BPF_MAP_TYPE_DEVMAP_HASH); |
| 12 | + __uint(key_size, sizeof(int)); |
| 13 | + __uint(value_size, sizeof(int)); |
| 14 | + __uint(max_entries, 32); |
| 15 | +} forward_map_general SEC(".maps"); |
| 16 | + |
| 17 | +struct { |
| 18 | + __uint(type, BPF_MAP_TYPE_DEVMAP_HASH); |
| 19 | + __uint(key_size, sizeof(int)); |
| 20 | + __uint(value_size, sizeof(struct bpf_devmap_val)); |
| 21 | + __uint(max_entries, 32); |
| 22 | +} forward_map_native SEC(".maps"); |
| 23 | + |
| 24 | +struct { |
| 25 | + __uint(type, BPF_MAP_TYPE_PERCPU_ARRAY); |
| 26 | + __type(key, u32); |
| 27 | + __type(value, long); |
| 28 | + __uint(max_entries, 1); |
| 29 | +} rxcnt SEC(".maps"); |
| 30 | + |
| 31 | +/* map to store egress interfaces mac addresses, set the |
| 32 | + * max_entries to 1 and extend it in user sapce prog. |
| 33 | + */ |
| 34 | +struct { |
| 35 | + __uint(type, BPF_MAP_TYPE_ARRAY); |
| 36 | + __type(key, u32); |
| 37 | + __type(value, __be64); |
| 38 | + __uint(max_entries, 1); |
| 39 | +} mac_map SEC(".maps"); |
| 40 | + |
| 41 | +static int xdp_redirect_map(struct xdp_md *ctx, void *forward_map) |
| 42 | +{ |
| 43 | + long *value; |
| 44 | + u32 key = 0; |
| 45 | + |
| 46 | + /* count packet in global counter */ |
| 47 | + value = bpf_map_lookup_elem(&rxcnt, &key); |
| 48 | + if (value) |
| 49 | + *value += 1; |
| 50 | + |
| 51 | + return bpf_redirect_map_multi(forward_map, NULL, BPF_F_EXCLUDE_INGRESS); |
| 52 | +} |
| 53 | + |
| 54 | +SEC("xdp_redirect_general") |
| 55 | +int xdp_redirect_map_general(struct xdp_md *ctx) |
| 56 | +{ |
| 57 | + return xdp_redirect_map(ctx, &forward_map_general); |
| 58 | +} |
| 59 | + |
| 60 | +SEC("xdp_redirect_native") |
| 61 | +int xdp_redirect_map_native(struct xdp_md *ctx) |
| 62 | +{ |
| 63 | + return xdp_redirect_map(ctx, &forward_map_native); |
| 64 | +} |
| 65 | + |
| 66 | +SEC("xdp_devmap/map_prog") |
| 67 | +int xdp_devmap_prog(struct xdp_md *ctx) |
| 68 | +{ |
| 69 | + void *data_end = (void *)(long)ctx->data_end; |
| 70 | + void *data = (void *)(long)ctx->data; |
| 71 | + u32 key = ctx->egress_ifindex; |
| 72 | + struct ethhdr *eth = data; |
| 73 | + __be64 *mac; |
| 74 | + u64 nh_off; |
| 75 | + |
| 76 | + nh_off = sizeof(*eth); |
| 77 | + if (data + nh_off > data_end) |
| 78 | + return XDP_DROP; |
| 79 | + |
| 80 | + mac = bpf_map_lookup_elem(&mac_map, &key); |
| 81 | + if (mac) |
| 82 | + __builtin_memcpy(eth->h_source, mac, ETH_ALEN); |
| 83 | + |
| 84 | + return XDP_PASS; |
| 85 | +} |
| 86 | + |
| 87 | +char _license[] SEC("license") = "GPL"; |
0 commit comments