1 /* SPDX-License-Identifier: GPL-2.0
2 * Copyright (c) 2017 Jesper Dangaard Brouer, Red Hat Inc.
4 * Example howto extract XDP RX-queue info
6 #include <uapi/linux/bpf.h>
7 #include <uapi/linux/if_ether.h>
8 #include <uapi/linux/in.h>
9 #include "bpf_helpers.h"
11 /* Config setup from with userspace
13 * User-side setup ifindex in config_map, to verify that
14 * ctx->ingress_ifindex is correct (against configured ifindex)
21 enum cfg_options_flags {
26 struct bpf_map_def SEC("maps") config_map = {
27 .type = BPF_MAP_TYPE_ARRAY,
28 .key_size = sizeof(int),
29 .value_size = sizeof(struct config),
33 /* Common stats data record (shared with userspace) */
39 struct bpf_map_def SEC("maps") stats_global_map = {
40 .type = BPF_MAP_TYPE_PERCPU_ARRAY,
41 .key_size = sizeof(u32),
42 .value_size = sizeof(struct datarec),
48 /* Stats per rx_queue_index (per CPU) */
49 struct bpf_map_def SEC("maps") rx_queue_index_map = {
50 .type = BPF_MAP_TYPE_PERCPU_ARRAY,
51 .key_size = sizeof(u32),
52 .value_size = sizeof(struct datarec),
53 .max_entries = MAX_RXQs + 1,
56 static __always_inline
57 void swap_src_dst_mac(void *data)
59 unsigned short *p = data;
60 unsigned short dst[3];
74 int xdp_prognum0(struct xdp_md *ctx)
76 void *data_end = (void *)(long)ctx->data_end;
77 void *data = (void *)(long)ctx->data;
78 struct datarec *rec, *rxq_rec;
80 struct config *config;
83 /* Global stats record */
84 rec = bpf_map_lookup_elem(&stats_global_map, &key);
89 /* Accessing ctx->ingress_ifindex, cause BPF to rewrite BPF
90 * instructions inside kernel to access xdp_rxq->dev->ifindex
92 ingress_ifindex = ctx->ingress_ifindex;
94 config = bpf_map_lookup_elem(&config_map, &key);
98 /* Simple test: check ctx provided ifindex is as expected */
99 if (ingress_ifindex != config->ifindex) {
100 /* count this error case */
105 /* Update stats per rx_queue_index. Handle if rx_queue_index
106 * is larger than stats map can contain info for.
108 key = ctx->rx_queue_index;
111 rxq_rec = bpf_map_lookup_elem(&rx_queue_index_map, &key);
114 rxq_rec->processed++;
118 /* Default: Don't touch packet data, only count packets */
119 if (unlikely(config->options & (READ_MEM|SWAP_MAC))) {
120 struct ethhdr *eth = data;
122 if (eth + 1 > data_end)
125 /* Avoid compiler removing this: Drop non 802.3 Ethertypes */
126 if (ntohs(eth->h_proto) < ETH_P_802_3_MIN)
129 /* XDP_TX requires changing MAC-addrs, else HW may drop.
130 * Can also be enabled with --swapmac (for test purposes)
132 if (unlikely(config->options & SWAP_MAC))
133 swap_src_dst_mac(data);
136 return config->action;
139 char _license[] SEC("license") = "GPL";