1 // SPDX-License-Identifier: GPL-2.0
3 #include <structmember.h>
7 #include <perf/cpumap.h>
8 #ifdef HAVE_LIBTRACEEVENT
9 #include <traceevent/event-parse.h>
11 #include <perf/mmap.h>
13 #include "callchain.h"
16 #include "print_binary.h"
17 #include "thread_map.h"
18 #include "trace-event.h"
21 #include "metricgroup.h"
24 #include <internal/lib.h>
27 #if PY_MAJOR_VERSION < 3
28 #define _PyUnicode_FromString(arg) \
29 PyString_FromString(arg)
30 #define _PyUnicode_AsString(arg) \
31 PyString_AsString(arg)
32 #define _PyUnicode_FromFormat(...) \
33 PyString_FromFormat(__VA_ARGS__)
34 #define _PyLong_FromLong(arg) \
39 #define _PyUnicode_FromString(arg) \
40 PyUnicode_FromString(arg)
41 #define _PyUnicode_FromFormat(...) \
42 PyUnicode_FromFormat(__VA_ARGS__)
43 #define _PyLong_FromLong(arg) \
48 #define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
52 * Provide these two so that we don't have to link against callchain.c and
53 * start dragging hist.c, etc.
55 struct callchain_param callchain_param;
57 int parse_callchain_record(const char *arg __maybe_unused,
58 struct callchain_param *param __maybe_unused)
64 * Add these not to drag util/env.c
66 struct perf_env perf_env;
68 const char *perf_env__cpuid(struct perf_env *env __maybe_unused)
73 // This one is a bit easier, wouldn't drag too much, but leave it as a stub we need it here
74 const char *perf_env__arch(struct perf_env *env __maybe_unused)
80 * These ones are needed not to drag the PMU bandwagon, jevents generated
81 * pmu_sys_event_tables, etc and evsel__find_pmu() is used so far just for
82 * doing per PMU perf_event_attr.exclude_guest handling, not really needed, so
83 * far, for the perf python binding known usecases, revisit if this become
86 struct perf_pmu *evsel__find_pmu(const struct evsel *evsel __maybe_unused)
91 int perf_pmu__scan_file(struct perf_pmu *pmu, const char *name, const char *fmt, ...)
96 bool evsel__is_aux_event(const struct evsel *evsel __maybe_unused)
102 * Add this one here not to drag util/metricgroup.c
104 int metricgroup__copy_metric_events(struct evlist *evlist, struct cgroup *cgrp,
105 struct rblist *new_metric_events,
106 struct rblist *old_metric_events)
112 * XXX: All these evsel destructors need some better mechanism, like a linked
113 * list of destructors registered when the relevant code indeed is used instead
114 * of having more and more calls in perf_evsel__delete(). -- acme
116 * For now, add some more:
118 * Not to drag the BPF bandwagon...
120 void bpf_counter__destroy(struct evsel *evsel);
121 int bpf_counter__install_pe(struct evsel *evsel, int cpu, int fd);
122 int bpf_counter__disable(struct evsel *evsel);
124 void bpf_counter__destroy(struct evsel *evsel __maybe_unused)
128 int bpf_counter__install_pe(struct evsel *evsel __maybe_unused, int cpu __maybe_unused, int fd __maybe_unused)
133 int bpf_counter__disable(struct evsel *evsel __maybe_unused)
139 * Support debug printing even though util/debug.c is not linked. That means
140 * implementing 'verbose' and 'eprintf'.
145 int eprintf(int level, int var, const char *fmt, ...);
147 int eprintf(int level, int var, const char *fmt, ...)
154 ret = vfprintf(stderr, fmt, args);
161 /* Define PyVarObject_HEAD_INIT for python 2.5 */
162 #ifndef PyVarObject_HEAD_INIT
163 # define PyVarObject_HEAD_INIT(type, size) PyObject_HEAD_INIT(type) size,
166 #if PY_MAJOR_VERSION < 3
167 PyMODINIT_FUNC initperf(void);
169 PyMODINIT_FUNC PyInit_perf(void);
172 #define member_def(type, member, ptype, help) \
174 offsetof(struct pyrf_event, event) + offsetof(struct type, member), \
177 #define sample_member_def(name, member, ptype, help) \
179 offsetof(struct pyrf_event, sample) + offsetof(struct perf_sample, member), \
185 struct perf_sample sample;
186 union perf_event event;
189 #define sample_members \
190 sample_member_def(sample_ip, ip, T_ULONGLONG, "event type"), \
191 sample_member_def(sample_pid, pid, T_INT, "event pid"), \
192 sample_member_def(sample_tid, tid, T_INT, "event tid"), \
193 sample_member_def(sample_time, time, T_ULONGLONG, "event timestamp"), \
194 sample_member_def(sample_addr, addr, T_ULONGLONG, "event addr"), \
195 sample_member_def(sample_id, id, T_ULONGLONG, "event id"), \
196 sample_member_def(sample_stream_id, stream_id, T_ULONGLONG, "event stream id"), \
197 sample_member_def(sample_period, period, T_ULONGLONG, "event period"), \
198 sample_member_def(sample_cpu, cpu, T_UINT, "event cpu"),
200 static char pyrf_mmap_event__doc[] = PyDoc_STR("perf mmap event object.");
202 static PyMemberDef pyrf_mmap_event__members[] = {
204 member_def(perf_event_header, type, T_UINT, "event type"),
205 member_def(perf_event_header, misc, T_UINT, "event misc"),
206 member_def(perf_record_mmap, pid, T_UINT, "event pid"),
207 member_def(perf_record_mmap, tid, T_UINT, "event tid"),
208 member_def(perf_record_mmap, start, T_ULONGLONG, "start of the map"),
209 member_def(perf_record_mmap, len, T_ULONGLONG, "map length"),
210 member_def(perf_record_mmap, pgoff, T_ULONGLONG, "page offset"),
211 member_def(perf_record_mmap, filename, T_STRING_INPLACE, "backing store"),
215 static PyObject *pyrf_mmap_event__repr(struct pyrf_event *pevent)
220 if (asprintf(&s, "{ type: mmap, pid: %u, tid: %u, start: %#" PRI_lx64 ", "
221 "length: %#" PRI_lx64 ", offset: %#" PRI_lx64 ", "
223 pevent->event.mmap.pid, pevent->event.mmap.tid,
224 pevent->event.mmap.start, pevent->event.mmap.len,
225 pevent->event.mmap.pgoff, pevent->event.mmap.filename) < 0) {
226 ret = PyErr_NoMemory();
228 ret = _PyUnicode_FromString(s);
234 static PyTypeObject pyrf_mmap_event__type = {
235 PyVarObject_HEAD_INIT(NULL, 0)
236 .tp_name = "perf.mmap_event",
237 .tp_basicsize = sizeof(struct pyrf_event),
238 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
239 .tp_doc = pyrf_mmap_event__doc,
240 .tp_members = pyrf_mmap_event__members,
241 .tp_repr = (reprfunc)pyrf_mmap_event__repr,
244 static char pyrf_task_event__doc[] = PyDoc_STR("perf task (fork/exit) event object.");
246 static PyMemberDef pyrf_task_event__members[] = {
248 member_def(perf_event_header, type, T_UINT, "event type"),
249 member_def(perf_record_fork, pid, T_UINT, "event pid"),
250 member_def(perf_record_fork, ppid, T_UINT, "event ppid"),
251 member_def(perf_record_fork, tid, T_UINT, "event tid"),
252 member_def(perf_record_fork, ptid, T_UINT, "event ptid"),
253 member_def(perf_record_fork, time, T_ULONGLONG, "timestamp"),
257 static PyObject *pyrf_task_event__repr(struct pyrf_event *pevent)
259 return _PyUnicode_FromFormat("{ type: %s, pid: %u, ppid: %u, tid: %u, "
260 "ptid: %u, time: %" PRI_lu64 "}",
261 pevent->event.header.type == PERF_RECORD_FORK ? "fork" : "exit",
262 pevent->event.fork.pid,
263 pevent->event.fork.ppid,
264 pevent->event.fork.tid,
265 pevent->event.fork.ptid,
266 pevent->event.fork.time);
269 static PyTypeObject pyrf_task_event__type = {
270 PyVarObject_HEAD_INIT(NULL, 0)
271 .tp_name = "perf.task_event",
272 .tp_basicsize = sizeof(struct pyrf_event),
273 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
274 .tp_doc = pyrf_task_event__doc,
275 .tp_members = pyrf_task_event__members,
276 .tp_repr = (reprfunc)pyrf_task_event__repr,
279 static char pyrf_comm_event__doc[] = PyDoc_STR("perf comm event object.");
281 static PyMemberDef pyrf_comm_event__members[] = {
283 member_def(perf_event_header, type, T_UINT, "event type"),
284 member_def(perf_record_comm, pid, T_UINT, "event pid"),
285 member_def(perf_record_comm, tid, T_UINT, "event tid"),
286 member_def(perf_record_comm, comm, T_STRING_INPLACE, "process name"),
290 static PyObject *pyrf_comm_event__repr(struct pyrf_event *pevent)
292 return _PyUnicode_FromFormat("{ type: comm, pid: %u, tid: %u, comm: %s }",
293 pevent->event.comm.pid,
294 pevent->event.comm.tid,
295 pevent->event.comm.comm);
298 static PyTypeObject pyrf_comm_event__type = {
299 PyVarObject_HEAD_INIT(NULL, 0)
300 .tp_name = "perf.comm_event",
301 .tp_basicsize = sizeof(struct pyrf_event),
302 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
303 .tp_doc = pyrf_comm_event__doc,
304 .tp_members = pyrf_comm_event__members,
305 .tp_repr = (reprfunc)pyrf_comm_event__repr,
308 static char pyrf_throttle_event__doc[] = PyDoc_STR("perf throttle event object.");
310 static PyMemberDef pyrf_throttle_event__members[] = {
312 member_def(perf_event_header, type, T_UINT, "event type"),
313 member_def(perf_record_throttle, time, T_ULONGLONG, "timestamp"),
314 member_def(perf_record_throttle, id, T_ULONGLONG, "event id"),
315 member_def(perf_record_throttle, stream_id, T_ULONGLONG, "event stream id"),
319 static PyObject *pyrf_throttle_event__repr(struct pyrf_event *pevent)
321 struct perf_record_throttle *te = (struct perf_record_throttle *)(&pevent->event.header + 1);
323 return _PyUnicode_FromFormat("{ type: %sthrottle, time: %" PRI_lu64 ", id: %" PRI_lu64
324 ", stream_id: %" PRI_lu64 " }",
325 pevent->event.header.type == PERF_RECORD_THROTTLE ? "" : "un",
326 te->time, te->id, te->stream_id);
329 static PyTypeObject pyrf_throttle_event__type = {
330 PyVarObject_HEAD_INIT(NULL, 0)
331 .tp_name = "perf.throttle_event",
332 .tp_basicsize = sizeof(struct pyrf_event),
333 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
334 .tp_doc = pyrf_throttle_event__doc,
335 .tp_members = pyrf_throttle_event__members,
336 .tp_repr = (reprfunc)pyrf_throttle_event__repr,
339 static char pyrf_lost_event__doc[] = PyDoc_STR("perf lost event object.");
341 static PyMemberDef pyrf_lost_event__members[] = {
343 member_def(perf_record_lost, id, T_ULONGLONG, "event id"),
344 member_def(perf_record_lost, lost, T_ULONGLONG, "number of lost events"),
348 static PyObject *pyrf_lost_event__repr(struct pyrf_event *pevent)
353 if (asprintf(&s, "{ type: lost, id: %#" PRI_lx64 ", "
354 "lost: %#" PRI_lx64 " }",
355 pevent->event.lost.id, pevent->event.lost.lost) < 0) {
356 ret = PyErr_NoMemory();
358 ret = _PyUnicode_FromString(s);
364 static PyTypeObject pyrf_lost_event__type = {
365 PyVarObject_HEAD_INIT(NULL, 0)
366 .tp_name = "perf.lost_event",
367 .tp_basicsize = sizeof(struct pyrf_event),
368 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
369 .tp_doc = pyrf_lost_event__doc,
370 .tp_members = pyrf_lost_event__members,
371 .tp_repr = (reprfunc)pyrf_lost_event__repr,
374 static char pyrf_read_event__doc[] = PyDoc_STR("perf read event object.");
376 static PyMemberDef pyrf_read_event__members[] = {
378 member_def(perf_record_read, pid, T_UINT, "event pid"),
379 member_def(perf_record_read, tid, T_UINT, "event tid"),
383 static PyObject *pyrf_read_event__repr(struct pyrf_event *pevent)
385 return _PyUnicode_FromFormat("{ type: read, pid: %u, tid: %u }",
386 pevent->event.read.pid,
387 pevent->event.read.tid);
389 * FIXME: return the array of read values,
390 * making this method useful ;-)
394 static PyTypeObject pyrf_read_event__type = {
395 PyVarObject_HEAD_INIT(NULL, 0)
396 .tp_name = "perf.read_event",
397 .tp_basicsize = sizeof(struct pyrf_event),
398 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
399 .tp_doc = pyrf_read_event__doc,
400 .tp_members = pyrf_read_event__members,
401 .tp_repr = (reprfunc)pyrf_read_event__repr,
404 static char pyrf_sample_event__doc[] = PyDoc_STR("perf sample event object.");
406 static PyMemberDef pyrf_sample_event__members[] = {
408 member_def(perf_event_header, type, T_UINT, "event type"),
412 static PyObject *pyrf_sample_event__repr(struct pyrf_event *pevent)
417 if (asprintf(&s, "{ type: sample }") < 0) {
418 ret = PyErr_NoMemory();
420 ret = _PyUnicode_FromString(s);
426 #ifdef HAVE_LIBTRACEEVENT
427 static bool is_tracepoint(struct pyrf_event *pevent)
429 return pevent->evsel->core.attr.type == PERF_TYPE_TRACEPOINT;
433 tracepoint_field(struct pyrf_event *pe, struct tep_format_field *field)
435 struct tep_handle *pevent = field->event->tep;
436 void *data = pe->sample.raw_data;
437 PyObject *ret = NULL;
438 unsigned long long val;
439 unsigned int offset, len;
441 if (field->flags & TEP_FIELD_IS_ARRAY) {
442 offset = field->offset;
444 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
445 val = tep_read_number(pevent, data + offset, len);
449 if (tep_field_is_relative(field->flags))
450 offset += field->offset + field->size;
452 if (field->flags & TEP_FIELD_IS_STRING &&
453 is_printable_array(data + offset, len)) {
454 ret = _PyUnicode_FromString((char *)data + offset);
456 ret = PyByteArray_FromStringAndSize((const char *) data + offset, len);
457 field->flags &= ~TEP_FIELD_IS_STRING;
460 val = tep_read_number(pevent, data + field->offset,
462 if (field->flags & TEP_FIELD_IS_POINTER)
463 ret = PyLong_FromUnsignedLong((unsigned long) val);
464 else if (field->flags & TEP_FIELD_IS_SIGNED)
465 ret = PyLong_FromLong((long) val);
467 ret = PyLong_FromUnsignedLong((unsigned long) val);
474 get_tracepoint_field(struct pyrf_event *pevent, PyObject *attr_name)
476 const char *str = _PyUnicode_AsString(PyObject_Str(attr_name));
477 struct evsel *evsel = pevent->evsel;
478 struct tep_format_field *field;
480 if (!evsel->tp_format) {
481 struct tep_event *tp_format;
483 tp_format = trace_event__tp_format_id(evsel->core.attr.config);
484 if (IS_ERR_OR_NULL(tp_format))
487 evsel->tp_format = tp_format;
490 field = tep_find_any_field(evsel->tp_format, str);
494 return tracepoint_field(pevent, field);
496 #endif /* HAVE_LIBTRACEEVENT */
499 pyrf_sample_event__getattro(struct pyrf_event *pevent, PyObject *attr_name)
501 PyObject *obj = NULL;
503 #ifdef HAVE_LIBTRACEEVENT
504 if (is_tracepoint(pevent))
505 obj = get_tracepoint_field(pevent, attr_name);
508 return obj ?: PyObject_GenericGetAttr((PyObject *) pevent, attr_name);
511 static PyTypeObject pyrf_sample_event__type = {
512 PyVarObject_HEAD_INIT(NULL, 0)
513 .tp_name = "perf.sample_event",
514 .tp_basicsize = sizeof(struct pyrf_event),
515 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
516 .tp_doc = pyrf_sample_event__doc,
517 .tp_members = pyrf_sample_event__members,
518 .tp_repr = (reprfunc)pyrf_sample_event__repr,
519 .tp_getattro = (getattrofunc) pyrf_sample_event__getattro,
522 static char pyrf_context_switch_event__doc[] = PyDoc_STR("perf context_switch event object.");
524 static PyMemberDef pyrf_context_switch_event__members[] = {
526 member_def(perf_event_header, type, T_UINT, "event type"),
527 member_def(perf_record_switch, next_prev_pid, T_UINT, "next/prev pid"),
528 member_def(perf_record_switch, next_prev_tid, T_UINT, "next/prev tid"),
532 static PyObject *pyrf_context_switch_event__repr(struct pyrf_event *pevent)
537 if (asprintf(&s, "{ type: context_switch, next_prev_pid: %u, next_prev_tid: %u, switch_out: %u }",
538 pevent->event.context_switch.next_prev_pid,
539 pevent->event.context_switch.next_prev_tid,
540 !!(pevent->event.header.misc & PERF_RECORD_MISC_SWITCH_OUT)) < 0) {
541 ret = PyErr_NoMemory();
543 ret = _PyUnicode_FromString(s);
549 static PyTypeObject pyrf_context_switch_event__type = {
550 PyVarObject_HEAD_INIT(NULL, 0)
551 .tp_name = "perf.context_switch_event",
552 .tp_basicsize = sizeof(struct pyrf_event),
553 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
554 .tp_doc = pyrf_context_switch_event__doc,
555 .tp_members = pyrf_context_switch_event__members,
556 .tp_repr = (reprfunc)pyrf_context_switch_event__repr,
559 static int pyrf_event__setup_types(void)
562 pyrf_mmap_event__type.tp_new =
563 pyrf_task_event__type.tp_new =
564 pyrf_comm_event__type.tp_new =
565 pyrf_lost_event__type.tp_new =
566 pyrf_read_event__type.tp_new =
567 pyrf_sample_event__type.tp_new =
568 pyrf_context_switch_event__type.tp_new =
569 pyrf_throttle_event__type.tp_new = PyType_GenericNew;
570 err = PyType_Ready(&pyrf_mmap_event__type);
573 err = PyType_Ready(&pyrf_lost_event__type);
576 err = PyType_Ready(&pyrf_task_event__type);
579 err = PyType_Ready(&pyrf_comm_event__type);
582 err = PyType_Ready(&pyrf_throttle_event__type);
585 err = PyType_Ready(&pyrf_read_event__type);
588 err = PyType_Ready(&pyrf_sample_event__type);
591 err = PyType_Ready(&pyrf_context_switch_event__type);
598 static PyTypeObject *pyrf_event__type[] = {
599 [PERF_RECORD_MMAP] = &pyrf_mmap_event__type,
600 [PERF_RECORD_LOST] = &pyrf_lost_event__type,
601 [PERF_RECORD_COMM] = &pyrf_comm_event__type,
602 [PERF_RECORD_EXIT] = &pyrf_task_event__type,
603 [PERF_RECORD_THROTTLE] = &pyrf_throttle_event__type,
604 [PERF_RECORD_UNTHROTTLE] = &pyrf_throttle_event__type,
605 [PERF_RECORD_FORK] = &pyrf_task_event__type,
606 [PERF_RECORD_READ] = &pyrf_read_event__type,
607 [PERF_RECORD_SAMPLE] = &pyrf_sample_event__type,
608 [PERF_RECORD_SWITCH] = &pyrf_context_switch_event__type,
609 [PERF_RECORD_SWITCH_CPU_WIDE] = &pyrf_context_switch_event__type,
612 static PyObject *pyrf_event__new(union perf_event *event)
614 struct pyrf_event *pevent;
617 if ((event->header.type < PERF_RECORD_MMAP ||
618 event->header.type > PERF_RECORD_SAMPLE) &&
619 !(event->header.type == PERF_RECORD_SWITCH ||
620 event->header.type == PERF_RECORD_SWITCH_CPU_WIDE))
623 ptype = pyrf_event__type[event->header.type];
624 pevent = PyObject_New(struct pyrf_event, ptype);
626 memcpy(&pevent->event, event, event->header.size);
627 return (PyObject *)pevent;
630 struct pyrf_cpu_map {
633 struct perf_cpu_map *cpus;
636 static int pyrf_cpu_map__init(struct pyrf_cpu_map *pcpus,
637 PyObject *args, PyObject *kwargs)
639 static char *kwlist[] = { "cpustr", NULL };
642 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s",
646 pcpus->cpus = perf_cpu_map__new(cpustr);
647 if (pcpus->cpus == NULL)
652 static void pyrf_cpu_map__delete(struct pyrf_cpu_map *pcpus)
654 perf_cpu_map__put(pcpus->cpus);
655 Py_TYPE(pcpus)->tp_free((PyObject*)pcpus);
658 static Py_ssize_t pyrf_cpu_map__length(PyObject *obj)
660 struct pyrf_cpu_map *pcpus = (void *)obj;
662 return perf_cpu_map__nr(pcpus->cpus);
665 static PyObject *pyrf_cpu_map__item(PyObject *obj, Py_ssize_t i)
667 struct pyrf_cpu_map *pcpus = (void *)obj;
669 if (i >= perf_cpu_map__nr(pcpus->cpus))
672 return Py_BuildValue("i", perf_cpu_map__cpu(pcpus->cpus, i).cpu);
675 static PySequenceMethods pyrf_cpu_map__sequence_methods = {
676 .sq_length = pyrf_cpu_map__length,
677 .sq_item = pyrf_cpu_map__item,
680 static char pyrf_cpu_map__doc[] = PyDoc_STR("cpu map object.");
682 static PyTypeObject pyrf_cpu_map__type = {
683 PyVarObject_HEAD_INIT(NULL, 0)
684 .tp_name = "perf.cpu_map",
685 .tp_basicsize = sizeof(struct pyrf_cpu_map),
686 .tp_dealloc = (destructor)pyrf_cpu_map__delete,
687 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
688 .tp_doc = pyrf_cpu_map__doc,
689 .tp_as_sequence = &pyrf_cpu_map__sequence_methods,
690 .tp_init = (initproc)pyrf_cpu_map__init,
693 static int pyrf_cpu_map__setup_types(void)
695 pyrf_cpu_map__type.tp_new = PyType_GenericNew;
696 return PyType_Ready(&pyrf_cpu_map__type);
699 struct pyrf_thread_map {
702 struct perf_thread_map *threads;
705 static int pyrf_thread_map__init(struct pyrf_thread_map *pthreads,
706 PyObject *args, PyObject *kwargs)
708 static char *kwlist[] = { "pid", "tid", "uid", NULL };
709 int pid = -1, tid = -1, uid = UINT_MAX;
711 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|iii",
712 kwlist, &pid, &tid, &uid))
715 pthreads->threads = thread_map__new(pid, tid, uid);
716 if (pthreads->threads == NULL)
721 static void pyrf_thread_map__delete(struct pyrf_thread_map *pthreads)
723 perf_thread_map__put(pthreads->threads);
724 Py_TYPE(pthreads)->tp_free((PyObject*)pthreads);
727 static Py_ssize_t pyrf_thread_map__length(PyObject *obj)
729 struct pyrf_thread_map *pthreads = (void *)obj;
731 return perf_thread_map__nr(pthreads->threads);
734 static PyObject *pyrf_thread_map__item(PyObject *obj, Py_ssize_t i)
736 struct pyrf_thread_map *pthreads = (void *)obj;
738 if (i >= perf_thread_map__nr(pthreads->threads))
741 return Py_BuildValue("i", perf_thread_map__pid(pthreads->threads, i));
744 static PySequenceMethods pyrf_thread_map__sequence_methods = {
745 .sq_length = pyrf_thread_map__length,
746 .sq_item = pyrf_thread_map__item,
749 static char pyrf_thread_map__doc[] = PyDoc_STR("thread map object.");
751 static PyTypeObject pyrf_thread_map__type = {
752 PyVarObject_HEAD_INIT(NULL, 0)
753 .tp_name = "perf.thread_map",
754 .tp_basicsize = sizeof(struct pyrf_thread_map),
755 .tp_dealloc = (destructor)pyrf_thread_map__delete,
756 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
757 .tp_doc = pyrf_thread_map__doc,
758 .tp_as_sequence = &pyrf_thread_map__sequence_methods,
759 .tp_init = (initproc)pyrf_thread_map__init,
762 static int pyrf_thread_map__setup_types(void)
764 pyrf_thread_map__type.tp_new = PyType_GenericNew;
765 return PyType_Ready(&pyrf_thread_map__type);
774 static int pyrf_evsel__init(struct pyrf_evsel *pevsel,
775 PyObject *args, PyObject *kwargs)
777 struct perf_event_attr attr = {
778 .type = PERF_TYPE_HARDWARE,
779 .config = PERF_COUNT_HW_CPU_CYCLES,
780 .sample_type = PERF_SAMPLE_PERIOD | PERF_SAMPLE_TID,
782 static char *kwlist[] = {
814 u64 sample_period = 0;
836 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
837 "|iKiKKiiiiiiiiiiiiiiiiiiiiiiKK", kwlist,
838 &attr.type, &attr.config, &attr.sample_freq,
839 &sample_period, &attr.sample_type,
840 &attr.read_format, &disabled, &inherit,
841 &pinned, &exclusive, &exclude_user,
842 &exclude_kernel, &exclude_hv, &exclude_idle,
843 &mmap, &context_switch, &comm, &freq, &inherit_stat,
844 &enable_on_exec, &task, &watermark,
845 &precise_ip, &mmap_data, &sample_id_all,
846 &attr.wakeup_events, &attr.bp_type,
847 &attr.bp_addr, &attr.bp_len, &idx))
851 if (sample_period != 0) {
852 if (attr.sample_freq != 0)
853 return -1; /* FIXME: throw right exception */
854 attr.sample_period = sample_period;
858 attr.disabled = disabled;
859 attr.inherit = inherit;
860 attr.pinned = pinned;
861 attr.exclusive = exclusive;
862 attr.exclude_user = exclude_user;
863 attr.exclude_kernel = exclude_kernel;
864 attr.exclude_hv = exclude_hv;
865 attr.exclude_idle = exclude_idle;
867 attr.context_switch = context_switch;
870 attr.inherit_stat = inherit_stat;
871 attr.enable_on_exec = enable_on_exec;
873 attr.watermark = watermark;
874 attr.precise_ip = precise_ip;
875 attr.mmap_data = mmap_data;
876 attr.sample_id_all = sample_id_all;
877 attr.size = sizeof(attr);
879 evsel__init(&pevsel->evsel, &attr, idx);
883 static void pyrf_evsel__delete(struct pyrf_evsel *pevsel)
885 evsel__exit(&pevsel->evsel);
886 Py_TYPE(pevsel)->tp_free((PyObject*)pevsel);
889 static PyObject *pyrf_evsel__open(struct pyrf_evsel *pevsel,
890 PyObject *args, PyObject *kwargs)
892 struct evsel *evsel = &pevsel->evsel;
893 struct perf_cpu_map *cpus = NULL;
894 struct perf_thread_map *threads = NULL;
895 PyObject *pcpus = NULL, *pthreads = NULL;
896 int group = 0, inherit = 0;
897 static char *kwlist[] = { "cpus", "threads", "group", "inherit", NULL };
899 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOii", kwlist,
900 &pcpus, &pthreads, &group, &inherit))
903 if (pthreads != NULL)
904 threads = ((struct pyrf_thread_map *)pthreads)->threads;
907 cpus = ((struct pyrf_cpu_map *)pcpus)->cpus;
909 evsel->core.attr.inherit = inherit;
911 * This will group just the fds for this single evsel, to group
912 * multiple events, use evlist.open().
914 if (evsel__open(evsel, cpus, threads) < 0) {
915 PyErr_SetFromErrno(PyExc_OSError);
923 static PyMethodDef pyrf_evsel__methods[] = {
926 .ml_meth = (PyCFunction)pyrf_evsel__open,
927 .ml_flags = METH_VARARGS | METH_KEYWORDS,
928 .ml_doc = PyDoc_STR("open the event selector file descriptor table.")
933 static char pyrf_evsel__doc[] = PyDoc_STR("perf event selector list object.");
935 static PyTypeObject pyrf_evsel__type = {
936 PyVarObject_HEAD_INIT(NULL, 0)
937 .tp_name = "perf.evsel",
938 .tp_basicsize = sizeof(struct pyrf_evsel),
939 .tp_dealloc = (destructor)pyrf_evsel__delete,
940 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
941 .tp_doc = pyrf_evsel__doc,
942 .tp_methods = pyrf_evsel__methods,
943 .tp_init = (initproc)pyrf_evsel__init,
946 static int pyrf_evsel__setup_types(void)
948 pyrf_evsel__type.tp_new = PyType_GenericNew;
949 return PyType_Ready(&pyrf_evsel__type);
955 struct evlist evlist;
958 static int pyrf_evlist__init(struct pyrf_evlist *pevlist,
959 PyObject *args, PyObject *kwargs __maybe_unused)
961 PyObject *pcpus = NULL, *pthreads = NULL;
962 struct perf_cpu_map *cpus;
963 struct perf_thread_map *threads;
965 if (!PyArg_ParseTuple(args, "OO", &pcpus, &pthreads))
968 threads = ((struct pyrf_thread_map *)pthreads)->threads;
969 cpus = ((struct pyrf_cpu_map *)pcpus)->cpus;
970 evlist__init(&pevlist->evlist, cpus, threads);
974 static void pyrf_evlist__delete(struct pyrf_evlist *pevlist)
976 evlist__exit(&pevlist->evlist);
977 Py_TYPE(pevlist)->tp_free((PyObject*)pevlist);
980 static PyObject *pyrf_evlist__mmap(struct pyrf_evlist *pevlist,
981 PyObject *args, PyObject *kwargs)
983 struct evlist *evlist = &pevlist->evlist;
984 static char *kwlist[] = { "pages", "overwrite", NULL };
985 int pages = 128, overwrite = false;
987 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii", kwlist,
991 if (evlist__mmap(evlist, pages) < 0) {
992 PyErr_SetFromErrno(PyExc_OSError);
1000 static PyObject *pyrf_evlist__poll(struct pyrf_evlist *pevlist,
1001 PyObject *args, PyObject *kwargs)
1003 struct evlist *evlist = &pevlist->evlist;
1004 static char *kwlist[] = { "timeout", NULL };
1005 int timeout = -1, n;
1007 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", kwlist, &timeout))
1010 n = evlist__poll(evlist, timeout);
1012 PyErr_SetFromErrno(PyExc_OSError);
1016 return Py_BuildValue("i", n);
1019 static PyObject *pyrf_evlist__get_pollfd(struct pyrf_evlist *pevlist,
1020 PyObject *args __maybe_unused,
1021 PyObject *kwargs __maybe_unused)
1023 struct evlist *evlist = &pevlist->evlist;
1024 PyObject *list = PyList_New(0);
1027 for (i = 0; i < evlist->core.pollfd.nr; ++i) {
1029 #if PY_MAJOR_VERSION < 3
1030 FILE *fp = fdopen(evlist->core.pollfd.entries[i].fd, "r");
1035 file = PyFile_FromFile(fp, "perf", "r", NULL);
1037 file = PyFile_FromFd(evlist->core.pollfd.entries[i].fd, "perf", "r", -1,
1038 NULL, NULL, NULL, 0);
1043 if (PyList_Append(list, file) != 0) {
1053 return PyErr_NoMemory();
1057 static PyObject *pyrf_evlist__add(struct pyrf_evlist *pevlist,
1059 PyObject *kwargs __maybe_unused)
1061 struct evlist *evlist = &pevlist->evlist;
1063 struct evsel *evsel;
1065 if (!PyArg_ParseTuple(args, "O", &pevsel))
1069 evsel = &((struct pyrf_evsel *)pevsel)->evsel;
1070 evsel->core.idx = evlist->core.nr_entries;
1071 evlist__add(evlist, evsel);
1073 return Py_BuildValue("i", evlist->core.nr_entries);
1076 static struct mmap *get_md(struct evlist *evlist, int cpu)
1080 for (i = 0; i < evlist->core.nr_mmaps; i++) {
1081 struct mmap *md = &evlist->mmap[i];
1083 if (md->core.cpu.cpu == cpu)
1090 static PyObject *pyrf_evlist__read_on_cpu(struct pyrf_evlist *pevlist,
1091 PyObject *args, PyObject *kwargs)
1093 struct evlist *evlist = &pevlist->evlist;
1094 union perf_event *event;
1095 int sample_id_all = 1, cpu;
1096 static char *kwlist[] = { "cpu", "sample_id_all", NULL };
1100 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i", kwlist,
1101 &cpu, &sample_id_all))
1104 md = get_md(evlist, cpu);
1108 if (perf_mmap__read_init(&md->core) < 0)
1111 event = perf_mmap__read_event(&md->core);
1112 if (event != NULL) {
1113 PyObject *pyevent = pyrf_event__new(event);
1114 struct pyrf_event *pevent = (struct pyrf_event *)pyevent;
1115 struct evsel *evsel;
1117 if (pyevent == NULL)
1118 return PyErr_NoMemory();
1120 evsel = evlist__event2evsel(evlist, event);
1126 pevent->evsel = evsel;
1128 err = evsel__parse_sample(evsel, event, &pevent->sample);
1130 /* Consume the even only after we parsed it out. */
1131 perf_mmap__consume(&md->core);
1134 return PyErr_Format(PyExc_OSError,
1135 "perf: can't parse sample, err=%d", err);
1143 static PyObject *pyrf_evlist__open(struct pyrf_evlist *pevlist,
1144 PyObject *args, PyObject *kwargs)
1146 struct evlist *evlist = &pevlist->evlist;
1148 if (evlist__open(evlist) < 0) {
1149 PyErr_SetFromErrno(PyExc_OSError);
1157 static PyMethodDef pyrf_evlist__methods[] = {
1160 .ml_meth = (PyCFunction)pyrf_evlist__mmap,
1161 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1162 .ml_doc = PyDoc_STR("mmap the file descriptor table.")
1166 .ml_meth = (PyCFunction)pyrf_evlist__open,
1167 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1168 .ml_doc = PyDoc_STR("open the file descriptors.")
1172 .ml_meth = (PyCFunction)pyrf_evlist__poll,
1173 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1174 .ml_doc = PyDoc_STR("poll the file descriptor table.")
1177 .ml_name = "get_pollfd",
1178 .ml_meth = (PyCFunction)pyrf_evlist__get_pollfd,
1179 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1180 .ml_doc = PyDoc_STR("get the poll file descriptor table.")
1184 .ml_meth = (PyCFunction)pyrf_evlist__add,
1185 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1186 .ml_doc = PyDoc_STR("adds an event selector to the list.")
1189 .ml_name = "read_on_cpu",
1190 .ml_meth = (PyCFunction)pyrf_evlist__read_on_cpu,
1191 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1192 .ml_doc = PyDoc_STR("reads an event.")
1194 { .ml_name = NULL, }
1197 static Py_ssize_t pyrf_evlist__length(PyObject *obj)
1199 struct pyrf_evlist *pevlist = (void *)obj;
1201 return pevlist->evlist.core.nr_entries;
1204 static PyObject *pyrf_evlist__item(PyObject *obj, Py_ssize_t i)
1206 struct pyrf_evlist *pevlist = (void *)obj;
1209 if (i >= pevlist->evlist.core.nr_entries)
1212 evlist__for_each_entry(&pevlist->evlist, pos) {
1217 return Py_BuildValue("O", container_of(pos, struct pyrf_evsel, evsel));
1220 static PySequenceMethods pyrf_evlist__sequence_methods = {
1221 .sq_length = pyrf_evlist__length,
1222 .sq_item = pyrf_evlist__item,
1225 static char pyrf_evlist__doc[] = PyDoc_STR("perf event selector list object.");
1227 static PyTypeObject pyrf_evlist__type = {
1228 PyVarObject_HEAD_INIT(NULL, 0)
1229 .tp_name = "perf.evlist",
1230 .tp_basicsize = sizeof(struct pyrf_evlist),
1231 .tp_dealloc = (destructor)pyrf_evlist__delete,
1232 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
1233 .tp_as_sequence = &pyrf_evlist__sequence_methods,
1234 .tp_doc = pyrf_evlist__doc,
1235 .tp_methods = pyrf_evlist__methods,
1236 .tp_init = (initproc)pyrf_evlist__init,
1239 static int pyrf_evlist__setup_types(void)
1241 pyrf_evlist__type.tp_new = PyType_GenericNew;
1242 return PyType_Ready(&pyrf_evlist__type);
1245 #define PERF_CONST(name) { #name, PERF_##name }
1250 } perf__constants[] = {
1251 PERF_CONST(TYPE_HARDWARE),
1252 PERF_CONST(TYPE_SOFTWARE),
1253 PERF_CONST(TYPE_TRACEPOINT),
1254 PERF_CONST(TYPE_HW_CACHE),
1255 PERF_CONST(TYPE_RAW),
1256 PERF_CONST(TYPE_BREAKPOINT),
1258 PERF_CONST(COUNT_HW_CPU_CYCLES),
1259 PERF_CONST(COUNT_HW_INSTRUCTIONS),
1260 PERF_CONST(COUNT_HW_CACHE_REFERENCES),
1261 PERF_CONST(COUNT_HW_CACHE_MISSES),
1262 PERF_CONST(COUNT_HW_BRANCH_INSTRUCTIONS),
1263 PERF_CONST(COUNT_HW_BRANCH_MISSES),
1264 PERF_CONST(COUNT_HW_BUS_CYCLES),
1265 PERF_CONST(COUNT_HW_CACHE_L1D),
1266 PERF_CONST(COUNT_HW_CACHE_L1I),
1267 PERF_CONST(COUNT_HW_CACHE_LL),
1268 PERF_CONST(COUNT_HW_CACHE_DTLB),
1269 PERF_CONST(COUNT_HW_CACHE_ITLB),
1270 PERF_CONST(COUNT_HW_CACHE_BPU),
1271 PERF_CONST(COUNT_HW_CACHE_OP_READ),
1272 PERF_CONST(COUNT_HW_CACHE_OP_WRITE),
1273 PERF_CONST(COUNT_HW_CACHE_OP_PREFETCH),
1274 PERF_CONST(COUNT_HW_CACHE_RESULT_ACCESS),
1275 PERF_CONST(COUNT_HW_CACHE_RESULT_MISS),
1277 PERF_CONST(COUNT_HW_STALLED_CYCLES_FRONTEND),
1278 PERF_CONST(COUNT_HW_STALLED_CYCLES_BACKEND),
1280 PERF_CONST(COUNT_SW_CPU_CLOCK),
1281 PERF_CONST(COUNT_SW_TASK_CLOCK),
1282 PERF_CONST(COUNT_SW_PAGE_FAULTS),
1283 PERF_CONST(COUNT_SW_CONTEXT_SWITCHES),
1284 PERF_CONST(COUNT_SW_CPU_MIGRATIONS),
1285 PERF_CONST(COUNT_SW_PAGE_FAULTS_MIN),
1286 PERF_CONST(COUNT_SW_PAGE_FAULTS_MAJ),
1287 PERF_CONST(COUNT_SW_ALIGNMENT_FAULTS),
1288 PERF_CONST(COUNT_SW_EMULATION_FAULTS),
1289 PERF_CONST(COUNT_SW_DUMMY),
1291 PERF_CONST(SAMPLE_IP),
1292 PERF_CONST(SAMPLE_TID),
1293 PERF_CONST(SAMPLE_TIME),
1294 PERF_CONST(SAMPLE_ADDR),
1295 PERF_CONST(SAMPLE_READ),
1296 PERF_CONST(SAMPLE_CALLCHAIN),
1297 PERF_CONST(SAMPLE_ID),
1298 PERF_CONST(SAMPLE_CPU),
1299 PERF_CONST(SAMPLE_PERIOD),
1300 PERF_CONST(SAMPLE_STREAM_ID),
1301 PERF_CONST(SAMPLE_RAW),
1303 PERF_CONST(FORMAT_TOTAL_TIME_ENABLED),
1304 PERF_CONST(FORMAT_TOTAL_TIME_RUNNING),
1305 PERF_CONST(FORMAT_ID),
1306 PERF_CONST(FORMAT_GROUP),
1308 PERF_CONST(RECORD_MMAP),
1309 PERF_CONST(RECORD_LOST),
1310 PERF_CONST(RECORD_COMM),
1311 PERF_CONST(RECORD_EXIT),
1312 PERF_CONST(RECORD_THROTTLE),
1313 PERF_CONST(RECORD_UNTHROTTLE),
1314 PERF_CONST(RECORD_FORK),
1315 PERF_CONST(RECORD_READ),
1316 PERF_CONST(RECORD_SAMPLE),
1317 PERF_CONST(RECORD_MMAP2),
1318 PERF_CONST(RECORD_AUX),
1319 PERF_CONST(RECORD_ITRACE_START),
1320 PERF_CONST(RECORD_LOST_SAMPLES),
1321 PERF_CONST(RECORD_SWITCH),
1322 PERF_CONST(RECORD_SWITCH_CPU_WIDE),
1324 PERF_CONST(RECORD_MISC_SWITCH_OUT),
1328 static PyObject *pyrf__tracepoint(struct pyrf_evsel *pevsel,
1329 PyObject *args, PyObject *kwargs)
1331 #ifndef HAVE_LIBTRACEEVENT
1334 struct tep_event *tp_format;
1335 static char *kwlist[] = { "sys", "name", NULL };
1339 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss", kwlist,
1343 tp_format = trace_event__tp_format(sys, name);
1344 if (IS_ERR(tp_format))
1345 return _PyLong_FromLong(-1);
1347 return _PyLong_FromLong(tp_format->id);
1348 #endif // HAVE_LIBTRACEEVENT
1351 static PyMethodDef perf__methods[] = {
1353 .ml_name = "tracepoint",
1354 .ml_meth = (PyCFunction) pyrf__tracepoint,
1355 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1356 .ml_doc = PyDoc_STR("Get tracepoint config.")
1358 { .ml_name = NULL, }
1361 #if PY_MAJOR_VERSION < 3
1362 PyMODINIT_FUNC initperf(void)
1364 PyMODINIT_FUNC PyInit_perf(void)
1370 #if PY_MAJOR_VERSION < 3
1371 PyObject *module = Py_InitModule("perf", perf__methods);
1373 static struct PyModuleDef moduledef = {
1374 PyModuleDef_HEAD_INIT,
1375 "perf", /* m_name */
1378 perf__methods, /* m_methods */
1379 NULL, /* m_reload */
1380 NULL, /* m_traverse */
1384 PyObject *module = PyModule_Create(&moduledef);
1387 if (module == NULL ||
1388 pyrf_event__setup_types() < 0 ||
1389 pyrf_evlist__setup_types() < 0 ||
1390 pyrf_evsel__setup_types() < 0 ||
1391 pyrf_thread_map__setup_types() < 0 ||
1392 pyrf_cpu_map__setup_types() < 0)
1393 #if PY_MAJOR_VERSION < 3
1399 /* The page_size is placed in util object. */
1400 page_size = sysconf(_SC_PAGE_SIZE);
1402 Py_INCREF(&pyrf_evlist__type);
1403 PyModule_AddObject(module, "evlist", (PyObject*)&pyrf_evlist__type);
1405 Py_INCREF(&pyrf_evsel__type);
1406 PyModule_AddObject(module, "evsel", (PyObject*)&pyrf_evsel__type);
1408 Py_INCREF(&pyrf_mmap_event__type);
1409 PyModule_AddObject(module, "mmap_event", (PyObject *)&pyrf_mmap_event__type);
1411 Py_INCREF(&pyrf_lost_event__type);
1412 PyModule_AddObject(module, "lost_event", (PyObject *)&pyrf_lost_event__type);
1414 Py_INCREF(&pyrf_comm_event__type);
1415 PyModule_AddObject(module, "comm_event", (PyObject *)&pyrf_comm_event__type);
1417 Py_INCREF(&pyrf_task_event__type);
1418 PyModule_AddObject(module, "task_event", (PyObject *)&pyrf_task_event__type);
1420 Py_INCREF(&pyrf_throttle_event__type);
1421 PyModule_AddObject(module, "throttle_event", (PyObject *)&pyrf_throttle_event__type);
1423 Py_INCREF(&pyrf_task_event__type);
1424 PyModule_AddObject(module, "task_event", (PyObject *)&pyrf_task_event__type);
1426 Py_INCREF(&pyrf_read_event__type);
1427 PyModule_AddObject(module, "read_event", (PyObject *)&pyrf_read_event__type);
1429 Py_INCREF(&pyrf_sample_event__type);
1430 PyModule_AddObject(module, "sample_event", (PyObject *)&pyrf_sample_event__type);
1432 Py_INCREF(&pyrf_context_switch_event__type);
1433 PyModule_AddObject(module, "switch_event", (PyObject *)&pyrf_context_switch_event__type);
1435 Py_INCREF(&pyrf_thread_map__type);
1436 PyModule_AddObject(module, "thread_map", (PyObject*)&pyrf_thread_map__type);
1438 Py_INCREF(&pyrf_cpu_map__type);
1439 PyModule_AddObject(module, "cpu_map", (PyObject*)&pyrf_cpu_map__type);
1441 dict = PyModule_GetDict(module);
1445 for (i = 0; perf__constants[i].name != NULL; i++) {
1446 obj = _PyLong_FromLong(perf__constants[i].value);
1449 PyDict_SetItemString(dict, perf__constants[i].name, obj);
1454 if (PyErr_Occurred())
1455 PyErr_SetString(PyExc_ImportError, "perf: Init failed!");
1456 #if PY_MAJOR_VERSION >= 3
1462 * Dummy, to avoid dragging all the test_attr infrastructure in the python
1465 void test_attr__open(struct perf_event_attr *attr, pid_t pid, struct perf_cpu cpu,
1466 int fd, int group_fd, unsigned long flags)