Loading...
1#include <stdio.h>
2#include <unistd.h>
3#include <stdlib.h>
4#include <stdbool.h>
5#include <string.h>
6#include <fcntl.h>
7#include <poll.h>
8#include <sys/ioctl.h>
9#include <linux/perf_event.h>
10#include <linux/bpf.h>
11#include "libbpf.h"
12#include "bpf_load.h"
13#include "perf-sys.h"
14
15#define SAMPLE_PERIOD 0x7fffffffffffffffULL
16
17static void test_bpf_perf_event(void)
18{
19 int nr_cpus = sysconf(_SC_NPROCESSORS_CONF);
20 int *pmu_fd = malloc(nr_cpus * sizeof(int));
21 int status, i;
22
23 struct perf_event_attr attr_insn_pmu = {
24 .freq = 0,
25 .sample_period = SAMPLE_PERIOD,
26 .inherit = 0,
27 .type = PERF_TYPE_HARDWARE,
28 .read_format = 0,
29 .sample_type = 0,
30 .config = 0,/* PMU: cycles */
31 };
32
33 for (i = 0; i < nr_cpus; i++) {
34 pmu_fd[i] = sys_perf_event_open(&attr_insn_pmu, -1/*pid*/, i/*cpu*/, -1/*group_fd*/, 0);
35 if (pmu_fd[i] < 0) {
36 printf("event syscall failed\n");
37 goto exit;
38 }
39
40 bpf_map_update_elem(map_fd[0], &i, &pmu_fd[i], BPF_ANY);
41 ioctl(pmu_fd[i], PERF_EVENT_IOC_ENABLE, 0);
42 }
43
44 status = system("ls > /dev/null");
45 if (status)
46 goto exit;
47 status = system("sleep 2");
48 if (status)
49 goto exit;
50
51exit:
52 for (i = 0; i < nr_cpus; i++)
53 close(pmu_fd[i]);
54 close(map_fd[0]);
55 free(pmu_fd);
56}
57
58int main(int argc, char **argv)
59{
60 char filename[256];
61
62 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
63
64 if (load_bpf_file(filename)) {
65 printf("%s", bpf_log_buf);
66 return 1;
67 }
68
69 test_bpf_perf_event();
70 read_trace_pipe();
71
72 return 0;
73}