samples/bpf: example of get selected PMU counter value
[linux-block.git] / samples / bpf / tracex6_user.c
CommitLineData
47efb302
KX
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
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));
20 unsigned long value;
21 int 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] = 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
38 bpf_update_elem(map_fd[0], &i, &pmu_fd[i], BPF_ANY);
39 ioctl(pmu_fd[i], PERF_EVENT_IOC_ENABLE, 0);
40 }
41
42 system("ls");
43 system("pwd");
44 system("sleep 2");
45
46 for (i = 0; i < nr_cpus; i++)
47 close(pmu_fd[i]);
48
49 close(map_fd);
50
51 free(pmu_fd);
52}
53
54int main(int argc, char **argv)
55{
56 char filename[256];
57
58 snprintf(filename, sizeof(filename), "%s_kern.o", argv[0]);
59
60 if (load_bpf_file(filename)) {
61 printf("%s", bpf_log_buf);
62 return 1;
63 }
64
65 test_bpf_perf_event();
66
67 return 0;
68}