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