xref: /linux/tools/testing/selftests/bpf/prog_tests/xdp.c (revision 0a94608f0f7de9b1135ffea3546afe68eafef57f)
1 // SPDX-License-Identifier: GPL-2.0
2 #include <test_progs.h>
3 #include <network_helpers.h>
4 
5 void test_xdp(void)
6 {
7 	struct vip key4 = {.protocol = 6, .family = AF_INET};
8 	struct vip key6 = {.protocol = 6, .family = AF_INET6};
9 	struct iptnl_info value4 = {.family = AF_INET};
10 	struct iptnl_info value6 = {.family = AF_INET6};
11 	const char *file = "./test_xdp.o";
12 	struct bpf_object *obj;
13 	char buf[128];
14 	struct ipv6hdr iph6;
15 	struct iphdr iph;
16 	int err, prog_fd, map_fd;
17 	LIBBPF_OPTS(bpf_test_run_opts, topts,
18 		.data_in = &pkt_v4,
19 		.data_size_in = sizeof(pkt_v4),
20 		.data_out = buf,
21 		.data_size_out = sizeof(buf),
22 		.repeat = 1,
23 	);
24 
25 	err = bpf_prog_test_load(file, BPF_PROG_TYPE_XDP, &obj, &prog_fd);
26 	if (CHECK_FAIL(err))
27 		return;
28 
29 	map_fd = bpf_find_map(__func__, obj, "vip2tnl");
30 	if (map_fd < 0)
31 		goto out;
32 	bpf_map_update_elem(map_fd, &key4, &value4, 0);
33 	bpf_map_update_elem(map_fd, &key6, &value6, 0);
34 
35 	err = bpf_prog_test_run_opts(prog_fd, &topts);
36 	memcpy(&iph, buf + sizeof(struct ethhdr), sizeof(iph));
37 	ASSERT_OK(err, "test_run");
38 	ASSERT_EQ(topts.retval, XDP_TX, "ipv4 test_run retval");
39 	ASSERT_EQ(topts.data_size_out, 74, "ipv4 test_run data_size_out");
40 	ASSERT_EQ(iph.protocol, IPPROTO_IPIP, "ipv4 test_run iph.protocol");
41 
42 	topts.data_in = &pkt_v6;
43 	topts.data_size_in = sizeof(pkt_v6);
44 	topts.data_size_out = sizeof(buf);
45 
46 	err = bpf_prog_test_run_opts(prog_fd, &topts);
47 	memcpy(&iph6, buf + sizeof(struct ethhdr), sizeof(iph6));
48 	ASSERT_OK(err, "test_run");
49 	ASSERT_EQ(topts.retval, XDP_TX, "ipv6 test_run retval");
50 	ASSERT_EQ(topts.data_size_out, 114, "ipv6 test_run data_size_out");
51 	ASSERT_EQ(iph6.nexthdr, IPPROTO_IPV6, "ipv6 test_run iph6.nexthdr");
52 out:
53 	bpf_object__close(obj);
54 }
55