blob: 8ea4976cfcf1201a52f0ce4f4f27f06454c1f61f [file] [log] [blame]
Kaixu Xia47efb302015-08-06 07:02:36 +00001#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
14#define SAMPLE_PERIOD 0x7fffffffffffffffULL
15
16static void test_bpf_perf_event(void)
17{
18 int nr_cpus = sysconf(_SC_NPROCESSORS_CONF);
19 int *pmu_fd = malloc(nr_cpus * sizeof(int));
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000020 int status, i;
Kaixu Xia47efb302015-08-06 07:02:36 +000021
22 struct perf_event_attr attr_insn_pmu = {
23 .freq = 0,
24 .sample_period = SAMPLE_PERIOD,
25 .inherit = 0,
26 .type = PERF_TYPE_HARDWARE,
27 .read_format = 0,
28 .sample_type = 0,
29 .config = 0,/* PMU: cycles */
30 };
31
32 for (i = 0; i < nr_cpus; i++) {
33 pmu_fd[i] = perf_event_open(&attr_insn_pmu, -1/*pid*/, i/*cpu*/, -1/*group_fd*/, 0);
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000034 if (pmu_fd[i] < 0) {
Kaixu Xia47efb302015-08-06 07:02:36 +000035 printf("event syscall failed\n");
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000036 goto exit;
37 }
Kaixu Xia47efb302015-08-06 07:02:36 +000038
39 bpf_update_elem(map_fd[0], &i, &pmu_fd[i], BPF_ANY);
40 ioctl(pmu_fd[i], PERF_EVENT_IOC_ENABLE, 0);
41 }
42
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000043 status = system("ls > /dev/null");
44 if (status)
45 goto exit;
46 status = system("sleep 2");
47 if (status)
48 goto exit;
Kaixu Xia47efb302015-08-06 07:02:36 +000049
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000050exit:
Kaixu Xia47efb302015-08-06 07:02:36 +000051 for (i = 0; i < nr_cpus; i++)
52 close(pmu_fd[i]);
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000053 close(map_fd[0]);
Kaixu Xia47efb302015-08-06 07:02:36 +000054 free(pmu_fd);
55}
56
57int main(int argc, char **argv)
58{
59 char filename[256];
60
61 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
62
63 if (load_bpf_file(filename)) {
64 printf("%s", bpf_log_buf);
65 return 1;
66 }
67
68 test_bpf_perf_event();
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000069 read_trace_pipe();
Kaixu Xia47efb302015-08-06 07:02:36 +000070
71 return 0;
72}