1 // SPDX-License-Identifier: GPL-2.0
2 #include <test_progs.h>
3 #include <network_helpers.h>
4 
test_skb_ctx(void)5 void test_skb_ctx(void)
6 {
7 	struct __sk_buff skb = {
8 		.cb[0] = 1,
9 		.cb[1] = 2,
10 		.cb[2] = 3,
11 		.cb[3] = 4,
12 		.cb[4] = 5,
13 		.priority = 6,
14 		.ingress_ifindex = 11,
15 		.ifindex = 1,
16 		.tstamp = 7,
17 		.wire_len = 100,
18 		.gso_segs = 8,
19 		.mark = 9,
20 		.gso_size = 10,
21 		.hwtstamp = 11,
22 	};
23 	LIBBPF_OPTS(bpf_test_run_opts, tattr,
24 		.data_in = &pkt_v4,
25 		.data_size_in = sizeof(pkt_v4),
26 		.ctx_in = &skb,
27 		.ctx_size_in = sizeof(skb),
28 		.ctx_out = &skb,
29 		.ctx_size_out = sizeof(skb),
30 	);
31 	struct bpf_object *obj;
32 	int err, prog_fd, i;
33 
34 	err = bpf_prog_test_load("./test_skb_ctx.bpf.o", BPF_PROG_TYPE_SCHED_CLS,
35 				 &obj, &prog_fd);
36 	if (!ASSERT_OK(err, "load"))
37 		return;
38 
39 	/* ctx_in != NULL, ctx_size_in == 0 */
40 
41 	tattr.ctx_size_in = 0;
42 	err = bpf_prog_test_run_opts(prog_fd, &tattr);
43 	ASSERT_NEQ(err, 0, "ctx_size_in");
44 	tattr.ctx_size_in = sizeof(skb);
45 
46 	/* ctx_out != NULL, ctx_size_out == 0 */
47 
48 	tattr.ctx_size_out = 0;
49 	err = bpf_prog_test_run_opts(prog_fd, &tattr);
50 	ASSERT_NEQ(err, 0, "ctx_size_out");
51 	tattr.ctx_size_out = sizeof(skb);
52 
53 	/* non-zero [len, tc_index] fields should be rejected*/
54 
55 	skb.len = 1;
56 	err = bpf_prog_test_run_opts(prog_fd, &tattr);
57 	ASSERT_NEQ(err, 0, "len");
58 	skb.len = 0;
59 
60 	skb.tc_index = 1;
61 	err = bpf_prog_test_run_opts(prog_fd, &tattr);
62 	ASSERT_NEQ(err, 0, "tc_index");
63 	skb.tc_index = 0;
64 
65 	/* non-zero [hash, sk] fields should be rejected */
66 
67 	skb.hash = 1;
68 	err = bpf_prog_test_run_opts(prog_fd, &tattr);
69 	ASSERT_NEQ(err, 0, "hash");
70 	skb.hash = 0;
71 
72 	skb.sk = (struct bpf_sock *)1;
73 	err = bpf_prog_test_run_opts(prog_fd, &tattr);
74 	ASSERT_NEQ(err, 0, "sk");
75 	skb.sk = 0;
76 
77 	err = bpf_prog_test_run_opts(prog_fd, &tattr);
78 	ASSERT_OK(err, "test_run");
79 	ASSERT_OK(tattr.retval, "test_run retval");
80 	ASSERT_EQ(tattr.ctx_size_out, sizeof(skb), "ctx_size_out");
81 
82 	for (i = 0; i < 5; i++)
83 		ASSERT_EQ(skb.cb[i], i + 2, "ctx_out_cb");
84 	ASSERT_EQ(skb.priority, 7, "ctx_out_priority");
85 	ASSERT_EQ(skb.ifindex, 1, "ctx_out_ifindex");
86 	ASSERT_EQ(skb.ingress_ifindex, 11, "ctx_out_ingress_ifindex");
87 	ASSERT_EQ(skb.tstamp, 8, "ctx_out_tstamp");
88 	ASSERT_EQ(skb.mark, 10, "ctx_out_mark");
89 
90 	bpf_object__close(obj);
91 }
92