xref: /linux-6.15/tools/perf/util/python.c (revision cc8bf352)
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_format_field *field;
346 
347 	if (!evsel->tp_format) {
348 		struct tep_event *tp_format;
349 
350 		tp_format = trace_event__tp_format_id(evsel->core.attr.config);
351 		if (IS_ERR_OR_NULL(tp_format))
352 			return NULL;
353 
354 		evsel->tp_format = tp_format;
355 	}
356 
357 	field = tep_find_any_field(evsel->tp_format, str);
358 	if (!field)
359 		return NULL;
360 
361 	return tracepoint_field(pevent, field);
362 }
363 #endif /* HAVE_LIBTRACEEVENT */
364 
365 static PyObject*
366 pyrf_sample_event__getattro(struct pyrf_event *pevent, PyObject *attr_name)
367 {
368 	PyObject *obj = NULL;
369 
370 #ifdef HAVE_LIBTRACEEVENT
371 	if (is_tracepoint(pevent))
372 		obj = get_tracepoint_field(pevent, attr_name);
373 #endif
374 
375 	return obj ?: PyObject_GenericGetAttr((PyObject *) pevent, attr_name);
376 }
377 
378 static PyTypeObject pyrf_sample_event__type = {
379 	PyVarObject_HEAD_INIT(NULL, 0)
380 	.tp_name	= "perf.sample_event",
381 	.tp_basicsize	= sizeof(struct pyrf_event),
382 	.tp_flags	= Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
383 	.tp_doc		= pyrf_sample_event__doc,
384 	.tp_members	= pyrf_sample_event__members,
385 	.tp_repr	= (reprfunc)pyrf_sample_event__repr,
386 	.tp_getattro	= (getattrofunc) pyrf_sample_event__getattro,
387 };
388 
389 static const char pyrf_context_switch_event__doc[] = PyDoc_STR("perf context_switch event object.");
390 
391 static PyMemberDef pyrf_context_switch_event__members[] = {
392 	sample_members
393 	member_def(perf_event_header, type, T_UINT, "event type"),
394 	member_def(perf_record_switch, next_prev_pid, T_UINT, "next/prev pid"),
395 	member_def(perf_record_switch, next_prev_tid, T_UINT, "next/prev tid"),
396 	{ .name = NULL, },
397 };
398 
399 static PyObject *pyrf_context_switch_event__repr(const struct pyrf_event *pevent)
400 {
401 	PyObject *ret;
402 	char *s;
403 
404 	if (asprintf(&s, "{ type: context_switch, next_prev_pid: %u, next_prev_tid: %u, switch_out: %u }",
405 		     pevent->event.context_switch.next_prev_pid,
406 		     pevent->event.context_switch.next_prev_tid,
407 		     !!(pevent->event.header.misc & PERF_RECORD_MISC_SWITCH_OUT)) < 0) {
408 		ret = PyErr_NoMemory();
409 	} else {
410 		ret = PyUnicode_FromString(s);
411 		free(s);
412 	}
413 	return ret;
414 }
415 
416 static PyTypeObject pyrf_context_switch_event__type = {
417 	PyVarObject_HEAD_INIT(NULL, 0)
418 	.tp_name	= "perf.context_switch_event",
419 	.tp_basicsize	= sizeof(struct pyrf_event),
420 	.tp_flags	= Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
421 	.tp_doc		= pyrf_context_switch_event__doc,
422 	.tp_members	= pyrf_context_switch_event__members,
423 	.tp_repr	= (reprfunc)pyrf_context_switch_event__repr,
424 };
425 
426 static int pyrf_event__setup_types(void)
427 {
428 	int err;
429 	pyrf_mmap_event__type.tp_new =
430 	pyrf_task_event__type.tp_new =
431 	pyrf_comm_event__type.tp_new =
432 	pyrf_lost_event__type.tp_new =
433 	pyrf_read_event__type.tp_new =
434 	pyrf_sample_event__type.tp_new =
435 	pyrf_context_switch_event__type.tp_new =
436 	pyrf_throttle_event__type.tp_new = PyType_GenericNew;
437 
438 	pyrf_sample_event__type.tp_dealloc = (destructor)pyrf_sample_event__delete,
439 
440 	err = PyType_Ready(&pyrf_mmap_event__type);
441 	if (err < 0)
442 		goto out;
443 	err = PyType_Ready(&pyrf_lost_event__type);
444 	if (err < 0)
445 		goto out;
446 	err = PyType_Ready(&pyrf_task_event__type);
447 	if (err < 0)
448 		goto out;
449 	err = PyType_Ready(&pyrf_comm_event__type);
450 	if (err < 0)
451 		goto out;
452 	err = PyType_Ready(&pyrf_throttle_event__type);
453 	if (err < 0)
454 		goto out;
455 	err = PyType_Ready(&pyrf_read_event__type);
456 	if (err < 0)
457 		goto out;
458 	err = PyType_Ready(&pyrf_sample_event__type);
459 	if (err < 0)
460 		goto out;
461 	err = PyType_Ready(&pyrf_context_switch_event__type);
462 	if (err < 0)
463 		goto out;
464 out:
465 	return err;
466 }
467 
468 static PyTypeObject *pyrf_event__type[] = {
469 	[PERF_RECORD_MMAP]	 = &pyrf_mmap_event__type,
470 	[PERF_RECORD_LOST]	 = &pyrf_lost_event__type,
471 	[PERF_RECORD_COMM]	 = &pyrf_comm_event__type,
472 	[PERF_RECORD_EXIT]	 = &pyrf_task_event__type,
473 	[PERF_RECORD_THROTTLE]	 = &pyrf_throttle_event__type,
474 	[PERF_RECORD_UNTHROTTLE] = &pyrf_throttle_event__type,
475 	[PERF_RECORD_FORK]	 = &pyrf_task_event__type,
476 	[PERF_RECORD_READ]	 = &pyrf_read_event__type,
477 	[PERF_RECORD_SAMPLE]	 = &pyrf_sample_event__type,
478 	[PERF_RECORD_SWITCH]	 = &pyrf_context_switch_event__type,
479 	[PERF_RECORD_SWITCH_CPU_WIDE]  = &pyrf_context_switch_event__type,
480 };
481 
482 static PyObject *pyrf_event__new(const union perf_event *event)
483 {
484 	struct pyrf_event *pevent;
485 	PyTypeObject *ptype;
486 
487 	if ((event->header.type < PERF_RECORD_MMAP ||
488 	     event->header.type > PERF_RECORD_SAMPLE) &&
489 	    !(event->header.type == PERF_RECORD_SWITCH ||
490 	      event->header.type == PERF_RECORD_SWITCH_CPU_WIDE))
491 		return NULL;
492 
493 	ptype = pyrf_event__type[event->header.type];
494 	pevent = PyObject_New(struct pyrf_event, ptype);
495 	if (pevent != NULL)
496 		memcpy(&pevent->event, event, event->header.size);
497 	return (PyObject *)pevent;
498 }
499 
500 struct pyrf_cpu_map {
501 	PyObject_HEAD
502 
503 	struct perf_cpu_map *cpus;
504 };
505 
506 static int pyrf_cpu_map__init(struct pyrf_cpu_map *pcpus,
507 			      PyObject *args, PyObject *kwargs)
508 {
509 	static char *kwlist[] = { "cpustr", NULL };
510 	char *cpustr = NULL;
511 
512 	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|s",
513 					 kwlist, &cpustr))
514 		return -1;
515 
516 	pcpus->cpus = perf_cpu_map__new(cpustr);
517 	if (pcpus->cpus == NULL)
518 		return -1;
519 	return 0;
520 }
521 
522 static void pyrf_cpu_map__delete(struct pyrf_cpu_map *pcpus)
523 {
524 	perf_cpu_map__put(pcpus->cpus);
525 	Py_TYPE(pcpus)->tp_free((PyObject*)pcpus);
526 }
527 
528 static Py_ssize_t pyrf_cpu_map__length(PyObject *obj)
529 {
530 	struct pyrf_cpu_map *pcpus = (void *)obj;
531 
532 	return perf_cpu_map__nr(pcpus->cpus);
533 }
534 
535 static PyObject *pyrf_cpu_map__item(PyObject *obj, Py_ssize_t i)
536 {
537 	struct pyrf_cpu_map *pcpus = (void *)obj;
538 
539 	if (i >= perf_cpu_map__nr(pcpus->cpus))
540 		return NULL;
541 
542 	return Py_BuildValue("i", perf_cpu_map__cpu(pcpus->cpus, i).cpu);
543 }
544 
545 static PySequenceMethods pyrf_cpu_map__sequence_methods = {
546 	.sq_length = pyrf_cpu_map__length,
547 	.sq_item   = pyrf_cpu_map__item,
548 };
549 
550 static const char pyrf_cpu_map__doc[] = PyDoc_STR("cpu map object.");
551 
552 static PyTypeObject pyrf_cpu_map__type = {
553 	PyVarObject_HEAD_INIT(NULL, 0)
554 	.tp_name	= "perf.cpu_map",
555 	.tp_basicsize	= sizeof(struct pyrf_cpu_map),
556 	.tp_dealloc	= (destructor)pyrf_cpu_map__delete,
557 	.tp_flags	= Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
558 	.tp_doc		= pyrf_cpu_map__doc,
559 	.tp_as_sequence	= &pyrf_cpu_map__sequence_methods,
560 	.tp_init	= (initproc)pyrf_cpu_map__init,
561 };
562 
563 static int pyrf_cpu_map__setup_types(void)
564 {
565 	pyrf_cpu_map__type.tp_new = PyType_GenericNew;
566 	return PyType_Ready(&pyrf_cpu_map__type);
567 }
568 
569 struct pyrf_thread_map {
570 	PyObject_HEAD
571 
572 	struct perf_thread_map *threads;
573 };
574 
575 static int pyrf_thread_map__init(struct pyrf_thread_map *pthreads,
576 				 PyObject *args, PyObject *kwargs)
577 {
578 	static char *kwlist[] = { "pid", "tid", "uid", NULL };
579 	int pid = -1, tid = -1, uid = UINT_MAX;
580 
581 	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|iii",
582 					 kwlist, &pid, &tid, &uid))
583 		return -1;
584 
585 	pthreads->threads = thread_map__new(pid, tid, uid);
586 	if (pthreads->threads == NULL)
587 		return -1;
588 	return 0;
589 }
590 
591 static void pyrf_thread_map__delete(struct pyrf_thread_map *pthreads)
592 {
593 	perf_thread_map__put(pthreads->threads);
594 	Py_TYPE(pthreads)->tp_free((PyObject*)pthreads);
595 }
596 
597 static Py_ssize_t pyrf_thread_map__length(PyObject *obj)
598 {
599 	struct pyrf_thread_map *pthreads = (void *)obj;
600 
601 	return perf_thread_map__nr(pthreads->threads);
602 }
603 
604 static PyObject *pyrf_thread_map__item(PyObject *obj, Py_ssize_t i)
605 {
606 	struct pyrf_thread_map *pthreads = (void *)obj;
607 
608 	if (i >= perf_thread_map__nr(pthreads->threads))
609 		return NULL;
610 
611 	return Py_BuildValue("i", perf_thread_map__pid(pthreads->threads, i));
612 }
613 
614 static PySequenceMethods pyrf_thread_map__sequence_methods = {
615 	.sq_length = pyrf_thread_map__length,
616 	.sq_item   = pyrf_thread_map__item,
617 };
618 
619 static const char pyrf_thread_map__doc[] = PyDoc_STR("thread map object.");
620 
621 static PyTypeObject pyrf_thread_map__type = {
622 	PyVarObject_HEAD_INIT(NULL, 0)
623 	.tp_name	= "perf.thread_map",
624 	.tp_basicsize	= sizeof(struct pyrf_thread_map),
625 	.tp_dealloc	= (destructor)pyrf_thread_map__delete,
626 	.tp_flags	= Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
627 	.tp_doc		= pyrf_thread_map__doc,
628 	.tp_as_sequence	= &pyrf_thread_map__sequence_methods,
629 	.tp_init	= (initproc)pyrf_thread_map__init,
630 };
631 
632 static int pyrf_thread_map__setup_types(void)
633 {
634 	pyrf_thread_map__type.tp_new = PyType_GenericNew;
635 	return PyType_Ready(&pyrf_thread_map__type);
636 }
637 
638 struct pyrf_evsel {
639 	PyObject_HEAD
640 
641 	struct evsel evsel;
642 };
643 
644 static int pyrf_evsel__init(struct pyrf_evsel *pevsel,
645 			    PyObject *args, PyObject *kwargs)
646 {
647 	struct perf_event_attr attr = {
648 		.type = PERF_TYPE_HARDWARE,
649 		.config = PERF_COUNT_HW_CPU_CYCLES,
650 		.sample_type = PERF_SAMPLE_PERIOD | PERF_SAMPLE_TID,
651 	};
652 	static char *kwlist[] = {
653 		"type",
654 		"config",
655 		"sample_freq",
656 		"sample_period",
657 		"sample_type",
658 		"read_format",
659 		"disabled",
660 		"inherit",
661 		"pinned",
662 		"exclusive",
663 		"exclude_user",
664 		"exclude_kernel",
665 		"exclude_hv",
666 		"exclude_idle",
667 		"mmap",
668 		"context_switch",
669 		"comm",
670 		"freq",
671 		"inherit_stat",
672 		"enable_on_exec",
673 		"task",
674 		"watermark",
675 		"precise_ip",
676 		"mmap_data",
677 		"sample_id_all",
678 		"wakeup_events",
679 		"bp_type",
680 		"bp_addr",
681 		"bp_len",
682 		 NULL
683 	};
684 	u64 sample_period = 0;
685 	u32 disabled = 0,
686 	    inherit = 0,
687 	    pinned = 0,
688 	    exclusive = 0,
689 	    exclude_user = 0,
690 	    exclude_kernel = 0,
691 	    exclude_hv = 0,
692 	    exclude_idle = 0,
693 	    mmap = 0,
694 	    context_switch = 0,
695 	    comm = 0,
696 	    freq = 1,
697 	    inherit_stat = 0,
698 	    enable_on_exec = 0,
699 	    task = 0,
700 	    watermark = 0,
701 	    precise_ip = 0,
702 	    mmap_data = 0,
703 	    sample_id_all = 1;
704 	int idx = 0;
705 
706 	if (!PyArg_ParseTupleAndKeywords(args, kwargs,
707 					 "|iKiKKiiiiiiiiiiiiiiiiiiiiiiKK", kwlist,
708 					 &attr.type, &attr.config, &attr.sample_freq,
709 					 &sample_period, &attr.sample_type,
710 					 &attr.read_format, &disabled, &inherit,
711 					 &pinned, &exclusive, &exclude_user,
712 					 &exclude_kernel, &exclude_hv, &exclude_idle,
713 					 &mmap, &context_switch, &comm, &freq, &inherit_stat,
714 					 &enable_on_exec, &task, &watermark,
715 					 &precise_ip, &mmap_data, &sample_id_all,
716 					 &attr.wakeup_events, &attr.bp_type,
717 					 &attr.bp_addr, &attr.bp_len, &idx))
718 		return -1;
719 
720 	/* union... */
721 	if (sample_period != 0) {
722 		if (attr.sample_freq != 0)
723 			return -1; /* FIXME: throw right exception */
724 		attr.sample_period = sample_period;
725 	}
726 
727 	/* Bitfields */
728 	attr.disabled	    = disabled;
729 	attr.inherit	    = inherit;
730 	attr.pinned	    = pinned;
731 	attr.exclusive	    = exclusive;
732 	attr.exclude_user   = exclude_user;
733 	attr.exclude_kernel = exclude_kernel;
734 	attr.exclude_hv	    = exclude_hv;
735 	attr.exclude_idle   = exclude_idle;
736 	attr.mmap	    = mmap;
737 	attr.context_switch = context_switch;
738 	attr.comm	    = comm;
739 	attr.freq	    = freq;
740 	attr.inherit_stat   = inherit_stat;
741 	attr.enable_on_exec = enable_on_exec;
742 	attr.task	    = task;
743 	attr.watermark	    = watermark;
744 	attr.precise_ip	    = precise_ip;
745 	attr.mmap_data	    = mmap_data;
746 	attr.sample_id_all  = sample_id_all;
747 	attr.size	    = sizeof(attr);
748 
749 	evsel__init(&pevsel->evsel, &attr, idx);
750 	return 0;
751 }
752 
753 static void pyrf_evsel__delete(struct pyrf_evsel *pevsel)
754 {
755 	evsel__exit(&pevsel->evsel);
756 	Py_TYPE(pevsel)->tp_free((PyObject*)pevsel);
757 }
758 
759 static PyObject *pyrf_evsel__open(struct pyrf_evsel *pevsel,
760 				  PyObject *args, PyObject *kwargs)
761 {
762 	struct evsel *evsel = &pevsel->evsel;
763 	struct perf_cpu_map *cpus = NULL;
764 	struct perf_thread_map *threads = NULL;
765 	PyObject *pcpus = NULL, *pthreads = NULL;
766 	int group = 0, inherit = 0;
767 	static char *kwlist[] = { "cpus", "threads", "group", "inherit", NULL };
768 
769 	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|OOii", kwlist,
770 					 &pcpus, &pthreads, &group, &inherit))
771 		return NULL;
772 
773 	if (pthreads != NULL)
774 		threads = ((struct pyrf_thread_map *)pthreads)->threads;
775 
776 	if (pcpus != NULL)
777 		cpus = ((struct pyrf_cpu_map *)pcpus)->cpus;
778 
779 	evsel->core.attr.inherit = inherit;
780 	/*
781 	 * This will group just the fds for this single evsel, to group
782 	 * multiple events, use evlist.open().
783 	 */
784 	if (evsel__open(evsel, cpus, threads) < 0) {
785 		PyErr_SetFromErrno(PyExc_OSError);
786 		return NULL;
787 	}
788 
789 	Py_INCREF(Py_None);
790 	return Py_None;
791 }
792 
793 static PyObject *pyrf_evsel__str(PyObject *self)
794 {
795 	struct pyrf_evsel *pevsel = (void *)self;
796 	struct evsel *evsel = &pevsel->evsel;
797 
798 	if (!evsel->pmu)
799 		return PyUnicode_FromFormat("evsel(%s)", evsel__name(evsel));
800 
801 	return PyUnicode_FromFormat("evsel(%s/%s/)", evsel->pmu->name, evsel__name(evsel));
802 }
803 
804 static PyMethodDef pyrf_evsel__methods[] = {
805 	{
806 		.ml_name  = "open",
807 		.ml_meth  = (PyCFunction)pyrf_evsel__open,
808 		.ml_flags = METH_VARARGS | METH_KEYWORDS,
809 		.ml_doc	  = PyDoc_STR("open the event selector file descriptor table.")
810 	},
811 	{ .ml_name = NULL, }
812 };
813 
814 #define evsel_member_def(member, ptype, help) \
815 	{ #member, ptype, \
816 	  offsetof(struct pyrf_evsel, evsel.member), \
817 	  0, help }
818 
819 #define evsel_attr_member_def(member, ptype, help) \
820 	{ #member, ptype, \
821 	  offsetof(struct pyrf_evsel, evsel.core.attr.member), \
822 	  0, help }
823 
824 static PyMemberDef pyrf_evsel__members[] = {
825 	evsel_member_def(tracking, T_BOOL, "tracking event."),
826 	evsel_attr_member_def(type, T_UINT, "attribute type."),
827 	evsel_attr_member_def(size, T_UINT, "attribute size."),
828 	evsel_attr_member_def(config, T_ULONGLONG, "attribute config."),
829 	evsel_attr_member_def(sample_period, T_ULONGLONG, "attribute sample_period."),
830 	evsel_attr_member_def(sample_type, T_ULONGLONG, "attribute sample_type."),
831 	evsel_attr_member_def(read_format, T_ULONGLONG, "attribute read_format."),
832 	evsel_attr_member_def(wakeup_events, T_UINT, "attribute wakeup_events."),
833 	{ .name = NULL, },
834 };
835 
836 static const char pyrf_evsel__doc[] = PyDoc_STR("perf event selector list object.");
837 
838 static PyTypeObject pyrf_evsel__type = {
839 	PyVarObject_HEAD_INIT(NULL, 0)
840 	.tp_name	= "perf.evsel",
841 	.tp_basicsize	= sizeof(struct pyrf_evsel),
842 	.tp_dealloc	= (destructor)pyrf_evsel__delete,
843 	.tp_flags	= Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
844 	.tp_doc		= pyrf_evsel__doc,
845 	.tp_members	= pyrf_evsel__members,
846 	.tp_methods	= pyrf_evsel__methods,
847 	.tp_init	= (initproc)pyrf_evsel__init,
848 	.tp_str         = pyrf_evsel__str,
849 	.tp_repr        = pyrf_evsel__str,
850 };
851 
852 static int pyrf_evsel__setup_types(void)
853 {
854 	pyrf_evsel__type.tp_new = PyType_GenericNew;
855 	return PyType_Ready(&pyrf_evsel__type);
856 }
857 
858 struct pyrf_evlist {
859 	PyObject_HEAD
860 
861 	struct evlist evlist;
862 };
863 
864 static int pyrf_evlist__init(struct pyrf_evlist *pevlist,
865 			     PyObject *args, PyObject *kwargs __maybe_unused)
866 {
867 	PyObject *pcpus = NULL, *pthreads = NULL;
868 	struct perf_cpu_map *cpus;
869 	struct perf_thread_map *threads;
870 
871 	if (!PyArg_ParseTuple(args, "OO", &pcpus, &pthreads))
872 		return -1;
873 
874 	threads = ((struct pyrf_thread_map *)pthreads)->threads;
875 	cpus = ((struct pyrf_cpu_map *)pcpus)->cpus;
876 	evlist__init(&pevlist->evlist, cpus, threads);
877 	return 0;
878 }
879 
880 static void pyrf_evlist__delete(struct pyrf_evlist *pevlist)
881 {
882 	evlist__exit(&pevlist->evlist);
883 	Py_TYPE(pevlist)->tp_free((PyObject*)pevlist);
884 }
885 
886 static PyObject *pyrf_evlist__mmap(struct pyrf_evlist *pevlist,
887 				   PyObject *args, PyObject *kwargs)
888 {
889 	struct evlist *evlist = &pevlist->evlist;
890 	static char *kwlist[] = { "pages", "overwrite", NULL };
891 	int pages = 128, overwrite = false;
892 
893 	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ii", kwlist,
894 					 &pages, &overwrite))
895 		return NULL;
896 
897 	if (evlist__mmap(evlist, pages) < 0) {
898 		PyErr_SetFromErrno(PyExc_OSError);
899 		return NULL;
900 	}
901 
902 	Py_INCREF(Py_None);
903 	return Py_None;
904 }
905 
906 static PyObject *pyrf_evlist__poll(struct pyrf_evlist *pevlist,
907 				   PyObject *args, PyObject *kwargs)
908 {
909 	struct evlist *evlist = &pevlist->evlist;
910 	static char *kwlist[] = { "timeout", NULL };
911 	int timeout = -1, n;
912 
913 	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|i", kwlist, &timeout))
914 		return NULL;
915 
916 	n = evlist__poll(evlist, timeout);
917 	if (n < 0) {
918 		PyErr_SetFromErrno(PyExc_OSError);
919 		return NULL;
920 	}
921 
922 	return Py_BuildValue("i", n);
923 }
924 
925 static PyObject *pyrf_evlist__get_pollfd(struct pyrf_evlist *pevlist,
926 					 PyObject *args __maybe_unused,
927 					 PyObject *kwargs __maybe_unused)
928 {
929 	struct evlist *evlist = &pevlist->evlist;
930         PyObject *list = PyList_New(0);
931 	int i;
932 
933 	for (i = 0; i < evlist->core.pollfd.nr; ++i) {
934 		PyObject *file;
935 		file = PyFile_FromFd(evlist->core.pollfd.entries[i].fd, "perf", "r", -1,
936 				     NULL, NULL, NULL, 0);
937 		if (file == NULL)
938 			goto free_list;
939 
940 		if (PyList_Append(list, file) != 0) {
941 			Py_DECREF(file);
942 			goto free_list;
943 		}
944 
945 		Py_DECREF(file);
946 	}
947 
948 	return list;
949 free_list:
950 	return PyErr_NoMemory();
951 }
952 
953 
954 static PyObject *pyrf_evlist__add(struct pyrf_evlist *pevlist,
955 				  PyObject *args,
956 				  PyObject *kwargs __maybe_unused)
957 {
958 	struct evlist *evlist = &pevlist->evlist;
959 	PyObject *pevsel;
960 	struct evsel *evsel;
961 
962 	if (!PyArg_ParseTuple(args, "O", &pevsel))
963 		return NULL;
964 
965 	Py_INCREF(pevsel);
966 	evsel = &((struct pyrf_evsel *)pevsel)->evsel;
967 	evsel->core.idx = evlist->core.nr_entries;
968 	evlist__add(evlist, evsel);
969 
970 	return Py_BuildValue("i", evlist->core.nr_entries);
971 }
972 
973 static struct mmap *get_md(struct evlist *evlist, int cpu)
974 {
975 	int i;
976 
977 	for (i = 0; i < evlist->core.nr_mmaps; i++) {
978 		struct mmap *md = &evlist->mmap[i];
979 
980 		if (md->core.cpu.cpu == cpu)
981 			return md;
982 	}
983 
984 	return NULL;
985 }
986 
987 static PyObject *pyrf_evlist__read_on_cpu(struct pyrf_evlist *pevlist,
988 					  PyObject *args, PyObject *kwargs)
989 {
990 	struct evlist *evlist = &pevlist->evlist;
991 	union perf_event *event;
992 	int sample_id_all = 1, cpu;
993 	static char *kwlist[] = { "cpu", "sample_id_all", NULL };
994 	struct mmap *md;
995 	int err;
996 
997 	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "i|i", kwlist,
998 					 &cpu, &sample_id_all))
999 		return NULL;
1000 
1001 	md = get_md(evlist, cpu);
1002 	if (!md)
1003 		return NULL;
1004 
1005 	if (perf_mmap__read_init(&md->core) < 0)
1006 		goto end;
1007 
1008 	event = perf_mmap__read_event(&md->core);
1009 	if (event != NULL) {
1010 		PyObject *pyevent = pyrf_event__new(event);
1011 		struct pyrf_event *pevent = (struct pyrf_event *)pyevent;
1012 		struct evsel *evsel;
1013 
1014 		if (pyevent == NULL)
1015 			return PyErr_NoMemory();
1016 
1017 		evsel = evlist__event2evsel(evlist, event);
1018 		if (!evsel) {
1019 			Py_INCREF(Py_None);
1020 			return Py_None;
1021 		}
1022 
1023 		pevent->evsel = evsel;
1024 
1025 		err = evsel__parse_sample(evsel, event, &pevent->sample);
1026 
1027 		/* Consume the even only after we parsed it out. */
1028 		perf_mmap__consume(&md->core);
1029 
1030 		if (err)
1031 			return PyErr_Format(PyExc_OSError,
1032 					    "perf: can't parse sample, err=%d", err);
1033 		return pyevent;
1034 	}
1035 end:
1036 	Py_INCREF(Py_None);
1037 	return Py_None;
1038 }
1039 
1040 static PyObject *pyrf_evlist__open(struct pyrf_evlist *pevlist,
1041 				   PyObject *args, PyObject *kwargs)
1042 {
1043 	struct evlist *evlist = &pevlist->evlist;
1044 
1045 	if (evlist__open(evlist) < 0) {
1046 		PyErr_SetFromErrno(PyExc_OSError);
1047 		return NULL;
1048 	}
1049 
1050 	Py_INCREF(Py_None);
1051 	return Py_None;
1052 }
1053 
1054 static PyObject *pyrf_evlist__disable(struct pyrf_evlist *pevlist)
1055 {
1056 	evlist__disable(&pevlist->evlist);
1057 	Py_INCREF(Py_None);
1058 	return Py_None;
1059 }
1060 
1061 static PyObject *pyrf_evlist__enable(struct pyrf_evlist *pevlist)
1062 {
1063 	evlist__enable(&pevlist->evlist);
1064 	Py_INCREF(Py_None);
1065 	return Py_None;
1066 }
1067 
1068 static PyMethodDef pyrf_evlist__methods[] = {
1069 	{
1070 		.ml_name  = "mmap",
1071 		.ml_meth  = (PyCFunction)pyrf_evlist__mmap,
1072 		.ml_flags = METH_VARARGS | METH_KEYWORDS,
1073 		.ml_doc	  = PyDoc_STR("mmap the file descriptor table.")
1074 	},
1075 	{
1076 		.ml_name  = "open",
1077 		.ml_meth  = (PyCFunction)pyrf_evlist__open,
1078 		.ml_flags = METH_VARARGS | METH_KEYWORDS,
1079 		.ml_doc	  = PyDoc_STR("open the file descriptors.")
1080 	},
1081 	{
1082 		.ml_name  = "poll",
1083 		.ml_meth  = (PyCFunction)pyrf_evlist__poll,
1084 		.ml_flags = METH_VARARGS | METH_KEYWORDS,
1085 		.ml_doc	  = PyDoc_STR("poll the file descriptor table.")
1086 	},
1087 	{
1088 		.ml_name  = "get_pollfd",
1089 		.ml_meth  = (PyCFunction)pyrf_evlist__get_pollfd,
1090 		.ml_flags = METH_VARARGS | METH_KEYWORDS,
1091 		.ml_doc	  = PyDoc_STR("get the poll file descriptor table.")
1092 	},
1093 	{
1094 		.ml_name  = "add",
1095 		.ml_meth  = (PyCFunction)pyrf_evlist__add,
1096 		.ml_flags = METH_VARARGS | METH_KEYWORDS,
1097 		.ml_doc	  = PyDoc_STR("adds an event selector to the list.")
1098 	},
1099 	{
1100 		.ml_name  = "read_on_cpu",
1101 		.ml_meth  = (PyCFunction)pyrf_evlist__read_on_cpu,
1102 		.ml_flags = METH_VARARGS | METH_KEYWORDS,
1103 		.ml_doc	  = PyDoc_STR("reads an event.")
1104 	},
1105 	{
1106 		.ml_name  = "disable",
1107 		.ml_meth  = (PyCFunction)pyrf_evlist__disable,
1108 		.ml_flags = METH_NOARGS,
1109 		.ml_doc	  = PyDoc_STR("Disable the evsels in the evlist.")
1110 	},
1111 	{
1112 		.ml_name  = "enable",
1113 		.ml_meth  = (PyCFunction)pyrf_evlist__enable,
1114 		.ml_flags = METH_NOARGS,
1115 		.ml_doc	  = PyDoc_STR("Enable the evsels in the evlist.")
1116 	},
1117 	{ .ml_name = NULL, }
1118 };
1119 
1120 static Py_ssize_t pyrf_evlist__length(PyObject *obj)
1121 {
1122 	struct pyrf_evlist *pevlist = (void *)obj;
1123 
1124 	return pevlist->evlist.core.nr_entries;
1125 }
1126 
1127 static PyObject *pyrf_evlist__item(PyObject *obj, Py_ssize_t i)
1128 {
1129 	struct pyrf_evlist *pevlist = (void *)obj;
1130 	struct evsel *pos;
1131 
1132 	if (i >= pevlist->evlist.core.nr_entries) {
1133 		PyErr_SetString(PyExc_IndexError, "Index out of range");
1134 		return NULL;
1135 	}
1136 
1137 	evlist__for_each_entry(&pevlist->evlist, pos) {
1138 		if (i-- == 0)
1139 			break;
1140 	}
1141 
1142 	return Py_BuildValue("O", container_of(pos, struct pyrf_evsel, evsel));
1143 }
1144 
1145 static PyObject *pyrf_evlist__str(PyObject *self)
1146 {
1147 	struct pyrf_evlist *pevlist = (void *)self;
1148 	struct evsel *pos;
1149 	struct strbuf sb = STRBUF_INIT;
1150 	bool first = true;
1151 	PyObject *result;
1152 
1153 	strbuf_addstr(&sb, "evlist([");
1154 	evlist__for_each_entry(&pevlist->evlist, pos) {
1155 		if (!first)
1156 			strbuf_addch(&sb, ',');
1157 		if (!pos->pmu)
1158 			strbuf_addstr(&sb, evsel__name(pos));
1159 		else
1160 			strbuf_addf(&sb, "%s/%s/", pos->pmu->name, evsel__name(pos));
1161 		first = false;
1162 	}
1163 	strbuf_addstr(&sb, "])");
1164 	result = PyUnicode_FromString(sb.buf);
1165 	strbuf_release(&sb);
1166 	return result;
1167 }
1168 
1169 static PySequenceMethods pyrf_evlist__sequence_methods = {
1170 	.sq_length = pyrf_evlist__length,
1171 	.sq_item   = pyrf_evlist__item,
1172 };
1173 
1174 static const char pyrf_evlist__doc[] = PyDoc_STR("perf event selector list object.");
1175 
1176 static PyTypeObject pyrf_evlist__type = {
1177 	PyVarObject_HEAD_INIT(NULL, 0)
1178 	.tp_name	= "perf.evlist",
1179 	.tp_basicsize	= sizeof(struct pyrf_evlist),
1180 	.tp_dealloc	= (destructor)pyrf_evlist__delete,
1181 	.tp_flags	= Py_TPFLAGS_DEFAULT|Py_TPFLAGS_BASETYPE,
1182 	.tp_as_sequence	= &pyrf_evlist__sequence_methods,
1183 	.tp_doc		= pyrf_evlist__doc,
1184 	.tp_methods	= pyrf_evlist__methods,
1185 	.tp_init	= (initproc)pyrf_evlist__init,
1186 	.tp_repr        = pyrf_evlist__str,
1187 	.tp_str         = pyrf_evlist__str,
1188 };
1189 
1190 static int pyrf_evlist__setup_types(void)
1191 {
1192 	pyrf_evlist__type.tp_new = PyType_GenericNew;
1193 	return PyType_Ready(&pyrf_evlist__type);
1194 }
1195 
1196 #define PERF_CONST(name) { #name, PERF_##name }
1197 
1198 struct perf_constant {
1199 	const char *name;
1200 	int	    value;
1201 };
1202 
1203 static const struct perf_constant perf__constants[] = {
1204 	PERF_CONST(TYPE_HARDWARE),
1205 	PERF_CONST(TYPE_SOFTWARE),
1206 	PERF_CONST(TYPE_TRACEPOINT),
1207 	PERF_CONST(TYPE_HW_CACHE),
1208 	PERF_CONST(TYPE_RAW),
1209 	PERF_CONST(TYPE_BREAKPOINT),
1210 
1211 	PERF_CONST(COUNT_HW_CPU_CYCLES),
1212 	PERF_CONST(COUNT_HW_INSTRUCTIONS),
1213 	PERF_CONST(COUNT_HW_CACHE_REFERENCES),
1214 	PERF_CONST(COUNT_HW_CACHE_MISSES),
1215 	PERF_CONST(COUNT_HW_BRANCH_INSTRUCTIONS),
1216 	PERF_CONST(COUNT_HW_BRANCH_MISSES),
1217 	PERF_CONST(COUNT_HW_BUS_CYCLES),
1218 	PERF_CONST(COUNT_HW_CACHE_L1D),
1219 	PERF_CONST(COUNT_HW_CACHE_L1I),
1220 	PERF_CONST(COUNT_HW_CACHE_LL),
1221 	PERF_CONST(COUNT_HW_CACHE_DTLB),
1222 	PERF_CONST(COUNT_HW_CACHE_ITLB),
1223 	PERF_CONST(COUNT_HW_CACHE_BPU),
1224 	PERF_CONST(COUNT_HW_CACHE_OP_READ),
1225 	PERF_CONST(COUNT_HW_CACHE_OP_WRITE),
1226 	PERF_CONST(COUNT_HW_CACHE_OP_PREFETCH),
1227 	PERF_CONST(COUNT_HW_CACHE_RESULT_ACCESS),
1228 	PERF_CONST(COUNT_HW_CACHE_RESULT_MISS),
1229 
1230 	PERF_CONST(COUNT_HW_STALLED_CYCLES_FRONTEND),
1231 	PERF_CONST(COUNT_HW_STALLED_CYCLES_BACKEND),
1232 
1233 	PERF_CONST(COUNT_SW_CPU_CLOCK),
1234 	PERF_CONST(COUNT_SW_TASK_CLOCK),
1235 	PERF_CONST(COUNT_SW_PAGE_FAULTS),
1236 	PERF_CONST(COUNT_SW_CONTEXT_SWITCHES),
1237 	PERF_CONST(COUNT_SW_CPU_MIGRATIONS),
1238 	PERF_CONST(COUNT_SW_PAGE_FAULTS_MIN),
1239 	PERF_CONST(COUNT_SW_PAGE_FAULTS_MAJ),
1240 	PERF_CONST(COUNT_SW_ALIGNMENT_FAULTS),
1241 	PERF_CONST(COUNT_SW_EMULATION_FAULTS),
1242 	PERF_CONST(COUNT_SW_DUMMY),
1243 
1244 	PERF_CONST(SAMPLE_IP),
1245 	PERF_CONST(SAMPLE_TID),
1246 	PERF_CONST(SAMPLE_TIME),
1247 	PERF_CONST(SAMPLE_ADDR),
1248 	PERF_CONST(SAMPLE_READ),
1249 	PERF_CONST(SAMPLE_CALLCHAIN),
1250 	PERF_CONST(SAMPLE_ID),
1251 	PERF_CONST(SAMPLE_CPU),
1252 	PERF_CONST(SAMPLE_PERIOD),
1253 	PERF_CONST(SAMPLE_STREAM_ID),
1254 	PERF_CONST(SAMPLE_RAW),
1255 
1256 	PERF_CONST(FORMAT_TOTAL_TIME_ENABLED),
1257 	PERF_CONST(FORMAT_TOTAL_TIME_RUNNING),
1258 	PERF_CONST(FORMAT_ID),
1259 	PERF_CONST(FORMAT_GROUP),
1260 
1261 	PERF_CONST(RECORD_MMAP),
1262 	PERF_CONST(RECORD_LOST),
1263 	PERF_CONST(RECORD_COMM),
1264 	PERF_CONST(RECORD_EXIT),
1265 	PERF_CONST(RECORD_THROTTLE),
1266 	PERF_CONST(RECORD_UNTHROTTLE),
1267 	PERF_CONST(RECORD_FORK),
1268 	PERF_CONST(RECORD_READ),
1269 	PERF_CONST(RECORD_SAMPLE),
1270 	PERF_CONST(RECORD_MMAP2),
1271 	PERF_CONST(RECORD_AUX),
1272 	PERF_CONST(RECORD_ITRACE_START),
1273 	PERF_CONST(RECORD_LOST_SAMPLES),
1274 	PERF_CONST(RECORD_SWITCH),
1275 	PERF_CONST(RECORD_SWITCH_CPU_WIDE),
1276 
1277 	PERF_CONST(RECORD_MISC_SWITCH_OUT),
1278 	{ .name = NULL, },
1279 };
1280 
1281 static PyObject *pyrf__tracepoint(struct pyrf_evsel *pevsel,
1282 				  PyObject *args, PyObject *kwargs)
1283 {
1284 #ifndef HAVE_LIBTRACEEVENT
1285 	return NULL;
1286 #else
1287 	struct tep_event *tp_format;
1288 	static char *kwlist[] = { "sys", "name", NULL };
1289 	char *sys  = NULL;
1290 	char *name = NULL;
1291 
1292 	if (!PyArg_ParseTupleAndKeywords(args, kwargs, "|ss", kwlist,
1293 					 &sys, &name))
1294 		return NULL;
1295 
1296 	tp_format = trace_event__tp_format(sys, name);
1297 	if (IS_ERR(tp_format))
1298 		return PyLong_FromLong(-1);
1299 
1300 	return PyLong_FromLong(tp_format->id);
1301 #endif // HAVE_LIBTRACEEVENT
1302 }
1303 
1304 static PyObject *pyrf_evsel__from_evsel(struct evsel *evsel)
1305 {
1306 	struct pyrf_evsel *pevsel = PyObject_New(struct pyrf_evsel, &pyrf_evsel__type);
1307 
1308 	if (!pevsel)
1309 		return NULL;
1310 
1311 	memset(&pevsel->evsel, 0, sizeof(pevsel->evsel));
1312 	evsel__init(&pevsel->evsel, &evsel->core.attr, evsel->core.idx);
1313 
1314 	evsel__clone(&pevsel->evsel, evsel);
1315 	return (PyObject *)pevsel;
1316 }
1317 
1318 static PyObject *pyrf_evlist__from_evlist(struct evlist *evlist)
1319 {
1320 	struct pyrf_evlist *pevlist = PyObject_New(struct pyrf_evlist, &pyrf_evlist__type);
1321 	struct evsel *pos;
1322 
1323 	if (!pevlist)
1324 		return NULL;
1325 
1326 	memset(&pevlist->evlist, 0, sizeof(pevlist->evlist));
1327 	evlist__init(&pevlist->evlist, evlist->core.all_cpus, evlist->core.threads);
1328 	evlist__for_each_entry(evlist, pos) {
1329 		struct pyrf_evsel *pevsel = (void *)pyrf_evsel__from_evsel(pos);
1330 
1331 		evlist__add(&pevlist->evlist, &pevsel->evsel);
1332 	}
1333 	return (PyObject *)pevlist;
1334 }
1335 
1336 static PyObject *pyrf__parse_events(PyObject *self, PyObject *args)
1337 {
1338 	const char *input;
1339 	struct evlist evlist = {};
1340 	struct parse_events_error err;
1341 	PyObject *result;
1342 
1343 	if (!PyArg_ParseTuple(args, "s", &input))
1344 		return NULL;
1345 
1346 	parse_events_error__init(&err);
1347 	evlist__init(&evlist, NULL, NULL);
1348 	if (parse_events(&evlist, input, &err)) {
1349 		parse_events_error__print(&err, input);
1350 		PyErr_SetFromErrno(PyExc_OSError);
1351 		return NULL;
1352 	}
1353 	result = pyrf_evlist__from_evlist(&evlist);
1354 	evlist__exit(&evlist);
1355 	return result;
1356 }
1357 
1358 static PyMethodDef perf__methods[] = {
1359 	{
1360 		.ml_name  = "tracepoint",
1361 		.ml_meth  = (PyCFunction) pyrf__tracepoint,
1362 		.ml_flags = METH_VARARGS | METH_KEYWORDS,
1363 		.ml_doc	  = PyDoc_STR("Get tracepoint config.")
1364 	},
1365 	{
1366 		.ml_name  = "parse_events",
1367 		.ml_meth  = (PyCFunction) pyrf__parse_events,
1368 		.ml_flags = METH_VARARGS,
1369 		.ml_doc	  = PyDoc_STR("Parse a string of events and return an evlist.")
1370 	},
1371 	{ .ml_name = NULL, }
1372 };
1373 
1374 PyMODINIT_FUNC PyInit_perf(void)
1375 {
1376 	PyObject *obj;
1377 	int i;
1378 	PyObject *dict;
1379 	static struct PyModuleDef moduledef = {
1380 		PyModuleDef_HEAD_INIT,
1381 		"perf",			/* m_name */
1382 		"",			/* m_doc */
1383 		-1,			/* m_size */
1384 		perf__methods,		/* m_methods */
1385 		NULL,			/* m_reload */
1386 		NULL,			/* m_traverse */
1387 		NULL,			/* m_clear */
1388 		NULL,			/* m_free */
1389 	};
1390 	PyObject *module = PyModule_Create(&moduledef);
1391 
1392 	if (module == NULL ||
1393 	    pyrf_event__setup_types() < 0 ||
1394 	    pyrf_evlist__setup_types() < 0 ||
1395 	    pyrf_evsel__setup_types() < 0 ||
1396 	    pyrf_thread_map__setup_types() < 0 ||
1397 	    pyrf_cpu_map__setup_types() < 0)
1398 		return module;
1399 
1400 	/* The page_size is placed in util object. */
1401 	page_size = sysconf(_SC_PAGE_SIZE);
1402 
1403 	Py_INCREF(&pyrf_evlist__type);
1404 	PyModule_AddObject(module, "evlist", (PyObject*)&pyrf_evlist__type);
1405 
1406 	Py_INCREF(&pyrf_evsel__type);
1407 	PyModule_AddObject(module, "evsel", (PyObject*)&pyrf_evsel__type);
1408 
1409 	Py_INCREF(&pyrf_mmap_event__type);
1410 	PyModule_AddObject(module, "mmap_event", (PyObject *)&pyrf_mmap_event__type);
1411 
1412 	Py_INCREF(&pyrf_lost_event__type);
1413 	PyModule_AddObject(module, "lost_event", (PyObject *)&pyrf_lost_event__type);
1414 
1415 	Py_INCREF(&pyrf_comm_event__type);
1416 	PyModule_AddObject(module, "comm_event", (PyObject *)&pyrf_comm_event__type);
1417 
1418 	Py_INCREF(&pyrf_task_event__type);
1419 	PyModule_AddObject(module, "task_event", (PyObject *)&pyrf_task_event__type);
1420 
1421 	Py_INCREF(&pyrf_throttle_event__type);
1422 	PyModule_AddObject(module, "throttle_event", (PyObject *)&pyrf_throttle_event__type);
1423 
1424 	Py_INCREF(&pyrf_task_event__type);
1425 	PyModule_AddObject(module, "task_event", (PyObject *)&pyrf_task_event__type);
1426 
1427 	Py_INCREF(&pyrf_read_event__type);
1428 	PyModule_AddObject(module, "read_event", (PyObject *)&pyrf_read_event__type);
1429 
1430 	Py_INCREF(&pyrf_sample_event__type);
1431 	PyModule_AddObject(module, "sample_event", (PyObject *)&pyrf_sample_event__type);
1432 
1433 	Py_INCREF(&pyrf_context_switch_event__type);
1434 	PyModule_AddObject(module, "switch_event", (PyObject *)&pyrf_context_switch_event__type);
1435 
1436 	Py_INCREF(&pyrf_thread_map__type);
1437 	PyModule_AddObject(module, "thread_map", (PyObject*)&pyrf_thread_map__type);
1438 
1439 	Py_INCREF(&pyrf_cpu_map__type);
1440 	PyModule_AddObject(module, "cpu_map", (PyObject*)&pyrf_cpu_map__type);
1441 
1442 	dict = PyModule_GetDict(module);
1443 	if (dict == NULL)
1444 		goto error;
1445 
1446 	for (i = 0; perf__constants[i].name != NULL; i++) {
1447 		obj = PyLong_FromLong(perf__constants[i].value);
1448 		if (obj == NULL)
1449 			goto error;
1450 		PyDict_SetItemString(dict, perf__constants[i].name, obj);
1451 		Py_DECREF(obj);
1452 	}
1453 
1454 error:
1455 	if (PyErr_Occurred())
1456 		PyErr_SetString(PyExc_ImportError, "perf: Init failed!");
1457 	return module;
1458 }
1459