xref: /linux/tools/testing/selftests/bpf/progs/test_xdp_meta.c (revision 1a9239bb4253f9076b5b4b2a1a4e8d7defd77a95)
1 #include <linux/bpf.h>
2 #include <linux/if_ether.h>
3 #include <linux/pkt_cls.h>
4 
5 #include <bpf/bpf_helpers.h>
6 
7 #define META_SIZE 32
8 
9 #define ctx_ptr(ctx, mem) (void *)(unsigned long)ctx->mem
10 
11 /* Demonstrates how metadata can be passed from an XDP program to a TC program
12  * using bpf_xdp_adjust_meta.
13  * For the sake of testing the metadata support in drivers, the XDP program uses
14  * a fixed-size payload after the Ethernet header as metadata. The TC program
15  * copies the metadata it receives into a map so it can be checked from
16  * userspace.
17  */
18 
19 struct {
20 	__uint(type, BPF_MAP_TYPE_ARRAY);
21 	__uint(max_entries, 1);
22 	__type(key, __u32);
23 	__uint(value_size, META_SIZE);
24 } test_result SEC(".maps");
25 
26 SEC("tc")
ing_cls(struct __sk_buff * ctx)27 int ing_cls(struct __sk_buff *ctx)
28 {
29 	__u8 *data, *data_meta;
30 	__u32 key = 0;
31 
32 	data_meta = ctx_ptr(ctx, data_meta);
33 	data      = ctx_ptr(ctx, data);
34 
35 	if (data_meta + META_SIZE > data)
36 		return TC_ACT_SHOT;
37 
38 	bpf_map_update_elem(&test_result, &key, data_meta, BPF_ANY);
39 
40 	return TC_ACT_SHOT;
41 }
42 
43 SEC("xdp")
ing_xdp(struct xdp_md * ctx)44 int ing_xdp(struct xdp_md *ctx)
45 {
46 	__u8 *data, *data_meta, *data_end, *payload;
47 	struct ethhdr *eth;
48 	int ret;
49 
50 	ret = bpf_xdp_adjust_meta(ctx, -META_SIZE);
51 	if (ret < 0)
52 		return XDP_DROP;
53 
54 	data_meta = ctx_ptr(ctx, data_meta);
55 	data_end  = ctx_ptr(ctx, data_end);
56 	data      = ctx_ptr(ctx, data);
57 
58 	eth = (struct ethhdr *)data;
59 	payload = data + sizeof(struct ethhdr);
60 
61 	if (payload + META_SIZE > data_end ||
62 	    data_meta + META_SIZE > data)
63 		return XDP_DROP;
64 
65 	/* The Linux networking stack may send other packets on the test
66 	 * interface that interfere with the test. Just drop them.
67 	 * The test packets can be recognized by their ethertype of zero.
68 	 */
69 	if (eth->h_proto != 0)
70 		return XDP_DROP;
71 
72 	__builtin_memcpy(data_meta, payload, META_SIZE);
73 	return XDP_PASS;
74 }
75 
76 char _license[] SEC("license") = "GPL";
77