1 // SPDX-License-Identifier: GPL-2.0
2 #include <uapi/linux/bpf.h>
3 #include <linux/if_link.h>
4 #include <test_progs.h>
5 
6 #include "test_xdp_devmap_helpers.skel.h"
7 #include "test_xdp_with_devmap_helpers.skel.h"
8 
9 #define IFINDEX_LO 1
10 
11 void test_xdp_with_devmap_helpers(void)
12 {
13 	struct test_xdp_with_devmap_helpers *skel;
14 	struct bpf_prog_info info = {};
15 	struct bpf_devmap_val val = {
16 		.ifindex = IFINDEX_LO,
17 	};
18 	__u32 len = sizeof(info);
19 	__u32 duration = 0, idx = 0;
20 	int err, dm_fd, map_fd;
21 
22 
23 	skel = test_xdp_with_devmap_helpers__open_and_load();
24 	if (CHECK_FAIL(!skel)) {
25 		perror("test_xdp_with_devmap_helpers__open_and_load");
26 		return;
27 	}
28 
29 	/* can not attach program with DEVMAPs that allow programs
30 	 * as xdp generic
31 	 */
32 	dm_fd = bpf_program__fd(skel->progs.xdp_redir_prog);
33 	err = bpf_set_link_xdp_fd(IFINDEX_LO, dm_fd, XDP_FLAGS_SKB_MODE);
34 	CHECK(err == 0, "Generic attach of program with 8-byte devmap",
35 	      "should have failed\n");
36 
37 	dm_fd = bpf_program__fd(skel->progs.xdp_dummy_dm);
38 	map_fd = bpf_map__fd(skel->maps.dm_ports);
39 	err = bpf_obj_get_info_by_fd(dm_fd, &info, &len);
40 	if (CHECK_FAIL(err))
41 		goto out_close;
42 
43 	val.bpf_prog.fd = dm_fd;
44 	err = bpf_map_update_elem(map_fd, &idx, &val, 0);
45 	CHECK(err, "Add program to devmap entry",
46 	      "err %d errno %d\n", err, errno);
47 
48 	err = bpf_map_lookup_elem(map_fd, &idx, &val);
49 	CHECK(err, "Read devmap entry", "err %d errno %d\n", err, errno);
50 	CHECK(info.id != val.bpf_prog.id, "Expected program id in devmap entry",
51 	      "expected %u read %u\n", info.id, val.bpf_prog.id);
52 
53 	/* can not attach BPF_XDP_DEVMAP program to a device */
54 	err = bpf_set_link_xdp_fd(IFINDEX_LO, dm_fd, XDP_FLAGS_SKB_MODE);
55 	CHECK(err == 0, "Attach of BPF_XDP_DEVMAP program",
56 	      "should have failed\n");
57 
58 	val.ifindex = 1;
59 	val.bpf_prog.fd = bpf_program__fd(skel->progs.xdp_dummy_prog);
60 	err = bpf_map_update_elem(map_fd, &idx, &val, 0);
61 	CHECK(err == 0, "Add non-BPF_XDP_DEVMAP program to devmap entry",
62 	      "should have failed\n");
63 
64 out_close:
65 	test_xdp_with_devmap_helpers__destroy(skel);
66 }
67 
68 void test_neg_xdp_devmap_helpers(void)
69 {
70 	struct test_xdp_devmap_helpers *skel;
71 	__u32 duration = 0;
72 
73 	skel = test_xdp_devmap_helpers__open_and_load();
74 	if (CHECK(skel,
75 		  "Load of XDP program accessing egress ifindex without attach type",
76 		  "should have failed\n")) {
77 		test_xdp_devmap_helpers__destroy(skel);
78 	}
79 }
80 
81 
82 void test_xdp_devmap_attach(void)
83 {
84 	if (test__start_subtest("DEVMAP with programs in entries"))
85 		test_xdp_with_devmap_helpers();
86 
87 	if (test__start_subtest("Verifier check of DEVMAP programs"))
88 		test_neg_xdp_devmap_helpers();
89 }
90