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