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