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