-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbasic03_prog_kern.c
More file actions
78 lines (68 loc) · 2.17 KB
/
basic03_prog_kern.c
File metadata and controls
78 lines (68 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/* SPDX-License-Identifier: GPL-2.0 */
#include <linux/bpf.h>
#include <bpf/bpf_helpers.h>
#include "common_kern_user.h" /* defines: struct datarec; */
/* Lesson#1: See how a map is defined.
* - Here an array with XDP_ACTION_MAX (max_)entries are created.
* - The idea is to keep stats per (enum) xdp_action
*/
struct {
__uint(type, BPF_MAP_TYPE_ARRAY);
__type(key, __u32);
__type(value, struct datarec);
__uint(max_entries, XDP_ACTION_MAX);
} xdp_stats_map SEC(".maps");
/* LLVM maps __sync_fetch_and_add() as a built-in function to the BPF atomic add
* instruction (that is BPF_STX | BPF_XADD | BPF_W for word sizes)
*/
#ifndef lock_xadd
#define lock_xadd(ptr, val) ((void) __sync_fetch_and_add(ptr, val))
#endif
SEC("xdp")
int xdp_stats1_func(struct xdp_md *ctx)
{
void *data_end = (void *)(long)ctx->data_end;
void *data = (void *)(long)ctx->data;
struct datarec *rec;
__u32 key = XDP_PASS; /* XDP_PASS = 2 */
/* Lookup in kernel BPF-side return pointer to actual data record */
rec = bpf_map_lookup_elem(&xdp_stats_map, &key);
/* BPF kernel-side verifier will reject program if the NULL pointer
* check isn't performed here. Even-though this is a static array where
* we know key lookup XDP_PASS always will succeed.
*/
if (!rec)
return XDP_ABORTED;
__u64 bytes = data_end - data;
lock_xadd(&rec->rx_packets, 1);
lock_xadd(&rec->rx_bytes, bytes);
return XDP_PASS;
}
char _license[] SEC("license") = "GPL";
/* Copied from: $KERNEL/include/uapi/linux/bpf.h
*
* User return codes for XDP prog type.
* A valid XDP program must return one of these defined values. All other
* return codes are reserved for future use. Unknown return codes will
* result in packet drops and a warning via bpf_warn_invalid_xdp_action().
*
enum xdp_action {
XDP_ABORTED = 0,
XDP_DROP,
XDP_PASS,
XDP_TX,
XDP_REDIRECT,
};
* user accessible metadata for XDP packet hook
* new fields must be added to the end of this structure
*
struct xdp_md {
// (Note: type __u32 is NOT the real-type)
__u32 data;
__u32 data_end;
__u32 data_meta;
// Below access go through struct xdp_rxq_info
__u32 ingress_ifindex; // rxq->dev->ifindex
__u32 rx_queue_index; // rxq->queue_index
};
*/