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