Debian Codegraph @

perf/perf.c

raw symbols SCIP
1 /************************************************************************/
2 /* * The Rocq Prover / The Rocq Development Team */
3 /* v * Copyright INRIA, CNRS and contributors */
4 /* <O___,, * (see version control and CREDITS file for authors & dates) */
5 /* \VV/ **************************************************************/
6 /* // * This file is distributed under the terms of the */
7 /* * GNU Lesser General Public License Version 2.1 */
8 /* * (see LICENSE file for the text of the license) */
9 /************************************************************************/
10
11 #include <linux/perf_event.h>
12 #include <sys/syscall.h>
13 #include <sys/ioctl.h>
14 #include <unistd.h>
15
16 #include <errno.h>
17 #include <string.h>
18
19 #include <caml/mlvalues.h>
20 #include <caml/memory.h>
21 #include <caml/alloc.h>
22 #include <caml/fail.h>
23
24 static int perf_event_open(struct perf_event_attr *hw_event, pid_t pid,
25 int cpu, int group_fd, unsigned long flags) {
26 return syscall(SYS_perf_event_open, hw_event, pid, cpu, group_fd, flags);
27 }
28
29 #define NOT_INITIALIZED (-2)
30
31 int fd = NOT_INITIALIZED;
32
33 CAMLprim value CAML_init(value unit) {
34 CAMLparam1(unit);
35
36 if (fd != NOT_INITIALIZED) {
37 caml_failwith("counter already initialized");
38 }
39
40 struct perf_event_attr pe;
41 memset(&pe, 0, sizeof(pe));
42
43 pe.type = PERF_TYPE_HARDWARE;
44 pe.size = sizeof(pe);
45 pe.config = PERF_COUNT_HW_INSTRUCTIONS;
46 pe.disabled = 1;
47 pe.exclude_kernel = 1;
48 pe.exclude_hv = 1;
49
50 fd = perf_event_open(&pe, 0, -1, -1, 0);
51 if (fd == -1) {
52 fd = NOT_INITIALIZED;
53 caml_failwith("initialisation failure");
54 }
55
56 if (ioctl(fd, PERF_EVENT_IOC_RESET , 0) == -1) {
57 close(fd);
58 fd = NOT_INITIALIZED;
59 caml_failwith("could not initially reset counter");
60 }
61
62 if (ioctl(fd, PERF_EVENT_IOC_ENABLE, 0) == -1) {
63 close(fd);
64 fd = NOT_INITIALIZED;
65 caml_failwith("could not initailly enable counter");
66 }
67
68 CAMLreturn(Val_unit);
69 }
70
71 CAMLprim value CAML_drop(value unit) {
72 CAMLparam1(unit);
73
74 if (fd == NOT_INITIALIZED) {
75 caml_failwith("counter not initialized");
76 }
77
78 close(fd);
79 fd = NOT_INITIALIZED;
80
81 CAMLreturn(Val_unit);
82 }
83
84 CAMLprim value CAML_peek(value unit) {
85 CAMLparam1(unit);
86
87 if (fd == NOT_INITIALIZED) caml_failwith("counter not initialized");
88
89 if (ioctl(fd, PERF_EVENT_IOC_DISABLE, 0) == -1) {
90 caml_failwith("could not disable counter");
91 }
92
93 int64_t count = 0;
94 size_t n = read(fd, &count, sizeof(count));
95
96 if (n != sizeof(count)) {
97 caml_failwith("could not retrieve counter");
98 }
99
100 value ret = caml_copy_int64(count);
101
102 if (ioctl(fd, PERF_EVENT_IOC_ENABLE, 0) == -1) {
103 caml_failwith("could not enable counter");
104 }
105
106 CAMLreturn(ret);
107 }