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