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