xref: /OK3568_Linux_fs/kernel/samples/bpf/xdp_sample_pkts_kern.c (revision 4882a59341e53eb6f0b4789bf948001014eff981)
1*4882a593Smuzhiyun // SPDX-License-Identifier: GPL-2.0
2*4882a593Smuzhiyun #include <linux/ptrace.h>
3*4882a593Smuzhiyun #include <linux/version.h>
4*4882a593Smuzhiyun #include <uapi/linux/bpf.h>
5*4882a593Smuzhiyun #include <bpf/bpf_helpers.h>
6*4882a593Smuzhiyun 
7*4882a593Smuzhiyun #define SAMPLE_SIZE 64ul
8*4882a593Smuzhiyun 
9*4882a593Smuzhiyun struct {
10*4882a593Smuzhiyun 	__uint(type, BPF_MAP_TYPE_PERF_EVENT_ARRAY);
11*4882a593Smuzhiyun 	__uint(key_size, sizeof(int));
12*4882a593Smuzhiyun 	__uint(value_size, sizeof(u32));
13*4882a593Smuzhiyun } my_map SEC(".maps");
14*4882a593Smuzhiyun 
15*4882a593Smuzhiyun SEC("xdp_sample")
xdp_sample_prog(struct xdp_md * ctx)16*4882a593Smuzhiyun int xdp_sample_prog(struct xdp_md *ctx)
17*4882a593Smuzhiyun {
18*4882a593Smuzhiyun 	void *data_end = (void *)(long)ctx->data_end;
19*4882a593Smuzhiyun 	void *data = (void *)(long)ctx->data;
20*4882a593Smuzhiyun 
21*4882a593Smuzhiyun 	/* Metadata will be in the perf event before the packet data. */
22*4882a593Smuzhiyun 	struct S {
23*4882a593Smuzhiyun 		u16 cookie;
24*4882a593Smuzhiyun 		u16 pkt_len;
25*4882a593Smuzhiyun 	} __packed metadata;
26*4882a593Smuzhiyun 
27*4882a593Smuzhiyun 	if (data < data_end) {
28*4882a593Smuzhiyun 		/* The XDP perf_event_output handler will use the upper 32 bits
29*4882a593Smuzhiyun 		 * of the flags argument as a number of bytes to include of the
30*4882a593Smuzhiyun 		 * packet payload in the event data. If the size is too big, the
31*4882a593Smuzhiyun 		 * call to bpf_perf_event_output will fail and return -EFAULT.
32*4882a593Smuzhiyun 		 *
33*4882a593Smuzhiyun 		 * See bpf_xdp_event_output in net/core/filter.c.
34*4882a593Smuzhiyun 		 *
35*4882a593Smuzhiyun 		 * The BPF_F_CURRENT_CPU flag means that the event output fd
36*4882a593Smuzhiyun 		 * will be indexed by the CPU number in the event map.
37*4882a593Smuzhiyun 		 */
38*4882a593Smuzhiyun 		u64 flags = BPF_F_CURRENT_CPU;
39*4882a593Smuzhiyun 		u16 sample_size;
40*4882a593Smuzhiyun 		int ret;
41*4882a593Smuzhiyun 
42*4882a593Smuzhiyun 		metadata.cookie = 0xdead;
43*4882a593Smuzhiyun 		metadata.pkt_len = (u16)(data_end - data);
44*4882a593Smuzhiyun 		sample_size = min(metadata.pkt_len, SAMPLE_SIZE);
45*4882a593Smuzhiyun 		flags |= (u64)sample_size << 32;
46*4882a593Smuzhiyun 
47*4882a593Smuzhiyun 		ret = bpf_perf_event_output(ctx, &my_map, flags,
48*4882a593Smuzhiyun 					    &metadata, sizeof(metadata));
49*4882a593Smuzhiyun 		if (ret)
50*4882a593Smuzhiyun 			bpf_printk("perf_event_output failed: %d\n", ret);
51*4882a593Smuzhiyun 	}
52*4882a593Smuzhiyun 
53*4882a593Smuzhiyun 	return XDP_PASS;
54*4882a593Smuzhiyun }
55*4882a593Smuzhiyun 
56*4882a593Smuzhiyun char _license[] SEC("license") = "GPL";
57*4882a593Smuzhiyun u32 _version SEC("version") = LINUX_VERSION_CODE;
58