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
{
28 __uint(type
, BPF_MAP_TYPE_ARRAY
);
30 __type(value
, struct config
);
31 __uint(max_entries
, 1);
32 } config_map
SEC(".maps");
34 /* Common stats data record (shared with userspace) */
41 __uint(type
, BPF_MAP_TYPE_PERCPU_ARRAY
);
43 __type(value
, struct datarec
);
44 __uint(max_entries
, 1);
45 } stats_global_map
SEC(".maps");
49 /* Stats per rx_queue_index (per CPU) */
51 __uint(type
, BPF_MAP_TYPE_PERCPU_ARRAY
);
53 __type(value
, struct datarec
);
54 __uint(max_entries
, MAX_RXQs
+ 1);
55 } rx_queue_index_map
SEC(".maps");
57 static __always_inline
58 void swap_src_dst_mac(void *data
)
60 unsigned short *p
= data
;
61 unsigned short dst
[3];
75 int xdp_prognum0(struct xdp_md
*ctx
)
77 void *data_end
= (void *)(long)ctx
->data_end
;
78 void *data
= (void *)(long)ctx
->data
;
79 struct datarec
*rec
, *rxq_rec
;
81 struct config
*config
;
84 /* Global stats record */
85 rec
= bpf_map_lookup_elem(&stats_global_map
, &key
);
90 /* Accessing ctx->ingress_ifindex, cause BPF to rewrite BPF
91 * instructions inside kernel to access xdp_rxq->dev->ifindex
93 ingress_ifindex
= ctx
->ingress_ifindex
;
95 config
= bpf_map_lookup_elem(&config_map
, &key
);
99 /* Simple test: check ctx provided ifindex is as expected */
100 if (ingress_ifindex
!= config
->ifindex
) {
101 /* count this error case */
106 /* Update stats per rx_queue_index. Handle if rx_queue_index
107 * is larger than stats map can contain info for.
109 key
= ctx
->rx_queue_index
;
112 rxq_rec
= bpf_map_lookup_elem(&rx_queue_index_map
, &key
);
115 rxq_rec
->processed
++;
119 /* Default: Don't touch packet data, only count packets */
120 if (unlikely(config
->options
& (READ_MEM
|SWAP_MAC
))) {
121 struct ethhdr
*eth
= data
;
123 if (eth
+ 1 > data_end
)
126 /* Avoid compiler removing this: Drop non 802.3 Ethertypes */
127 if (ntohs(eth
->h_proto
) < ETH_P_802_3_MIN
)
130 /* XDP_TX requires changing MAC-addrs, else HW may drop.
131 * Can also be enabled with --swapmac (for test purposes)
133 if (unlikely(config
->options
& SWAP_MAC
))
134 swap_src_dst_mac(data
);
137 return config
->action
;
140 char _license
[] SEC("license") = "GPL";