Skip to content

Commit 64d550b

Browse files
committed
common: generalize xdp_stats_map from packet04
Create two header files in common/ that makes it easy to create xdp_stats for XDP/BPF programs. Signed-off-by: Jesper Dangaard Brouer <brouer@redhat.com>
1 parent 2f030d2 commit 64d550b

2 files changed

Lines changed: 69 additions & 0 deletions

File tree

common/xdp_stats_kern.h

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
/* SPDX-License-Identifier: GPL-2.0 */
2+
3+
/* Used *ONLY* by BPF-prog running kernel side. */
4+
#ifndef __XDP_STATS_KERN_H
5+
#define __XDP_STATS_KERN_H
6+
7+
/* Data record type 'struct datarec' is defined in common/xdp_stats_kern_user.h,
8+
* programs using this header must first include that file.
9+
*/
10+
#ifndef __XDP_STATS_KERN_USER_H
11+
#warning "You forgot to #include <../common/xdp_stats_kern_user.h>"
12+
#include <../common/xdp_stats_kern_user.h>
13+
#endif
14+
15+
/* Keeps stats per (enum) xdp_action */
16+
struct bpf_map_def SEC("maps") xdp_stats_map = {
17+
.type = BPF_MAP_TYPE_PERCPU_ARRAY,
18+
.key_size = sizeof(__u32),
19+
.value_size = sizeof(struct datarec),
20+
.max_entries = XDP_ACTION_MAX,
21+
};
22+
23+
static __always_inline
24+
__u32 xdp_stats_record_action(struct xdp_md *ctx, __u32 action)
25+
{
26+
void *data_end = (void *)(long)ctx->data_end;
27+
void *data = (void *)(long)ctx->data;
28+
29+
if (action >= XDP_ACTION_MAX)
30+
return XDP_ABORTED;
31+
32+
/* Lookup in kernel BPF-side return pointer to actual data record */
33+
struct datarec *rec = bpf_map_lookup_elem(&xdp_stats_map, &action);
34+
if (!rec)
35+
return XDP_ABORTED;
36+
37+
/* Calculate packet length */
38+
__u64 bytes = data_end - data;
39+
40+
/* BPF_MAP_TYPE_PERCPU_ARRAY returns a data record specific to current
41+
* CPU and XDP hooks runs under Softirq, which makes it safe to update
42+
* without atomic operations.
43+
*/
44+
rec->rx_packets++;
45+
rec->rx_bytes += bytes;
46+
47+
return action;
48+
}
49+
50+
#endif /* __XDP_STATS_KERN_H */

common/xdp_stats_kern_user.h

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
/* SPDX-License-Identifier: GPL-2.0 */
2+
3+
/* Used by BPF-prog kernel side BPF-progs and userspace programs,
4+
* for sharing xdp_stats common struct and DEFINEs.
5+
*/
6+
#ifndef __XDP_STATS_KERN_USER_H
7+
#define __XDP_STATS_KERN_USER_H
8+
9+
/* This is the data record stored in the map */
10+
struct datarec {
11+
__u64 rx_packets;
12+
__u64 rx_bytes;
13+
};
14+
15+
#ifndef XDP_ACTION_MAX
16+
#define XDP_ACTION_MAX (XDP_REDIRECT + 1)
17+
#endif
18+
19+
#endif /* __XDP_STATS_KERN_USER_H */

0 commit comments

Comments
 (0)