xref: /openbmc/linux/tools/perf/util/evlist.c (revision bef7a78d)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
4  *
5  * Parts came from builtin-{top,stat,record}.c, see those files for further
6  * copyright notes.
7  */
8 #include <api/fs/fs.h>
9 #include <errno.h>
10 #include <inttypes.h>
11 #include <poll.h>
12 #include "cpumap.h"
13 #include "util/mmap.h"
14 #include "thread_map.h"
15 #include "target.h"
16 #include "evlist.h"
17 #include "evsel.h"
18 #include "debug.h"
19 #include "units.h"
20 #include <internal/lib.h> // page_size
21 #include "affinity.h"
22 #include "../perf.h"
23 #include "asm/bug.h"
24 #include "bpf-event.h"
25 #include "util/string2.h"
26 #include "util/perf_api_probe.h"
27 #include <signal.h>
28 #include <unistd.h>
29 #include <sched.h>
30 #include <stdlib.h>
31 
32 #include "parse-events.h"
33 #include <subcmd/parse-options.h>
34 
35 #include <fcntl.h>
36 #include <sys/ioctl.h>
37 #include <sys/mman.h>
38 
39 #include <linux/bitops.h>
40 #include <linux/hash.h>
41 #include <linux/log2.h>
42 #include <linux/err.h>
43 #include <linux/string.h>
44 #include <linux/zalloc.h>
45 #include <perf/evlist.h>
46 #include <perf/evsel.h>
47 #include <perf/cpumap.h>
48 #include <perf/mmap.h>
49 
50 #include <internal/xyarray.h>
51 
52 #ifdef LACKS_SIGQUEUE_PROTOTYPE
53 int sigqueue(pid_t pid, int sig, const union sigval value);
54 #endif
55 
56 #define FD(e, x, y) (*(int *)xyarray__entry(e->core.fd, x, y))
57 #define SID(e, x, y) xyarray__entry(e->core.sample_id, x, y)
58 
59 void evlist__init(struct evlist *evlist, struct perf_cpu_map *cpus,
60 		  struct perf_thread_map *threads)
61 {
62 	perf_evlist__init(&evlist->core);
63 	perf_evlist__set_maps(&evlist->core, cpus, threads);
64 	evlist->workload.pid = -1;
65 	evlist->bkw_mmap_state = BKW_MMAP_NOTREADY;
66 	evlist->ctl_fd.fd = -1;
67 	evlist->ctl_fd.ack = -1;
68 	evlist->ctl_fd.pos = -1;
69 }
70 
71 struct evlist *evlist__new(void)
72 {
73 	struct evlist *evlist = zalloc(sizeof(*evlist));
74 
75 	if (evlist != NULL)
76 		evlist__init(evlist, NULL, NULL);
77 
78 	return evlist;
79 }
80 
81 struct evlist *evlist__new_default(void)
82 {
83 	struct evlist *evlist = evlist__new();
84 
85 	if (evlist && evlist__add_default(evlist)) {
86 		evlist__delete(evlist);
87 		evlist = NULL;
88 	}
89 
90 	return evlist;
91 }
92 
93 struct evlist *evlist__new_dummy(void)
94 {
95 	struct evlist *evlist = evlist__new();
96 
97 	if (evlist && evlist__add_dummy(evlist)) {
98 		evlist__delete(evlist);
99 		evlist = NULL;
100 	}
101 
102 	return evlist;
103 }
104 
105 /**
106  * evlist__set_id_pos - set the positions of event ids.
107  * @evlist: selected event list
108  *
109  * Events with compatible sample types all have the same id_pos
110  * and is_pos.  For convenience, put a copy on evlist.
111  */
112 void evlist__set_id_pos(struct evlist *evlist)
113 {
114 	struct evsel *first = evlist__first(evlist);
115 
116 	evlist->id_pos = first->id_pos;
117 	evlist->is_pos = first->is_pos;
118 }
119 
120 static void evlist__update_id_pos(struct evlist *evlist)
121 {
122 	struct evsel *evsel;
123 
124 	evlist__for_each_entry(evlist, evsel)
125 		evsel__calc_id_pos(evsel);
126 
127 	evlist__set_id_pos(evlist);
128 }
129 
130 static void evlist__purge(struct evlist *evlist)
131 {
132 	struct evsel *pos, *n;
133 
134 	evlist__for_each_entry_safe(evlist, n, pos) {
135 		list_del_init(&pos->core.node);
136 		pos->evlist = NULL;
137 		evsel__delete(pos);
138 	}
139 
140 	evlist->core.nr_entries = 0;
141 }
142 
143 void evlist__exit(struct evlist *evlist)
144 {
145 	zfree(&evlist->mmap);
146 	zfree(&evlist->overwrite_mmap);
147 	perf_evlist__exit(&evlist->core);
148 }
149 
150 void evlist__delete(struct evlist *evlist)
151 {
152 	if (evlist == NULL)
153 		return;
154 
155 	evlist__munmap(evlist);
156 	evlist__close(evlist);
157 	evlist__purge(evlist);
158 	evlist__exit(evlist);
159 	free(evlist);
160 }
161 
162 void evlist__add(struct evlist *evlist, struct evsel *entry)
163 {
164 	entry->evlist = evlist;
165 	entry->idx = evlist->core.nr_entries;
166 	entry->tracking = !entry->idx;
167 
168 	perf_evlist__add(&evlist->core, &entry->core);
169 
170 	if (evlist->core.nr_entries == 1)
171 		evlist__set_id_pos(evlist);
172 }
173 
174 void evlist__remove(struct evlist *evlist, struct evsel *evsel)
175 {
176 	evsel->evlist = NULL;
177 	perf_evlist__remove(&evlist->core, &evsel->core);
178 }
179 
180 void evlist__splice_list_tail(struct evlist *evlist, struct list_head *list)
181 {
182 	while (!list_empty(list)) {
183 		struct evsel *evsel, *temp, *leader = NULL;
184 
185 		__evlist__for_each_entry_safe(list, temp, evsel) {
186 			list_del_init(&evsel->core.node);
187 			evlist__add(evlist, evsel);
188 			leader = evsel;
189 			break;
190 		}
191 
192 		__evlist__for_each_entry_safe(list, temp, evsel) {
193 			if (evsel->leader == leader) {
194 				list_del_init(&evsel->core.node);
195 				evlist__add(evlist, evsel);
196 			}
197 		}
198 	}
199 }
200 
201 int __evlist__set_tracepoints_handlers(struct evlist *evlist,
202 				       const struct evsel_str_handler *assocs, size_t nr_assocs)
203 {
204 	size_t i;
205 	int err;
206 
207 	for (i = 0; i < nr_assocs; i++) {
208 		// Adding a handler for an event not in this evlist, just ignore it.
209 		struct evsel *evsel = evlist__find_tracepoint_by_name(evlist, assocs[i].name);
210 		if (evsel == NULL)
211 			continue;
212 
213 		err = -EEXIST;
214 		if (evsel->handler != NULL)
215 			goto out;
216 		evsel->handler = assocs[i].handler;
217 	}
218 
219 	err = 0;
220 out:
221 	return err;
222 }
223 
224 void __evlist__set_leader(struct list_head *list)
225 {
226 	struct evsel *evsel, *leader;
227 
228 	leader = list_entry(list->next, struct evsel, core.node);
229 	evsel = list_entry(list->prev, struct evsel, core.node);
230 
231 	leader->core.nr_members = evsel->idx - leader->idx + 1;
232 
233 	__evlist__for_each_entry(list, evsel) {
234 		evsel->leader = leader;
235 	}
236 }
237 
238 void evlist__set_leader(struct evlist *evlist)
239 {
240 	if (evlist->core.nr_entries) {
241 		evlist->nr_groups = evlist->core.nr_entries > 1 ? 1 : 0;
242 		__evlist__set_leader(&evlist->core.entries);
243 	}
244 }
245 
246 int __evlist__add_default(struct evlist *evlist, bool precise)
247 {
248 	struct evsel *evsel = evsel__new_cycles(precise);
249 
250 	if (evsel == NULL)
251 		return -ENOMEM;
252 
253 	evlist__add(evlist, evsel);
254 	return 0;
255 }
256 
257 int evlist__add_dummy(struct evlist *evlist)
258 {
259 	struct perf_event_attr attr = {
260 		.type	= PERF_TYPE_SOFTWARE,
261 		.config = PERF_COUNT_SW_DUMMY,
262 		.size	= sizeof(attr), /* to capture ABI version */
263 	};
264 	struct evsel *evsel = evsel__new_idx(&attr, evlist->core.nr_entries);
265 
266 	if (evsel == NULL)
267 		return -ENOMEM;
268 
269 	evlist__add(evlist, evsel);
270 	return 0;
271 }
272 
273 static int evlist__add_attrs(struct evlist *evlist, struct perf_event_attr *attrs, size_t nr_attrs)
274 {
275 	struct evsel *evsel, *n;
276 	LIST_HEAD(head);
277 	size_t i;
278 
279 	for (i = 0; i < nr_attrs; i++) {
280 		evsel = evsel__new_idx(attrs + i, evlist->core.nr_entries + i);
281 		if (evsel == NULL)
282 			goto out_delete_partial_list;
283 		list_add_tail(&evsel->core.node, &head);
284 	}
285 
286 	evlist__splice_list_tail(evlist, &head);
287 
288 	return 0;
289 
290 out_delete_partial_list:
291 	__evlist__for_each_entry_safe(&head, n, evsel)
292 		evsel__delete(evsel);
293 	return -1;
294 }
295 
296 int __evlist__add_default_attrs(struct evlist *evlist, struct perf_event_attr *attrs, size_t nr_attrs)
297 {
298 	size_t i;
299 
300 	for (i = 0; i < nr_attrs; i++)
301 		event_attr_init(attrs + i);
302 
303 	return evlist__add_attrs(evlist, attrs, nr_attrs);
304 }
305 
306 struct evsel *evlist__find_tracepoint_by_id(struct evlist *evlist, int id)
307 {
308 	struct evsel *evsel;
309 
310 	evlist__for_each_entry(evlist, evsel) {
311 		if (evsel->core.attr.type   == PERF_TYPE_TRACEPOINT &&
312 		    (int)evsel->core.attr.config == id)
313 			return evsel;
314 	}
315 
316 	return NULL;
317 }
318 
319 struct evsel *evlist__find_tracepoint_by_name(struct evlist *evlist, const char *name)
320 {
321 	struct evsel *evsel;
322 
323 	evlist__for_each_entry(evlist, evsel) {
324 		if ((evsel->core.attr.type == PERF_TYPE_TRACEPOINT) &&
325 		    (strcmp(evsel->name, name) == 0))
326 			return evsel;
327 	}
328 
329 	return NULL;
330 }
331 
332 int evlist__add_newtp(struct evlist *evlist, const char *sys, const char *name, void *handler)
333 {
334 	struct evsel *evsel = evsel__newtp(sys, name);
335 
336 	if (IS_ERR(evsel))
337 		return -1;
338 
339 	evsel->handler = handler;
340 	evlist__add(evlist, evsel);
341 	return 0;
342 }
343 
344 static int evlist__nr_threads(struct evlist *evlist, struct evsel *evsel)
345 {
346 	if (evsel->core.system_wide)
347 		return 1;
348 	else
349 		return perf_thread_map__nr(evlist->core.threads);
350 }
351 
352 void evlist__cpu_iter_start(struct evlist *evlist)
353 {
354 	struct evsel *pos;
355 
356 	/*
357 	 * Reset the per evsel cpu_iter. This is needed because
358 	 * each evsel's cpumap may have a different index space,
359 	 * and some operations need the index to modify
360 	 * the FD xyarray (e.g. open, close)
361 	 */
362 	evlist__for_each_entry(evlist, pos)
363 		pos->cpu_iter = 0;
364 }
365 
366 bool evsel__cpu_iter_skip_no_inc(struct evsel *ev, int cpu)
367 {
368 	if (ev->cpu_iter >= ev->core.cpus->nr)
369 		return true;
370 	if (cpu >= 0 && ev->core.cpus->map[ev->cpu_iter] != cpu)
371 		return true;
372 	return false;
373 }
374 
375 bool evsel__cpu_iter_skip(struct evsel *ev, int cpu)
376 {
377 	if (!evsel__cpu_iter_skip_no_inc(ev, cpu)) {
378 		ev->cpu_iter++;
379 		return false;
380 	}
381 	return true;
382 }
383 
384 static int evsel__strcmp(struct evsel *pos, char *evsel_name)
385 {
386 	if (!evsel_name)
387 		return 0;
388 	if (evsel__is_dummy_event(pos))
389 		return 1;
390 	return strcmp(pos->name, evsel_name);
391 }
392 
393 static int evlist__is_enabled(struct evlist *evlist)
394 {
395 	struct evsel *pos;
396 
397 	evlist__for_each_entry(evlist, pos) {
398 		if (!evsel__is_group_leader(pos) || !pos->core.fd)
399 			continue;
400 		/* If at least one event is enabled, evlist is enabled. */
401 		if (!pos->disabled)
402 			return true;
403 	}
404 	return false;
405 }
406 
407 static void __evlist__disable(struct evlist *evlist, char *evsel_name)
408 {
409 	struct evsel *pos;
410 	struct affinity affinity;
411 	int cpu, i, imm = 0;
412 	bool has_imm = false;
413 
414 	if (affinity__setup(&affinity) < 0)
415 		return;
416 
417 	/* Disable 'immediate' events last */
418 	for (imm = 0; imm <= 1; imm++) {
419 		evlist__for_each_cpu(evlist, i, cpu) {
420 			affinity__set(&affinity, cpu);
421 
422 			evlist__for_each_entry(evlist, pos) {
423 				if (evsel__strcmp(pos, evsel_name))
424 					continue;
425 				if (evsel__cpu_iter_skip(pos, cpu))
426 					continue;
427 				if (pos->disabled || !evsel__is_group_leader(pos) || !pos->core.fd)
428 					continue;
429 				if (pos->immediate)
430 					has_imm = true;
431 				if (pos->immediate != imm)
432 					continue;
433 				evsel__disable_cpu(pos, pos->cpu_iter - 1);
434 			}
435 		}
436 		if (!has_imm)
437 			break;
438 	}
439 
440 	affinity__cleanup(&affinity);
441 	evlist__for_each_entry(evlist, pos) {
442 		if (evsel__strcmp(pos, evsel_name))
443 			continue;
444 		if (!evsel__is_group_leader(pos) || !pos->core.fd)
445 			continue;
446 		pos->disabled = true;
447 	}
448 
449 	/*
450 	 * If we disabled only single event, we need to check
451 	 * the enabled state of the evlist manually.
452 	 */
453 	if (evsel_name)
454 		evlist->enabled = evlist__is_enabled(evlist);
455 	else
456 		evlist->enabled = false;
457 }
458 
459 void evlist__disable(struct evlist *evlist)
460 {
461 	__evlist__disable(evlist, NULL);
462 }
463 
464 void evlist__disable_evsel(struct evlist *evlist, char *evsel_name)
465 {
466 	__evlist__disable(evlist, evsel_name);
467 }
468 
469 static void __evlist__enable(struct evlist *evlist, char *evsel_name)
470 {
471 	struct evsel *pos;
472 	struct affinity affinity;
473 	int cpu, i;
474 
475 	if (affinity__setup(&affinity) < 0)
476 		return;
477 
478 	evlist__for_each_cpu(evlist, i, cpu) {
479 		affinity__set(&affinity, cpu);
480 
481 		evlist__for_each_entry(evlist, pos) {
482 			if (evsel__strcmp(pos, evsel_name))
483 				continue;
484 			if (evsel__cpu_iter_skip(pos, cpu))
485 				continue;
486 			if (!evsel__is_group_leader(pos) || !pos->core.fd)
487 				continue;
488 			evsel__enable_cpu(pos, pos->cpu_iter - 1);
489 		}
490 	}
491 	affinity__cleanup(&affinity);
492 	evlist__for_each_entry(evlist, pos) {
493 		if (evsel__strcmp(pos, evsel_name))
494 			continue;
495 		if (!evsel__is_group_leader(pos) || !pos->core.fd)
496 			continue;
497 		pos->disabled = false;
498 	}
499 
500 	/*
501 	 * Even single event sets the 'enabled' for evlist,
502 	 * so the toggle can work properly and toggle to
503 	 * 'disabled' state.
504 	 */
505 	evlist->enabled = true;
506 }
507 
508 void evlist__enable(struct evlist *evlist)
509 {
510 	__evlist__enable(evlist, NULL);
511 }
512 
513 void evlist__enable_evsel(struct evlist *evlist, char *evsel_name)
514 {
515 	__evlist__enable(evlist, evsel_name);
516 }
517 
518 void evlist__toggle_enable(struct evlist *evlist)
519 {
520 	(evlist->enabled ? evlist__disable : evlist__enable)(evlist);
521 }
522 
523 static int evlist__enable_event_cpu(struct evlist *evlist, struct evsel *evsel, int cpu)
524 {
525 	int thread;
526 	int nr_threads = evlist__nr_threads(evlist, evsel);
527 
528 	if (!evsel->core.fd)
529 		return -EINVAL;
530 
531 	for (thread = 0; thread < nr_threads; thread++) {
532 		int err = ioctl(FD(evsel, cpu, thread), PERF_EVENT_IOC_ENABLE, 0);
533 		if (err)
534 			return err;
535 	}
536 	return 0;
537 }
538 
539 static int evlist__enable_event_thread(struct evlist *evlist, struct evsel *evsel, int thread)
540 {
541 	int cpu;
542 	int nr_cpus = perf_cpu_map__nr(evlist->core.cpus);
543 
544 	if (!evsel->core.fd)
545 		return -EINVAL;
546 
547 	for (cpu = 0; cpu < nr_cpus; cpu++) {
548 		int err = ioctl(FD(evsel, cpu, thread), PERF_EVENT_IOC_ENABLE, 0);
549 		if (err)
550 			return err;
551 	}
552 	return 0;
553 }
554 
555 int evlist__enable_event_idx(struct evlist *evlist, struct evsel *evsel, int idx)
556 {
557 	bool per_cpu_mmaps = !perf_cpu_map__empty(evlist->core.cpus);
558 
559 	if (per_cpu_mmaps)
560 		return evlist__enable_event_cpu(evlist, evsel, idx);
561 
562 	return evlist__enable_event_thread(evlist, evsel, idx);
563 }
564 
565 int evlist__add_pollfd(struct evlist *evlist, int fd)
566 {
567 	return perf_evlist__add_pollfd(&evlist->core, fd, NULL, POLLIN, fdarray_flag__default);
568 }
569 
570 int evlist__filter_pollfd(struct evlist *evlist, short revents_and_mask)
571 {
572 	return perf_evlist__filter_pollfd(&evlist->core, revents_and_mask);
573 }
574 
575 int evlist__poll(struct evlist *evlist, int timeout)
576 {
577 	return perf_evlist__poll(&evlist->core, timeout);
578 }
579 
580 struct perf_sample_id *evlist__id2sid(struct evlist *evlist, u64 id)
581 {
582 	struct hlist_head *head;
583 	struct perf_sample_id *sid;
584 	int hash;
585 
586 	hash = hash_64(id, PERF_EVLIST__HLIST_BITS);
587 	head = &evlist->core.heads[hash];
588 
589 	hlist_for_each_entry(sid, head, node)
590 		if (sid->id == id)
591 			return sid;
592 
593 	return NULL;
594 }
595 
596 struct evsel *evlist__id2evsel(struct evlist *evlist, u64 id)
597 {
598 	struct perf_sample_id *sid;
599 
600 	if (evlist->core.nr_entries == 1 || !id)
601 		return evlist__first(evlist);
602 
603 	sid = evlist__id2sid(evlist, id);
604 	if (sid)
605 		return container_of(sid->evsel, struct evsel, core);
606 
607 	if (!evlist__sample_id_all(evlist))
608 		return evlist__first(evlist);
609 
610 	return NULL;
611 }
612 
613 struct evsel *evlist__id2evsel_strict(struct evlist *evlist, u64 id)
614 {
615 	struct perf_sample_id *sid;
616 
617 	if (!id)
618 		return NULL;
619 
620 	sid = evlist__id2sid(evlist, id);
621 	if (sid)
622 		return container_of(sid->evsel, struct evsel, core);
623 
624 	return NULL;
625 }
626 
627 static int evlist__event2id(struct evlist *evlist, union perf_event *event, u64 *id)
628 {
629 	const __u64 *array = event->sample.array;
630 	ssize_t n;
631 
632 	n = (event->header.size - sizeof(event->header)) >> 3;
633 
634 	if (event->header.type == PERF_RECORD_SAMPLE) {
635 		if (evlist->id_pos >= n)
636 			return -1;
637 		*id = array[evlist->id_pos];
638 	} else {
639 		if (evlist->is_pos > n)
640 			return -1;
641 		n -= evlist->is_pos;
642 		*id = array[n];
643 	}
644 	return 0;
645 }
646 
647 struct evsel *evlist__event2evsel(struct evlist *evlist, union perf_event *event)
648 {
649 	struct evsel *first = evlist__first(evlist);
650 	struct hlist_head *head;
651 	struct perf_sample_id *sid;
652 	int hash;
653 	u64 id;
654 
655 	if (evlist->core.nr_entries == 1)
656 		return first;
657 
658 	if (!first->core.attr.sample_id_all &&
659 	    event->header.type != PERF_RECORD_SAMPLE)
660 		return first;
661 
662 	if (evlist__event2id(evlist, event, &id))
663 		return NULL;
664 
665 	/* Synthesized events have an id of zero */
666 	if (!id)
667 		return first;
668 
669 	hash = hash_64(id, PERF_EVLIST__HLIST_BITS);
670 	head = &evlist->core.heads[hash];
671 
672 	hlist_for_each_entry(sid, head, node) {
673 		if (sid->id == id)
674 			return container_of(sid->evsel, struct evsel, core);
675 	}
676 	return NULL;
677 }
678 
679 static int evlist__set_paused(struct evlist *evlist, bool value)
680 {
681 	int i;
682 
683 	if (!evlist->overwrite_mmap)
684 		return 0;
685 
686 	for (i = 0; i < evlist->core.nr_mmaps; i++) {
687 		int fd = evlist->overwrite_mmap[i].core.fd;
688 		int err;
689 
690 		if (fd < 0)
691 			continue;
692 		err = ioctl(fd, PERF_EVENT_IOC_PAUSE_OUTPUT, value ? 1 : 0);
693 		if (err)
694 			return err;
695 	}
696 	return 0;
697 }
698 
699 static int evlist__pause(struct evlist *evlist)
700 {
701 	return evlist__set_paused(evlist, true);
702 }
703 
704 static int evlist__resume(struct evlist *evlist)
705 {
706 	return evlist__set_paused(evlist, false);
707 }
708 
709 static void evlist__munmap_nofree(struct evlist *evlist)
710 {
711 	int i;
712 
713 	if (evlist->mmap)
714 		for (i = 0; i < evlist->core.nr_mmaps; i++)
715 			perf_mmap__munmap(&evlist->mmap[i].core);
716 
717 	if (evlist->overwrite_mmap)
718 		for (i = 0; i < evlist->core.nr_mmaps; i++)
719 			perf_mmap__munmap(&evlist->overwrite_mmap[i].core);
720 }
721 
722 void evlist__munmap(struct evlist *evlist)
723 {
724 	evlist__munmap_nofree(evlist);
725 	zfree(&evlist->mmap);
726 	zfree(&evlist->overwrite_mmap);
727 }
728 
729 static void perf_mmap__unmap_cb(struct perf_mmap *map)
730 {
731 	struct mmap *m = container_of(map, struct mmap, core);
732 
733 	mmap__munmap(m);
734 }
735 
736 static struct mmap *evlist__alloc_mmap(struct evlist *evlist,
737 				       bool overwrite)
738 {
739 	int i;
740 	struct mmap *map;
741 
742 	map = zalloc(evlist->core.nr_mmaps * sizeof(struct mmap));
743 	if (!map)
744 		return NULL;
745 
746 	for (i = 0; i < evlist->core.nr_mmaps; i++) {
747 		struct perf_mmap *prev = i ? &map[i - 1].core : NULL;
748 
749 		/*
750 		 * When the perf_mmap() call is made we grab one refcount, plus
751 		 * one extra to let perf_mmap__consume() get the last
752 		 * events after all real references (perf_mmap__get()) are
753 		 * dropped.
754 		 *
755 		 * Each PERF_EVENT_IOC_SET_OUTPUT points to this mmap and
756 		 * thus does perf_mmap__get() on it.
757 		 */
758 		perf_mmap__init(&map[i].core, prev, overwrite, perf_mmap__unmap_cb);
759 	}
760 
761 	return map;
762 }
763 
764 static void
765 perf_evlist__mmap_cb_idx(struct perf_evlist *_evlist,
766 			 struct perf_mmap_param *_mp,
767 			 int idx, bool per_cpu)
768 {
769 	struct evlist *evlist = container_of(_evlist, struct evlist, core);
770 	struct mmap_params *mp = container_of(_mp, struct mmap_params, core);
771 
772 	auxtrace_mmap_params__set_idx(&mp->auxtrace_mp, evlist, idx, per_cpu);
773 }
774 
775 static struct perf_mmap*
776 perf_evlist__mmap_cb_get(struct perf_evlist *_evlist, bool overwrite, int idx)
777 {
778 	struct evlist *evlist = container_of(_evlist, struct evlist, core);
779 	struct mmap *maps;
780 
781 	maps = overwrite ? evlist->overwrite_mmap : evlist->mmap;
782 
783 	if (!maps) {
784 		maps = evlist__alloc_mmap(evlist, overwrite);
785 		if (!maps)
786 			return NULL;
787 
788 		if (overwrite) {
789 			evlist->overwrite_mmap = maps;
790 			if (evlist->bkw_mmap_state == BKW_MMAP_NOTREADY)
791 				evlist__toggle_bkw_mmap(evlist, BKW_MMAP_RUNNING);
792 		} else {
793 			evlist->mmap = maps;
794 		}
795 	}
796 
797 	return &maps[idx].core;
798 }
799 
800 static int
801 perf_evlist__mmap_cb_mmap(struct perf_mmap *_map, struct perf_mmap_param *_mp,
802 			  int output, int cpu)
803 {
804 	struct mmap *map = container_of(_map, struct mmap, core);
805 	struct mmap_params *mp = container_of(_mp, struct mmap_params, core);
806 
807 	return mmap__mmap(map, mp, output, cpu);
808 }
809 
810 unsigned long perf_event_mlock_kb_in_pages(void)
811 {
812 	unsigned long pages;
813 	int max;
814 
815 	if (sysctl__read_int("kernel/perf_event_mlock_kb", &max) < 0) {
816 		/*
817 		 * Pick a once upon a time good value, i.e. things look
818 		 * strange since we can't read a sysctl value, but lets not
819 		 * die yet...
820 		 */
821 		max = 512;
822 	} else {
823 		max -= (page_size / 1024);
824 	}
825 
826 	pages = (max * 1024) / page_size;
827 	if (!is_power_of_2(pages))
828 		pages = rounddown_pow_of_two(pages);
829 
830 	return pages;
831 }
832 
833 size_t evlist__mmap_size(unsigned long pages)
834 {
835 	if (pages == UINT_MAX)
836 		pages = perf_event_mlock_kb_in_pages();
837 	else if (!is_power_of_2(pages))
838 		return 0;
839 
840 	return (pages + 1) * page_size;
841 }
842 
843 static long parse_pages_arg(const char *str, unsigned long min,
844 			    unsigned long max)
845 {
846 	unsigned long pages, val;
847 	static struct parse_tag tags[] = {
848 		{ .tag  = 'B', .mult = 1       },
849 		{ .tag  = 'K', .mult = 1 << 10 },
850 		{ .tag  = 'M', .mult = 1 << 20 },
851 		{ .tag  = 'G', .mult = 1 << 30 },
852 		{ .tag  = 0 },
853 	};
854 
855 	if (str == NULL)
856 		return -EINVAL;
857 
858 	val = parse_tag_value(str, tags);
859 	if (val != (unsigned long) -1) {
860 		/* we got file size value */
861 		pages = PERF_ALIGN(val, page_size) / page_size;
862 	} else {
863 		/* we got pages count value */
864 		char *eptr;
865 		pages = strtoul(str, &eptr, 10);
866 		if (*eptr != '\0')
867 			return -EINVAL;
868 	}
869 
870 	if (pages == 0 && min == 0) {
871 		/* leave number of pages at 0 */
872 	} else if (!is_power_of_2(pages)) {
873 		char buf[100];
874 
875 		/* round pages up to next power of 2 */
876 		pages = roundup_pow_of_two(pages);
877 		if (!pages)
878 			return -EINVAL;
879 
880 		unit_number__scnprintf(buf, sizeof(buf), pages * page_size);
881 		pr_info("rounding mmap pages size to %s (%lu pages)\n",
882 			buf, pages);
883 	}
884 
885 	if (pages > max)
886 		return -EINVAL;
887 
888 	return pages;
889 }
890 
891 int __evlist__parse_mmap_pages(unsigned int *mmap_pages, const char *str)
892 {
893 	unsigned long max = UINT_MAX;
894 	long pages;
895 
896 	if (max > SIZE_MAX / page_size)
897 		max = SIZE_MAX / page_size;
898 
899 	pages = parse_pages_arg(str, 1, max);
900 	if (pages < 0) {
901 		pr_err("Invalid argument for --mmap_pages/-m\n");
902 		return -1;
903 	}
904 
905 	*mmap_pages = pages;
906 	return 0;
907 }
908 
909 int evlist__parse_mmap_pages(const struct option *opt, const char *str, int unset __maybe_unused)
910 {
911 	return __evlist__parse_mmap_pages(opt->value, str);
912 }
913 
914 /**
915  * evlist__mmap_ex - Create mmaps to receive events.
916  * @evlist: list of events
917  * @pages: map length in pages
918  * @overwrite: overwrite older events?
919  * @auxtrace_pages - auxtrace map length in pages
920  * @auxtrace_overwrite - overwrite older auxtrace data?
921  *
922  * If @overwrite is %false the user needs to signal event consumption using
923  * perf_mmap__write_tail().  Using evlist__mmap_read() does this
924  * automatically.
925  *
926  * Similarly, if @auxtrace_overwrite is %false the user needs to signal data
927  * consumption using auxtrace_mmap__write_tail().
928  *
929  * Return: %0 on success, negative error code otherwise.
930  */
931 int evlist__mmap_ex(struct evlist *evlist, unsigned int pages,
932 			 unsigned int auxtrace_pages,
933 			 bool auxtrace_overwrite, int nr_cblocks, int affinity, int flush,
934 			 int comp_level)
935 {
936 	/*
937 	 * Delay setting mp.prot: set it before calling perf_mmap__mmap.
938 	 * Its value is decided by evsel's write_backward.
939 	 * So &mp should not be passed through const pointer.
940 	 */
941 	struct mmap_params mp = {
942 		.nr_cblocks	= nr_cblocks,
943 		.affinity	= affinity,
944 		.flush		= flush,
945 		.comp_level	= comp_level
946 	};
947 	struct perf_evlist_mmap_ops ops = {
948 		.idx  = perf_evlist__mmap_cb_idx,
949 		.get  = perf_evlist__mmap_cb_get,
950 		.mmap = perf_evlist__mmap_cb_mmap,
951 	};
952 
953 	evlist->core.mmap_len = evlist__mmap_size(pages);
954 	pr_debug("mmap size %zuB\n", evlist->core.mmap_len);
955 
956 	auxtrace_mmap_params__init(&mp.auxtrace_mp, evlist->core.mmap_len,
957 				   auxtrace_pages, auxtrace_overwrite);
958 
959 	return perf_evlist__mmap_ops(&evlist->core, &ops, &mp.core);
960 }
961 
962 int evlist__mmap(struct evlist *evlist, unsigned int pages)
963 {
964 	return evlist__mmap_ex(evlist, pages, 0, false, 0, PERF_AFFINITY_SYS, 1, 0);
965 }
966 
967 int evlist__create_maps(struct evlist *evlist, struct target *target)
968 {
969 	bool all_threads = (target->per_thread && target->system_wide);
970 	struct perf_cpu_map *cpus;
971 	struct perf_thread_map *threads;
972 
973 	/*
974 	 * If specify '-a' and '--per-thread' to perf record, perf record
975 	 * will override '--per-thread'. target->per_thread = false and
976 	 * target->system_wide = true.
977 	 *
978 	 * If specify '--per-thread' only to perf record,
979 	 * target->per_thread = true and target->system_wide = false.
980 	 *
981 	 * So target->per_thread && target->system_wide is false.
982 	 * For perf record, thread_map__new_str doesn't call
983 	 * thread_map__new_all_cpus. That will keep perf record's
984 	 * current behavior.
985 	 *
986 	 * For perf stat, it allows the case that target->per_thread and
987 	 * target->system_wide are all true. It means to collect system-wide
988 	 * per-thread data. thread_map__new_str will call
989 	 * thread_map__new_all_cpus to enumerate all threads.
990 	 */
991 	threads = thread_map__new_str(target->pid, target->tid, target->uid,
992 				      all_threads);
993 
994 	if (!threads)
995 		return -1;
996 
997 	if (target__uses_dummy_map(target))
998 		cpus = perf_cpu_map__dummy_new();
999 	else
1000 		cpus = perf_cpu_map__new(target->cpu_list);
1001 
1002 	if (!cpus)
1003 		goto out_delete_threads;
1004 
1005 	evlist->core.has_user_cpus = !!target->cpu_list;
1006 
1007 	perf_evlist__set_maps(&evlist->core, cpus, threads);
1008 
1009 	/* as evlist now has references, put count here */
1010 	perf_cpu_map__put(cpus);
1011 	perf_thread_map__put(threads);
1012 
1013 	return 0;
1014 
1015 out_delete_threads:
1016 	perf_thread_map__put(threads);
1017 	return -1;
1018 }
1019 
1020 int evlist__apply_filters(struct evlist *evlist, struct evsel **err_evsel)
1021 {
1022 	struct evsel *evsel;
1023 	int err = 0;
1024 
1025 	evlist__for_each_entry(evlist, evsel) {
1026 		if (evsel->filter == NULL)
1027 			continue;
1028 
1029 		/*
1030 		 * filters only work for tracepoint event, which doesn't have cpu limit.
1031 		 * So evlist and evsel should always be same.
1032 		 */
1033 		err = perf_evsel__apply_filter(&evsel->core, evsel->filter);
1034 		if (err) {
1035 			*err_evsel = evsel;
1036 			break;
1037 		}
1038 	}
1039 
1040 	return err;
1041 }
1042 
1043 int evlist__set_tp_filter(struct evlist *evlist, const char *filter)
1044 {
1045 	struct evsel *evsel;
1046 	int err = 0;
1047 
1048 	if (filter == NULL)
1049 		return -1;
1050 
1051 	evlist__for_each_entry(evlist, evsel) {
1052 		if (evsel->core.attr.type != PERF_TYPE_TRACEPOINT)
1053 			continue;
1054 
1055 		err = evsel__set_filter(evsel, filter);
1056 		if (err)
1057 			break;
1058 	}
1059 
1060 	return err;
1061 }
1062 
1063 int evlist__append_tp_filter(struct evlist *evlist, const char *filter)
1064 {
1065 	struct evsel *evsel;
1066 	int err = 0;
1067 
1068 	if (filter == NULL)
1069 		return -1;
1070 
1071 	evlist__for_each_entry(evlist, evsel) {
1072 		if (evsel->core.attr.type != PERF_TYPE_TRACEPOINT)
1073 			continue;
1074 
1075 		err = evsel__append_tp_filter(evsel, filter);
1076 		if (err)
1077 			break;
1078 	}
1079 
1080 	return err;
1081 }
1082 
1083 char *asprintf__tp_filter_pids(size_t npids, pid_t *pids)
1084 {
1085 	char *filter;
1086 	size_t i;
1087 
1088 	for (i = 0; i < npids; ++i) {
1089 		if (i == 0) {
1090 			if (asprintf(&filter, "common_pid != %d", pids[i]) < 0)
1091 				return NULL;
1092 		} else {
1093 			char *tmp;
1094 
1095 			if (asprintf(&tmp, "%s && common_pid != %d", filter, pids[i]) < 0)
1096 				goto out_free;
1097 
1098 			free(filter);
1099 			filter = tmp;
1100 		}
1101 	}
1102 
1103 	return filter;
1104 out_free:
1105 	free(filter);
1106 	return NULL;
1107 }
1108 
1109 int evlist__set_tp_filter_pids(struct evlist *evlist, size_t npids, pid_t *pids)
1110 {
1111 	char *filter = asprintf__tp_filter_pids(npids, pids);
1112 	int ret = evlist__set_tp_filter(evlist, filter);
1113 
1114 	free(filter);
1115 	return ret;
1116 }
1117 
1118 int evlist__set_tp_filter_pid(struct evlist *evlist, pid_t pid)
1119 {
1120 	return evlist__set_tp_filter_pids(evlist, 1, &pid);
1121 }
1122 
1123 int evlist__append_tp_filter_pids(struct evlist *evlist, size_t npids, pid_t *pids)
1124 {
1125 	char *filter = asprintf__tp_filter_pids(npids, pids);
1126 	int ret = evlist__append_tp_filter(evlist, filter);
1127 
1128 	free(filter);
1129 	return ret;
1130 }
1131 
1132 int evlist__append_tp_filter_pid(struct evlist *evlist, pid_t pid)
1133 {
1134 	return evlist__append_tp_filter_pids(evlist, 1, &pid);
1135 }
1136 
1137 bool evlist__valid_sample_type(struct evlist *evlist)
1138 {
1139 	struct evsel *pos;
1140 
1141 	if (evlist->core.nr_entries == 1)
1142 		return true;
1143 
1144 	if (evlist->id_pos < 0 || evlist->is_pos < 0)
1145 		return false;
1146 
1147 	evlist__for_each_entry(evlist, pos) {
1148 		if (pos->id_pos != evlist->id_pos ||
1149 		    pos->is_pos != evlist->is_pos)
1150 			return false;
1151 	}
1152 
1153 	return true;
1154 }
1155 
1156 u64 __evlist__combined_sample_type(struct evlist *evlist)
1157 {
1158 	struct evsel *evsel;
1159 
1160 	if (evlist->combined_sample_type)
1161 		return evlist->combined_sample_type;
1162 
1163 	evlist__for_each_entry(evlist, evsel)
1164 		evlist->combined_sample_type |= evsel->core.attr.sample_type;
1165 
1166 	return evlist->combined_sample_type;
1167 }
1168 
1169 u64 evlist__combined_sample_type(struct evlist *evlist)
1170 {
1171 	evlist->combined_sample_type = 0;
1172 	return __evlist__combined_sample_type(evlist);
1173 }
1174 
1175 u64 evlist__combined_branch_type(struct evlist *evlist)
1176 {
1177 	struct evsel *evsel;
1178 	u64 branch_type = 0;
1179 
1180 	evlist__for_each_entry(evlist, evsel)
1181 		branch_type |= evsel->core.attr.branch_sample_type;
1182 	return branch_type;
1183 }
1184 
1185 bool evlist__valid_read_format(struct evlist *evlist)
1186 {
1187 	struct evsel *first = evlist__first(evlist), *pos = first;
1188 	u64 read_format = first->core.attr.read_format;
1189 	u64 sample_type = first->core.attr.sample_type;
1190 
1191 	evlist__for_each_entry(evlist, pos) {
1192 		if (read_format != pos->core.attr.read_format) {
1193 			pr_debug("Read format differs %#" PRIx64 " vs %#" PRIx64 "\n",
1194 				 read_format, (u64)pos->core.attr.read_format);
1195 		}
1196 	}
1197 
1198 	/* PERF_SAMPLE_READ imples PERF_FORMAT_ID. */
1199 	if ((sample_type & PERF_SAMPLE_READ) &&
1200 	    !(read_format & PERF_FORMAT_ID)) {
1201 		return false;
1202 	}
1203 
1204 	return true;
1205 }
1206 
1207 u16 evlist__id_hdr_size(struct evlist *evlist)
1208 {
1209 	struct evsel *first = evlist__first(evlist);
1210 	struct perf_sample *data;
1211 	u64 sample_type;
1212 	u16 size = 0;
1213 
1214 	if (!first->core.attr.sample_id_all)
1215 		goto out;
1216 
1217 	sample_type = first->core.attr.sample_type;
1218 
1219 	if (sample_type & PERF_SAMPLE_TID)
1220 		size += sizeof(data->tid) * 2;
1221 
1222        if (sample_type & PERF_SAMPLE_TIME)
1223 		size += sizeof(data->time);
1224 
1225 	if (sample_type & PERF_SAMPLE_ID)
1226 		size += sizeof(data->id);
1227 
1228 	if (sample_type & PERF_SAMPLE_STREAM_ID)
1229 		size += sizeof(data->stream_id);
1230 
1231 	if (sample_type & PERF_SAMPLE_CPU)
1232 		size += sizeof(data->cpu) * 2;
1233 
1234 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
1235 		size += sizeof(data->id);
1236 out:
1237 	return size;
1238 }
1239 
1240 bool evlist__valid_sample_id_all(struct evlist *evlist)
1241 {
1242 	struct evsel *first = evlist__first(evlist), *pos = first;
1243 
1244 	evlist__for_each_entry_continue(evlist, pos) {
1245 		if (first->core.attr.sample_id_all != pos->core.attr.sample_id_all)
1246 			return false;
1247 	}
1248 
1249 	return true;
1250 }
1251 
1252 bool evlist__sample_id_all(struct evlist *evlist)
1253 {
1254 	struct evsel *first = evlist__first(evlist);
1255 	return first->core.attr.sample_id_all;
1256 }
1257 
1258 void evlist__set_selected(struct evlist *evlist, struct evsel *evsel)
1259 {
1260 	evlist->selected = evsel;
1261 }
1262 
1263 void evlist__close(struct evlist *evlist)
1264 {
1265 	struct evsel *evsel;
1266 	struct affinity affinity;
1267 	int cpu, i;
1268 
1269 	/*
1270 	 * With perf record core.cpus is usually NULL.
1271 	 * Use the old method to handle this for now.
1272 	 */
1273 	if (!evlist->core.cpus) {
1274 		evlist__for_each_entry_reverse(evlist, evsel)
1275 			evsel__close(evsel);
1276 		return;
1277 	}
1278 
1279 	if (affinity__setup(&affinity) < 0)
1280 		return;
1281 	evlist__for_each_cpu(evlist, i, cpu) {
1282 		affinity__set(&affinity, cpu);
1283 
1284 		evlist__for_each_entry_reverse(evlist, evsel) {
1285 			if (evsel__cpu_iter_skip(evsel, cpu))
1286 			    continue;
1287 			perf_evsel__close_cpu(&evsel->core, evsel->cpu_iter - 1);
1288 		}
1289 	}
1290 	affinity__cleanup(&affinity);
1291 	evlist__for_each_entry_reverse(evlist, evsel) {
1292 		perf_evsel__free_fd(&evsel->core);
1293 		perf_evsel__free_id(&evsel->core);
1294 	}
1295 }
1296 
1297 static int evlist__create_syswide_maps(struct evlist *evlist)
1298 {
1299 	struct perf_cpu_map *cpus;
1300 	struct perf_thread_map *threads;
1301 	int err = -ENOMEM;
1302 
1303 	/*
1304 	 * Try reading /sys/devices/system/cpu/online to get
1305 	 * an all cpus map.
1306 	 *
1307 	 * FIXME: -ENOMEM is the best we can do here, the cpu_map
1308 	 * code needs an overhaul to properly forward the
1309 	 * error, and we may not want to do that fallback to a
1310 	 * default cpu identity map :-\
1311 	 */
1312 	cpus = perf_cpu_map__new(NULL);
1313 	if (!cpus)
1314 		goto out;
1315 
1316 	threads = perf_thread_map__new_dummy();
1317 	if (!threads)
1318 		goto out_put;
1319 
1320 	perf_evlist__set_maps(&evlist->core, cpus, threads);
1321 
1322 	perf_thread_map__put(threads);
1323 out_put:
1324 	perf_cpu_map__put(cpus);
1325 out:
1326 	return err;
1327 }
1328 
1329 int evlist__open(struct evlist *evlist)
1330 {
1331 	struct evsel *evsel;
1332 	int err;
1333 
1334 	/*
1335 	 * Default: one fd per CPU, all threads, aka systemwide
1336 	 * as sys_perf_event_open(cpu = -1, thread = -1) is EINVAL
1337 	 */
1338 	if (evlist->core.threads == NULL && evlist->core.cpus == NULL) {
1339 		err = evlist__create_syswide_maps(evlist);
1340 		if (err < 0)
1341 			goto out_err;
1342 	}
1343 
1344 	evlist__update_id_pos(evlist);
1345 
1346 	evlist__for_each_entry(evlist, evsel) {
1347 		err = evsel__open(evsel, evsel->core.cpus, evsel->core.threads);
1348 		if (err < 0)
1349 			goto out_err;
1350 	}
1351 
1352 	return 0;
1353 out_err:
1354 	evlist__close(evlist);
1355 	errno = -err;
1356 	return err;
1357 }
1358 
1359 int evlist__prepare_workload(struct evlist *evlist, struct target *target, const char *argv[],
1360 			     bool pipe_output, void (*exec_error)(int signo, siginfo_t *info, void *ucontext))
1361 {
1362 	int child_ready_pipe[2], go_pipe[2];
1363 	char bf;
1364 
1365 	if (pipe(child_ready_pipe) < 0) {
1366 		perror("failed to create 'ready' pipe");
1367 		return -1;
1368 	}
1369 
1370 	if (pipe(go_pipe) < 0) {
1371 		perror("failed to create 'go' pipe");
1372 		goto out_close_ready_pipe;
1373 	}
1374 
1375 	evlist->workload.pid = fork();
1376 	if (evlist->workload.pid < 0) {
1377 		perror("failed to fork");
1378 		goto out_close_pipes;
1379 	}
1380 
1381 	if (!evlist->workload.pid) {
1382 		int ret;
1383 
1384 		if (pipe_output)
1385 			dup2(2, 1);
1386 
1387 		signal(SIGTERM, SIG_DFL);
1388 
1389 		close(child_ready_pipe[0]);
1390 		close(go_pipe[1]);
1391 		fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
1392 
1393 		/*
1394 		 * Tell the parent we're ready to go
1395 		 */
1396 		close(child_ready_pipe[1]);
1397 
1398 		/*
1399 		 * Wait until the parent tells us to go.
1400 		 */
1401 		ret = read(go_pipe[0], &bf, 1);
1402 		/*
1403 		 * The parent will ask for the execvp() to be performed by
1404 		 * writing exactly one byte, in workload.cork_fd, usually via
1405 		 * evlist__start_workload().
1406 		 *
1407 		 * For cancelling the workload without actually running it,
1408 		 * the parent will just close workload.cork_fd, without writing
1409 		 * anything, i.e. read will return zero and we just exit()
1410 		 * here.
1411 		 */
1412 		if (ret != 1) {
1413 			if (ret == -1)
1414 				perror("unable to read pipe");
1415 			exit(ret);
1416 		}
1417 
1418 		execvp(argv[0], (char **)argv);
1419 
1420 		if (exec_error) {
1421 			union sigval val;
1422 
1423 			val.sival_int = errno;
1424 			if (sigqueue(getppid(), SIGUSR1, val))
1425 				perror(argv[0]);
1426 		} else
1427 			perror(argv[0]);
1428 		exit(-1);
1429 	}
1430 
1431 	if (exec_error) {
1432 		struct sigaction act = {
1433 			.sa_flags     = SA_SIGINFO,
1434 			.sa_sigaction = exec_error,
1435 		};
1436 		sigaction(SIGUSR1, &act, NULL);
1437 	}
1438 
1439 	if (target__none(target)) {
1440 		if (evlist->core.threads == NULL) {
1441 			fprintf(stderr, "FATAL: evlist->threads need to be set at this point (%s:%d).\n",
1442 				__func__, __LINE__);
1443 			goto out_close_pipes;
1444 		}
1445 		perf_thread_map__set_pid(evlist->core.threads, 0, evlist->workload.pid);
1446 	}
1447 
1448 	close(child_ready_pipe[1]);
1449 	close(go_pipe[0]);
1450 	/*
1451 	 * wait for child to settle
1452 	 */
1453 	if (read(child_ready_pipe[0], &bf, 1) == -1) {
1454 		perror("unable to read pipe");
1455 		goto out_close_pipes;
1456 	}
1457 
1458 	fcntl(go_pipe[1], F_SETFD, FD_CLOEXEC);
1459 	evlist->workload.cork_fd = go_pipe[1];
1460 	close(child_ready_pipe[0]);
1461 	return 0;
1462 
1463 out_close_pipes:
1464 	close(go_pipe[0]);
1465 	close(go_pipe[1]);
1466 out_close_ready_pipe:
1467 	close(child_ready_pipe[0]);
1468 	close(child_ready_pipe[1]);
1469 	return -1;
1470 }
1471 
1472 int evlist__start_workload(struct evlist *evlist)
1473 {
1474 	if (evlist->workload.cork_fd > 0) {
1475 		char bf = 0;
1476 		int ret;
1477 		/*
1478 		 * Remove the cork, let it rip!
1479 		 */
1480 		ret = write(evlist->workload.cork_fd, &bf, 1);
1481 		if (ret < 0)
1482 			perror("unable to write to pipe");
1483 
1484 		close(evlist->workload.cork_fd);
1485 		return ret;
1486 	}
1487 
1488 	return 0;
1489 }
1490 
1491 int evlist__parse_sample(struct evlist *evlist, union perf_event *event, struct perf_sample *sample)
1492 {
1493 	struct evsel *evsel = evlist__event2evsel(evlist, event);
1494 
1495 	if (!evsel)
1496 		return -EFAULT;
1497 	return evsel__parse_sample(evsel, event, sample);
1498 }
1499 
1500 int evlist__parse_sample_timestamp(struct evlist *evlist, union perf_event *event, u64 *timestamp)
1501 {
1502 	struct evsel *evsel = evlist__event2evsel(evlist, event);
1503 
1504 	if (!evsel)
1505 		return -EFAULT;
1506 	return evsel__parse_sample_timestamp(evsel, event, timestamp);
1507 }
1508 
1509 int evlist__strerror_open(struct evlist *evlist, int err, char *buf, size_t size)
1510 {
1511 	int printed, value;
1512 	char sbuf[STRERR_BUFSIZE], *emsg = str_error_r(err, sbuf, sizeof(sbuf));
1513 
1514 	switch (err) {
1515 	case EACCES:
1516 	case EPERM:
1517 		printed = scnprintf(buf, size,
1518 				    "Error:\t%s.\n"
1519 				    "Hint:\tCheck /proc/sys/kernel/perf_event_paranoid setting.", emsg);
1520 
1521 		value = perf_event_paranoid();
1522 
1523 		printed += scnprintf(buf + printed, size - printed, "\nHint:\t");
1524 
1525 		if (value >= 2) {
1526 			printed += scnprintf(buf + printed, size - printed,
1527 					     "For your workloads it needs to be <= 1\nHint:\t");
1528 		}
1529 		printed += scnprintf(buf + printed, size - printed,
1530 				     "For system wide tracing it needs to be set to -1.\n");
1531 
1532 		printed += scnprintf(buf + printed, size - printed,
1533 				    "Hint:\tTry: 'sudo sh -c \"echo -1 > /proc/sys/kernel/perf_event_paranoid\"'\n"
1534 				    "Hint:\tThe current value is %d.", value);
1535 		break;
1536 	case EINVAL: {
1537 		struct evsel *first = evlist__first(evlist);
1538 		int max_freq;
1539 
1540 		if (sysctl__read_int("kernel/perf_event_max_sample_rate", &max_freq) < 0)
1541 			goto out_default;
1542 
1543 		if (first->core.attr.sample_freq < (u64)max_freq)
1544 			goto out_default;
1545 
1546 		printed = scnprintf(buf, size,
1547 				    "Error:\t%s.\n"
1548 				    "Hint:\tCheck /proc/sys/kernel/perf_event_max_sample_rate.\n"
1549 				    "Hint:\tThe current value is %d and %" PRIu64 " is being requested.",
1550 				    emsg, max_freq, first->core.attr.sample_freq);
1551 		break;
1552 	}
1553 	default:
1554 out_default:
1555 		scnprintf(buf, size, "%s", emsg);
1556 		break;
1557 	}
1558 
1559 	return 0;
1560 }
1561 
1562 int evlist__strerror_mmap(struct evlist *evlist, int err, char *buf, size_t size)
1563 {
1564 	char sbuf[STRERR_BUFSIZE], *emsg = str_error_r(err, sbuf, sizeof(sbuf));
1565 	int pages_attempted = evlist->core.mmap_len / 1024, pages_max_per_user, printed = 0;
1566 
1567 	switch (err) {
1568 	case EPERM:
1569 		sysctl__read_int("kernel/perf_event_mlock_kb", &pages_max_per_user);
1570 		printed += scnprintf(buf + printed, size - printed,
1571 				     "Error:\t%s.\n"
1572 				     "Hint:\tCheck /proc/sys/kernel/perf_event_mlock_kb (%d kB) setting.\n"
1573 				     "Hint:\tTried using %zd kB.\n",
1574 				     emsg, pages_max_per_user, pages_attempted);
1575 
1576 		if (pages_attempted >= pages_max_per_user) {
1577 			printed += scnprintf(buf + printed, size - printed,
1578 					     "Hint:\tTry 'sudo sh -c \"echo %d > /proc/sys/kernel/perf_event_mlock_kb\"', or\n",
1579 					     pages_max_per_user + pages_attempted);
1580 		}
1581 
1582 		printed += scnprintf(buf + printed, size - printed,
1583 				     "Hint:\tTry using a smaller -m/--mmap-pages value.");
1584 		break;
1585 	default:
1586 		scnprintf(buf, size, "%s", emsg);
1587 		break;
1588 	}
1589 
1590 	return 0;
1591 }
1592 
1593 void evlist__to_front(struct evlist *evlist, struct evsel *move_evsel)
1594 {
1595 	struct evsel *evsel, *n;
1596 	LIST_HEAD(move);
1597 
1598 	if (move_evsel == evlist__first(evlist))
1599 		return;
1600 
1601 	evlist__for_each_entry_safe(evlist, n, evsel) {
1602 		if (evsel->leader == move_evsel->leader)
1603 			list_move_tail(&evsel->core.node, &move);
1604 	}
1605 
1606 	list_splice(&move, &evlist->core.entries);
1607 }
1608 
1609 struct evsel *evlist__get_tracking_event(struct evlist *evlist)
1610 {
1611 	struct evsel *evsel;
1612 
1613 	evlist__for_each_entry(evlist, evsel) {
1614 		if (evsel->tracking)
1615 			return evsel;
1616 	}
1617 
1618 	return evlist__first(evlist);
1619 }
1620 
1621 void evlist__set_tracking_event(struct evlist *evlist, struct evsel *tracking_evsel)
1622 {
1623 	struct evsel *evsel;
1624 
1625 	if (tracking_evsel->tracking)
1626 		return;
1627 
1628 	evlist__for_each_entry(evlist, evsel) {
1629 		if (evsel != tracking_evsel)
1630 			evsel->tracking = false;
1631 	}
1632 
1633 	tracking_evsel->tracking = true;
1634 }
1635 
1636 struct evsel *evlist__find_evsel_by_str(struct evlist *evlist, const char *str)
1637 {
1638 	struct evsel *evsel;
1639 
1640 	evlist__for_each_entry(evlist, evsel) {
1641 		if (!evsel->name)
1642 			continue;
1643 		if (strcmp(str, evsel->name) == 0)
1644 			return evsel;
1645 	}
1646 
1647 	return NULL;
1648 }
1649 
1650 void evlist__toggle_bkw_mmap(struct evlist *evlist, enum bkw_mmap_state state)
1651 {
1652 	enum bkw_mmap_state old_state = evlist->bkw_mmap_state;
1653 	enum action {
1654 		NONE,
1655 		PAUSE,
1656 		RESUME,
1657 	} action = NONE;
1658 
1659 	if (!evlist->overwrite_mmap)
1660 		return;
1661 
1662 	switch (old_state) {
1663 	case BKW_MMAP_NOTREADY: {
1664 		if (state != BKW_MMAP_RUNNING)
1665 			goto state_err;
1666 		break;
1667 	}
1668 	case BKW_MMAP_RUNNING: {
1669 		if (state != BKW_MMAP_DATA_PENDING)
1670 			goto state_err;
1671 		action = PAUSE;
1672 		break;
1673 	}
1674 	case BKW_MMAP_DATA_PENDING: {
1675 		if (state != BKW_MMAP_EMPTY)
1676 			goto state_err;
1677 		break;
1678 	}
1679 	case BKW_MMAP_EMPTY: {
1680 		if (state != BKW_MMAP_RUNNING)
1681 			goto state_err;
1682 		action = RESUME;
1683 		break;
1684 	}
1685 	default:
1686 		WARN_ONCE(1, "Shouldn't get there\n");
1687 	}
1688 
1689 	evlist->bkw_mmap_state = state;
1690 
1691 	switch (action) {
1692 	case PAUSE:
1693 		evlist__pause(evlist);
1694 		break;
1695 	case RESUME:
1696 		evlist__resume(evlist);
1697 		break;
1698 	case NONE:
1699 	default:
1700 		break;
1701 	}
1702 
1703 state_err:
1704 	return;
1705 }
1706 
1707 bool evlist__exclude_kernel(struct evlist *evlist)
1708 {
1709 	struct evsel *evsel;
1710 
1711 	evlist__for_each_entry(evlist, evsel) {
1712 		if (!evsel->core.attr.exclude_kernel)
1713 			return false;
1714 	}
1715 
1716 	return true;
1717 }
1718 
1719 /*
1720  * Events in data file are not collect in groups, but we still want
1721  * the group display. Set the artificial group and set the leader's
1722  * forced_leader flag to notify the display code.
1723  */
1724 void evlist__force_leader(struct evlist *evlist)
1725 {
1726 	if (!evlist->nr_groups) {
1727 		struct evsel *leader = evlist__first(evlist);
1728 
1729 		evlist__set_leader(evlist);
1730 		leader->forced_leader = true;
1731 	}
1732 }
1733 
1734 struct evsel *evlist__reset_weak_group(struct evlist *evsel_list, struct evsel *evsel, bool close)
1735 {
1736 	struct evsel *c2, *leader;
1737 	bool is_open = true;
1738 
1739 	leader = evsel->leader;
1740 	pr_debug("Weak group for %s/%d failed\n",
1741 			leader->name, leader->core.nr_members);
1742 
1743 	/*
1744 	 * for_each_group_member doesn't work here because it doesn't
1745 	 * include the first entry.
1746 	 */
1747 	evlist__for_each_entry(evsel_list, c2) {
1748 		if (c2 == evsel)
1749 			is_open = false;
1750 		if (c2->leader == leader) {
1751 			if (is_open && close)
1752 				perf_evsel__close(&c2->core);
1753 			c2->leader = c2;
1754 			c2->core.nr_members = 0;
1755 			/*
1756 			 * Set this for all former members of the group
1757 			 * to indicate they get reopened.
1758 			 */
1759 			c2->reset_group = true;
1760 		}
1761 	}
1762 	return leader;
1763 }
1764 
1765 static int evlist__parse_control_fifo(const char *str, int *ctl_fd, int *ctl_fd_ack, bool *ctl_fd_close)
1766 {
1767 	char *s, *p;
1768 	int ret = 0, fd;
1769 
1770 	if (strncmp(str, "fifo:", 5))
1771 		return -EINVAL;
1772 
1773 	str += 5;
1774 	if (!*str || *str == ',')
1775 		return -EINVAL;
1776 
1777 	s = strdup(str);
1778 	if (!s)
1779 		return -ENOMEM;
1780 
1781 	p = strchr(s, ',');
1782 	if (p)
1783 		*p = '\0';
1784 
1785 	/*
1786 	 * O_RDWR avoids POLLHUPs which is necessary to allow the other
1787 	 * end of a FIFO to be repeatedly opened and closed.
1788 	 */
1789 	fd = open(s, O_RDWR | O_NONBLOCK | O_CLOEXEC);
1790 	if (fd < 0) {
1791 		pr_err("Failed to open '%s'\n", s);
1792 		ret = -errno;
1793 		goto out_free;
1794 	}
1795 	*ctl_fd = fd;
1796 	*ctl_fd_close = true;
1797 
1798 	if (p && *++p) {
1799 		/* O_RDWR | O_NONBLOCK means the other end need not be open */
1800 		fd = open(p, O_RDWR | O_NONBLOCK | O_CLOEXEC);
1801 		if (fd < 0) {
1802 			pr_err("Failed to open '%s'\n", p);
1803 			ret = -errno;
1804 			goto out_free;
1805 		}
1806 		*ctl_fd_ack = fd;
1807 	}
1808 
1809 out_free:
1810 	free(s);
1811 	return ret;
1812 }
1813 
1814 int evlist__parse_control(const char *str, int *ctl_fd, int *ctl_fd_ack, bool *ctl_fd_close)
1815 {
1816 	char *comma = NULL, *endptr = NULL;
1817 
1818 	*ctl_fd_close = false;
1819 
1820 	if (strncmp(str, "fd:", 3))
1821 		return evlist__parse_control_fifo(str, ctl_fd, ctl_fd_ack, ctl_fd_close);
1822 
1823 	*ctl_fd = strtoul(&str[3], &endptr, 0);
1824 	if (endptr == &str[3])
1825 		return -EINVAL;
1826 
1827 	comma = strchr(str, ',');
1828 	if (comma) {
1829 		if (endptr != comma)
1830 			return -EINVAL;
1831 
1832 		*ctl_fd_ack = strtoul(comma + 1, &endptr, 0);
1833 		if (endptr == comma + 1 || *endptr != '\0')
1834 			return -EINVAL;
1835 	}
1836 
1837 	return 0;
1838 }
1839 
1840 void evlist__close_control(int ctl_fd, int ctl_fd_ack, bool *ctl_fd_close)
1841 {
1842 	if (*ctl_fd_close) {
1843 		*ctl_fd_close = false;
1844 		close(ctl_fd);
1845 		if (ctl_fd_ack >= 0)
1846 			close(ctl_fd_ack);
1847 	}
1848 }
1849 
1850 int evlist__initialize_ctlfd(struct evlist *evlist, int fd, int ack)
1851 {
1852 	if (fd == -1) {
1853 		pr_debug("Control descriptor is not initialized\n");
1854 		return 0;
1855 	}
1856 
1857 	evlist->ctl_fd.pos = perf_evlist__add_pollfd(&evlist->core, fd, NULL, POLLIN,
1858 						     fdarray_flag__nonfilterable);
1859 	if (evlist->ctl_fd.pos < 0) {
1860 		evlist->ctl_fd.pos = -1;
1861 		pr_err("Failed to add ctl fd entry: %m\n");
1862 		return -1;
1863 	}
1864 
1865 	evlist->ctl_fd.fd = fd;
1866 	evlist->ctl_fd.ack = ack;
1867 
1868 	return 0;
1869 }
1870 
1871 bool evlist__ctlfd_initialized(struct evlist *evlist)
1872 {
1873 	return evlist->ctl_fd.pos >= 0;
1874 }
1875 
1876 int evlist__finalize_ctlfd(struct evlist *evlist)
1877 {
1878 	struct pollfd *entries = evlist->core.pollfd.entries;
1879 
1880 	if (!evlist__ctlfd_initialized(evlist))
1881 		return 0;
1882 
1883 	entries[evlist->ctl_fd.pos].fd = -1;
1884 	entries[evlist->ctl_fd.pos].events = 0;
1885 	entries[evlist->ctl_fd.pos].revents = 0;
1886 
1887 	evlist->ctl_fd.pos = -1;
1888 	evlist->ctl_fd.ack = -1;
1889 	evlist->ctl_fd.fd = -1;
1890 
1891 	return 0;
1892 }
1893 
1894 static int evlist__ctlfd_recv(struct evlist *evlist, enum evlist_ctl_cmd *cmd,
1895 			      char *cmd_data, size_t data_size)
1896 {
1897 	int err;
1898 	char c;
1899 	size_t bytes_read = 0;
1900 
1901 	*cmd = EVLIST_CTL_CMD_UNSUPPORTED;
1902 	memset(cmd_data, 0, data_size);
1903 	data_size--;
1904 
1905 	do {
1906 		err = read(evlist->ctl_fd.fd, &c, 1);
1907 		if (err > 0) {
1908 			if (c == '\n' || c == '\0')
1909 				break;
1910 			cmd_data[bytes_read++] = c;
1911 			if (bytes_read == data_size)
1912 				break;
1913 			continue;
1914 		} else if (err == -1) {
1915 			if (errno == EINTR)
1916 				continue;
1917 			if (errno == EAGAIN || errno == EWOULDBLOCK)
1918 				err = 0;
1919 			else
1920 				pr_err("Failed to read from ctlfd %d: %m\n", evlist->ctl_fd.fd);
1921 		}
1922 		break;
1923 	} while (1);
1924 
1925 	pr_debug("Message from ctl_fd: \"%s%s\"\n", cmd_data,
1926 		 bytes_read == data_size ? "" : c == '\n' ? "\\n" : "\\0");
1927 
1928 	if (bytes_read > 0) {
1929 		if (!strncmp(cmd_data, EVLIST_CTL_CMD_ENABLE_TAG,
1930 			     (sizeof(EVLIST_CTL_CMD_ENABLE_TAG)-1))) {
1931 			*cmd = EVLIST_CTL_CMD_ENABLE;
1932 		} else if (!strncmp(cmd_data, EVLIST_CTL_CMD_DISABLE_TAG,
1933 				    (sizeof(EVLIST_CTL_CMD_DISABLE_TAG)-1))) {
1934 			*cmd = EVLIST_CTL_CMD_DISABLE;
1935 		} else if (!strncmp(cmd_data, EVLIST_CTL_CMD_SNAPSHOT_TAG,
1936 				    (sizeof(EVLIST_CTL_CMD_SNAPSHOT_TAG)-1))) {
1937 			*cmd = EVLIST_CTL_CMD_SNAPSHOT;
1938 			pr_debug("is snapshot\n");
1939 		}
1940 	}
1941 
1942 	return bytes_read ? (int)bytes_read : err;
1943 }
1944 
1945 int evlist__ctlfd_ack(struct evlist *evlist)
1946 {
1947 	int err;
1948 
1949 	if (evlist->ctl_fd.ack == -1)
1950 		return 0;
1951 
1952 	err = write(evlist->ctl_fd.ack, EVLIST_CTL_CMD_ACK_TAG,
1953 		    sizeof(EVLIST_CTL_CMD_ACK_TAG));
1954 	if (err == -1)
1955 		pr_err("failed to write to ctl_ack_fd %d: %m\n", evlist->ctl_fd.ack);
1956 
1957 	return err;
1958 }
1959 
1960 int evlist__ctlfd_process(struct evlist *evlist, enum evlist_ctl_cmd *cmd)
1961 {
1962 	int err = 0;
1963 	char cmd_data[EVLIST_CTL_CMD_MAX_LEN];
1964 	int ctlfd_pos = evlist->ctl_fd.pos;
1965 	struct pollfd *entries = evlist->core.pollfd.entries;
1966 
1967 	if (!evlist__ctlfd_initialized(evlist) || !entries[ctlfd_pos].revents)
1968 		return 0;
1969 
1970 	if (entries[ctlfd_pos].revents & POLLIN) {
1971 		err = evlist__ctlfd_recv(evlist, cmd, cmd_data,
1972 					 EVLIST_CTL_CMD_MAX_LEN);
1973 		if (err > 0) {
1974 			switch (*cmd) {
1975 			case EVLIST_CTL_CMD_ENABLE:
1976 				evlist__enable(evlist);
1977 				break;
1978 			case EVLIST_CTL_CMD_DISABLE:
1979 				evlist__disable(evlist);
1980 				break;
1981 			case EVLIST_CTL_CMD_SNAPSHOT:
1982 				break;
1983 			case EVLIST_CTL_CMD_ACK:
1984 			case EVLIST_CTL_CMD_UNSUPPORTED:
1985 			default:
1986 				pr_debug("ctlfd: unsupported %d\n", *cmd);
1987 				break;
1988 			}
1989 			if (!(*cmd == EVLIST_CTL_CMD_ACK || *cmd == EVLIST_CTL_CMD_UNSUPPORTED ||
1990 			      *cmd == EVLIST_CTL_CMD_SNAPSHOT))
1991 				evlist__ctlfd_ack(evlist);
1992 		}
1993 	}
1994 
1995 	if (entries[ctlfd_pos].revents & (POLLHUP | POLLERR))
1996 		evlist__finalize_ctlfd(evlist);
1997 	else
1998 		entries[ctlfd_pos].revents = 0;
1999 
2000 	return err;
2001 }
2002 
2003 struct evsel *evlist__find_evsel(struct evlist *evlist, int idx)
2004 {
2005 	struct evsel *evsel;
2006 
2007 	evlist__for_each_entry(evlist, evsel) {
2008 		if (evsel->idx == idx)
2009 			return evsel;
2010 	}
2011 	return NULL;
2012 }
2013