xref: /linux/tools/testing/selftests/bpf/prog_tests/cgrp_kfunc.c (revision c532de5a67a70f8533d495f8f2aaa9a0491c3ad0)
1 // SPDX-License-Identifier: GPL-2.0
2 /* Copyright (c) 2022 Meta Platforms, Inc. and affiliates. */
3 
4 #define _GNU_SOURCE
5 #include <cgroup_helpers.h>
6 #include <test_progs.h>
7 
8 #include "cgrp_kfunc_failure.skel.h"
9 #include "cgrp_kfunc_success.skel.h"
10 
11 static struct cgrp_kfunc_success *open_load_cgrp_kfunc_skel(void)
12 {
13 	struct cgrp_kfunc_success *skel;
14 	int err;
15 
16 	skel = cgrp_kfunc_success__open();
17 	if (!ASSERT_OK_PTR(skel, "skel_open"))
18 		return NULL;
19 
20 	skel->bss->pid = getpid();
21 
22 	err = cgrp_kfunc_success__load(skel);
23 	if (!ASSERT_OK(err, "skel_load"))
24 		goto cleanup;
25 
26 	return skel;
27 
28 cleanup:
29 	cgrp_kfunc_success__destroy(skel);
30 	return NULL;
31 }
32 
33 static int mkdir_rm_test_dir(void)
34 {
35 	int fd;
36 	const char *cgrp_path = "cgrp_kfunc";
37 
38 	fd = create_and_get_cgroup(cgrp_path);
39 	if (!ASSERT_GT(fd, 0, "mkdir_cgrp_fd"))
40 		return -1;
41 
42 	close(fd);
43 	remove_cgroup(cgrp_path);
44 
45 	return 0;
46 }
47 
48 static void run_success_test(const char *prog_name)
49 {
50 	struct cgrp_kfunc_success *skel;
51 	struct bpf_program *prog;
52 	struct bpf_link *link = NULL;
53 
54 	skel = open_load_cgrp_kfunc_skel();
55 	if (!ASSERT_OK_PTR(skel, "open_load_skel"))
56 		return;
57 
58 	if (!ASSERT_OK(skel->bss->err, "pre_mkdir_err"))
59 		goto cleanup;
60 
61 	prog = bpf_object__find_program_by_name(skel->obj, prog_name);
62 	if (!ASSERT_OK_PTR(prog, "bpf_object__find_program_by_name"))
63 		goto cleanup;
64 
65 	link = bpf_program__attach(prog);
66 	if (!ASSERT_OK_PTR(link, "attached_link"))
67 		goto cleanup;
68 
69 	ASSERT_EQ(skel->bss->invocations, 0, "pre_rmdir_count");
70 	if (!ASSERT_OK(mkdir_rm_test_dir(), "cgrp_mkdir"))
71 		goto cleanup;
72 
73 	ASSERT_EQ(skel->bss->invocations, 1, "post_rmdir_count");
74 	ASSERT_OK(skel->bss->err, "post_rmdir_err");
75 
76 cleanup:
77 	bpf_link__destroy(link);
78 	cgrp_kfunc_success__destroy(skel);
79 }
80 
81 static const char * const success_tests[] = {
82 	"test_cgrp_acquire_release_argument",
83 	"test_cgrp_acquire_leave_in_map",
84 	"test_cgrp_xchg_release",
85 	"test_cgrp_get_release",
86 	"test_cgrp_get_ancestors",
87 	"test_cgrp_from_id",
88 };
89 
90 void test_cgrp_kfunc(void)
91 {
92 	int i, err;
93 
94 	err = setup_cgroup_environment();
95 	if (!ASSERT_OK(err, "cgrp_env_setup"))
96 		goto cleanup;
97 
98 	for (i = 0; i < ARRAY_SIZE(success_tests); i++) {
99 		if (!test__start_subtest(success_tests[i]))
100 			continue;
101 
102 		run_success_test(success_tests[i]);
103 	}
104 
105 	RUN_TESTS(cgrp_kfunc_failure);
106 
107 cleanup:
108 	cleanup_cgroup_environment();
109 }
110