1 // SPDX-License-Identifier: GPL-2.0
2 #include <test_progs.h>
3 #include <network_helpers.h>
4 
5 static void *spin_lock_thread(void *arg)
6 {
7 	__u32 duration, retval;
8 	int err, prog_fd = *(u32 *) arg;
9 
10 	err = bpf_prog_test_run(prog_fd, 10000, &pkt_v4, sizeof(pkt_v4),
11 				NULL, NULL, &retval, &duration);
12 	CHECK(err || retval, "",
13 	      "err %d errno %d retval %d duration %d\n",
14 	      err, errno, retval, duration);
15 	pthread_exit(arg);
16 }
17 
18 static void *parallel_map_access(void *arg)
19 {
20 	int err, map_fd = *(u32 *) arg;
21 	int vars[17], i, j, rnd, key = 0;
22 
23 	for (i = 0; i < 10000; i++) {
24 		err = bpf_map_lookup_elem_flags(map_fd, &key, vars, BPF_F_LOCK);
25 		if (CHECK_FAIL(err)) {
26 			printf("lookup failed\n");
27 			goto out;
28 		}
29 		if (CHECK_FAIL(vars[0] != 0)) {
30 			printf("lookup #%d var[0]=%d\n", i, vars[0]);
31 			goto out;
32 		}
33 		rnd = vars[1];
34 		for (j = 2; j < 17; j++) {
35 			if (vars[j] == rnd)
36 				continue;
37 			printf("lookup #%d var[1]=%d var[%d]=%d\n",
38 			       i, rnd, j, vars[j]);
39 			CHECK_FAIL(vars[j] != rnd);
40 			goto out;
41 		}
42 	}
43 out:
44 	pthread_exit(arg);
45 }
46 
47 void test_map_lock(void)
48 {
49 	const char *file = "./test_map_lock.o";
50 	int prog_fd, map_fd[2], vars[17] = {};
51 	pthread_t thread_id[6];
52 	struct bpf_object *obj = NULL;
53 	int err = 0, key = 0, i;
54 	void *ret;
55 
56 	err = bpf_prog_load(file, BPF_PROG_TYPE_CGROUP_SKB, &obj, &prog_fd);
57 	if (CHECK_FAIL(err)) {
58 		printf("test_map_lock:bpf_prog_load errno %d\n", errno);
59 		goto close_prog;
60 	}
61 	map_fd[0] = bpf_find_map(__func__, obj, "hash_map");
62 	if (CHECK_FAIL(map_fd[0] < 0))
63 		goto close_prog;
64 	map_fd[1] = bpf_find_map(__func__, obj, "array_map");
65 	if (CHECK_FAIL(map_fd[1] < 0))
66 		goto close_prog;
67 
68 	bpf_map_update_elem(map_fd[0], &key, vars, BPF_F_LOCK);
69 
70 	for (i = 0; i < 4; i++)
71 		if (CHECK_FAIL(pthread_create(&thread_id[i], NULL,
72 					      &spin_lock_thread, &prog_fd)))
73 			goto close_prog;
74 	for (i = 4; i < 6; i++)
75 		if (CHECK_FAIL(pthread_create(&thread_id[i], NULL,
76 					      &parallel_map_access,
77 					      &map_fd[i - 4])))
78 			goto close_prog;
79 	for (i = 0; i < 4; i++)
80 		if (CHECK_FAIL(pthread_join(thread_id[i], &ret) ||
81 			       ret != (void *)&prog_fd))
82 			goto close_prog;
83 	for (i = 4; i < 6; i++)
84 		if (CHECK_FAIL(pthread_join(thread_id[i], &ret) ||
85 			       ret != (void *)&map_fd[i - 4]))
86 			goto close_prog;
87 close_prog:
88 	bpf_object__close(obj);
89 }
90