perf python: Add perf.tracepoint method
[cascardo/linux.git] / tools / perf / util / python.c
1 #include <Python.h>
2 #include <structmember.h>
3 #include <inttypes.h>
4 #include <poll.h>
5 #include <linux/err.h>
6 #include "evlist.h"
7 #include "evsel.h"
8 #include "event.h"
9 #include "cpumap.h"
10 #include "thread_map.h"
11
12 /*
13  * Support debug printing even though util/debug.c is not linked.  That means
14  * implementing 'verbose' and 'eprintf'.
15  */
16 int verbose;
17
18 int eprintf(int level, int var, const char *fmt, ...)
19 {
20         va_list args;
21         int ret = 0;
22
23         if (var >= level) {
24                 va_start(args, fmt);
25                 ret = vfprintf(stderr, fmt, args);
26                 va_end(args);
27         }
28
29         return ret;
30 }
31
32 /* Define PyVarObject_HEAD_INIT for python 2.5 */
33 #ifndef PyVarObject_HEAD_INIT
34 # define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
35 #endif
36
37 PyMODINIT_FUNC initperf(void);
38
39 #define member_def(type, member, ptype, help) \
40         { #member, ptype, \
41           offsetof(struct pyrf_event, event) + offsetof(struct type, member), \
42           0, help }
43
44 #define sample_member_def(name, member, ptype, help) \
45         { #name, ptype, \
46           offsetof(struct pyrf_event, sample) + offsetof(struct perf_sample, member), \
47           0, help }
48
49 struct pyrf_event {
50         PyObject_HEAD
51         struct perf_sample sample;
52         union perf_event   event;
53 };
54
55 #define sample_members \
56         sample_member_def(sample_ip, ip, T_ULONGLONG, "event type"),                     \
57         sample_member_def(sample_pid, pid, T_INT, "event pid"),                  \
58         sample_member_def(sample_tid, tid, T_INT, "event tid"),                  \
59         sample_member_def(sample_time, time, T_ULONGLONG, "event timestamp"),            \
60         sample_member_def(sample_addr, addr, T_ULONGLONG, "event addr"),                 \
61         sample_member_def(sample_id, id, T_ULONGLONG, "event id"),                       \
62         sample_member_def(sample_stream_id, stream_id, T_ULONGLONG, "event stream id"), \
63         sample_member_def(sample_period, period, T_ULONGLONG, "event period"),           \
64         sample_member_def(sample_cpu, cpu, T_UINT, "event cpu"),
65
66 static char pyrf_mmap_event__doc[] = PyDoc_STR("perf mmap event object.");
67
68 static PyMemberDef pyrf_mmap_event__members[] = {
69         sample_members
70         member_def(perf_event_header, type, T_UINT, "event type"),
71         member_def(perf_event_header, misc, T_UINT, "event misc"),
72         member_def(mmap_event, pid, T_UINT, "event pid"),
73         member_def(mmap_event, tid, T_UINT, "event tid"),
74         member_def(mmap_event, start, T_ULONGLONG, "start of the map"),
75         member_def(mmap_event, len, T_ULONGLONG, "map length"),
76         member_def(mmap_event, pgoff, T_ULONGLONG, "page offset"),
77         member_def(mmap_event, filename, T_STRING_INPLACE, "backing store"),
78         { .name = NULL, },
79 };
80
81 static PyObject *pyrf_mmap_event__repr(struct pyrf_event *pevent)
82 {
83         PyObject *ret;
84         char *s;
85
86         if (asprintf(&s, "{ type: mmap, pid: %u, tid: %u, start: %#" PRIx64 ", "
87                          "length: %#" PRIx64 ", offset: %#" PRIx64 ", "
88                          "filename: %s }",
89                      pevent->event.mmap.pid, pevent->event.mmap.tid,
90                      pevent->event.mmap.start, pevent->event.mmap.len,
91                      pevent->event.mmap.pgoff, pevent->event.mmap.filename) < 0) {
92                 ret = PyErr_NoMemory();
93         } else {
94                 ret = PyString_FromString(s);
95                 free(s);
96         }
97         return ret;
98 }
99
100 static PyTypeObject pyrf_mmap_event__type = {
101         PyVarObject_HEAD_INIT(NULL, 0)
102         .tp_name        = "perf.mmap_event",
103         .tp_basicsize   = sizeof(struct pyrf_event),
104         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
105         .tp_doc         = pyrf_mmap_event__doc,
106         .tp_members     = pyrf_mmap_event__members,
107         .tp_repr        = (reprfunc)pyrf_mmap_event__repr,
108 };
109
110 static char pyrf_task_event__doc[] = PyDoc_STR("perf task (fork/exit) event object.");
111
112 static PyMemberDef pyrf_task_event__members[] = {
113         sample_members
114         member_def(perf_event_header, type, T_UINT, "event type"),
115         member_def(fork_event, pid, T_UINT, "event pid"),
116         member_def(fork_event, ppid, T_UINT, "event ppid"),
117         member_def(fork_event, tid, T_UINT, "event tid"),
118         member_def(fork_event, ptid, T_UINT, "event ptid"),
119         member_def(fork_event, time, T_ULONGLONG, "timestamp"),
120         { .name = NULL, },
121 };
122
123 static PyObject *pyrf_task_event__repr(struct pyrf_event *pevent)
124 {
125         return PyString_FromFormat("{ type: %s, pid: %u, ppid: %u, tid: %u, "
126                                    "ptid: %u, time: %" PRIu64 "}",
127                                    pevent->event.header.type == PERF_RECORD_FORK ? "fork" : "exit",
128                                    pevent->event.fork.pid,
129                                    pevent->event.fork.ppid,
130                                    pevent->event.fork.tid,
131                                    pevent->event.fork.ptid,
132                                    pevent->event.fork.time);
133 }
134
135 static PyTypeObject pyrf_task_event__type = {
136         PyVarObject_HEAD_INIT(NULL, 0)
137         .tp_name        = "perf.task_event",
138         .tp_basicsize   = sizeof(struct pyrf_event),
139         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
140         .tp_doc         = pyrf_task_event__doc,
141         .tp_members     = pyrf_task_event__members,
142         .tp_repr        = (reprfunc)pyrf_task_event__repr,
143 };
144
145 static char pyrf_comm_event__doc[] = PyDoc_STR("perf comm event object.");
146
147 static PyMemberDef pyrf_comm_event__members[] = {
148         sample_members
149         member_def(perf_event_header, type, T_UINT, "event type"),
150         member_def(comm_event, pid, T_UINT, "event pid"),
151         member_def(comm_event, tid, T_UINT, "event tid"),
152         member_def(comm_event, comm, T_STRING_INPLACE, "process name"),
153         { .name = NULL, },
154 };
155
156 static PyObject *pyrf_comm_event__repr(struct pyrf_event *pevent)
157 {
158         return PyString_FromFormat("{ type: comm, pid: %u, tid: %u, comm: %s }",
159                                    pevent->event.comm.pid,
160                                    pevent->event.comm.tid,
161                                    pevent->event.comm.comm);
162 }
163
164 static PyTypeObject pyrf_comm_event__type = {
165         PyVarObject_HEAD_INIT(NULL, 0)
166         .tp_name        = "perf.comm_event",
167         .tp_basicsize   = sizeof(struct pyrf_event),
168         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
169         .tp_doc         = pyrf_comm_event__doc,
170         .tp_members     = pyrf_comm_event__members,
171         .tp_repr        = (reprfunc)pyrf_comm_event__repr,
172 };
173
174 static char pyrf_throttle_event__doc[] = PyDoc_STR("perf throttle event object.");
175
176 static PyMemberDef pyrf_throttle_event__members[] = {
177         sample_members
178         member_def(perf_event_header, type, T_UINT, "event type"),
179         member_def(throttle_event, time, T_ULONGLONG, "timestamp"),
180         member_def(throttle_event, id, T_ULONGLONG, "event id"),
181         member_def(throttle_event, stream_id, T_ULONGLONG, "event stream id"),
182         { .name = NULL, },
183 };
184
185 static PyObject *pyrf_throttle_event__repr(struct pyrf_event *pevent)
186 {
187         struct throttle_event *te = (struct throttle_event *)(&pevent->event.header + 1);
188
189         return PyString_FromFormat("{ type: %sthrottle, time: %" PRIu64 ", id: %" PRIu64
190                                    ", stream_id: %" PRIu64 " }",
191                                    pevent->event.header.type == PERF_RECORD_THROTTLE ? "" : "un",
192                                    te->time, te->id, te->stream_id);
193 }
194
195 static PyTypeObject pyrf_throttle_event__type = {
196         PyVarObject_HEAD_INIT(NULL, 0)
197         .tp_name        = "perf.throttle_event",
198         .tp_basicsize   = sizeof(struct pyrf_event),
199         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
200         .tp_doc         = pyrf_throttle_event__doc,
201         .tp_members     = pyrf_throttle_event__members,
202         .tp_repr        = (reprfunc)pyrf_throttle_event__repr,
203 };
204
205 static char pyrf_lost_event__doc[] = PyDoc_STR("perf lost event object.");
206
207 static PyMemberDef pyrf_lost_event__members[] = {
208         sample_members
209         member_def(lost_event, id, T_ULONGLONG, "event id"),
210         member_def(lost_event, lost, T_ULONGLONG, "number of lost events"),
211         { .name = NULL, },
212 };
213
214 static PyObject *pyrf_lost_event__repr(struct pyrf_event *pevent)
215 {
216         PyObject *ret;
217         char *s;
218
219         if (asprintf(&s, "{ type: lost, id: %#" PRIx64 ", "
220                          "lost: %#" PRIx64 " }",
221                      pevent->event.lost.id, pevent->event.lost.lost) < 0) {
222                 ret = PyErr_NoMemory();
223         } else {
224                 ret = PyString_FromString(s);
225                 free(s);
226         }
227         return ret;
228 }
229
230 static PyTypeObject pyrf_lost_event__type = {
231         PyVarObject_HEAD_INIT(NULL, 0)
232         .tp_name        = "perf.lost_event",
233         .tp_basicsize   = sizeof(struct pyrf_event),
234         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
235         .tp_doc         = pyrf_lost_event__doc,
236         .tp_members     = pyrf_lost_event__members,
237         .tp_repr        = (reprfunc)pyrf_lost_event__repr,
238 };
239
240 static char pyrf_read_event__doc[] = PyDoc_STR("perf read event object.");
241
242 static PyMemberDef pyrf_read_event__members[] = {
243         sample_members
244         member_def(read_event, pid, T_UINT, "event pid"),
245         member_def(read_event, tid, T_UINT, "event tid"),
246         { .name = NULL, },
247 };
248
249 static PyObject *pyrf_read_event__repr(struct pyrf_event *pevent)
250 {
251         return PyString_FromFormat("{ type: read, pid: %u, tid: %u }",
252                                    pevent->event.read.pid,
253                                    pevent->event.read.tid);
254         /*
255          * FIXME: return the array of read values,
256          * making this method useful ;-)
257          */
258 }
259
260 static PyTypeObject pyrf_read_event__type = {
261         PyVarObject_HEAD_INIT(NULL, 0)
262         .tp_name        = "perf.read_event",
263         .tp_basicsize   = sizeof(struct pyrf_event),
264         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
265         .tp_doc         = pyrf_read_event__doc,
266         .tp_members     = pyrf_read_event__members,
267         .tp_repr        = (reprfunc)pyrf_read_event__repr,
268 };
269
270 static char pyrf_sample_event__doc[] = PyDoc_STR("perf sample event object.");
271
272 static PyMemberDef pyrf_sample_event__members[] = {
273         sample_members
274         member_def(perf_event_header, type, T_UINT, "event type"),
275         { .name = NULL, },
276 };
277
278 static PyObject *pyrf_sample_event__repr(struct pyrf_event *pevent)
279 {
280         PyObject *ret;
281         char *s;
282
283         if (asprintf(&s, "{ type: sample }") < 0) {
284                 ret = PyErr_NoMemory();
285         } else {
286                 ret = PyString_FromString(s);
287                 free(s);
288         }
289         return ret;
290 }
291
292 static PyTypeObject pyrf_sample_event__type = {
293         PyVarObject_HEAD_INIT(NULL, 0)
294         .tp_name        = "perf.sample_event",
295         .tp_basicsize   = sizeof(struct pyrf_event),
296         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
297         .tp_doc         = pyrf_sample_event__doc,
298         .tp_members     = pyrf_sample_event__members,
299         .tp_repr        = (reprfunc)pyrf_sample_event__repr,
300 };
301
302 static char pyrf_context_switch_event__doc[] = PyDoc_STR("perf context_switch event object.");
303
304 static PyMemberDef pyrf_context_switch_event__members[] = {
305         sample_members
306         member_def(perf_event_header, type, T_UINT, "event type"),
307         member_def(context_switch_event, next_prev_pid, T_UINT, "next/prev pid"),
308         member_def(context_switch_event, next_prev_tid, T_UINT, "next/prev tid"),
309         { .name = NULL, },
310 };
311
312 static PyObject *pyrf_context_switch_event__repr(struct pyrf_event *pevent)
313 {
314         PyObject *ret;
315         char *s;
316
317         if (asprintf(&s, "{ type: context_switch, next_prev_pid: %u, next_prev_tid: %u, switch_out: %u }",
318                      pevent->event.context_switch.next_prev_pid,
319                      pevent->event.context_switch.next_prev_tid,
320                      !!(pevent->event.header.misc & PERF_RECORD_MISC_SWITCH_OUT)) < 0) {
321                 ret = PyErr_NoMemory();
322         } else {
323                 ret = PyString_FromString(s);
324                 free(s);
325         }
326         return ret;
327 }
328
329 static PyTypeObject pyrf_context_switch_event__type = {
330         PyVarObject_HEAD_INIT(NULL, 0)
331         .tp_name        = "perf.context_switch_event",
332         .tp_basicsize   = sizeof(struct pyrf_event),
333         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
334         .tp_doc         = pyrf_context_switch_event__doc,
335         .tp_members     = pyrf_context_switch_event__members,
336         .tp_repr        = (reprfunc)pyrf_context_switch_event__repr,
337 };
338
339 static int pyrf_event__setup_types(void)
340 {
341         int err;
342         pyrf_mmap_event__type.tp_new =
343         pyrf_task_event__type.tp_new =
344         pyrf_comm_event__type.tp_new =
345         pyrf_lost_event__type.tp_new =
346         pyrf_read_event__type.tp_new =
347         pyrf_sample_event__type.tp_new =
348         pyrf_context_switch_event__type.tp_new =
349         pyrf_throttle_event__type.tp_new = PyType_GenericNew;
350         err = PyType_Ready(&pyrf_mmap_event__type);
351         if (err < 0)
352                 goto out;
353         err = PyType_Ready(&pyrf_lost_event__type);
354         if (err < 0)
355                 goto out;
356         err = PyType_Ready(&pyrf_task_event__type);
357         if (err < 0)
358                 goto out;
359         err = PyType_Ready(&pyrf_comm_event__type);
360         if (err < 0)
361                 goto out;
362         err = PyType_Ready(&pyrf_throttle_event__type);
363         if (err < 0)
364                 goto out;
365         err = PyType_Ready(&pyrf_read_event__type);
366         if (err < 0)
367                 goto out;
368         err = PyType_Ready(&pyrf_sample_event__type);
369         if (err < 0)
370                 goto out;
371         err = PyType_Ready(&pyrf_context_switch_event__type);
372         if (err < 0)
373                 goto out;
374 out:
375         return err;
376 }
377
378 static PyTypeObject *pyrf_event__type[] = {
379         [PERF_RECORD_MMAP]       = &pyrf_mmap_event__type,
380         [PERF_RECORD_LOST]       = &pyrf_lost_event__type,
381         [PERF_RECORD_COMM]       = &pyrf_comm_event__type,
382         [PERF_RECORD_EXIT]       = &pyrf_task_event__type,
383         [PERF_RECORD_THROTTLE]   = &pyrf_throttle_event__type,
384         [PERF_RECORD_UNTHROTTLE] = &pyrf_throttle_event__type,
385         [PERF_RECORD_FORK]       = &pyrf_task_event__type,
386         [PERF_RECORD_READ]       = &pyrf_read_event__type,
387         [PERF_RECORD_SAMPLE]     = &pyrf_sample_event__type,
388         [PERF_RECORD_SWITCH]     = &pyrf_context_switch_event__type,
389         [PERF_RECORD_SWITCH_CPU_WIDE]  = &pyrf_context_switch_event__type,
390 };
391
392 static PyObject *pyrf_event__new(union perf_event *event)
393 {
394         struct pyrf_event *pevent;
395         PyTypeObject *ptype;
396
397         if ((event->header.type < PERF_RECORD_MMAP ||
398              event->header.type > PERF_RECORD_SAMPLE) &&
399             !(event->header.type == PERF_RECORD_SWITCH ||
400               event->header.type == PERF_RECORD_SWITCH_CPU_WIDE))
401                 return NULL;
402
403         ptype = pyrf_event__type[event->header.type];
404         pevent = PyObject_New(struct pyrf_event, ptype);
405         if (pevent != NULL)
406                 memcpy(&pevent->event, event, event->header.size);
407         return (PyObject *)pevent;
408 }
409
410 struct pyrf_cpu_map {
411         PyObject_HEAD
412
413         struct cpu_map *cpus;
414 };
415
416 static int pyrf_cpu_map__init(struct pyrf_cpu_map *pcpus,
417                               PyObject *args, PyObject *kwargs)
418 {
419         static char *kwlist[] = { "cpustr", NULL };
420         char *cpustr = NULL;
421
422         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s",
423                                          kwlist, &cpustr))
424                 return -1;
425
426         pcpus->cpus = cpu_map__new(cpustr);
427         if (pcpus->cpus == NULL)
428                 return -1;
429         return 0;
430 }
431
432 static void pyrf_cpu_map__delete(struct pyrf_cpu_map *pcpus)
433 {
434         cpu_map__put(pcpus->cpus);
435         pcpus->ob_type->tp_free((PyObject*)pcpus);
436 }
437
438 static Py_ssize_t pyrf_cpu_map__length(PyObject *obj)
439 {
440         struct pyrf_cpu_map *pcpus = (void *)obj;
441
442         return pcpus->cpus->nr;
443 }
444
445 static PyObject *pyrf_cpu_map__item(PyObject *obj, Py_ssize_t i)
446 {
447         struct pyrf_cpu_map *pcpus = (void *)obj;
448
449         if (i >= pcpus->cpus->nr)
450                 return NULL;
451
452         return Py_BuildValue("i", pcpus->cpus->map[i]);
453 }
454
455 static PySequenceMethods pyrf_cpu_map__sequence_methods = {
456         .sq_length = pyrf_cpu_map__length,
457         .sq_item   = pyrf_cpu_map__item,
458 };
459
460 static char pyrf_cpu_map__doc[] = PyDoc_STR("cpu map object.");
461
462 static PyTypeObject pyrf_cpu_map__type = {
463         PyVarObject_HEAD_INIT(NULL, 0)
464         .tp_name        = "perf.cpu_map",
465         .tp_basicsize   = sizeof(struct pyrf_cpu_map),
466         .tp_dealloc     = (destructor)pyrf_cpu_map__delete,
467         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
468         .tp_doc         = pyrf_cpu_map__doc,
469         .tp_as_sequence = &pyrf_cpu_map__sequence_methods,
470         .tp_init        = (initproc)pyrf_cpu_map__init,
471 };
472
473 static int pyrf_cpu_map__setup_types(void)
474 {
475         pyrf_cpu_map__type.tp_new = PyType_GenericNew;
476         return PyType_Ready(&pyrf_cpu_map__type);
477 }
478
479 struct pyrf_thread_map {
480         PyObject_HEAD
481
482         struct thread_map *threads;
483 };
484
485 static int pyrf_thread_map__init(struct pyrf_thread_map *pthreads,
486                                  PyObject *args, PyObject *kwargs)
487 {
488         static char *kwlist[] = { "pid", "tid", "uid", NULL };
489         int pid = -1, tid = -1, uid = UINT_MAX;
490
491         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|iii",
492                                          kwlist, &pid, &tid, &uid))
493                 return -1;
494
495         pthreads->threads = thread_map__new(pid, tid, uid);
496         if (pthreads->threads == NULL)
497                 return -1;
498         return 0;
499 }
500
501 static void pyrf_thread_map__delete(struct pyrf_thread_map *pthreads)
502 {
503         thread_map__put(pthreads->threads);
504         pthreads->ob_type->tp_free((PyObject*)pthreads);
505 }
506
507 static Py_ssize_t pyrf_thread_map__length(PyObject *obj)
508 {
509         struct pyrf_thread_map *pthreads = (void *)obj;
510
511         return pthreads->threads->nr;
512 }
513
514 static PyObject *pyrf_thread_map__item(PyObject *obj, Py_ssize_t i)
515 {
516         struct pyrf_thread_map *pthreads = (void *)obj;
517
518         if (i >= pthreads->threads->nr)
519                 return NULL;
520
521         return Py_BuildValue("i", pthreads->threads->map[i]);
522 }
523
524 static PySequenceMethods pyrf_thread_map__sequence_methods = {
525         .sq_length = pyrf_thread_map__length,
526         .sq_item   = pyrf_thread_map__item,
527 };
528
529 static char pyrf_thread_map__doc[] = PyDoc_STR("thread map object.");
530
531 static PyTypeObject pyrf_thread_map__type = {
532         PyVarObject_HEAD_INIT(NULL, 0)
533         .tp_name        = "perf.thread_map",
534         .tp_basicsize   = sizeof(struct pyrf_thread_map),
535         .tp_dealloc     = (destructor)pyrf_thread_map__delete,
536         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
537         .tp_doc         = pyrf_thread_map__doc,
538         .tp_as_sequence = &pyrf_thread_map__sequence_methods,
539         .tp_init        = (initproc)pyrf_thread_map__init,
540 };
541
542 static int pyrf_thread_map__setup_types(void)
543 {
544         pyrf_thread_map__type.tp_new = PyType_GenericNew;
545         return PyType_Ready(&pyrf_thread_map__type);
546 }
547
548 struct pyrf_evsel {
549         PyObject_HEAD
550
551         struct perf_evsel evsel;
552 };
553
554 static int pyrf_evsel__init(struct pyrf_evsel *pevsel,
555                             PyObject *args, PyObject *kwargs)
556 {
557         struct perf_event_attr attr = {
558                 .type = PERF_TYPE_HARDWARE,
559                 .config = PERF_COUNT_HW_CPU_CYCLES,
560                 .sample_type = PERF_SAMPLE_PERIOD | PERF_SAMPLE_TID,
561         };
562         static char *kwlist[] = {
563                 "type",
564                 "config",
565                 "sample_freq",
566                 "sample_period",
567                 "sample_type",
568                 "read_format",
569                 "disabled",
570                 "inherit",
571                 "pinned",
572                 "exclusive",
573                 "exclude_user",
574                 "exclude_kernel",
575                 "exclude_hv",
576                 "exclude_idle",
577                 "mmap",
578                 "context_switch",
579                 "comm",
580                 "freq",
581                 "inherit_stat",
582                 "enable_on_exec",
583                 "task",
584                 "watermark",
585                 "precise_ip",
586                 "mmap_data",
587                 "sample_id_all",
588                 "wakeup_events",
589                 "bp_type",
590                 "bp_addr",
591                 "bp_len",
592                  NULL
593         };
594         u64 sample_period = 0;
595         u32 disabled = 0,
596             inherit = 0,
597             pinned = 0,
598             exclusive = 0,
599             exclude_user = 0,
600             exclude_kernel = 0,
601             exclude_hv = 0,
602             exclude_idle = 0,
603             mmap = 0,
604             context_switch = 0,
605             comm = 0,
606             freq = 1,
607             inherit_stat = 0,
608             enable_on_exec = 0,
609             task = 0,
610             watermark = 0,
611             precise_ip = 0,
612             mmap_data = 0,
613             sample_id_all = 1;
614         int idx = 0;
615
616         if (!PyArg_ParseTupleAndKeywords(args, kwargs,
617                                          "|iKiKKiiiiiiiiiiiiiiiiiiiiiiKK", kwlist,
618                                          &attr.type, &attr.config, &attr.sample_freq,
619                                          &sample_period, &attr.sample_type,
620                                          &attr.read_format, &disabled, &inherit,
621                                          &pinned, &exclusive, &exclude_user,
622                                          &exclude_kernel, &exclude_hv, &exclude_idle,
623                                          &mmap, &context_switch, &comm, &freq, &inherit_stat,
624                                          &enable_on_exec, &task, &watermark,
625                                          &precise_ip, &mmap_data, &sample_id_all,
626                                          &attr.wakeup_events, &attr.bp_type,
627                                          &attr.bp_addr, &attr.bp_len, &idx))
628                 return -1;
629
630         /* union... */
631         if (sample_period != 0) {
632                 if (attr.sample_freq != 0)
633                         return -1; /* FIXME: throw right exception */
634                 attr.sample_period = sample_period;
635         }
636
637         /* Bitfields */
638         attr.disabled       = disabled;
639         attr.inherit        = inherit;
640         attr.pinned         = pinned;
641         attr.exclusive      = exclusive;
642         attr.exclude_user   = exclude_user;
643         attr.exclude_kernel = exclude_kernel;
644         attr.exclude_hv     = exclude_hv;
645         attr.exclude_idle   = exclude_idle;
646         attr.mmap           = mmap;
647         attr.context_switch = context_switch;
648         attr.comm           = comm;
649         attr.freq           = freq;
650         attr.inherit_stat   = inherit_stat;
651         attr.enable_on_exec = enable_on_exec;
652         attr.task           = task;
653         attr.watermark      = watermark;
654         attr.precise_ip     = precise_ip;
655         attr.mmap_data      = mmap_data;
656         attr.sample_id_all  = sample_id_all;
657         attr.size           = sizeof(attr);
658
659         perf_evsel__init(&pevsel->evsel, &attr, idx);
660         return 0;
661 }
662
663 static void pyrf_evsel__delete(struct pyrf_evsel *pevsel)
664 {
665         perf_evsel__exit(&pevsel->evsel);
666         pevsel->ob_type->tp_free((PyObject*)pevsel);
667 }
668
669 static PyObject *pyrf_evsel__open(struct pyrf_evsel *pevsel,
670                                   PyObject *args, PyObject *kwargs)
671 {
672         struct perf_evsel *evsel = &pevsel->evsel;
673         struct cpu_map *cpus = NULL;
674         struct thread_map *threads = NULL;
675         PyObject *pcpus = NULL, *pthreads = NULL;
676         int group = 0, inherit = 0;
677         static char *kwlist[] = { "cpus", "threads", "group", "inherit", NULL };
678
679         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOii", kwlist,
680                                          &pcpus, &pthreads, &group, &inherit))
681                 return NULL;
682
683         if (pthreads != NULL)
684                 threads = ((struct pyrf_thread_map *)pthreads)->threads;
685
686         if (pcpus != NULL)
687                 cpus = ((struct pyrf_cpu_map *)pcpus)->cpus;
688
689         evsel->attr.inherit = inherit;
690         /*
691          * This will group just the fds for this single evsel, to group
692          * multiple events, use evlist.open().
693          */
694         if (perf_evsel__open(evsel, cpus, threads) < 0) {
695                 PyErr_SetFromErrno(PyExc_OSError);
696                 return NULL;
697         }
698
699         Py_INCREF(Py_None);
700         return Py_None;
701 }
702
703 static PyMethodDef pyrf_evsel__methods[] = {
704         {
705                 .ml_name  = "open",
706                 .ml_meth  = (PyCFunction)pyrf_evsel__open,
707                 .ml_flags = METH_VARARGS | METH_KEYWORDS,
708                 .ml_doc   = PyDoc_STR("open the event selector file descriptor table.")
709         },
710         { .ml_name = NULL, }
711 };
712
713 static char pyrf_evsel__doc[] = PyDoc_STR("perf event selector list object.");
714
715 static PyTypeObject pyrf_evsel__type = {
716         PyVarObject_HEAD_INIT(NULL, 0)
717         .tp_name        = "perf.evsel",
718         .tp_basicsize   = sizeof(struct pyrf_evsel),
719         .tp_dealloc     = (destructor)pyrf_evsel__delete,
720         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
721         .tp_doc         = pyrf_evsel__doc,
722         .tp_methods     = pyrf_evsel__methods,
723         .tp_init        = (initproc)pyrf_evsel__init,
724 };
725
726 static int pyrf_evsel__setup_types(void)
727 {
728         pyrf_evsel__type.tp_new = PyType_GenericNew;
729         return PyType_Ready(&pyrf_evsel__type);
730 }
731
732 struct pyrf_evlist {
733         PyObject_HEAD
734
735         struct perf_evlist evlist;
736 };
737
738 static int pyrf_evlist__init(struct pyrf_evlist *pevlist,
739                              PyObject *args, PyObject *kwargs __maybe_unused)
740 {
741         PyObject *pcpus = NULL, *pthreads = NULL;
742         struct cpu_map *cpus;
743         struct thread_map *threads;
744
745         if (!PyArg_ParseTuple(args, "OO", &pcpus, &pthreads))
746                 return -1;
747
748         threads = ((struct pyrf_thread_map *)pthreads)->threads;
749         cpus = ((struct pyrf_cpu_map *)pcpus)->cpus;
750         perf_evlist__init(&pevlist->evlist, cpus, threads);
751         return 0;
752 }
753
754 static void pyrf_evlist__delete(struct pyrf_evlist *pevlist)
755 {
756         perf_evlist__exit(&pevlist->evlist);
757         pevlist->ob_type->tp_free((PyObject*)pevlist);
758 }
759
760 static PyObject *pyrf_evlist__mmap(struct pyrf_evlist *pevlist,
761                                    PyObject *args, PyObject *kwargs)
762 {
763         struct perf_evlist *evlist = &pevlist->evlist;
764         static char *kwlist[] = { "pages", "overwrite", NULL };
765         int pages = 128, overwrite = false;
766
767         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii", kwlist,
768                                          &pages, &overwrite))
769                 return NULL;
770
771         if (perf_evlist__mmap(evlist, pages, overwrite) < 0) {
772                 PyErr_SetFromErrno(PyExc_OSError);
773                 return NULL;
774         }
775
776         Py_INCREF(Py_None);
777         return Py_None;
778 }
779
780 static PyObject *pyrf_evlist__poll(struct pyrf_evlist *pevlist,
781                                    PyObject *args, PyObject *kwargs)
782 {
783         struct perf_evlist *evlist = &pevlist->evlist;
784         static char *kwlist[] = { "timeout", NULL };
785         int timeout = -1, n;
786
787         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", kwlist, &timeout))
788                 return NULL;
789
790         n = perf_evlist__poll(evlist, timeout);
791         if (n < 0) {
792                 PyErr_SetFromErrno(PyExc_OSError);
793                 return NULL;
794         }
795
796         return Py_BuildValue("i", n);
797 }
798
799 static PyObject *pyrf_evlist__get_pollfd(struct pyrf_evlist *pevlist,
800                                          PyObject *args __maybe_unused,
801                                          PyObject *kwargs __maybe_unused)
802 {
803         struct perf_evlist *evlist = &pevlist->evlist;
804         PyObject *list = PyList_New(0);
805         int i;
806
807         for (i = 0; i < evlist->pollfd.nr; ++i) {
808                 PyObject *file;
809                 FILE *fp = fdopen(evlist->pollfd.entries[i].fd, "r");
810
811                 if (fp == NULL)
812                         goto free_list;
813
814                 file = PyFile_FromFile(fp, "perf", "r", NULL);
815                 if (file == NULL)
816                         goto free_list;
817
818                 if (PyList_Append(list, file) != 0) {
819                         Py_DECREF(file);
820                         goto free_list;
821                 }
822
823                 Py_DECREF(file);
824         }
825
826         return list;
827 free_list:
828         return PyErr_NoMemory();
829 }
830
831
832 static PyObject *pyrf_evlist__add(struct pyrf_evlist *pevlist,
833                                   PyObject *args,
834                                   PyObject *kwargs __maybe_unused)
835 {
836         struct perf_evlist *evlist = &pevlist->evlist;
837         PyObject *pevsel;
838         struct perf_evsel *evsel;
839
840         if (!PyArg_ParseTuple(args, "O", &pevsel))
841                 return NULL;
842
843         Py_INCREF(pevsel);
844         evsel = &((struct pyrf_evsel *)pevsel)->evsel;
845         evsel->idx = evlist->nr_entries;
846         perf_evlist__add(evlist, evsel);
847
848         return Py_BuildValue("i", evlist->nr_entries);
849 }
850
851 static PyObject *pyrf_evlist__read_on_cpu(struct pyrf_evlist *pevlist,
852                                           PyObject *args, PyObject *kwargs)
853 {
854         struct perf_evlist *evlist = &pevlist->evlist;
855         union perf_event *event;
856         int sample_id_all = 1, cpu;
857         static char *kwlist[] = { "cpu", "sample_id_all", NULL };
858         int err;
859
860         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i", kwlist,
861                                          &cpu, &sample_id_all))
862                 return NULL;
863
864         event = perf_evlist__mmap_read(evlist, cpu);
865         if (event != NULL) {
866                 PyObject *pyevent = pyrf_event__new(event);
867                 struct pyrf_event *pevent = (struct pyrf_event *)pyevent;
868
869                 if (pyevent == NULL)
870                         return PyErr_NoMemory();
871
872                 err = perf_evlist__parse_sample(evlist, event, &pevent->sample);
873
874                 /* Consume the even only after we parsed it out. */
875                 perf_evlist__mmap_consume(evlist, cpu);
876
877                 if (err)
878                         return PyErr_Format(PyExc_OSError,
879                                             "perf: can't parse sample, err=%d", err);
880                 return pyevent;
881         }
882
883         Py_INCREF(Py_None);
884         return Py_None;
885 }
886
887 static PyObject *pyrf_evlist__open(struct pyrf_evlist *pevlist,
888                                    PyObject *args, PyObject *kwargs)
889 {
890         struct perf_evlist *evlist = &pevlist->evlist;
891         int group = 0;
892         static char *kwlist[] = { "group", NULL };
893
894         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOii", kwlist, &group))
895                 return NULL;
896
897         if (group)
898                 perf_evlist__set_leader(evlist);
899
900         if (perf_evlist__open(evlist) < 0) {
901                 PyErr_SetFromErrno(PyExc_OSError);
902                 return NULL;
903         }
904
905         Py_INCREF(Py_None);
906         return Py_None;
907 }
908
909 static PyMethodDef pyrf_evlist__methods[] = {
910         {
911                 .ml_name  = "mmap",
912                 .ml_meth  = (PyCFunction)pyrf_evlist__mmap,
913                 .ml_flags = METH_VARARGS | METH_KEYWORDS,
914                 .ml_doc   = PyDoc_STR("mmap the file descriptor table.")
915         },
916         {
917                 .ml_name  = "open",
918                 .ml_meth  = (PyCFunction)pyrf_evlist__open,
919                 .ml_flags = METH_VARARGS | METH_KEYWORDS,
920                 .ml_doc   = PyDoc_STR("open the file descriptors.")
921         },
922         {
923                 .ml_name  = "poll",
924                 .ml_meth  = (PyCFunction)pyrf_evlist__poll,
925                 .ml_flags = METH_VARARGS | METH_KEYWORDS,
926                 .ml_doc   = PyDoc_STR("poll the file descriptor table.")
927         },
928         {
929                 .ml_name  = "get_pollfd",
930                 .ml_meth  = (PyCFunction)pyrf_evlist__get_pollfd,
931                 .ml_flags = METH_VARARGS | METH_KEYWORDS,
932                 .ml_doc   = PyDoc_STR("get the poll file descriptor table.")
933         },
934         {
935                 .ml_name  = "add",
936                 .ml_meth  = (PyCFunction)pyrf_evlist__add,
937                 .ml_flags = METH_VARARGS | METH_KEYWORDS,
938                 .ml_doc   = PyDoc_STR("adds an event selector to the list.")
939         },
940         {
941                 .ml_name  = "read_on_cpu",
942                 .ml_meth  = (PyCFunction)pyrf_evlist__read_on_cpu,
943                 .ml_flags = METH_VARARGS | METH_KEYWORDS,
944                 .ml_doc   = PyDoc_STR("reads an event.")
945         },
946         { .ml_name = NULL, }
947 };
948
949 static Py_ssize_t pyrf_evlist__length(PyObject *obj)
950 {
951         struct pyrf_evlist *pevlist = (void *)obj;
952
953         return pevlist->evlist.nr_entries;
954 }
955
956 static PyObject *pyrf_evlist__item(PyObject *obj, Py_ssize_t i)
957 {
958         struct pyrf_evlist *pevlist = (void *)obj;
959         struct perf_evsel *pos;
960
961         if (i >= pevlist->evlist.nr_entries)
962                 return NULL;
963
964         evlist__for_each_entry(&pevlist->evlist, pos) {
965                 if (i-- == 0)
966                         break;
967         }
968
969         return Py_BuildValue("O", container_of(pos, struct pyrf_evsel, evsel));
970 }
971
972 static PySequenceMethods pyrf_evlist__sequence_methods = {
973         .sq_length = pyrf_evlist__length,
974         .sq_item   = pyrf_evlist__item,
975 };
976
977 static char pyrf_evlist__doc[] = PyDoc_STR("perf event selector list object.");
978
979 static PyTypeObject pyrf_evlist__type = {
980         PyVarObject_HEAD_INIT(NULL, 0)
981         .tp_name        = "perf.evlist",
982         .tp_basicsize   = sizeof(struct pyrf_evlist),
983         .tp_dealloc     = (destructor)pyrf_evlist__delete,
984         .tp_flags       = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
985         .tp_as_sequence = &pyrf_evlist__sequence_methods,
986         .tp_doc         = pyrf_evlist__doc,
987         .tp_methods     = pyrf_evlist__methods,
988         .tp_init        = (initproc)pyrf_evlist__init,
989 };
990
991 static int pyrf_evlist__setup_types(void)
992 {
993         pyrf_evlist__type.tp_new = PyType_GenericNew;
994         return PyType_Ready(&pyrf_evlist__type);
995 }
996
997 #define PERF_CONST(name) { #name, PERF_##name }
998
999 static struct {
1000         const char *name;
1001         int         value;
1002 } perf__constants[] = {
1003         PERF_CONST(TYPE_HARDWARE),
1004         PERF_CONST(TYPE_SOFTWARE),
1005         PERF_CONST(TYPE_TRACEPOINT),
1006         PERF_CONST(TYPE_HW_CACHE),
1007         PERF_CONST(TYPE_RAW),
1008         PERF_CONST(TYPE_BREAKPOINT),
1009
1010         PERF_CONST(COUNT_HW_CPU_CYCLES),
1011         PERF_CONST(COUNT_HW_INSTRUCTIONS),
1012         PERF_CONST(COUNT_HW_CACHE_REFERENCES),
1013         PERF_CONST(COUNT_HW_CACHE_MISSES),
1014         PERF_CONST(COUNT_HW_BRANCH_INSTRUCTIONS),
1015         PERF_CONST(COUNT_HW_BRANCH_MISSES),
1016         PERF_CONST(COUNT_HW_BUS_CYCLES),
1017         PERF_CONST(COUNT_HW_CACHE_L1D),
1018         PERF_CONST(COUNT_HW_CACHE_L1I),
1019         PERF_CONST(COUNT_HW_CACHE_LL),
1020         PERF_CONST(COUNT_HW_CACHE_DTLB),
1021         PERF_CONST(COUNT_HW_CACHE_ITLB),
1022         PERF_CONST(COUNT_HW_CACHE_BPU),
1023         PERF_CONST(COUNT_HW_CACHE_OP_READ),
1024         PERF_CONST(COUNT_HW_CACHE_OP_WRITE),
1025         PERF_CONST(COUNT_HW_CACHE_OP_PREFETCH),
1026         PERF_CONST(COUNT_HW_CACHE_RESULT_ACCESS),
1027         PERF_CONST(COUNT_HW_CACHE_RESULT_MISS),
1028
1029         PERF_CONST(COUNT_HW_STALLED_CYCLES_FRONTEND),
1030         PERF_CONST(COUNT_HW_STALLED_CYCLES_BACKEND),
1031
1032         PERF_CONST(COUNT_SW_CPU_CLOCK),
1033         PERF_CONST(COUNT_SW_TASK_CLOCK),
1034         PERF_CONST(COUNT_SW_PAGE_FAULTS),
1035         PERF_CONST(COUNT_SW_CONTEXT_SWITCHES),
1036         PERF_CONST(COUNT_SW_CPU_MIGRATIONS),
1037         PERF_CONST(COUNT_SW_PAGE_FAULTS_MIN),
1038         PERF_CONST(COUNT_SW_PAGE_FAULTS_MAJ),
1039         PERF_CONST(COUNT_SW_ALIGNMENT_FAULTS),
1040         PERF_CONST(COUNT_SW_EMULATION_FAULTS),
1041         PERF_CONST(COUNT_SW_DUMMY),
1042
1043         PERF_CONST(SAMPLE_IP),
1044         PERF_CONST(SAMPLE_TID),
1045         PERF_CONST(SAMPLE_TIME),
1046         PERF_CONST(SAMPLE_ADDR),
1047         PERF_CONST(SAMPLE_READ),
1048         PERF_CONST(SAMPLE_CALLCHAIN),
1049         PERF_CONST(SAMPLE_ID),
1050         PERF_CONST(SAMPLE_CPU),
1051         PERF_CONST(SAMPLE_PERIOD),
1052         PERF_CONST(SAMPLE_STREAM_ID),
1053         PERF_CONST(SAMPLE_RAW),
1054
1055         PERF_CONST(FORMAT_TOTAL_TIME_ENABLED),
1056         PERF_CONST(FORMAT_TOTAL_TIME_RUNNING),
1057         PERF_CONST(FORMAT_ID),
1058         PERF_CONST(FORMAT_GROUP),
1059
1060         PERF_CONST(RECORD_MMAP),
1061         PERF_CONST(RECORD_LOST),
1062         PERF_CONST(RECORD_COMM),
1063         PERF_CONST(RECORD_EXIT),
1064         PERF_CONST(RECORD_THROTTLE),
1065         PERF_CONST(RECORD_UNTHROTTLE),
1066         PERF_CONST(RECORD_FORK),
1067         PERF_CONST(RECORD_READ),
1068         PERF_CONST(RECORD_SAMPLE),
1069         PERF_CONST(RECORD_MMAP2),
1070         PERF_CONST(RECORD_AUX),
1071         PERF_CONST(RECORD_ITRACE_START),
1072         PERF_CONST(RECORD_LOST_SAMPLES),
1073         PERF_CONST(RECORD_SWITCH),
1074         PERF_CONST(RECORD_SWITCH_CPU_WIDE),
1075
1076         PERF_CONST(RECORD_MISC_SWITCH_OUT),
1077         { .name = NULL, },
1078 };
1079
1080 static PyObject *pyrf__tracepoint(struct pyrf_evsel *pevsel,
1081                                   PyObject *args, PyObject *kwargs)
1082 {
1083         struct event_format *tp_format;
1084         static char *kwlist[] = { "sys", "name", NULL };
1085         char *sys  = NULL;
1086         char *name = NULL;
1087
1088         if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss", kwlist,
1089                                          &sys, &name))
1090                 return NULL;
1091
1092         tp_format = trace_event__tp_format(sys, name);
1093         if (IS_ERR(tp_format))
1094                 return PyInt_FromLong(-1);
1095
1096         return PyInt_FromLong(tp_format->id);
1097 }
1098
1099 static PyMethodDef perf__methods[] = {
1100         {
1101                 .ml_name  = "tracepoint",
1102                 .ml_meth  = (PyCFunction) pyrf__tracepoint,
1103                 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1104                 .ml_doc   = PyDoc_STR("Get tracepoint config.")
1105         },
1106         { .ml_name = NULL, }
1107 };
1108
1109 PyMODINIT_FUNC initperf(void)
1110 {
1111         PyObject *obj;
1112         int i;
1113         PyObject *dict, *module = Py_InitModule("perf", perf__methods);
1114
1115         if (module == NULL ||
1116             pyrf_event__setup_types() < 0 ||
1117             pyrf_evlist__setup_types() < 0 ||
1118             pyrf_evsel__setup_types() < 0 ||
1119             pyrf_thread_map__setup_types() < 0 ||
1120             pyrf_cpu_map__setup_types() < 0)
1121                 return;
1122
1123         /* The page_size is placed in util object. */
1124         page_size = sysconf(_SC_PAGE_SIZE);
1125
1126         Py_INCREF(&pyrf_evlist__type);
1127         PyModule_AddObject(module, "evlist", (PyObject*)&pyrf_evlist__type);
1128
1129         Py_INCREF(&pyrf_evsel__type);
1130         PyModule_AddObject(module, "evsel", (PyObject*)&pyrf_evsel__type);
1131
1132         Py_INCREF(&pyrf_mmap_event__type);
1133         PyModule_AddObject(module, "mmap_event", (PyObject *)&pyrf_mmap_event__type);
1134
1135         Py_INCREF(&pyrf_lost_event__type);
1136         PyModule_AddObject(module, "lost_event", (PyObject *)&pyrf_lost_event__type);
1137
1138         Py_INCREF(&pyrf_comm_event__type);
1139         PyModule_AddObject(module, "comm_event", (PyObject *)&pyrf_comm_event__type);
1140
1141         Py_INCREF(&pyrf_task_event__type);
1142         PyModule_AddObject(module, "task_event", (PyObject *)&pyrf_task_event__type);
1143
1144         Py_INCREF(&pyrf_throttle_event__type);
1145         PyModule_AddObject(module, "throttle_event", (PyObject *)&pyrf_throttle_event__type);
1146
1147         Py_INCREF(&pyrf_task_event__type);
1148         PyModule_AddObject(module, "task_event", (PyObject *)&pyrf_task_event__type);
1149
1150         Py_INCREF(&pyrf_read_event__type);
1151         PyModule_AddObject(module, "read_event", (PyObject *)&pyrf_read_event__type);
1152
1153         Py_INCREF(&pyrf_sample_event__type);
1154         PyModule_AddObject(module, "sample_event", (PyObject *)&pyrf_sample_event__type);
1155
1156         Py_INCREF(&pyrf_context_switch_event__type);
1157         PyModule_AddObject(module, "switch_event", (PyObject *)&pyrf_context_switch_event__type);
1158
1159         Py_INCREF(&pyrf_thread_map__type);
1160         PyModule_AddObject(module, "thread_map", (PyObject*)&pyrf_thread_map__type);
1161
1162         Py_INCREF(&pyrf_cpu_map__type);
1163         PyModule_AddObject(module, "cpu_map", (PyObject*)&pyrf_cpu_map__type);
1164
1165         dict = PyModule_GetDict(module);
1166         if (dict == NULL)
1167                 goto error;
1168
1169         for (i = 0; perf__constants[i].name != NULL; i++) {
1170                 obj = PyInt_FromLong(perf__constants[i].value);
1171                 if (obj == NULL)
1172                         goto error;
1173                 PyDict_SetItemString(dict, perf__constants[i].name, obj);
1174                 Py_DECREF(obj);
1175         }
1176
1177 error:
1178         if (PyErr_Occurred())
1179                 PyErr_SetString(PyExc_ImportError, "perf: Init failed!");
1180 }
1181
1182 /*
1183  * Dummy, to avoid dragging all the test_attr infrastructure in the python
1184  * binding.
1185  */
1186 void test_attr__open(struct perf_event_attr *attr, pid_t pid, int cpu,
1187                      int fd, int group_fd, unsigned long flags)
1188 {
1189 }