1 // SPDX-License-Identifier: GPL-2.0
2 #include <test_progs.h>
3 
test_task_fd_query_tp_core(const char * probe_name,const char * tp_name)4 static void test_task_fd_query_tp_core(const char *probe_name,
5 				       const char *tp_name)
6 {
7 	const char *file = "./test_tracepoint.bpf.o";
8 	int err, bytes, efd, prog_fd, pmu_fd;
9 	struct perf_event_attr attr = {};
10 	__u64 probe_offset, probe_addr;
11 	__u32 len, prog_id, fd_type;
12 	struct bpf_object *obj = NULL;
13 	__u32 duration = 0;
14 	char buf[256];
15 
16 	err = bpf_prog_test_load(file, BPF_PROG_TYPE_TRACEPOINT, &obj, &prog_fd);
17 	if (CHECK(err, "bpf_prog_test_load", "err %d errno %d\n", err, errno))
18 		goto close_prog;
19 
20 	if (access("/sys/kernel/tracing/trace", F_OK) == 0) {
21 		snprintf(buf, sizeof(buf),
22 			 "/sys/kernel/tracing/events/%s/id", probe_name);
23 	} else {
24 		snprintf(buf, sizeof(buf),
25 			 "/sys/kernel/debug/tracing/events/%s/id", probe_name);
26 	}
27 	efd = open(buf, O_RDONLY, 0);
28 	if (CHECK(efd < 0, "open", "err %d errno %d\n", efd, errno))
29 		goto close_prog;
30 	bytes = read(efd, buf, sizeof(buf));
31 	close(efd);
32 	if (CHECK(bytes <= 0 || bytes >= sizeof(buf), "read",
33 		  "bytes %d errno %d\n", bytes, errno))
34 		goto close_prog;
35 
36 	attr.config = strtol(buf, NULL, 0);
37 	attr.type = PERF_TYPE_TRACEPOINT;
38 	attr.sample_type = PERF_SAMPLE_RAW;
39 	attr.sample_period = 1;
40 	attr.wakeup_events = 1;
41 	pmu_fd = syscall(__NR_perf_event_open, &attr, -1 /* pid */,
42 			 0 /* cpu 0 */, -1 /* group id */,
43 			 0 /* flags */);
44 	if (CHECK(err, "perf_event_open", "err %d errno %d\n", err, errno))
45 		goto close_pmu;
46 
47 	err = ioctl(pmu_fd, PERF_EVENT_IOC_ENABLE, 0);
48 	if (CHECK(err, "perf_event_ioc_enable", "err %d errno %d\n", err,
49 		  errno))
50 		goto close_pmu;
51 
52 	err = ioctl(pmu_fd, PERF_EVENT_IOC_SET_BPF, prog_fd);
53 	if (CHECK(err, "perf_event_ioc_set_bpf", "err %d errno %d\n", err,
54 		  errno))
55 		goto close_pmu;
56 
57 	/* query (getpid(), pmu_fd) */
58 	len = sizeof(buf);
59 	err = bpf_task_fd_query(getpid(), pmu_fd, 0, buf, &len, &prog_id,
60 				&fd_type, &probe_offset, &probe_addr);
61 	if (CHECK(err < 0, "bpf_task_fd_query", "err %d errno %d\n", err,
62 		  errno))
63 		goto close_pmu;
64 
65 	err = (fd_type == BPF_FD_TYPE_TRACEPOINT) && !strcmp(buf, tp_name);
66 	if (CHECK(!err, "check_results", "fd_type %d tp_name %s\n",
67 		  fd_type, buf))
68 		goto close_pmu;
69 
70 close_pmu:
71 	close(pmu_fd);
72 close_prog:
73 	bpf_object__close(obj);
74 }
75 
test_task_fd_query_tp(void)76 void test_task_fd_query_tp(void)
77 {
78 	test_task_fd_query_tp_core("sched/sched_switch",
79 				   "sched_switch");
80 	test_task_fd_query_tp_core("syscalls/sys_enter_read",
81 				   "sys_enter_read");
82 }
83