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