2 * Copyright 2013, Michael Ellerman, IBM Corp.
3 * Licensed under GPLv2.
8 #include <sys/syscall.h>
11 #include <sys/ioctl.h>
16 int perf_event_open(struct perf_event_attr *attr, pid_t pid, int cpu,
17 int group_fd, unsigned long flags)
19 return syscall(__NR_perf_event_open, attr, pid, cpu,
23 void event_init_opts(struct event *e, u64 config, int type, char *name)
25 memset(e, 0, sizeof(*e));
30 e->attr.config = config;
31 e->attr.size = sizeof(e->attr);
32 /* This has to match the structure layout in the header */
33 e->attr.read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | \
34 PERF_FORMAT_TOTAL_TIME_RUNNING;
37 void event_init_named(struct event *e, u64 config, char *name)
39 event_init_opts(e, config, PERF_TYPE_RAW, name);
42 void event_init(struct event *e, u64 config)
44 event_init_opts(e, config, PERF_TYPE_RAW, "event");
47 #define PERF_CURRENT_PID 0
48 #define PERF_NO_PID -1
49 #define PERF_NO_CPU -1
50 #define PERF_NO_GROUP -1
52 int event_open_with_options(struct event *e, pid_t pid, int cpu, int group_fd)
54 e->fd = perf_event_open(&e->attr, pid, cpu, group_fd, 0);
56 perror("perf_event_open");
63 int event_open_with_group(struct event *e, int group_fd)
65 return event_open_with_options(e, PERF_CURRENT_PID, PERF_NO_CPU, group_fd);
68 int event_open_with_pid(struct event *e, pid_t pid)
70 return event_open_with_options(e, pid, PERF_NO_CPU, PERF_NO_GROUP);
73 int event_open_with_cpu(struct event *e, int cpu)
75 return event_open_with_options(e, PERF_NO_PID, cpu, PERF_NO_GROUP);
78 int event_open(struct event *e)
80 return event_open_with_options(e, PERF_CURRENT_PID, PERF_NO_CPU, PERF_NO_GROUP);
83 void event_close(struct event *e)
88 int event_enable(struct event *e)
90 return ioctl(e->fd, PERF_EVENT_IOC_ENABLE);
93 int event_disable(struct event *e)
95 return ioctl(e->fd, PERF_EVENT_IOC_DISABLE);
98 int event_reset(struct event *e)
100 return ioctl(e->fd, PERF_EVENT_IOC_RESET);
103 int event_read(struct event *e)
107 rc = read(e->fd, &e->result, sizeof(e->result));
108 if (rc != sizeof(e->result)) {
109 fprintf(stderr, "read error on event %p!\n", e);
116 void event_report_justified(struct event *e, int name_width, int result_width)
118 printf("%*s: result %*llu ", name_width, e->name, result_width,
121 if (e->result.running == e->result.enabled)
122 printf("running/enabled %llu\n", e->result.running);
124 printf("running %llu enabled %llu\n", e->result.running,
128 void event_report(struct event *e)
130 event_report_justified(e, 0, 0);