Linux kernel mirror (for testing)
git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel
os
linux
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#ifdef HAVE_LIBTRACEEVENT
9#include <event-parse.h>
10#endif
11#include <perf/mmap.h>
12#include "callchain.h"
13#include "evlist.h"
14#include "evsel.h"
15#include "event.h"
16#include "print_binary.h"
17#include "record.h"
18#include "strbuf.h"
19#include "thread_map.h"
20#include "trace-event.h"
21#include "mmap.h"
22#include "util/sample.h"
23#include <internal/lib.h>
24
25PyMODINIT_FUNC PyInit_perf(void);
26
27#define member_def(type, member, ptype, help) \
28 { #member, ptype, \
29 offsetof(struct pyrf_event, event) + offsetof(struct type, member), \
30 0, help }
31
32#define sample_member_def(name, member, ptype, help) \
33 { #name, ptype, \
34 offsetof(struct pyrf_event, sample) + offsetof(struct perf_sample, member), \
35 0, help }
36
37struct pyrf_event {
38 PyObject_HEAD
39 struct evsel *evsel;
40 struct perf_sample sample;
41 union perf_event event;
42};
43
44#define sample_members \
45 sample_member_def(sample_ip, ip, T_ULONGLONG, "event ip"), \
46 sample_member_def(sample_pid, pid, T_INT, "event pid"), \
47 sample_member_def(sample_tid, tid, T_INT, "event tid"), \
48 sample_member_def(sample_time, time, T_ULONGLONG, "event timestamp"), \
49 sample_member_def(sample_addr, addr, T_ULONGLONG, "event addr"), \
50 sample_member_def(sample_id, id, T_ULONGLONG, "event id"), \
51 sample_member_def(sample_stream_id, stream_id, T_ULONGLONG, "event stream id"), \
52 sample_member_def(sample_period, period, T_ULONGLONG, "event period"), \
53 sample_member_def(sample_cpu, cpu, T_UINT, "event cpu"),
54
55static const char pyrf_mmap_event__doc[] = PyDoc_STR("perf mmap event object.");
56
57static PyMemberDef pyrf_mmap_event__members[] = {
58 sample_members
59 member_def(perf_event_header, type, T_UINT, "event type"),
60 member_def(perf_event_header, misc, T_UINT, "event misc"),
61 member_def(perf_record_mmap, pid, T_UINT, "event pid"),
62 member_def(perf_record_mmap, tid, T_UINT, "event tid"),
63 member_def(perf_record_mmap, start, T_ULONGLONG, "start of the map"),
64 member_def(perf_record_mmap, len, T_ULONGLONG, "map length"),
65 member_def(perf_record_mmap, pgoff, T_ULONGLONG, "page offset"),
66 member_def(perf_record_mmap, filename, T_STRING_INPLACE, "backing store"),
67 { .name = NULL, },
68};
69
70static PyObject *pyrf_mmap_event__repr(const struct pyrf_event *pevent)
71{
72 PyObject *ret;
73 char *s;
74
75 if (asprintf(&s, "{ type: mmap, pid: %u, tid: %u, start: %#" PRI_lx64 ", "
76 "length: %#" PRI_lx64 ", offset: %#" PRI_lx64 ", "
77 "filename: %s }",
78 pevent->event.mmap.pid, pevent->event.mmap.tid,
79 pevent->event.mmap.start, pevent->event.mmap.len,
80 pevent->event.mmap.pgoff, pevent->event.mmap.filename) < 0) {
81 ret = PyErr_NoMemory();
82 } else {
83 ret = PyUnicode_FromString(s);
84 free(s);
85 }
86 return ret;
87}
88
89static PyTypeObject pyrf_mmap_event__type = {
90 PyVarObject_HEAD_INIT(NULL, 0)
91 .tp_name = "perf.mmap_event",
92 .tp_basicsize = sizeof(struct pyrf_event),
93 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
94 .tp_doc = pyrf_mmap_event__doc,
95 .tp_members = pyrf_mmap_event__members,
96 .tp_repr = (reprfunc)pyrf_mmap_event__repr,
97};
98
99static const char pyrf_task_event__doc[] = PyDoc_STR("perf task (fork/exit) event object.");
100
101static PyMemberDef pyrf_task_event__members[] = {
102 sample_members
103 member_def(perf_event_header, type, T_UINT, "event type"),
104 member_def(perf_record_fork, pid, T_UINT, "event pid"),
105 member_def(perf_record_fork, ppid, T_UINT, "event ppid"),
106 member_def(perf_record_fork, tid, T_UINT, "event tid"),
107 member_def(perf_record_fork, ptid, T_UINT, "event ptid"),
108 member_def(perf_record_fork, time, T_ULONGLONG, "timestamp"),
109 { .name = NULL, },
110};
111
112static PyObject *pyrf_task_event__repr(const struct pyrf_event *pevent)
113{
114 return PyUnicode_FromFormat("{ type: %s, pid: %u, ppid: %u, tid: %u, "
115 "ptid: %u, time: %" PRI_lu64 "}",
116 pevent->event.header.type == PERF_RECORD_FORK ? "fork" : "exit",
117 pevent->event.fork.pid,
118 pevent->event.fork.ppid,
119 pevent->event.fork.tid,
120 pevent->event.fork.ptid,
121 pevent->event.fork.time);
122}
123
124static PyTypeObject pyrf_task_event__type = {
125 PyVarObject_HEAD_INIT(NULL, 0)
126 .tp_name = "perf.task_event",
127 .tp_basicsize = sizeof(struct pyrf_event),
128 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
129 .tp_doc = pyrf_task_event__doc,
130 .tp_members = pyrf_task_event__members,
131 .tp_repr = (reprfunc)pyrf_task_event__repr,
132};
133
134static const char pyrf_comm_event__doc[] = PyDoc_STR("perf comm event object.");
135
136static PyMemberDef pyrf_comm_event__members[] = {
137 sample_members
138 member_def(perf_event_header, type, T_UINT, "event type"),
139 member_def(perf_record_comm, pid, T_UINT, "event pid"),
140 member_def(perf_record_comm, tid, T_UINT, "event tid"),
141 member_def(perf_record_comm, comm, T_STRING_INPLACE, "process name"),
142 { .name = NULL, },
143};
144
145static PyObject *pyrf_comm_event__repr(const struct pyrf_event *pevent)
146{
147 return PyUnicode_FromFormat("{ type: comm, pid: %u, tid: %u, comm: %s }",
148 pevent->event.comm.pid,
149 pevent->event.comm.tid,
150 pevent->event.comm.comm);
151}
152
153static PyTypeObject pyrf_comm_event__type = {
154 PyVarObject_HEAD_INIT(NULL, 0)
155 .tp_name = "perf.comm_event",
156 .tp_basicsize = sizeof(struct pyrf_event),
157 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
158 .tp_doc = pyrf_comm_event__doc,
159 .tp_members = pyrf_comm_event__members,
160 .tp_repr = (reprfunc)pyrf_comm_event__repr,
161};
162
163static const char pyrf_throttle_event__doc[] = PyDoc_STR("perf throttle event object.");
164
165static PyMemberDef pyrf_throttle_event__members[] = {
166 sample_members
167 member_def(perf_event_header, type, T_UINT, "event type"),
168 member_def(perf_record_throttle, time, T_ULONGLONG, "timestamp"),
169 member_def(perf_record_throttle, id, T_ULONGLONG, "event id"),
170 member_def(perf_record_throttle, stream_id, T_ULONGLONG, "event stream id"),
171 { .name = NULL, },
172};
173
174static PyObject *pyrf_throttle_event__repr(const struct pyrf_event *pevent)
175{
176 const struct perf_record_throttle *te = (const struct perf_record_throttle *)
177 (&pevent->event.header + 1);
178
179 return PyUnicode_FromFormat("{ type: %sthrottle, time: %" PRI_lu64 ", id: %" PRI_lu64
180 ", stream_id: %" PRI_lu64 " }",
181 pevent->event.header.type == PERF_RECORD_THROTTLE ? "" : "un",
182 te->time, te->id, te->stream_id);
183}
184
185static PyTypeObject pyrf_throttle_event__type = {
186 PyVarObject_HEAD_INIT(NULL, 0)
187 .tp_name = "perf.throttle_event",
188 .tp_basicsize = sizeof(struct pyrf_event),
189 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
190 .tp_doc = pyrf_throttle_event__doc,
191 .tp_members = pyrf_throttle_event__members,
192 .tp_repr = (reprfunc)pyrf_throttle_event__repr,
193};
194
195static const char pyrf_lost_event__doc[] = PyDoc_STR("perf lost event object.");
196
197static PyMemberDef pyrf_lost_event__members[] = {
198 sample_members
199 member_def(perf_record_lost, id, T_ULONGLONG, "event id"),
200 member_def(perf_record_lost, lost, T_ULONGLONG, "number of lost events"),
201 { .name = NULL, },
202};
203
204static PyObject *pyrf_lost_event__repr(const struct pyrf_event *pevent)
205{
206 PyObject *ret;
207 char *s;
208
209 if (asprintf(&s, "{ type: lost, id: %#" PRI_lx64 ", "
210 "lost: %#" PRI_lx64 " }",
211 pevent->event.lost.id, pevent->event.lost.lost) < 0) {
212 ret = PyErr_NoMemory();
213 } else {
214 ret = PyUnicode_FromString(s);
215 free(s);
216 }
217 return ret;
218}
219
220static PyTypeObject pyrf_lost_event__type = {
221 PyVarObject_HEAD_INIT(NULL, 0)
222 .tp_name = "perf.lost_event",
223 .tp_basicsize = sizeof(struct pyrf_event),
224 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
225 .tp_doc = pyrf_lost_event__doc,
226 .tp_members = pyrf_lost_event__members,
227 .tp_repr = (reprfunc)pyrf_lost_event__repr,
228};
229
230static const char pyrf_read_event__doc[] = PyDoc_STR("perf read event object.");
231
232static PyMemberDef pyrf_read_event__members[] = {
233 sample_members
234 member_def(perf_record_read, pid, T_UINT, "event pid"),
235 member_def(perf_record_read, tid, T_UINT, "event tid"),
236 { .name = NULL, },
237};
238
239static PyObject *pyrf_read_event__repr(const struct pyrf_event *pevent)
240{
241 return PyUnicode_FromFormat("{ type: read, pid: %u, tid: %u }",
242 pevent->event.read.pid,
243 pevent->event.read.tid);
244 /*
245 * FIXME: return the array of read values,
246 * making this method useful ;-)
247 */
248}
249
250static PyTypeObject pyrf_read_event__type = {
251 PyVarObject_HEAD_INIT(NULL, 0)
252 .tp_name = "perf.read_event",
253 .tp_basicsize = sizeof(struct pyrf_event),
254 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
255 .tp_doc = pyrf_read_event__doc,
256 .tp_members = pyrf_read_event__members,
257 .tp_repr = (reprfunc)pyrf_read_event__repr,
258};
259
260static const char pyrf_sample_event__doc[] = PyDoc_STR("perf sample event object.");
261
262static PyMemberDef pyrf_sample_event__members[] = {
263 sample_members
264 member_def(perf_event_header, type, T_UINT, "event type"),
265 { .name = NULL, },
266};
267
268static void pyrf_sample_event__delete(struct pyrf_event *pevent)
269{
270 perf_sample__exit(&pevent->sample);
271 Py_TYPE(pevent)->tp_free((PyObject*)pevent);
272}
273
274static PyObject *pyrf_sample_event__repr(const struct pyrf_event *pevent)
275{
276 PyObject *ret;
277 char *s;
278
279 if (asprintf(&s, "{ type: sample }") < 0) {
280 ret = PyErr_NoMemory();
281 } else {
282 ret = PyUnicode_FromString(s);
283 free(s);
284 }
285 return ret;
286}
287
288#ifdef HAVE_LIBTRACEEVENT
289static bool is_tracepoint(const struct pyrf_event *pevent)
290{
291 return pevent->evsel->core.attr.type == PERF_TYPE_TRACEPOINT;
292}
293
294static PyObject*
295tracepoint_field(const struct pyrf_event *pe, struct tep_format_field *field)
296{
297 struct tep_handle *pevent = field->event->tep;
298 void *data = pe->sample.raw_data;
299 PyObject *ret = NULL;
300 unsigned long long val;
301 unsigned int offset, len;
302
303 if (field->flags & TEP_FIELD_IS_ARRAY) {
304 offset = field->offset;
305 len = field->size;
306 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
307 val = tep_read_number(pevent, data + offset, len);
308 offset = val;
309 len = offset >> 16;
310 offset &= 0xffff;
311 if (tep_field_is_relative(field->flags))
312 offset += field->offset + field->size;
313 }
314 if (field->flags & TEP_FIELD_IS_STRING &&
315 is_printable_array(data + offset, len)) {
316 ret = PyUnicode_FromString((char *)data + offset);
317 } else {
318 ret = PyByteArray_FromStringAndSize((const char *) data + offset, len);
319 field->flags &= ~TEP_FIELD_IS_STRING;
320 }
321 } else {
322 val = tep_read_number(pevent, data + field->offset,
323 field->size);
324 if (field->flags & TEP_FIELD_IS_POINTER)
325 ret = PyLong_FromUnsignedLong((unsigned long) val);
326 else if (field->flags & TEP_FIELD_IS_SIGNED)
327 ret = PyLong_FromLong((long) val);
328 else
329 ret = PyLong_FromUnsignedLong((unsigned long) val);
330 }
331
332 return ret;
333}
334
335static PyObject*
336get_tracepoint_field(struct pyrf_event *pevent, PyObject *attr_name)
337{
338 const char *str = _PyUnicode_AsString(PyObject_Str(attr_name));
339 struct evsel *evsel = pevent->evsel;
340 struct tep_event *tp_format = evsel__tp_format(evsel);
341 struct tep_format_field *field;
342
343 if (IS_ERR_OR_NULL(tp_format))
344 return NULL;
345
346 field = tep_find_any_field(tp_format, str);
347 return field ? tracepoint_field(pevent, field) : NULL;
348}
349#endif /* HAVE_LIBTRACEEVENT */
350
351static PyObject*
352pyrf_sample_event__getattro(struct pyrf_event *pevent, PyObject *attr_name)
353{
354 PyObject *obj = NULL;
355
356#ifdef HAVE_LIBTRACEEVENT
357 if (is_tracepoint(pevent))
358 obj = get_tracepoint_field(pevent, attr_name);
359#endif
360
361 return obj ?: PyObject_GenericGetAttr((PyObject *) pevent, attr_name);
362}
363
364static PyTypeObject pyrf_sample_event__type = {
365 PyVarObject_HEAD_INIT(NULL, 0)
366 .tp_name = "perf.sample_event",
367 .tp_basicsize = sizeof(struct pyrf_event),
368 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
369 .tp_doc = pyrf_sample_event__doc,
370 .tp_members = pyrf_sample_event__members,
371 .tp_repr = (reprfunc)pyrf_sample_event__repr,
372 .tp_getattro = (getattrofunc) pyrf_sample_event__getattro,
373};
374
375static const char pyrf_context_switch_event__doc[] = PyDoc_STR("perf context_switch event object.");
376
377static PyMemberDef pyrf_context_switch_event__members[] = {
378 sample_members
379 member_def(perf_event_header, type, T_UINT, "event type"),
380 member_def(perf_record_switch, next_prev_pid, T_UINT, "next/prev pid"),
381 member_def(perf_record_switch, next_prev_tid, T_UINT, "next/prev tid"),
382 { .name = NULL, },
383};
384
385static PyObject *pyrf_context_switch_event__repr(const struct pyrf_event *pevent)
386{
387 PyObject *ret;
388 char *s;
389
390 if (asprintf(&s, "{ type: context_switch, next_prev_pid: %u, next_prev_tid: %u, switch_out: %u }",
391 pevent->event.context_switch.next_prev_pid,
392 pevent->event.context_switch.next_prev_tid,
393 !!(pevent->event.header.misc & PERF_RECORD_MISC_SWITCH_OUT)) < 0) {
394 ret = PyErr_NoMemory();
395 } else {
396 ret = PyUnicode_FromString(s);
397 free(s);
398 }
399 return ret;
400}
401
402static PyTypeObject pyrf_context_switch_event__type = {
403 PyVarObject_HEAD_INIT(NULL, 0)
404 .tp_name = "perf.context_switch_event",
405 .tp_basicsize = sizeof(struct pyrf_event),
406 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
407 .tp_doc = pyrf_context_switch_event__doc,
408 .tp_members = pyrf_context_switch_event__members,
409 .tp_repr = (reprfunc)pyrf_context_switch_event__repr,
410};
411
412static int pyrf_event__setup_types(void)
413{
414 int err;
415 pyrf_mmap_event__type.tp_new =
416 pyrf_task_event__type.tp_new =
417 pyrf_comm_event__type.tp_new =
418 pyrf_lost_event__type.tp_new =
419 pyrf_read_event__type.tp_new =
420 pyrf_sample_event__type.tp_new =
421 pyrf_context_switch_event__type.tp_new =
422 pyrf_throttle_event__type.tp_new = PyType_GenericNew;
423
424 pyrf_sample_event__type.tp_dealloc = (destructor)pyrf_sample_event__delete,
425
426 err = PyType_Ready(&pyrf_mmap_event__type);
427 if (err < 0)
428 goto out;
429 err = PyType_Ready(&pyrf_lost_event__type);
430 if (err < 0)
431 goto out;
432 err = PyType_Ready(&pyrf_task_event__type);
433 if (err < 0)
434 goto out;
435 err = PyType_Ready(&pyrf_comm_event__type);
436 if (err < 0)
437 goto out;
438 err = PyType_Ready(&pyrf_throttle_event__type);
439 if (err < 0)
440 goto out;
441 err = PyType_Ready(&pyrf_read_event__type);
442 if (err < 0)
443 goto out;
444 err = PyType_Ready(&pyrf_sample_event__type);
445 if (err < 0)
446 goto out;
447 err = PyType_Ready(&pyrf_context_switch_event__type);
448 if (err < 0)
449 goto out;
450out:
451 return err;
452}
453
454static PyTypeObject *pyrf_event__type[] = {
455 [PERF_RECORD_MMAP] = &pyrf_mmap_event__type,
456 [PERF_RECORD_LOST] = &pyrf_lost_event__type,
457 [PERF_RECORD_COMM] = &pyrf_comm_event__type,
458 [PERF_RECORD_EXIT] = &pyrf_task_event__type,
459 [PERF_RECORD_THROTTLE] = &pyrf_throttle_event__type,
460 [PERF_RECORD_UNTHROTTLE] = &pyrf_throttle_event__type,
461 [PERF_RECORD_FORK] = &pyrf_task_event__type,
462 [PERF_RECORD_READ] = &pyrf_read_event__type,
463 [PERF_RECORD_SAMPLE] = &pyrf_sample_event__type,
464 [PERF_RECORD_SWITCH] = &pyrf_context_switch_event__type,
465 [PERF_RECORD_SWITCH_CPU_WIDE] = &pyrf_context_switch_event__type,
466};
467
468static PyObject *pyrf_event__new(const union perf_event *event)
469{
470 struct pyrf_event *pevent;
471 PyTypeObject *ptype;
472
473 if ((event->header.type < PERF_RECORD_MMAP ||
474 event->header.type > PERF_RECORD_SAMPLE) &&
475 !(event->header.type == PERF_RECORD_SWITCH ||
476 event->header.type == PERF_RECORD_SWITCH_CPU_WIDE))
477 return NULL;
478
479 // FIXME this better be dynamic or we need to parse everything
480 // before calling perf_mmap__consume(), including tracepoint fields.
481 if (sizeof(pevent->event) < event->header.size)
482 return NULL;
483
484 ptype = pyrf_event__type[event->header.type];
485 pevent = PyObject_New(struct pyrf_event, ptype);
486 if (pevent != NULL)
487 memcpy(&pevent->event, event, event->header.size);
488 return (PyObject *)pevent;
489}
490
491struct pyrf_cpu_map {
492 PyObject_HEAD
493
494 struct perf_cpu_map *cpus;
495};
496
497static int pyrf_cpu_map__init(struct pyrf_cpu_map *pcpus,
498 PyObject *args, PyObject *kwargs)
499{
500 static char *kwlist[] = { "cpustr", NULL };
501 char *cpustr = NULL;
502
503 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s",
504 kwlist, &cpustr))
505 return -1;
506
507 pcpus->cpus = perf_cpu_map__new(cpustr);
508 if (pcpus->cpus == NULL)
509 return -1;
510 return 0;
511}
512
513static void pyrf_cpu_map__delete(struct pyrf_cpu_map *pcpus)
514{
515 perf_cpu_map__put(pcpus->cpus);
516 Py_TYPE(pcpus)->tp_free((PyObject*)pcpus);
517}
518
519static Py_ssize_t pyrf_cpu_map__length(PyObject *obj)
520{
521 struct pyrf_cpu_map *pcpus = (void *)obj;
522
523 return perf_cpu_map__nr(pcpus->cpus);
524}
525
526static PyObject *pyrf_cpu_map__item(PyObject *obj, Py_ssize_t i)
527{
528 struct pyrf_cpu_map *pcpus = (void *)obj;
529
530 if (i >= perf_cpu_map__nr(pcpus->cpus))
531 return NULL;
532
533 return Py_BuildValue("i", perf_cpu_map__cpu(pcpus->cpus, i).cpu);
534}
535
536static PySequenceMethods pyrf_cpu_map__sequence_methods = {
537 .sq_length = pyrf_cpu_map__length,
538 .sq_item = pyrf_cpu_map__item,
539};
540
541static const char pyrf_cpu_map__doc[] = PyDoc_STR("cpu map object.");
542
543static PyTypeObject pyrf_cpu_map__type = {
544 PyVarObject_HEAD_INIT(NULL, 0)
545 .tp_name = "perf.cpu_map",
546 .tp_basicsize = sizeof(struct pyrf_cpu_map),
547 .tp_dealloc = (destructor)pyrf_cpu_map__delete,
548 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
549 .tp_doc = pyrf_cpu_map__doc,
550 .tp_as_sequence = &pyrf_cpu_map__sequence_methods,
551 .tp_init = (initproc)pyrf_cpu_map__init,
552};
553
554static int pyrf_cpu_map__setup_types(void)
555{
556 pyrf_cpu_map__type.tp_new = PyType_GenericNew;
557 return PyType_Ready(&pyrf_cpu_map__type);
558}
559
560struct pyrf_thread_map {
561 PyObject_HEAD
562
563 struct perf_thread_map *threads;
564};
565
566static int pyrf_thread_map__init(struct pyrf_thread_map *pthreads,
567 PyObject *args, PyObject *kwargs)
568{
569 static char *kwlist[] = { "pid", "tid", "uid", NULL };
570 int pid = -1, tid = -1, uid = UINT_MAX;
571
572 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|iii",
573 kwlist, &pid, &tid, &uid))
574 return -1;
575
576 pthreads->threads = thread_map__new(pid, tid, uid);
577 if (pthreads->threads == NULL)
578 return -1;
579 return 0;
580}
581
582static void pyrf_thread_map__delete(struct pyrf_thread_map *pthreads)
583{
584 perf_thread_map__put(pthreads->threads);
585 Py_TYPE(pthreads)->tp_free((PyObject*)pthreads);
586}
587
588static Py_ssize_t pyrf_thread_map__length(PyObject *obj)
589{
590 struct pyrf_thread_map *pthreads = (void *)obj;
591
592 return perf_thread_map__nr(pthreads->threads);
593}
594
595static PyObject *pyrf_thread_map__item(PyObject *obj, Py_ssize_t i)
596{
597 struct pyrf_thread_map *pthreads = (void *)obj;
598
599 if (i >= perf_thread_map__nr(pthreads->threads))
600 return NULL;
601
602 return Py_BuildValue("i", perf_thread_map__pid(pthreads->threads, i));
603}
604
605static PySequenceMethods pyrf_thread_map__sequence_methods = {
606 .sq_length = pyrf_thread_map__length,
607 .sq_item = pyrf_thread_map__item,
608};
609
610static const char pyrf_thread_map__doc[] = PyDoc_STR("thread map object.");
611
612static PyTypeObject pyrf_thread_map__type = {
613 PyVarObject_HEAD_INIT(NULL, 0)
614 .tp_name = "perf.thread_map",
615 .tp_basicsize = sizeof(struct pyrf_thread_map),
616 .tp_dealloc = (destructor)pyrf_thread_map__delete,
617 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
618 .tp_doc = pyrf_thread_map__doc,
619 .tp_as_sequence = &pyrf_thread_map__sequence_methods,
620 .tp_init = (initproc)pyrf_thread_map__init,
621};
622
623static int pyrf_thread_map__setup_types(void)
624{
625 pyrf_thread_map__type.tp_new = PyType_GenericNew;
626 return PyType_Ready(&pyrf_thread_map__type);
627}
628
629struct pyrf_counts_values {
630 PyObject_HEAD
631
632 struct perf_counts_values values;
633};
634
635static const char pyrf_counts_values__doc[] = PyDoc_STR("perf counts values object.");
636
637static void pyrf_counts_values__delete(struct pyrf_counts_values *pcounts_values)
638{
639 Py_TYPE(pcounts_values)->tp_free((PyObject *)pcounts_values);
640}
641
642#define counts_values_member_def(member, ptype, help) \
643 { #member, ptype, \
644 offsetof(struct pyrf_counts_values, values.member), \
645 0, help }
646
647static PyMemberDef pyrf_counts_values_members[] = {
648 counts_values_member_def(val, T_ULONG, "Value of event"),
649 counts_values_member_def(ena, T_ULONG, "Time for which enabled"),
650 counts_values_member_def(run, T_ULONG, "Time for which running"),
651 counts_values_member_def(id, T_ULONG, "Unique ID for an event"),
652 counts_values_member_def(lost, T_ULONG, "Num of lost samples"),
653 { .name = NULL, },
654};
655
656static PyObject *pyrf_counts_values_get_values(struct pyrf_counts_values *self, void *closure)
657{
658 PyObject *vals = PyList_New(5);
659
660 if (!vals)
661 return NULL;
662 for (int i = 0; i < 5; i++)
663 PyList_SetItem(vals, i, PyLong_FromLong(self->values.values[i]));
664
665 return vals;
666}
667
668static int pyrf_counts_values_set_values(struct pyrf_counts_values *self, PyObject *list,
669 void *closure)
670{
671 Py_ssize_t size;
672 PyObject *item = NULL;
673
674 if (!PyList_Check(list)) {
675 PyErr_SetString(PyExc_TypeError, "Value assigned must be a list");
676 return -1;
677 }
678
679 size = PyList_Size(list);
680 for (Py_ssize_t i = 0; i < size; i++) {
681 item = PyList_GetItem(list, i);
682 if (!PyLong_Check(item)) {
683 PyErr_SetString(PyExc_TypeError, "List members should be numbers");
684 return -1;
685 }
686 self->values.values[i] = PyLong_AsLong(item);
687 }
688
689 return 0;
690}
691
692static PyGetSetDef pyrf_counts_values_getset[] = {
693 {"values", (getter)pyrf_counts_values_get_values, (setter)pyrf_counts_values_set_values,
694 "Name field", NULL},
695 { .name = NULL, },
696};
697
698static PyTypeObject pyrf_counts_values__type = {
699 PyVarObject_HEAD_INIT(NULL, 0)
700 .tp_name = "perf.counts_values",
701 .tp_basicsize = sizeof(struct pyrf_counts_values),
702 .tp_dealloc = (destructor)pyrf_counts_values__delete,
703 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
704 .tp_doc = pyrf_counts_values__doc,
705 .tp_members = pyrf_counts_values_members,
706 .tp_getset = pyrf_counts_values_getset,
707};
708
709static int pyrf_counts_values__setup_types(void)
710{
711 pyrf_counts_values__type.tp_new = PyType_GenericNew;
712 return PyType_Ready(&pyrf_counts_values__type);
713}
714
715struct pyrf_evsel {
716 PyObject_HEAD
717
718 struct evsel evsel;
719};
720
721static int pyrf_evsel__init(struct pyrf_evsel *pevsel,
722 PyObject *args, PyObject *kwargs)
723{
724 struct perf_event_attr attr = {
725 .type = PERF_TYPE_HARDWARE,
726 .config = PERF_COUNT_HW_CPU_CYCLES,
727 .sample_type = PERF_SAMPLE_PERIOD | PERF_SAMPLE_TID,
728 };
729 static char *kwlist[] = {
730 "type",
731 "config",
732 "sample_freq",
733 "sample_period",
734 "sample_type",
735 "read_format",
736 "disabled",
737 "inherit",
738 "pinned",
739 "exclusive",
740 "exclude_user",
741 "exclude_kernel",
742 "exclude_hv",
743 "exclude_idle",
744 "mmap",
745 "context_switch",
746 "comm",
747 "freq",
748 "inherit_stat",
749 "enable_on_exec",
750 "task",
751 "watermark",
752 "precise_ip",
753 "mmap_data",
754 "sample_id_all",
755 "wakeup_events",
756 "bp_type",
757 "bp_addr",
758 "bp_len",
759 NULL
760 };
761 u64 sample_period = 0;
762 u32 disabled = 0,
763 inherit = 0,
764 pinned = 0,
765 exclusive = 0,
766 exclude_user = 0,
767 exclude_kernel = 0,
768 exclude_hv = 0,
769 exclude_idle = 0,
770 mmap = 0,
771 context_switch = 0,
772 comm = 0,
773 freq = 1,
774 inherit_stat = 0,
775 enable_on_exec = 0,
776 task = 0,
777 watermark = 0,
778 precise_ip = 0,
779 mmap_data = 0,
780 sample_id_all = 1;
781 int idx = 0;
782
783 if (!PyArg_ParseTupleAndKeywords(args, kwargs,
784 "|iKiKKiiiiiiiiiiiiiiiiiiiiiiKK", kwlist,
785 &attr.type, &attr.config, &attr.sample_freq,
786 &sample_period, &attr.sample_type,
787 &attr.read_format, &disabled, &inherit,
788 &pinned, &exclusive, &exclude_user,
789 &exclude_kernel, &exclude_hv, &exclude_idle,
790 &mmap, &context_switch, &comm, &freq, &inherit_stat,
791 &enable_on_exec, &task, &watermark,
792 &precise_ip, &mmap_data, &sample_id_all,
793 &attr.wakeup_events, &attr.bp_type,
794 &attr.bp_addr, &attr.bp_len, &idx))
795 return -1;
796
797 /* union... */
798 if (sample_period != 0) {
799 if (attr.sample_freq != 0)
800 return -1; /* FIXME: throw right exception */
801 attr.sample_period = sample_period;
802 }
803
804 /* Bitfields */
805 attr.disabled = disabled;
806 attr.inherit = inherit;
807 attr.pinned = pinned;
808 attr.exclusive = exclusive;
809 attr.exclude_user = exclude_user;
810 attr.exclude_kernel = exclude_kernel;
811 attr.exclude_hv = exclude_hv;
812 attr.exclude_idle = exclude_idle;
813 attr.mmap = mmap;
814 attr.context_switch = context_switch;
815 attr.comm = comm;
816 attr.freq = freq;
817 attr.inherit_stat = inherit_stat;
818 attr.enable_on_exec = enable_on_exec;
819 attr.task = task;
820 attr.watermark = watermark;
821 attr.precise_ip = precise_ip;
822 attr.mmap_data = mmap_data;
823 attr.sample_id_all = sample_id_all;
824 attr.size = sizeof(attr);
825
826 evsel__init(&pevsel->evsel, &attr, idx);
827 return 0;
828}
829
830static void pyrf_evsel__delete(struct pyrf_evsel *pevsel)
831{
832 evsel__exit(&pevsel->evsel);
833 Py_TYPE(pevsel)->tp_free((PyObject*)pevsel);
834}
835
836static PyObject *pyrf_evsel__open(struct pyrf_evsel *pevsel,
837 PyObject *args, PyObject *kwargs)
838{
839 struct evsel *evsel = &pevsel->evsel;
840 struct perf_cpu_map *cpus = NULL;
841 struct perf_thread_map *threads = NULL;
842 PyObject *pcpus = NULL, *pthreads = NULL;
843 int group = 0, inherit = 0;
844 static char *kwlist[] = { "cpus", "threads", "group", "inherit", NULL };
845
846 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOii", kwlist,
847 &pcpus, &pthreads, &group, &inherit))
848 return NULL;
849
850 if (pthreads != NULL)
851 threads = ((struct pyrf_thread_map *)pthreads)->threads;
852
853 if (pcpus != NULL)
854 cpus = ((struct pyrf_cpu_map *)pcpus)->cpus;
855
856 evsel->core.attr.inherit = inherit;
857 /*
858 * This will group just the fds for this single evsel, to group
859 * multiple events, use evlist.open().
860 */
861 if (evsel__open(evsel, cpus, threads) < 0) {
862 PyErr_SetFromErrno(PyExc_OSError);
863 return NULL;
864 }
865
866 Py_INCREF(Py_None);
867 return Py_None;
868}
869
870static PyObject *pyrf_evsel__cpus(struct pyrf_evsel *pevsel)
871{
872 struct pyrf_cpu_map *pcpu_map = PyObject_New(struct pyrf_cpu_map, &pyrf_cpu_map__type);
873
874 if (pcpu_map)
875 pcpu_map->cpus = perf_cpu_map__get(pevsel->evsel.core.cpus);
876
877 return (PyObject *)pcpu_map;
878}
879
880static PyObject *pyrf_evsel__threads(struct pyrf_evsel *pevsel)
881{
882 struct pyrf_thread_map *pthread_map =
883 PyObject_New(struct pyrf_thread_map, &pyrf_thread_map__type);
884
885 if (pthread_map)
886 pthread_map->threads = perf_thread_map__get(pevsel->evsel.core.threads);
887
888 return (PyObject *)pthread_map;
889}
890
891static PyObject *pyrf_evsel__read(struct pyrf_evsel *pevsel,
892 PyObject *args, PyObject *kwargs)
893{
894 struct evsel *evsel = &pevsel->evsel;
895 int cpu = 0, cpu_idx, thread = 0, thread_idx;
896 struct perf_counts_values counts;
897 struct pyrf_counts_values *count_values = PyObject_New(struct pyrf_counts_values,
898 &pyrf_counts_values__type);
899
900 if (!count_values)
901 return NULL;
902
903 if (!PyArg_ParseTuple(args, "ii", &cpu, &thread))
904 return NULL;
905
906 cpu_idx = perf_cpu_map__idx(evsel->core.cpus, (struct perf_cpu){.cpu = cpu});
907 if (cpu_idx < 0) {
908 PyErr_Format(PyExc_TypeError, "CPU %d is not part of evsel's CPUs", cpu);
909 return NULL;
910 }
911 thread_idx = perf_thread_map__idx(evsel->core.threads, thread);
912 if (cpu_idx < 0) {
913 PyErr_Format(PyExc_TypeError, "Thread %d is not part of evsel's threads",
914 thread);
915 return NULL;
916 }
917 perf_evsel__read(&(evsel->core), cpu_idx, thread_idx, &counts);
918 count_values->values = counts;
919 return (PyObject *)count_values;
920}
921
922static PyObject *pyrf_evsel__str(PyObject *self)
923{
924 struct pyrf_evsel *pevsel = (void *)self;
925 struct evsel *evsel = &pevsel->evsel;
926
927 if (!evsel->pmu)
928 return PyUnicode_FromFormat("evsel(%s)", evsel__name(evsel));
929
930 return PyUnicode_FromFormat("evsel(%s/%s/)", evsel->pmu->name, evsel__name(evsel));
931}
932
933static PyMethodDef pyrf_evsel__methods[] = {
934 {
935 .ml_name = "open",
936 .ml_meth = (PyCFunction)pyrf_evsel__open,
937 .ml_flags = METH_VARARGS | METH_KEYWORDS,
938 .ml_doc = PyDoc_STR("open the event selector file descriptor table.")
939 },
940 {
941 .ml_name = "cpus",
942 .ml_meth = (PyCFunction)pyrf_evsel__cpus,
943 .ml_flags = METH_NOARGS,
944 .ml_doc = PyDoc_STR("CPUs the event is to be used with.")
945 },
946 {
947 .ml_name = "threads",
948 .ml_meth = (PyCFunction)pyrf_evsel__threads,
949 .ml_flags = METH_NOARGS,
950 .ml_doc = PyDoc_STR("threads the event is to be used with.")
951 },
952 {
953 .ml_name = "read",
954 .ml_meth = (PyCFunction)pyrf_evsel__read,
955 .ml_flags = METH_VARARGS | METH_KEYWORDS,
956 .ml_doc = PyDoc_STR("read counters")
957 },
958 { .ml_name = NULL, }
959};
960
961#define evsel_member_def(member, ptype, help) \
962 { #member, ptype, \
963 offsetof(struct pyrf_evsel, evsel.member), \
964 0, help }
965
966#define evsel_attr_member_def(member, ptype, help) \
967 { #member, ptype, \
968 offsetof(struct pyrf_evsel, evsel.core.attr.member), \
969 0, help }
970
971static PyMemberDef pyrf_evsel__members[] = {
972 evsel_member_def(tracking, T_BOOL, "tracking event."),
973 evsel_attr_member_def(type, T_UINT, "attribute type."),
974 evsel_attr_member_def(size, T_UINT, "attribute size."),
975 evsel_attr_member_def(config, T_ULONGLONG, "attribute config."),
976 evsel_attr_member_def(sample_period, T_ULONGLONG, "attribute sample_period."),
977 evsel_attr_member_def(sample_type, T_ULONGLONG, "attribute sample_type."),
978 evsel_attr_member_def(read_format, T_ULONGLONG, "attribute read_format."),
979 evsel_attr_member_def(wakeup_events, T_UINT, "attribute wakeup_events."),
980 { .name = NULL, },
981};
982
983static const char pyrf_evsel__doc[] = PyDoc_STR("perf event selector list object.");
984
985static PyTypeObject pyrf_evsel__type = {
986 PyVarObject_HEAD_INIT(NULL, 0)
987 .tp_name = "perf.evsel",
988 .tp_basicsize = sizeof(struct pyrf_evsel),
989 .tp_dealloc = (destructor)pyrf_evsel__delete,
990 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
991 .tp_doc = pyrf_evsel__doc,
992 .tp_members = pyrf_evsel__members,
993 .tp_methods = pyrf_evsel__methods,
994 .tp_init = (initproc)pyrf_evsel__init,
995 .tp_str = pyrf_evsel__str,
996 .tp_repr = pyrf_evsel__str,
997};
998
999static int pyrf_evsel__setup_types(void)
1000{
1001 pyrf_evsel__type.tp_new = PyType_GenericNew;
1002 return PyType_Ready(&pyrf_evsel__type);
1003}
1004
1005struct pyrf_evlist {
1006 PyObject_HEAD
1007
1008 struct evlist evlist;
1009};
1010
1011static int pyrf_evlist__init(struct pyrf_evlist *pevlist,
1012 PyObject *args, PyObject *kwargs __maybe_unused)
1013{
1014 PyObject *pcpus = NULL, *pthreads = NULL;
1015 struct perf_cpu_map *cpus;
1016 struct perf_thread_map *threads;
1017
1018 if (!PyArg_ParseTuple(args, "OO", &pcpus, &pthreads))
1019 return -1;
1020
1021 threads = ((struct pyrf_thread_map *)pthreads)->threads;
1022 cpus = ((struct pyrf_cpu_map *)pcpus)->cpus;
1023 evlist__init(&pevlist->evlist, cpus, threads);
1024 return 0;
1025}
1026
1027static void pyrf_evlist__delete(struct pyrf_evlist *pevlist)
1028{
1029 evlist__exit(&pevlist->evlist);
1030 Py_TYPE(pevlist)->tp_free((PyObject*)pevlist);
1031}
1032
1033static PyObject *pyrf_evlist__all_cpus(struct pyrf_evlist *pevlist)
1034{
1035 struct pyrf_cpu_map *pcpu_map = PyObject_New(struct pyrf_cpu_map, &pyrf_cpu_map__type);
1036
1037 if (pcpu_map)
1038 pcpu_map->cpus = perf_cpu_map__get(pevlist->evlist.core.all_cpus);
1039
1040 return (PyObject *)pcpu_map;
1041}
1042
1043static PyObject *pyrf_evlist__mmap(struct pyrf_evlist *pevlist,
1044 PyObject *args, PyObject *kwargs)
1045{
1046 struct evlist *evlist = &pevlist->evlist;
1047 static char *kwlist[] = { "pages", "overwrite", NULL };
1048 int pages = 128, overwrite = false;
1049
1050 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii", kwlist,
1051 &pages, &overwrite))
1052 return NULL;
1053
1054 if (evlist__mmap(evlist, pages) < 0) {
1055 PyErr_SetFromErrno(PyExc_OSError);
1056 return NULL;
1057 }
1058
1059 Py_INCREF(Py_None);
1060 return Py_None;
1061}
1062
1063static PyObject *pyrf_evlist__poll(struct pyrf_evlist *pevlist,
1064 PyObject *args, PyObject *kwargs)
1065{
1066 struct evlist *evlist = &pevlist->evlist;
1067 static char *kwlist[] = { "timeout", NULL };
1068 int timeout = -1, n;
1069
1070 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", kwlist, &timeout))
1071 return NULL;
1072
1073 n = evlist__poll(evlist, timeout);
1074 if (n < 0) {
1075 PyErr_SetFromErrno(PyExc_OSError);
1076 return NULL;
1077 }
1078
1079 return Py_BuildValue("i", n);
1080}
1081
1082static PyObject *pyrf_evlist__get_pollfd(struct pyrf_evlist *pevlist,
1083 PyObject *args __maybe_unused,
1084 PyObject *kwargs __maybe_unused)
1085{
1086 struct evlist *evlist = &pevlist->evlist;
1087 PyObject *list = PyList_New(0);
1088 int i;
1089
1090 for (i = 0; i < evlist->core.pollfd.nr; ++i) {
1091 PyObject *file;
1092 file = PyFile_FromFd(evlist->core.pollfd.entries[i].fd, "perf", "r", -1,
1093 NULL, NULL, NULL, 0);
1094 if (file == NULL)
1095 goto free_list;
1096
1097 if (PyList_Append(list, file) != 0) {
1098 Py_DECREF(file);
1099 goto free_list;
1100 }
1101
1102 Py_DECREF(file);
1103 }
1104
1105 return list;
1106free_list:
1107 return PyErr_NoMemory();
1108}
1109
1110
1111static PyObject *pyrf_evlist__add(struct pyrf_evlist *pevlist,
1112 PyObject *args,
1113 PyObject *kwargs __maybe_unused)
1114{
1115 struct evlist *evlist = &pevlist->evlist;
1116 PyObject *pevsel;
1117 struct evsel *evsel;
1118
1119 if (!PyArg_ParseTuple(args, "O", &pevsel))
1120 return NULL;
1121
1122 Py_INCREF(pevsel);
1123 evsel = &((struct pyrf_evsel *)pevsel)->evsel;
1124 evsel->core.idx = evlist->core.nr_entries;
1125 evlist__add(evlist, evsel);
1126
1127 return Py_BuildValue("i", evlist->core.nr_entries);
1128}
1129
1130static struct mmap *get_md(struct evlist *evlist, int cpu)
1131{
1132 int i;
1133
1134 for (i = 0; i < evlist->core.nr_mmaps; i++) {
1135 struct mmap *md = &evlist->mmap[i];
1136
1137 if (md->core.cpu.cpu == cpu)
1138 return md;
1139 }
1140
1141 return NULL;
1142}
1143
1144static PyObject *pyrf_evlist__read_on_cpu(struct pyrf_evlist *pevlist,
1145 PyObject *args, PyObject *kwargs)
1146{
1147 struct evlist *evlist = &pevlist->evlist;
1148 union perf_event *event;
1149 int sample_id_all = 1, cpu;
1150 static char *kwlist[] = { "cpu", "sample_id_all", NULL };
1151 struct mmap *md;
1152 int err;
1153
1154 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i", kwlist,
1155 &cpu, &sample_id_all))
1156 return NULL;
1157
1158 md = get_md(evlist, cpu);
1159 if (!md)
1160 return NULL;
1161
1162 if (perf_mmap__read_init(&md->core) < 0)
1163 goto end;
1164
1165 event = perf_mmap__read_event(&md->core);
1166 if (event != NULL) {
1167 PyObject *pyevent = pyrf_event__new(event);
1168 struct pyrf_event *pevent = (struct pyrf_event *)pyevent;
1169 struct evsel *evsel;
1170
1171 if (pyevent == NULL)
1172 return PyErr_NoMemory();
1173
1174 evsel = evlist__event2evsel(evlist, event);
1175 if (!evsel) {
1176 Py_DECREF(pyevent);
1177 Py_INCREF(Py_None);
1178 return Py_None;
1179 }
1180
1181 pevent->evsel = evsel;
1182
1183 perf_mmap__consume(&md->core);
1184
1185 err = evsel__parse_sample(evsel, &pevent->event, &pevent->sample);
1186 if (err) {
1187 Py_DECREF(pyevent);
1188 return PyErr_Format(PyExc_OSError,
1189 "perf: can't parse sample, err=%d", err);
1190 }
1191
1192 return pyevent;
1193 }
1194end:
1195 Py_INCREF(Py_None);
1196 return Py_None;
1197}
1198
1199static PyObject *pyrf_evlist__open(struct pyrf_evlist *pevlist,
1200 PyObject *args, PyObject *kwargs)
1201{
1202 struct evlist *evlist = &pevlist->evlist;
1203
1204 if (evlist__open(evlist) < 0) {
1205 PyErr_SetFromErrno(PyExc_OSError);
1206 return NULL;
1207 }
1208
1209 Py_INCREF(Py_None);
1210 return Py_None;
1211}
1212
1213static PyObject *pyrf_evlist__close(struct pyrf_evlist *pevlist)
1214{
1215 struct evlist *evlist = &pevlist->evlist;
1216
1217 evlist__close(evlist);
1218
1219 Py_INCREF(Py_None);
1220 return Py_None;
1221}
1222
1223static PyObject *pyrf_evlist__config(struct pyrf_evlist *pevlist)
1224{
1225 struct record_opts opts = {
1226 .sample_time = true,
1227 .mmap_pages = UINT_MAX,
1228 .user_freq = UINT_MAX,
1229 .user_interval = ULLONG_MAX,
1230 .freq = 4000,
1231 .target = {
1232 .uses_mmap = true,
1233 .default_per_cpu = true,
1234 },
1235 .nr_threads_synthesize = 1,
1236 .ctl_fd = -1,
1237 .ctl_fd_ack = -1,
1238 .no_buffering = true,
1239 .no_inherit = true,
1240 };
1241 struct evlist *evlist = &pevlist->evlist;
1242
1243 evlist__config(evlist, &opts, &callchain_param);
1244 Py_INCREF(Py_None);
1245 return Py_None;
1246}
1247
1248static PyObject *pyrf_evlist__disable(struct pyrf_evlist *pevlist)
1249{
1250 evlist__disable(&pevlist->evlist);
1251 Py_INCREF(Py_None);
1252 return Py_None;
1253}
1254
1255static PyObject *pyrf_evlist__enable(struct pyrf_evlist *pevlist)
1256{
1257 evlist__enable(&pevlist->evlist);
1258 Py_INCREF(Py_None);
1259 return Py_None;
1260}
1261
1262static PyMethodDef pyrf_evlist__methods[] = {
1263 {
1264 .ml_name = "all_cpus",
1265 .ml_meth = (PyCFunction)pyrf_evlist__all_cpus,
1266 .ml_flags = METH_NOARGS,
1267 .ml_doc = PyDoc_STR("CPU map union of all evsel CPU maps.")
1268 },
1269 {
1270 .ml_name = "mmap",
1271 .ml_meth = (PyCFunction)pyrf_evlist__mmap,
1272 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1273 .ml_doc = PyDoc_STR("mmap the file descriptor table.")
1274 },
1275 {
1276 .ml_name = "open",
1277 .ml_meth = (PyCFunction)pyrf_evlist__open,
1278 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1279 .ml_doc = PyDoc_STR("open the file descriptors.")
1280 },
1281 {
1282 .ml_name = "close",
1283 .ml_meth = (PyCFunction)pyrf_evlist__close,
1284 .ml_flags = METH_NOARGS,
1285 .ml_doc = PyDoc_STR("close the file descriptors.")
1286 },
1287 {
1288 .ml_name = "poll",
1289 .ml_meth = (PyCFunction)pyrf_evlist__poll,
1290 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1291 .ml_doc = PyDoc_STR("poll the file descriptor table.")
1292 },
1293 {
1294 .ml_name = "get_pollfd",
1295 .ml_meth = (PyCFunction)pyrf_evlist__get_pollfd,
1296 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1297 .ml_doc = PyDoc_STR("get the poll file descriptor table.")
1298 },
1299 {
1300 .ml_name = "add",
1301 .ml_meth = (PyCFunction)pyrf_evlist__add,
1302 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1303 .ml_doc = PyDoc_STR("adds an event selector to the list.")
1304 },
1305 {
1306 .ml_name = "read_on_cpu",
1307 .ml_meth = (PyCFunction)pyrf_evlist__read_on_cpu,
1308 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1309 .ml_doc = PyDoc_STR("reads an event.")
1310 },
1311 {
1312 .ml_name = "config",
1313 .ml_meth = (PyCFunction)pyrf_evlist__config,
1314 .ml_flags = METH_NOARGS,
1315 .ml_doc = PyDoc_STR("Apply default record options to the evlist.")
1316 },
1317 {
1318 .ml_name = "disable",
1319 .ml_meth = (PyCFunction)pyrf_evlist__disable,
1320 .ml_flags = METH_NOARGS,
1321 .ml_doc = PyDoc_STR("Disable the evsels in the evlist.")
1322 },
1323 {
1324 .ml_name = "enable",
1325 .ml_meth = (PyCFunction)pyrf_evlist__enable,
1326 .ml_flags = METH_NOARGS,
1327 .ml_doc = PyDoc_STR("Enable the evsels in the evlist.")
1328 },
1329 { .ml_name = NULL, }
1330};
1331
1332static Py_ssize_t pyrf_evlist__length(PyObject *obj)
1333{
1334 struct pyrf_evlist *pevlist = (void *)obj;
1335
1336 return pevlist->evlist.core.nr_entries;
1337}
1338
1339static PyObject *pyrf_evlist__item(PyObject *obj, Py_ssize_t i)
1340{
1341 struct pyrf_evlist *pevlist = (void *)obj;
1342 struct evsel *pos;
1343
1344 if (i >= pevlist->evlist.core.nr_entries) {
1345 PyErr_SetString(PyExc_IndexError, "Index out of range");
1346 return NULL;
1347 }
1348
1349 evlist__for_each_entry(&pevlist->evlist, pos) {
1350 if (i-- == 0)
1351 break;
1352 }
1353
1354 return Py_BuildValue("O", container_of(pos, struct pyrf_evsel, evsel));
1355}
1356
1357static PyObject *pyrf_evlist__str(PyObject *self)
1358{
1359 struct pyrf_evlist *pevlist = (void *)self;
1360 struct evsel *pos;
1361 struct strbuf sb = STRBUF_INIT;
1362 bool first = true;
1363 PyObject *result;
1364
1365 strbuf_addstr(&sb, "evlist([");
1366 evlist__for_each_entry(&pevlist->evlist, pos) {
1367 if (!first)
1368 strbuf_addch(&sb, ',');
1369 if (!pos->pmu)
1370 strbuf_addstr(&sb, evsel__name(pos));
1371 else
1372 strbuf_addf(&sb, "%s/%s/", pos->pmu->name, evsel__name(pos));
1373 first = false;
1374 }
1375 strbuf_addstr(&sb, "])");
1376 result = PyUnicode_FromString(sb.buf);
1377 strbuf_release(&sb);
1378 return result;
1379}
1380
1381static PySequenceMethods pyrf_evlist__sequence_methods = {
1382 .sq_length = pyrf_evlist__length,
1383 .sq_item = pyrf_evlist__item,
1384};
1385
1386static const char pyrf_evlist__doc[] = PyDoc_STR("perf event selector list object.");
1387
1388static PyTypeObject pyrf_evlist__type = {
1389 PyVarObject_HEAD_INIT(NULL, 0)
1390 .tp_name = "perf.evlist",
1391 .tp_basicsize = sizeof(struct pyrf_evlist),
1392 .tp_dealloc = (destructor)pyrf_evlist__delete,
1393 .tp_flags = Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
1394 .tp_as_sequence = &pyrf_evlist__sequence_methods,
1395 .tp_doc = pyrf_evlist__doc,
1396 .tp_methods = pyrf_evlist__methods,
1397 .tp_init = (initproc)pyrf_evlist__init,
1398 .tp_repr = pyrf_evlist__str,
1399 .tp_str = pyrf_evlist__str,
1400};
1401
1402static int pyrf_evlist__setup_types(void)
1403{
1404 pyrf_evlist__type.tp_new = PyType_GenericNew;
1405 return PyType_Ready(&pyrf_evlist__type);
1406}
1407
1408#define PERF_CONST(name) { #name, PERF_##name }
1409
1410struct perf_constant {
1411 const char *name;
1412 int value;
1413};
1414
1415static const struct perf_constant perf__constants[] = {
1416 PERF_CONST(TYPE_HARDWARE),
1417 PERF_CONST(TYPE_SOFTWARE),
1418 PERF_CONST(TYPE_TRACEPOINT),
1419 PERF_CONST(TYPE_HW_CACHE),
1420 PERF_CONST(TYPE_RAW),
1421 PERF_CONST(TYPE_BREAKPOINT),
1422
1423 PERF_CONST(COUNT_HW_CPU_CYCLES),
1424 PERF_CONST(COUNT_HW_INSTRUCTIONS),
1425 PERF_CONST(COUNT_HW_CACHE_REFERENCES),
1426 PERF_CONST(COUNT_HW_CACHE_MISSES),
1427 PERF_CONST(COUNT_HW_BRANCH_INSTRUCTIONS),
1428 PERF_CONST(COUNT_HW_BRANCH_MISSES),
1429 PERF_CONST(COUNT_HW_BUS_CYCLES),
1430 PERF_CONST(COUNT_HW_CACHE_L1D),
1431 PERF_CONST(COUNT_HW_CACHE_L1I),
1432 PERF_CONST(COUNT_HW_CACHE_LL),
1433 PERF_CONST(COUNT_HW_CACHE_DTLB),
1434 PERF_CONST(COUNT_HW_CACHE_ITLB),
1435 PERF_CONST(COUNT_HW_CACHE_BPU),
1436 PERF_CONST(COUNT_HW_CACHE_OP_READ),
1437 PERF_CONST(COUNT_HW_CACHE_OP_WRITE),
1438 PERF_CONST(COUNT_HW_CACHE_OP_PREFETCH),
1439 PERF_CONST(COUNT_HW_CACHE_RESULT_ACCESS),
1440 PERF_CONST(COUNT_HW_CACHE_RESULT_MISS),
1441
1442 PERF_CONST(COUNT_HW_STALLED_CYCLES_FRONTEND),
1443 PERF_CONST(COUNT_HW_STALLED_CYCLES_BACKEND),
1444
1445 PERF_CONST(COUNT_SW_CPU_CLOCK),
1446 PERF_CONST(COUNT_SW_TASK_CLOCK),
1447 PERF_CONST(COUNT_SW_PAGE_FAULTS),
1448 PERF_CONST(COUNT_SW_CONTEXT_SWITCHES),
1449 PERF_CONST(COUNT_SW_CPU_MIGRATIONS),
1450 PERF_CONST(COUNT_SW_PAGE_FAULTS_MIN),
1451 PERF_CONST(COUNT_SW_PAGE_FAULTS_MAJ),
1452 PERF_CONST(COUNT_SW_ALIGNMENT_FAULTS),
1453 PERF_CONST(COUNT_SW_EMULATION_FAULTS),
1454 PERF_CONST(COUNT_SW_DUMMY),
1455
1456 PERF_CONST(SAMPLE_IP),
1457 PERF_CONST(SAMPLE_TID),
1458 PERF_CONST(SAMPLE_TIME),
1459 PERF_CONST(SAMPLE_ADDR),
1460 PERF_CONST(SAMPLE_READ),
1461 PERF_CONST(SAMPLE_CALLCHAIN),
1462 PERF_CONST(SAMPLE_ID),
1463 PERF_CONST(SAMPLE_CPU),
1464 PERF_CONST(SAMPLE_PERIOD),
1465 PERF_CONST(SAMPLE_STREAM_ID),
1466 PERF_CONST(SAMPLE_RAW),
1467
1468 PERF_CONST(FORMAT_TOTAL_TIME_ENABLED),
1469 PERF_CONST(FORMAT_TOTAL_TIME_RUNNING),
1470 PERF_CONST(FORMAT_ID),
1471 PERF_CONST(FORMAT_GROUP),
1472
1473 PERF_CONST(RECORD_MMAP),
1474 PERF_CONST(RECORD_LOST),
1475 PERF_CONST(RECORD_COMM),
1476 PERF_CONST(RECORD_EXIT),
1477 PERF_CONST(RECORD_THROTTLE),
1478 PERF_CONST(RECORD_UNTHROTTLE),
1479 PERF_CONST(RECORD_FORK),
1480 PERF_CONST(RECORD_READ),
1481 PERF_CONST(RECORD_SAMPLE),
1482 PERF_CONST(RECORD_MMAP2),
1483 PERF_CONST(RECORD_AUX),
1484 PERF_CONST(RECORD_ITRACE_START),
1485 PERF_CONST(RECORD_LOST_SAMPLES),
1486 PERF_CONST(RECORD_SWITCH),
1487 PERF_CONST(RECORD_SWITCH_CPU_WIDE),
1488
1489 PERF_CONST(RECORD_MISC_SWITCH_OUT),
1490 { .name = NULL, },
1491};
1492
1493static PyObject *pyrf__tracepoint(struct pyrf_evsel *pevsel,
1494 PyObject *args, PyObject *kwargs)
1495{
1496#ifndef HAVE_LIBTRACEEVENT
1497 return NULL;
1498#else
1499 struct tep_event *tp_format;
1500 static char *kwlist[] = { "sys", "name", NULL };
1501 char *sys = NULL;
1502 char *name = NULL;
1503
1504 if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss", kwlist,
1505 &sys, &name))
1506 return NULL;
1507
1508 tp_format = trace_event__tp_format(sys, name);
1509 if (IS_ERR(tp_format))
1510 return PyLong_FromLong(-1);
1511
1512 return PyLong_FromLong(tp_format->id);
1513#endif // HAVE_LIBTRACEEVENT
1514}
1515
1516static PyObject *pyrf_evsel__from_evsel(struct evsel *evsel)
1517{
1518 struct pyrf_evsel *pevsel = PyObject_New(struct pyrf_evsel, &pyrf_evsel__type);
1519
1520 if (!pevsel)
1521 return NULL;
1522
1523 memset(&pevsel->evsel, 0, sizeof(pevsel->evsel));
1524 evsel__init(&pevsel->evsel, &evsel->core.attr, evsel->core.idx);
1525
1526 evsel__clone(&pevsel->evsel, evsel);
1527 if (evsel__is_group_leader(evsel))
1528 evsel__set_leader(&pevsel->evsel, &pevsel->evsel);
1529 return (PyObject *)pevsel;
1530}
1531
1532static PyObject *pyrf_evlist__from_evlist(struct evlist *evlist)
1533{
1534 struct pyrf_evlist *pevlist = PyObject_New(struct pyrf_evlist, &pyrf_evlist__type);
1535 struct evsel *pos;
1536
1537 if (!pevlist)
1538 return NULL;
1539
1540 memset(&pevlist->evlist, 0, sizeof(pevlist->evlist));
1541 evlist__init(&pevlist->evlist, evlist->core.all_cpus, evlist->core.threads);
1542 evlist__for_each_entry(evlist, pos) {
1543 struct pyrf_evsel *pevsel = (void *)pyrf_evsel__from_evsel(pos);
1544
1545 evlist__add(&pevlist->evlist, &pevsel->evsel);
1546 }
1547 return (PyObject *)pevlist;
1548}
1549
1550static PyObject *pyrf__parse_events(PyObject *self, PyObject *args)
1551{
1552 const char *input;
1553 struct evlist evlist = {};
1554 struct parse_events_error err;
1555 PyObject *result;
1556 PyObject *pcpus = NULL, *pthreads = NULL;
1557 struct perf_cpu_map *cpus;
1558 struct perf_thread_map *threads;
1559
1560 if (!PyArg_ParseTuple(args, "s|OO", &input, &pcpus, &pthreads))
1561 return NULL;
1562
1563 threads = pthreads ? ((struct pyrf_thread_map *)pthreads)->threads : NULL;
1564 cpus = pcpus ? ((struct pyrf_cpu_map *)pcpus)->cpus : NULL;
1565
1566 parse_events_error__init(&err);
1567 evlist__init(&evlist, cpus, threads);
1568 if (parse_events(&evlist, input, &err)) {
1569 parse_events_error__print(&err, input);
1570 PyErr_SetFromErrno(PyExc_OSError);
1571 return NULL;
1572 }
1573 result = pyrf_evlist__from_evlist(&evlist);
1574 evlist__exit(&evlist);
1575 return result;
1576}
1577
1578static PyMethodDef perf__methods[] = {
1579 {
1580 .ml_name = "tracepoint",
1581 .ml_meth = (PyCFunction) pyrf__tracepoint,
1582 .ml_flags = METH_VARARGS | METH_KEYWORDS,
1583 .ml_doc = PyDoc_STR("Get tracepoint config.")
1584 },
1585 {
1586 .ml_name = "parse_events",
1587 .ml_meth = (PyCFunction) pyrf__parse_events,
1588 .ml_flags = METH_VARARGS,
1589 .ml_doc = PyDoc_STR("Parse a string of events and return an evlist.")
1590 },
1591 { .ml_name = NULL, }
1592};
1593
1594PyMODINIT_FUNC PyInit_perf(void)
1595{
1596 PyObject *obj;
1597 int i;
1598 PyObject *dict;
1599 static struct PyModuleDef moduledef = {
1600 PyModuleDef_HEAD_INIT,
1601 "perf", /* m_name */
1602 "", /* m_doc */
1603 -1, /* m_size */
1604 perf__methods, /* m_methods */
1605 NULL, /* m_reload */
1606 NULL, /* m_traverse */
1607 NULL, /* m_clear */
1608 NULL, /* m_free */
1609 };
1610 PyObject *module = PyModule_Create(&moduledef);
1611
1612 if (module == NULL ||
1613 pyrf_event__setup_types() < 0 ||
1614 pyrf_evlist__setup_types() < 0 ||
1615 pyrf_evsel__setup_types() < 0 ||
1616 pyrf_thread_map__setup_types() < 0 ||
1617 pyrf_cpu_map__setup_types() < 0 ||
1618 pyrf_counts_values__setup_types() < 0)
1619 return module;
1620
1621 /* The page_size is placed in util object. */
1622 page_size = sysconf(_SC_PAGE_SIZE);
1623
1624 Py_INCREF(&pyrf_evlist__type);
1625 PyModule_AddObject(module, "evlist", (PyObject*)&pyrf_evlist__type);
1626
1627 Py_INCREF(&pyrf_evsel__type);
1628 PyModule_AddObject(module, "evsel", (PyObject*)&pyrf_evsel__type);
1629
1630 Py_INCREF(&pyrf_mmap_event__type);
1631 PyModule_AddObject(module, "mmap_event", (PyObject *)&pyrf_mmap_event__type);
1632
1633 Py_INCREF(&pyrf_lost_event__type);
1634 PyModule_AddObject(module, "lost_event", (PyObject *)&pyrf_lost_event__type);
1635
1636 Py_INCREF(&pyrf_comm_event__type);
1637 PyModule_AddObject(module, "comm_event", (PyObject *)&pyrf_comm_event__type);
1638
1639 Py_INCREF(&pyrf_task_event__type);
1640 PyModule_AddObject(module, "task_event", (PyObject *)&pyrf_task_event__type);
1641
1642 Py_INCREF(&pyrf_throttle_event__type);
1643 PyModule_AddObject(module, "throttle_event", (PyObject *)&pyrf_throttle_event__type);
1644
1645 Py_INCREF(&pyrf_task_event__type);
1646 PyModule_AddObject(module, "task_event", (PyObject *)&pyrf_task_event__type);
1647
1648 Py_INCREF(&pyrf_read_event__type);
1649 PyModule_AddObject(module, "read_event", (PyObject *)&pyrf_read_event__type);
1650
1651 Py_INCREF(&pyrf_sample_event__type);
1652 PyModule_AddObject(module, "sample_event", (PyObject *)&pyrf_sample_event__type);
1653
1654 Py_INCREF(&pyrf_context_switch_event__type);
1655 PyModule_AddObject(module, "switch_event", (PyObject *)&pyrf_context_switch_event__type);
1656
1657 Py_INCREF(&pyrf_thread_map__type);
1658 PyModule_AddObject(module, "thread_map", (PyObject*)&pyrf_thread_map__type);
1659
1660 Py_INCREF(&pyrf_cpu_map__type);
1661 PyModule_AddObject(module, "cpu_map", (PyObject*)&pyrf_cpu_map__type);
1662
1663 Py_INCREF(&pyrf_counts_values__type);
1664 PyModule_AddObject(module, "counts_values", (PyObject *)&pyrf_counts_values__type);
1665
1666 dict = PyModule_GetDict(module);
1667 if (dict == NULL)
1668 goto error;
1669
1670 for (i = 0; perf__constants[i].name != NULL; i++) {
1671 obj = PyLong_FromLong(perf__constants[i].value);
1672 if (obj == NULL)
1673 goto error;
1674 PyDict_SetItemString(dict, perf__constants[i].name, obj);
1675 Py_DECREF(obj);
1676 }
1677
1678error:
1679 if (PyErr_Occurred())
1680 PyErr_SetString(PyExc_ImportError, "perf: Init failed!");
1681 return module;
1682}