blob: ca7874ed77f4326db742366641c982612e9261b0 [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"
Joe Stringer205c8ad2016-12-08 18:46:19 -080013#include "perf-sys.h"
Kaixu Xia47efb302015-08-06 07:02:36 +000014
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));
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000021 int status, i;
Kaixu Xia47efb302015-08-06 07:02:36 +000022
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++) {
Joe Stringer205c8ad2016-12-08 18:46:19 -080034 pmu_fd[i] = sys_perf_event_open(&attr_insn_pmu, -1/*pid*/, i/*cpu*/, -1/*group_fd*/, 0);
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000035 if (pmu_fd[i] < 0) {
Kaixu Xia47efb302015-08-06 07:02:36 +000036 printf("event syscall failed\n");
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000037 goto exit;
38 }
Kaixu Xia47efb302015-08-06 07:02:36 +000039
Joe Stringerd40fc182016-12-14 14:43:38 -080040 bpf_map_update_elem(map_fd[0], &i, &pmu_fd[i], BPF_ANY);
Kaixu Xia47efb302015-08-06 07:02:36 +000041 ioctl(pmu_fd[i], PERF_EVENT_IOC_ENABLE, 0);
42 }
43
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000044 status = system("ls > /dev/null");
45 if (status)
46 goto exit;
47 status = system("sleep 2");
48 if (status)
49 goto exit;
Kaixu Xia47efb302015-08-06 07:02:36 +000050
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000051exit:
Kaixu Xia47efb302015-08-06 07:02:36 +000052 for (i = 0; i < nr_cpus; i++)
53 close(pmu_fd[i]);
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000054 close(map_fd[0]);
Kaixu Xia47efb302015-08-06 07:02:36 +000055 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();
Kaixu Xia5ed3ccb2015-08-12 09:37:53 +000070 read_trace_pipe();
Kaixu Xia47efb302015-08-06 07:02:36 +000071
72 return 0;
73}