1 // SPDX-License-Identifier: GPL-2.0-only
9 #include <linux/perf_event.h>
10 #include <linux/bpf.h>
13 #include <sys/syscall.h>
14 #include <sys/ioctl.h>
21 #include "trace_helpers.h"
25 static __u64
time_get_ns(void)
29 clock_gettime(CLOCK_MONOTONIC
, &ts
);
30 return ts
.tv_sec
* 1000000000ull + ts
.tv_nsec
;
33 static __u64 start_time
;
35 #define MAX_CNT 100000ll
37 static int print_bpf_output(void *data
, int size
)
45 if (e
->cookie
!= 0x12345678) {
46 printf("BUG pid %llx cookie %llx sized %d\n",
47 e
->pid
, e
->cookie
, size
);
48 return LIBBPF_PERF_EVENT_ERROR
;
54 printf("recv %lld events per sec\n",
55 MAX_CNT
* 1000000000ll / (time_get_ns() - start_time
));
56 return LIBBPF_PERF_EVENT_DONE
;
59 return LIBBPF_PERF_EVENT_CONT
;
62 static void test_bpf_perf_event(void)
64 struct perf_event_attr attr
= {
65 .sample_type
= PERF_SAMPLE_RAW
,
66 .type
= PERF_TYPE_SOFTWARE
,
67 .config
= PERF_COUNT_SW_BPF_OUTPUT
,
71 pmu_fd
= sys_perf_event_open(&attr
, -1/*pid*/, 0/*cpu*/, -1/*group_fd*/, 0);
74 assert(bpf_map_update_elem(map_fd
[0], &key
, &pmu_fd
, BPF_ANY
) == 0);
75 ioctl(pmu_fd
, PERF_EVENT_IOC_ENABLE
, 0);
78 int main(int argc
, char **argv
)
84 snprintf(filename
, sizeof(filename
), "%s_kern.o", argv
[0]);
86 if (load_bpf_file(filename
)) {
87 printf("%s", bpf_log_buf
);
91 test_bpf_perf_event();
93 if (perf_event_mmap(pmu_fd
) < 0)
96 f
= popen("taskset 1 dd if=/dev/zero of=/dev/null", "r");
99 start_time
= time_get_ns();
100 ret
= perf_event_poller(pmu_fd
, print_bpf_output
);