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