perf evlist: Change evlist__splice_list_tail() ordering
[linux-2.6-microblaze.git] / tools / perf / util / evlist.c
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 void evlist__disable(struct evlist *evlist)
385 {
386         struct evsel *pos;
387         struct affinity affinity;
388         int cpu, i, imm = 0;
389         bool has_imm = false;
390
391         if (affinity__setup(&affinity) < 0)
392                 return;
393
394         /* Disable 'immediate' events last */
395         for (imm = 0; imm <= 1; imm++) {
396                 evlist__for_each_cpu(evlist, i, cpu) {
397                         affinity__set(&affinity, cpu);
398
399                         evlist__for_each_entry(evlist, pos) {
400                                 if (evsel__cpu_iter_skip(pos, cpu))
401                                         continue;
402                                 if (pos->disabled || !evsel__is_group_leader(pos) || !pos->core.fd)
403                                         continue;
404                                 if (pos->immediate)
405                                         has_imm = true;
406                                 if (pos->immediate != imm)
407                                         continue;
408                                 evsel__disable_cpu(pos, pos->cpu_iter - 1);
409                         }
410                 }
411                 if (!has_imm)
412                         break;
413         }
414
415         affinity__cleanup(&affinity);
416         evlist__for_each_entry(evlist, pos) {
417                 if (!evsel__is_group_leader(pos) || !pos->core.fd)
418                         continue;
419                 pos->disabled = true;
420         }
421
422         evlist->enabled = false;
423 }
424
425 void evlist__enable(struct evlist *evlist)
426 {
427         struct evsel *pos;
428         struct affinity affinity;
429         int cpu, i;
430
431         if (affinity__setup(&affinity) < 0)
432                 return;
433
434         evlist__for_each_cpu(evlist, i, cpu) {
435                 affinity__set(&affinity, cpu);
436
437                 evlist__for_each_entry(evlist, pos) {
438                         if (evsel__cpu_iter_skip(pos, cpu))
439                                 continue;
440                         if (!evsel__is_group_leader(pos) || !pos->core.fd)
441                                 continue;
442                         evsel__enable_cpu(pos, pos->cpu_iter - 1);
443                 }
444         }
445         affinity__cleanup(&affinity);
446         evlist__for_each_entry(evlist, pos) {
447                 if (!evsel__is_group_leader(pos) || !pos->core.fd)
448                         continue;
449                 pos->disabled = false;
450         }
451
452         evlist->enabled = true;
453 }
454
455 void evlist__toggle_enable(struct evlist *evlist)
456 {
457         (evlist->enabled ? evlist__disable : evlist__enable)(evlist);
458 }
459
460 static int evlist__enable_event_cpu(struct evlist *evlist, struct evsel *evsel, int cpu)
461 {
462         int thread;
463         int nr_threads = evlist__nr_threads(evlist, evsel);
464
465         if (!evsel->core.fd)
466                 return -EINVAL;
467
468         for (thread = 0; thread < nr_threads; thread++) {
469                 int err = ioctl(FD(evsel, cpu, thread), PERF_EVENT_IOC_ENABLE, 0);
470                 if (err)
471                         return err;
472         }
473         return 0;
474 }
475
476 static int evlist__enable_event_thread(struct evlist *evlist, struct evsel *evsel, int thread)
477 {
478         int cpu;
479         int nr_cpus = perf_cpu_map__nr(evlist->core.cpus);
480
481         if (!evsel->core.fd)
482                 return -EINVAL;
483
484         for (cpu = 0; cpu < nr_cpus; cpu++) {
485                 int err = ioctl(FD(evsel, cpu, thread), PERF_EVENT_IOC_ENABLE, 0);
486                 if (err)
487                         return err;
488         }
489         return 0;
490 }
491
492 int evlist__enable_event_idx(struct evlist *evlist, struct evsel *evsel, int idx)
493 {
494         bool per_cpu_mmaps = !perf_cpu_map__empty(evlist->core.cpus);
495
496         if (per_cpu_mmaps)
497                 return evlist__enable_event_cpu(evlist, evsel, idx);
498
499         return evlist__enable_event_thread(evlist, evsel, idx);
500 }
501
502 int evlist__add_pollfd(struct evlist *evlist, int fd)
503 {
504         return perf_evlist__add_pollfd(&evlist->core, fd, NULL, POLLIN, fdarray_flag__default);
505 }
506
507 int evlist__filter_pollfd(struct evlist *evlist, short revents_and_mask)
508 {
509         return perf_evlist__filter_pollfd(&evlist->core, revents_and_mask);
510 }
511
512 int evlist__poll(struct evlist *evlist, int timeout)
513 {
514         return perf_evlist__poll(&evlist->core, timeout);
515 }
516
517 struct perf_sample_id *evlist__id2sid(struct evlist *evlist, u64 id)
518 {
519         struct hlist_head *head;
520         struct perf_sample_id *sid;
521         int hash;
522
523         hash = hash_64(id, PERF_EVLIST__HLIST_BITS);
524         head = &evlist->core.heads[hash];
525
526         hlist_for_each_entry(sid, head, node)
527                 if (sid->id == id)
528                         return sid;
529
530         return NULL;
531 }
532
533 struct evsel *evlist__id2evsel(struct evlist *evlist, u64 id)
534 {
535         struct perf_sample_id *sid;
536
537         if (evlist->core.nr_entries == 1 || !id)
538                 return evlist__first(evlist);
539
540         sid = evlist__id2sid(evlist, id);
541         if (sid)
542                 return container_of(sid->evsel, struct evsel, core);
543
544         if (!evlist__sample_id_all(evlist))
545                 return evlist__first(evlist);
546
547         return NULL;
548 }
549
550 struct evsel *evlist__id2evsel_strict(struct evlist *evlist, u64 id)
551 {
552         struct perf_sample_id *sid;
553
554         if (!id)
555                 return NULL;
556
557         sid = evlist__id2sid(evlist, id);
558         if (sid)
559                 return container_of(sid->evsel, struct evsel, core);
560
561         return NULL;
562 }
563
564 static int evlist__event2id(struct evlist *evlist, union perf_event *event, u64 *id)
565 {
566         const __u64 *array = event->sample.array;
567         ssize_t n;
568
569         n = (event->header.size - sizeof(event->header)) >> 3;
570
571         if (event->header.type == PERF_RECORD_SAMPLE) {
572                 if (evlist->id_pos >= n)
573                         return -1;
574                 *id = array[evlist->id_pos];
575         } else {
576                 if (evlist->is_pos > n)
577                         return -1;
578                 n -= evlist->is_pos;
579                 *id = array[n];
580         }
581         return 0;
582 }
583
584 struct evsel *evlist__event2evsel(struct evlist *evlist, union perf_event *event)
585 {
586         struct evsel *first = evlist__first(evlist);
587         struct hlist_head *head;
588         struct perf_sample_id *sid;
589         int hash;
590         u64 id;
591
592         if (evlist->core.nr_entries == 1)
593                 return first;
594
595         if (!first->core.attr.sample_id_all &&
596             event->header.type != PERF_RECORD_SAMPLE)
597                 return first;
598
599         if (evlist__event2id(evlist, event, &id))
600                 return NULL;
601
602         /* Synthesized events have an id of zero */
603         if (!id)
604                 return first;
605
606         hash = hash_64(id, PERF_EVLIST__HLIST_BITS);
607         head = &evlist->core.heads[hash];
608
609         hlist_for_each_entry(sid, head, node) {
610                 if (sid->id == id)
611                         return container_of(sid->evsel, struct evsel, core);
612         }
613         return NULL;
614 }
615
616 static int evlist__set_paused(struct evlist *evlist, bool value)
617 {
618         int i;
619
620         if (!evlist->overwrite_mmap)
621                 return 0;
622
623         for (i = 0; i < evlist->core.nr_mmaps; i++) {
624                 int fd = evlist->overwrite_mmap[i].core.fd;
625                 int err;
626
627                 if (fd < 0)
628                         continue;
629                 err = ioctl(fd, PERF_EVENT_IOC_PAUSE_OUTPUT, value ? 1 : 0);
630                 if (err)
631                         return err;
632         }
633         return 0;
634 }
635
636 static int evlist__pause(struct evlist *evlist)
637 {
638         return evlist__set_paused(evlist, true);
639 }
640
641 static int evlist__resume(struct evlist *evlist)
642 {
643         return evlist__set_paused(evlist, false);
644 }
645
646 static void evlist__munmap_nofree(struct evlist *evlist)
647 {
648         int i;
649
650         if (evlist->mmap)
651                 for (i = 0; i < evlist->core.nr_mmaps; i++)
652                         perf_mmap__munmap(&evlist->mmap[i].core);
653
654         if (evlist->overwrite_mmap)
655                 for (i = 0; i < evlist->core.nr_mmaps; i++)
656                         perf_mmap__munmap(&evlist->overwrite_mmap[i].core);
657 }
658
659 void evlist__munmap(struct evlist *evlist)
660 {
661         evlist__munmap_nofree(evlist);
662         zfree(&evlist->mmap);
663         zfree(&evlist->overwrite_mmap);
664 }
665
666 static void perf_mmap__unmap_cb(struct perf_mmap *map)
667 {
668         struct mmap *m = container_of(map, struct mmap, core);
669
670         mmap__munmap(m);
671 }
672
673 static struct mmap *evlist__alloc_mmap(struct evlist *evlist,
674                                        bool overwrite)
675 {
676         int i;
677         struct mmap *map;
678
679         map = zalloc(evlist->core.nr_mmaps * sizeof(struct mmap));
680         if (!map)
681                 return NULL;
682
683         for (i = 0; i < evlist->core.nr_mmaps; i++) {
684                 struct perf_mmap *prev = i ? &map[i - 1].core : NULL;
685
686                 /*
687                  * When the perf_mmap() call is made we grab one refcount, plus
688                  * one extra to let perf_mmap__consume() get the last
689                  * events after all real references (perf_mmap__get()) are
690                  * dropped.
691                  *
692                  * Each PERF_EVENT_IOC_SET_OUTPUT points to this mmap and
693                  * thus does perf_mmap__get() on it.
694                  */
695                 perf_mmap__init(&map[i].core, prev, overwrite, perf_mmap__unmap_cb);
696         }
697
698         return map;
699 }
700
701 static void
702 perf_evlist__mmap_cb_idx(struct perf_evlist *_evlist,
703                          struct perf_mmap_param *_mp,
704                          int idx, bool per_cpu)
705 {
706         struct evlist *evlist = container_of(_evlist, struct evlist, core);
707         struct mmap_params *mp = container_of(_mp, struct mmap_params, core);
708
709         auxtrace_mmap_params__set_idx(&mp->auxtrace_mp, evlist, idx, per_cpu);
710 }
711
712 static struct perf_mmap*
713 perf_evlist__mmap_cb_get(struct perf_evlist *_evlist, bool overwrite, int idx)
714 {
715         struct evlist *evlist = container_of(_evlist, struct evlist, core);
716         struct mmap *maps;
717
718         maps = overwrite ? evlist->overwrite_mmap : evlist->mmap;
719
720         if (!maps) {
721                 maps = evlist__alloc_mmap(evlist, overwrite);
722                 if (!maps)
723                         return NULL;
724
725                 if (overwrite) {
726                         evlist->overwrite_mmap = maps;
727                         if (evlist->bkw_mmap_state == BKW_MMAP_NOTREADY)
728                                 evlist__toggle_bkw_mmap(evlist, BKW_MMAP_RUNNING);
729                 } else {
730                         evlist->mmap = maps;
731                 }
732         }
733
734         return &maps[idx].core;
735 }
736
737 static int
738 perf_evlist__mmap_cb_mmap(struct perf_mmap *_map, struct perf_mmap_param *_mp,
739                           int output, int cpu)
740 {
741         struct mmap *map = container_of(_map, struct mmap, core);
742         struct mmap_params *mp = container_of(_mp, struct mmap_params, core);
743
744         return mmap__mmap(map, mp, output, cpu);
745 }
746
747 unsigned long perf_event_mlock_kb_in_pages(void)
748 {
749         unsigned long pages;
750         int max;
751
752         if (sysctl__read_int("kernel/perf_event_mlock_kb", &max) < 0) {
753                 /*
754                  * Pick a once upon a time good value, i.e. things look
755                  * strange since we can't read a sysctl value, but lets not
756                  * die yet...
757                  */
758                 max = 512;
759         } else {
760                 max -= (page_size / 1024);
761         }
762
763         pages = (max * 1024) / page_size;
764         if (!is_power_of_2(pages))
765                 pages = rounddown_pow_of_two(pages);
766
767         return pages;
768 }
769
770 size_t evlist__mmap_size(unsigned long pages)
771 {
772         if (pages == UINT_MAX)
773                 pages = perf_event_mlock_kb_in_pages();
774         else if (!is_power_of_2(pages))
775                 return 0;
776
777         return (pages + 1) * page_size;
778 }
779
780 static long parse_pages_arg(const char *str, unsigned long min,
781                             unsigned long max)
782 {
783         unsigned long pages, val;
784         static struct parse_tag tags[] = {
785                 { .tag  = 'B', .mult = 1       },
786                 { .tag  = 'K', .mult = 1 << 10 },
787                 { .tag  = 'M', .mult = 1 << 20 },
788                 { .tag  = 'G', .mult = 1 << 30 },
789                 { .tag  = 0 },
790         };
791
792         if (str == NULL)
793                 return -EINVAL;
794
795         val = parse_tag_value(str, tags);
796         if (val != (unsigned long) -1) {
797                 /* we got file size value */
798                 pages = PERF_ALIGN(val, page_size) / page_size;
799         } else {
800                 /* we got pages count value */
801                 char *eptr;
802                 pages = strtoul(str, &eptr, 10);
803                 if (*eptr != '\0')
804                         return -EINVAL;
805         }
806
807         if (pages == 0 && min == 0) {
808                 /* leave number of pages at 0 */
809         } else if (!is_power_of_2(pages)) {
810                 char buf[100];
811
812                 /* round pages up to next power of 2 */
813                 pages = roundup_pow_of_two(pages);
814                 if (!pages)
815                         return -EINVAL;
816
817                 unit_number__scnprintf(buf, sizeof(buf), pages * page_size);
818                 pr_info("rounding mmap pages size to %s (%lu pages)\n",
819                         buf, pages);
820         }
821
822         if (pages > max)
823                 return -EINVAL;
824
825         return pages;
826 }
827
828 int __evlist__parse_mmap_pages(unsigned int *mmap_pages, const char *str)
829 {
830         unsigned long max = UINT_MAX;
831         long pages;
832
833         if (max > SIZE_MAX / page_size)
834                 max = SIZE_MAX / page_size;
835
836         pages = parse_pages_arg(str, 1, max);
837         if (pages < 0) {
838                 pr_err("Invalid argument for --mmap_pages/-m\n");
839                 return -1;
840         }
841
842         *mmap_pages = pages;
843         return 0;
844 }
845
846 int evlist__parse_mmap_pages(const struct option *opt, const char *str, int unset __maybe_unused)
847 {
848         return __evlist__parse_mmap_pages(opt->value, str);
849 }
850
851 /**
852  * evlist__mmap_ex - Create mmaps to receive events.
853  * @evlist: list of events
854  * @pages: map length in pages
855  * @overwrite: overwrite older events?
856  * @auxtrace_pages - auxtrace map length in pages
857  * @auxtrace_overwrite - overwrite older auxtrace data?
858  *
859  * If @overwrite is %false the user needs to signal event consumption using
860  * perf_mmap__write_tail().  Using evlist__mmap_read() does this
861  * automatically.
862  *
863  * Similarly, if @auxtrace_overwrite is %false the user needs to signal data
864  * consumption using auxtrace_mmap__write_tail().
865  *
866  * Return: %0 on success, negative error code otherwise.
867  */
868 int evlist__mmap_ex(struct evlist *evlist, unsigned int pages,
869                          unsigned int auxtrace_pages,
870                          bool auxtrace_overwrite, int nr_cblocks, int affinity, int flush,
871                          int comp_level)
872 {
873         /*
874          * Delay setting mp.prot: set it before calling perf_mmap__mmap.
875          * Its value is decided by evsel's write_backward.
876          * So &mp should not be passed through const pointer.
877          */
878         struct mmap_params mp = {
879                 .nr_cblocks     = nr_cblocks,
880                 .affinity       = affinity,
881                 .flush          = flush,
882                 .comp_level     = comp_level
883         };
884         struct perf_evlist_mmap_ops ops = {
885                 .idx  = perf_evlist__mmap_cb_idx,
886                 .get  = perf_evlist__mmap_cb_get,
887                 .mmap = perf_evlist__mmap_cb_mmap,
888         };
889
890         evlist->core.mmap_len = evlist__mmap_size(pages);
891         pr_debug("mmap size %zuB\n", evlist->core.mmap_len);
892
893         auxtrace_mmap_params__init(&mp.auxtrace_mp, evlist->core.mmap_len,
894                                    auxtrace_pages, auxtrace_overwrite);
895
896         return perf_evlist__mmap_ops(&evlist->core, &ops, &mp.core);
897 }
898
899 int evlist__mmap(struct evlist *evlist, unsigned int pages)
900 {
901         return evlist__mmap_ex(evlist, pages, 0, false, 0, PERF_AFFINITY_SYS, 1, 0);
902 }
903
904 int evlist__create_maps(struct evlist *evlist, struct target *target)
905 {
906         bool all_threads = (target->per_thread && target->system_wide);
907         struct perf_cpu_map *cpus;
908         struct perf_thread_map *threads;
909
910         /*
911          * If specify '-a' and '--per-thread' to perf record, perf record
912          * will override '--per-thread'. target->per_thread = false and
913          * target->system_wide = true.
914          *
915          * If specify '--per-thread' only to perf record,
916          * target->per_thread = true and target->system_wide = false.
917          *
918          * So target->per_thread && target->system_wide is false.
919          * For perf record, thread_map__new_str doesn't call
920          * thread_map__new_all_cpus. That will keep perf record's
921          * current behavior.
922          *
923          * For perf stat, it allows the case that target->per_thread and
924          * target->system_wide are all true. It means to collect system-wide
925          * per-thread data. thread_map__new_str will call
926          * thread_map__new_all_cpus to enumerate all threads.
927          */
928         threads = thread_map__new_str(target->pid, target->tid, target->uid,
929                                       all_threads);
930
931         if (!threads)
932                 return -1;
933
934         if (target__uses_dummy_map(target))
935                 cpus = perf_cpu_map__dummy_new();
936         else
937                 cpus = perf_cpu_map__new(target->cpu_list);
938
939         if (!cpus)
940                 goto out_delete_threads;
941
942         evlist->core.has_user_cpus = !!target->cpu_list;
943
944         perf_evlist__set_maps(&evlist->core, cpus, threads);
945
946         /* as evlist now has references, put count here */
947         perf_cpu_map__put(cpus);
948         perf_thread_map__put(threads);
949
950         return 0;
951
952 out_delete_threads:
953         perf_thread_map__put(threads);
954         return -1;
955 }
956
957 int evlist__apply_filters(struct evlist *evlist, struct evsel **err_evsel)
958 {
959         struct evsel *evsel;
960         int err = 0;
961
962         evlist__for_each_entry(evlist, evsel) {
963                 if (evsel->filter == NULL)
964                         continue;
965
966                 /*
967                  * filters only work for tracepoint event, which doesn't have cpu limit.
968                  * So evlist and evsel should always be same.
969                  */
970                 err = perf_evsel__apply_filter(&evsel->core, evsel->filter);
971                 if (err) {
972                         *err_evsel = evsel;
973                         break;
974                 }
975         }
976
977         return err;
978 }
979
980 int evlist__set_tp_filter(struct evlist *evlist, const char *filter)
981 {
982         struct evsel *evsel;
983         int err = 0;
984
985         if (filter == NULL)
986                 return -1;
987
988         evlist__for_each_entry(evlist, evsel) {
989                 if (evsel->core.attr.type != PERF_TYPE_TRACEPOINT)
990                         continue;
991
992                 err = evsel__set_filter(evsel, filter);
993                 if (err)
994                         break;
995         }
996
997         return err;
998 }
999
1000 int evlist__append_tp_filter(struct evlist *evlist, const char *filter)
1001 {
1002         struct evsel *evsel;
1003         int err = 0;
1004
1005         if (filter == NULL)
1006                 return -1;
1007
1008         evlist__for_each_entry(evlist, evsel) {
1009                 if (evsel->core.attr.type != PERF_TYPE_TRACEPOINT)
1010                         continue;
1011
1012                 err = evsel__append_tp_filter(evsel, filter);
1013                 if (err)
1014                         break;
1015         }
1016
1017         return err;
1018 }
1019
1020 char *asprintf__tp_filter_pids(size_t npids, pid_t *pids)
1021 {
1022         char *filter;
1023         size_t i;
1024
1025         for (i = 0; i < npids; ++i) {
1026                 if (i == 0) {
1027                         if (asprintf(&filter, "common_pid != %d", pids[i]) < 0)
1028                                 return NULL;
1029                 } else {
1030                         char *tmp;
1031
1032                         if (asprintf(&tmp, "%s && common_pid != %d", filter, pids[i]) < 0)
1033                                 goto out_free;
1034
1035                         free(filter);
1036                         filter = tmp;
1037                 }
1038         }
1039
1040         return filter;
1041 out_free:
1042         free(filter);
1043         return NULL;
1044 }
1045
1046 int evlist__set_tp_filter_pids(struct evlist *evlist, size_t npids, pid_t *pids)
1047 {
1048         char *filter = asprintf__tp_filter_pids(npids, pids);
1049         int ret = evlist__set_tp_filter(evlist, filter);
1050
1051         free(filter);
1052         return ret;
1053 }
1054
1055 int evlist__set_tp_filter_pid(struct evlist *evlist, pid_t pid)
1056 {
1057         return evlist__set_tp_filter_pids(evlist, 1, &pid);
1058 }
1059
1060 int evlist__append_tp_filter_pids(struct evlist *evlist, size_t npids, pid_t *pids)
1061 {
1062         char *filter = asprintf__tp_filter_pids(npids, pids);
1063         int ret = evlist__append_tp_filter(evlist, filter);
1064
1065         free(filter);
1066         return ret;
1067 }
1068
1069 int evlist__append_tp_filter_pid(struct evlist *evlist, pid_t pid)
1070 {
1071         return evlist__append_tp_filter_pids(evlist, 1, &pid);
1072 }
1073
1074 bool evlist__valid_sample_type(struct evlist *evlist)
1075 {
1076         struct evsel *pos;
1077
1078         if (evlist->core.nr_entries == 1)
1079                 return true;
1080
1081         if (evlist->id_pos < 0 || evlist->is_pos < 0)
1082                 return false;
1083
1084         evlist__for_each_entry(evlist, pos) {
1085                 if (pos->id_pos != evlist->id_pos ||
1086                     pos->is_pos != evlist->is_pos)
1087                         return false;
1088         }
1089
1090         return true;
1091 }
1092
1093 u64 __evlist__combined_sample_type(struct evlist *evlist)
1094 {
1095         struct evsel *evsel;
1096
1097         if (evlist->combined_sample_type)
1098                 return evlist->combined_sample_type;
1099
1100         evlist__for_each_entry(evlist, evsel)
1101                 evlist->combined_sample_type |= evsel->core.attr.sample_type;
1102
1103         return evlist->combined_sample_type;
1104 }
1105
1106 u64 evlist__combined_sample_type(struct evlist *evlist)
1107 {
1108         evlist->combined_sample_type = 0;
1109         return __evlist__combined_sample_type(evlist);
1110 }
1111
1112 u64 evlist__combined_branch_type(struct evlist *evlist)
1113 {
1114         struct evsel *evsel;
1115         u64 branch_type = 0;
1116
1117         evlist__for_each_entry(evlist, evsel)
1118                 branch_type |= evsel->core.attr.branch_sample_type;
1119         return branch_type;
1120 }
1121
1122 bool evlist__valid_read_format(struct evlist *evlist)
1123 {
1124         struct evsel *first = evlist__first(evlist), *pos = first;
1125         u64 read_format = first->core.attr.read_format;
1126         u64 sample_type = first->core.attr.sample_type;
1127
1128         evlist__for_each_entry(evlist, pos) {
1129                 if (read_format != pos->core.attr.read_format) {
1130                         pr_debug("Read format differs %#" PRIx64 " vs %#" PRIx64 "\n",
1131                                  read_format, (u64)pos->core.attr.read_format);
1132                 }
1133         }
1134
1135         /* PERF_SAMPLE_READ imples PERF_FORMAT_ID. */
1136         if ((sample_type & PERF_SAMPLE_READ) &&
1137             !(read_format & PERF_FORMAT_ID)) {
1138                 return false;
1139         }
1140
1141         return true;
1142 }
1143
1144 u16 evlist__id_hdr_size(struct evlist *evlist)
1145 {
1146         struct evsel *first = evlist__first(evlist);
1147         struct perf_sample *data;
1148         u64 sample_type;
1149         u16 size = 0;
1150
1151         if (!first->core.attr.sample_id_all)
1152                 goto out;
1153
1154         sample_type = first->core.attr.sample_type;
1155
1156         if (sample_type & PERF_SAMPLE_TID)
1157                 size += sizeof(data->tid) * 2;
1158
1159        if (sample_type & PERF_SAMPLE_TIME)
1160                 size += sizeof(data->time);
1161
1162         if (sample_type & PERF_SAMPLE_ID)
1163                 size += sizeof(data->id);
1164
1165         if (sample_type & PERF_SAMPLE_STREAM_ID)
1166                 size += sizeof(data->stream_id);
1167
1168         if (sample_type & PERF_SAMPLE_CPU)
1169                 size += sizeof(data->cpu) * 2;
1170
1171         if (sample_type & PERF_SAMPLE_IDENTIFIER)
1172                 size += sizeof(data->id);
1173 out:
1174         return size;
1175 }
1176
1177 bool evlist__valid_sample_id_all(struct evlist *evlist)
1178 {
1179         struct evsel *first = evlist__first(evlist), *pos = first;
1180
1181         evlist__for_each_entry_continue(evlist, pos) {
1182                 if (first->core.attr.sample_id_all != pos->core.attr.sample_id_all)
1183                         return false;
1184         }
1185
1186         return true;
1187 }
1188
1189 bool evlist__sample_id_all(struct evlist *evlist)
1190 {
1191         struct evsel *first = evlist__first(evlist);
1192         return first->core.attr.sample_id_all;
1193 }
1194
1195 void evlist__set_selected(struct evlist *evlist, struct evsel *evsel)
1196 {
1197         evlist->selected = evsel;
1198 }
1199
1200 void evlist__close(struct evlist *evlist)
1201 {
1202         struct evsel *evsel;
1203         struct affinity affinity;
1204         int cpu, i;
1205
1206         /*
1207          * With perf record core.cpus is usually NULL.
1208          * Use the old method to handle this for now.
1209          */
1210         if (!evlist->core.cpus) {
1211                 evlist__for_each_entry_reverse(evlist, evsel)
1212                         evsel__close(evsel);
1213                 return;
1214         }
1215
1216         if (affinity__setup(&affinity) < 0)
1217                 return;
1218         evlist__for_each_cpu(evlist, i, cpu) {
1219                 affinity__set(&affinity, cpu);
1220
1221                 evlist__for_each_entry_reverse(evlist, evsel) {
1222                         if (evsel__cpu_iter_skip(evsel, cpu))
1223                             continue;
1224                         perf_evsel__close_cpu(&evsel->core, evsel->cpu_iter - 1);
1225                 }
1226         }
1227         affinity__cleanup(&affinity);
1228         evlist__for_each_entry_reverse(evlist, evsel) {
1229                 perf_evsel__free_fd(&evsel->core);
1230                 perf_evsel__free_id(&evsel->core);
1231         }
1232 }
1233
1234 static int evlist__create_syswide_maps(struct evlist *evlist)
1235 {
1236         struct perf_cpu_map *cpus;
1237         struct perf_thread_map *threads;
1238         int err = -ENOMEM;
1239
1240         /*
1241          * Try reading /sys/devices/system/cpu/online to get
1242          * an all cpus map.
1243          *
1244          * FIXME: -ENOMEM is the best we can do here, the cpu_map
1245          * code needs an overhaul to properly forward the
1246          * error, and we may not want to do that fallback to a
1247          * default cpu identity map :-\
1248          */
1249         cpus = perf_cpu_map__new(NULL);
1250         if (!cpus)
1251                 goto out;
1252
1253         threads = perf_thread_map__new_dummy();
1254         if (!threads)
1255                 goto out_put;
1256
1257         perf_evlist__set_maps(&evlist->core, cpus, threads);
1258
1259         perf_thread_map__put(threads);
1260 out_put:
1261         perf_cpu_map__put(cpus);
1262 out:
1263         return err;
1264 }
1265
1266 int evlist__open(struct evlist *evlist)
1267 {
1268         struct evsel *evsel;
1269         int err;
1270
1271         /*
1272          * Default: one fd per CPU, all threads, aka systemwide
1273          * as sys_perf_event_open(cpu = -1, thread = -1) is EINVAL
1274          */
1275         if (evlist->core.threads == NULL && evlist->core.cpus == NULL) {
1276                 err = evlist__create_syswide_maps(evlist);
1277                 if (err < 0)
1278                         goto out_err;
1279         }
1280
1281         evlist__update_id_pos(evlist);
1282
1283         evlist__for_each_entry(evlist, evsel) {
1284                 err = evsel__open(evsel, evsel->core.cpus, evsel->core.threads);
1285                 if (err < 0)
1286                         goto out_err;
1287         }
1288
1289         return 0;
1290 out_err:
1291         evlist__close(evlist);
1292         errno = -err;
1293         return err;
1294 }
1295
1296 int evlist__prepare_workload(struct evlist *evlist, struct target *target, const char *argv[],
1297                              bool pipe_output, void (*exec_error)(int signo, siginfo_t *info, void *ucontext))
1298 {
1299         int child_ready_pipe[2], go_pipe[2];
1300         char bf;
1301
1302         if (pipe(child_ready_pipe) < 0) {
1303                 perror("failed to create 'ready' pipe");
1304                 return -1;
1305         }
1306
1307         if (pipe(go_pipe) < 0) {
1308                 perror("failed to create 'go' pipe");
1309                 goto out_close_ready_pipe;
1310         }
1311
1312         evlist->workload.pid = fork();
1313         if (evlist->workload.pid < 0) {
1314                 perror("failed to fork");
1315                 goto out_close_pipes;
1316         }
1317
1318         if (!evlist->workload.pid) {
1319                 int ret;
1320
1321                 if (pipe_output)
1322                         dup2(2, 1);
1323
1324                 signal(SIGTERM, SIG_DFL);
1325
1326                 close(child_ready_pipe[0]);
1327                 close(go_pipe[1]);
1328                 fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
1329
1330                 /*
1331                  * Tell the parent we're ready to go
1332                  */
1333                 close(child_ready_pipe[1]);
1334
1335                 /*
1336                  * Wait until the parent tells us to go.
1337                  */
1338                 ret = read(go_pipe[0], &bf, 1);
1339                 /*
1340                  * The parent will ask for the execvp() to be performed by
1341                  * writing exactly one byte, in workload.cork_fd, usually via
1342                  * evlist__start_workload().
1343                  *
1344                  * For cancelling the workload without actually running it,
1345                  * the parent will just close workload.cork_fd, without writing
1346                  * anything, i.e. read will return zero and we just exit()
1347                  * here.
1348                  */
1349                 if (ret != 1) {
1350                         if (ret == -1)
1351                                 perror("unable to read pipe");
1352                         exit(ret);
1353                 }
1354
1355                 execvp(argv[0], (char **)argv);
1356
1357                 if (exec_error) {
1358                         union sigval val;
1359
1360                         val.sival_int = errno;
1361                         if (sigqueue(getppid(), SIGUSR1, val))
1362                                 perror(argv[0]);
1363                 } else
1364                         perror(argv[0]);
1365                 exit(-1);
1366         }
1367
1368         if (exec_error) {
1369                 struct sigaction act = {
1370                         .sa_flags     = SA_SIGINFO,
1371                         .sa_sigaction = exec_error,
1372                 };
1373                 sigaction(SIGUSR1, &act, NULL);
1374         }
1375
1376         if (target__none(target)) {
1377                 if (evlist->core.threads == NULL) {
1378                         fprintf(stderr, "FATAL: evlist->threads need to be set at this point (%s:%d).\n",
1379                                 __func__, __LINE__);
1380                         goto out_close_pipes;
1381                 }
1382                 perf_thread_map__set_pid(evlist->core.threads, 0, evlist->workload.pid);
1383         }
1384
1385         close(child_ready_pipe[1]);
1386         close(go_pipe[0]);
1387         /*
1388          * wait for child to settle
1389          */
1390         if (read(child_ready_pipe[0], &bf, 1) == -1) {
1391                 perror("unable to read pipe");
1392                 goto out_close_pipes;
1393         }
1394
1395         fcntl(go_pipe[1], F_SETFD, FD_CLOEXEC);
1396         evlist->workload.cork_fd = go_pipe[1];
1397         close(child_ready_pipe[0]);
1398         return 0;
1399
1400 out_close_pipes:
1401         close(go_pipe[0]);
1402         close(go_pipe[1]);
1403 out_close_ready_pipe:
1404         close(child_ready_pipe[0]);
1405         close(child_ready_pipe[1]);
1406         return -1;
1407 }
1408
1409 int evlist__start_workload(struct evlist *evlist)
1410 {
1411         if (evlist->workload.cork_fd > 0) {
1412                 char bf = 0;
1413                 int ret;
1414                 /*
1415                  * Remove the cork, let it rip!
1416                  */
1417                 ret = write(evlist->workload.cork_fd, &bf, 1);
1418                 if (ret < 0)
1419                         perror("unable to write to pipe");
1420
1421                 close(evlist->workload.cork_fd);
1422                 return ret;
1423         }
1424
1425         return 0;
1426 }
1427
1428 int evlist__parse_sample(struct evlist *evlist, union perf_event *event, struct perf_sample *sample)
1429 {
1430         struct evsel *evsel = evlist__event2evsel(evlist, event);
1431
1432         if (!evsel)
1433                 return -EFAULT;
1434         return evsel__parse_sample(evsel, event, sample);
1435 }
1436
1437 int evlist__parse_sample_timestamp(struct evlist *evlist, union perf_event *event, u64 *timestamp)
1438 {
1439         struct evsel *evsel = evlist__event2evsel(evlist, event);
1440
1441         if (!evsel)
1442                 return -EFAULT;
1443         return evsel__parse_sample_timestamp(evsel, event, timestamp);
1444 }
1445
1446 int evlist__strerror_open(struct evlist *evlist, int err, char *buf, size_t size)
1447 {
1448         int printed, value;
1449         char sbuf[STRERR_BUFSIZE], *emsg = str_error_r(err, sbuf, sizeof(sbuf));
1450
1451         switch (err) {
1452         case EACCES:
1453         case EPERM:
1454                 printed = scnprintf(buf, size,
1455                                     "Error:\t%s.\n"
1456                                     "Hint:\tCheck /proc/sys/kernel/perf_event_paranoid setting.", emsg);
1457
1458                 value = perf_event_paranoid();
1459
1460                 printed += scnprintf(buf + printed, size - printed, "\nHint:\t");
1461
1462                 if (value >= 2) {
1463                         printed += scnprintf(buf + printed, size - printed,
1464                                              "For your workloads it needs to be <= 1\nHint:\t");
1465                 }
1466                 printed += scnprintf(buf + printed, size - printed,
1467                                      "For system wide tracing it needs to be set to -1.\n");
1468
1469                 printed += scnprintf(buf + printed, size - printed,
1470                                     "Hint:\tTry: 'sudo sh -c \"echo -1 > /proc/sys/kernel/perf_event_paranoid\"'\n"
1471                                     "Hint:\tThe current value is %d.", value);
1472                 break;
1473         case EINVAL: {
1474                 struct evsel *first = evlist__first(evlist);
1475                 int max_freq;
1476
1477                 if (sysctl__read_int("kernel/perf_event_max_sample_rate", &max_freq) < 0)
1478                         goto out_default;
1479
1480                 if (first->core.attr.sample_freq < (u64)max_freq)
1481                         goto out_default;
1482
1483                 printed = scnprintf(buf, size,
1484                                     "Error:\t%s.\n"
1485                                     "Hint:\tCheck /proc/sys/kernel/perf_event_max_sample_rate.\n"
1486                                     "Hint:\tThe current value is %d and %" PRIu64 " is being requested.",
1487                                     emsg, max_freq, first->core.attr.sample_freq);
1488                 break;
1489         }
1490         default:
1491 out_default:
1492                 scnprintf(buf, size, "%s", emsg);
1493                 break;
1494         }
1495
1496         return 0;
1497 }
1498
1499 int evlist__strerror_mmap(struct evlist *evlist, int err, char *buf, size_t size)
1500 {
1501         char sbuf[STRERR_BUFSIZE], *emsg = str_error_r(err, sbuf, sizeof(sbuf));
1502         int pages_attempted = evlist->core.mmap_len / 1024, pages_max_per_user, printed = 0;
1503
1504         switch (err) {
1505         case EPERM:
1506                 sysctl__read_int("kernel/perf_event_mlock_kb", &pages_max_per_user);
1507                 printed += scnprintf(buf + printed, size - printed,
1508                                      "Error:\t%s.\n"
1509                                      "Hint:\tCheck /proc/sys/kernel/perf_event_mlock_kb (%d kB) setting.\n"
1510                                      "Hint:\tTried using %zd kB.\n",
1511                                      emsg, pages_max_per_user, pages_attempted);
1512
1513                 if (pages_attempted >= pages_max_per_user) {
1514                         printed += scnprintf(buf + printed, size - printed,
1515                                              "Hint:\tTry 'sudo sh -c \"echo %d > /proc/sys/kernel/perf_event_mlock_kb\"', or\n",
1516                                              pages_max_per_user + pages_attempted);
1517                 }
1518
1519                 printed += scnprintf(buf + printed, size - printed,
1520                                      "Hint:\tTry using a smaller -m/--mmap-pages value.");
1521                 break;
1522         default:
1523                 scnprintf(buf, size, "%s", emsg);
1524                 break;
1525         }
1526
1527         return 0;
1528 }
1529
1530 void evlist__to_front(struct evlist *evlist, struct evsel *move_evsel)
1531 {
1532         struct evsel *evsel, *n;
1533         LIST_HEAD(move);
1534
1535         if (move_evsel == evlist__first(evlist))
1536                 return;
1537
1538         evlist__for_each_entry_safe(evlist, n, evsel) {
1539                 if (evsel->leader == move_evsel->leader)
1540                         list_move_tail(&evsel->core.node, &move);
1541         }
1542
1543         list_splice(&move, &evlist->core.entries);
1544 }
1545
1546 struct evsel *evlist__get_tracking_event(struct evlist *evlist)
1547 {
1548         struct evsel *evsel;
1549
1550         evlist__for_each_entry(evlist, evsel) {
1551                 if (evsel->tracking)
1552                         return evsel;
1553         }
1554
1555         return evlist__first(evlist);
1556 }
1557
1558 void evlist__set_tracking_event(struct evlist *evlist, struct evsel *tracking_evsel)
1559 {
1560         struct evsel *evsel;
1561
1562         if (tracking_evsel->tracking)
1563                 return;
1564
1565         evlist__for_each_entry(evlist, evsel) {
1566                 if (evsel != tracking_evsel)
1567                         evsel->tracking = false;
1568         }
1569
1570         tracking_evsel->tracking = true;
1571 }
1572
1573 struct evsel *evlist__find_evsel_by_str(struct evlist *evlist, const char *str)
1574 {
1575         struct evsel *evsel;
1576
1577         evlist__for_each_entry(evlist, evsel) {
1578                 if (!evsel->name)
1579                         continue;
1580                 if (strcmp(str, evsel->name) == 0)
1581                         return evsel;
1582         }
1583
1584         return NULL;
1585 }
1586
1587 void evlist__toggle_bkw_mmap(struct evlist *evlist, enum bkw_mmap_state state)
1588 {
1589         enum bkw_mmap_state old_state = evlist->bkw_mmap_state;
1590         enum action {
1591                 NONE,
1592                 PAUSE,
1593                 RESUME,
1594         } action = NONE;
1595
1596         if (!evlist->overwrite_mmap)
1597                 return;
1598
1599         switch (old_state) {
1600         case BKW_MMAP_NOTREADY: {
1601                 if (state != BKW_MMAP_RUNNING)
1602                         goto state_err;
1603                 break;
1604         }
1605         case BKW_MMAP_RUNNING: {
1606                 if (state != BKW_MMAP_DATA_PENDING)
1607                         goto state_err;
1608                 action = PAUSE;
1609                 break;
1610         }
1611         case BKW_MMAP_DATA_PENDING: {
1612                 if (state != BKW_MMAP_EMPTY)
1613                         goto state_err;
1614                 break;
1615         }
1616         case BKW_MMAP_EMPTY: {
1617                 if (state != BKW_MMAP_RUNNING)
1618                         goto state_err;
1619                 action = RESUME;
1620                 break;
1621         }
1622         default:
1623                 WARN_ONCE(1, "Shouldn't get there\n");
1624         }
1625
1626         evlist->bkw_mmap_state = state;
1627
1628         switch (action) {
1629         case PAUSE:
1630                 evlist__pause(evlist);
1631                 break;
1632         case RESUME:
1633                 evlist__resume(evlist);
1634                 break;
1635         case NONE:
1636         default:
1637                 break;
1638         }
1639
1640 state_err:
1641         return;
1642 }
1643
1644 bool evlist__exclude_kernel(struct evlist *evlist)
1645 {
1646         struct evsel *evsel;
1647
1648         evlist__for_each_entry(evlist, evsel) {
1649                 if (!evsel->core.attr.exclude_kernel)
1650                         return false;
1651         }
1652
1653         return true;
1654 }
1655
1656 /*
1657  * Events in data file are not collect in groups, but we still want
1658  * the group display. Set the artificial group and set the leader's
1659  * forced_leader flag to notify the display code.
1660  */
1661 void evlist__force_leader(struct evlist *evlist)
1662 {
1663         if (!evlist->nr_groups) {
1664                 struct evsel *leader = evlist__first(evlist);
1665
1666                 evlist__set_leader(evlist);
1667                 leader->forced_leader = true;
1668         }
1669 }
1670
1671 struct evsel *evlist__reset_weak_group(struct evlist *evsel_list, struct evsel *evsel, bool close)
1672 {
1673         struct evsel *c2, *leader;
1674         bool is_open = true;
1675
1676         leader = evsel->leader;
1677         pr_debug("Weak group for %s/%d failed\n",
1678                         leader->name, leader->core.nr_members);
1679
1680         /*
1681          * for_each_group_member doesn't work here because it doesn't
1682          * include the first entry.
1683          */
1684         evlist__for_each_entry(evsel_list, c2) {
1685                 if (c2 == evsel)
1686                         is_open = false;
1687                 if (c2->leader == leader) {
1688                         if (is_open && close)
1689                                 perf_evsel__close(&c2->core);
1690                         c2->leader = c2;
1691                         c2->core.nr_members = 0;
1692                         /*
1693                          * Set this for all former members of the group
1694                          * to indicate they get reopened.
1695                          */
1696                         c2->reset_group = true;
1697                 }
1698         }
1699         return leader;
1700 }
1701
1702 static int evlist__parse_control_fifo(const char *str, int *ctl_fd, int *ctl_fd_ack, bool *ctl_fd_close)
1703 {
1704         char *s, *p;
1705         int ret = 0, fd;
1706
1707         if (strncmp(str, "fifo:", 5))
1708                 return -EINVAL;
1709
1710         str += 5;
1711         if (!*str || *str == ',')
1712                 return -EINVAL;
1713
1714         s = strdup(str);
1715         if (!s)
1716                 return -ENOMEM;
1717
1718         p = strchr(s, ',');
1719         if (p)
1720                 *p = '\0';
1721
1722         /*
1723          * O_RDWR avoids POLLHUPs which is necessary to allow the other
1724          * end of a FIFO to be repeatedly opened and closed.
1725          */
1726         fd = open(s, O_RDWR | O_NONBLOCK | O_CLOEXEC);
1727         if (fd < 0) {
1728                 pr_err("Failed to open '%s'\n", s);
1729                 ret = -errno;
1730                 goto out_free;
1731         }
1732         *ctl_fd = fd;
1733         *ctl_fd_close = true;
1734
1735         if (p && *++p) {
1736                 /* O_RDWR | O_NONBLOCK means the other end need not be open */
1737                 fd = open(p, O_RDWR | O_NONBLOCK | O_CLOEXEC);
1738                 if (fd < 0) {
1739                         pr_err("Failed to open '%s'\n", p);
1740                         ret = -errno;
1741                         goto out_free;
1742                 }
1743                 *ctl_fd_ack = fd;
1744         }
1745
1746 out_free:
1747         free(s);
1748         return ret;
1749 }
1750
1751 int evlist__parse_control(const char *str, int *ctl_fd, int *ctl_fd_ack, bool *ctl_fd_close)
1752 {
1753         char *comma = NULL, *endptr = NULL;
1754
1755         *ctl_fd_close = false;
1756
1757         if (strncmp(str, "fd:", 3))
1758                 return evlist__parse_control_fifo(str, ctl_fd, ctl_fd_ack, ctl_fd_close);
1759
1760         *ctl_fd = strtoul(&str[3], &endptr, 0);
1761         if (endptr == &str[3])
1762                 return -EINVAL;
1763
1764         comma = strchr(str, ',');
1765         if (comma) {
1766                 if (endptr != comma)
1767                         return -EINVAL;
1768
1769                 *ctl_fd_ack = strtoul(comma + 1, &endptr, 0);
1770                 if (endptr == comma + 1 || *endptr != '\0')
1771                         return -EINVAL;
1772         }
1773
1774         return 0;
1775 }
1776
1777 void evlist__close_control(int ctl_fd, int ctl_fd_ack, bool *ctl_fd_close)
1778 {
1779         if (*ctl_fd_close) {
1780                 *ctl_fd_close = false;
1781                 close(ctl_fd);
1782                 if (ctl_fd_ack >= 0)
1783                         close(ctl_fd_ack);
1784         }
1785 }
1786
1787 int evlist__initialize_ctlfd(struct evlist *evlist, int fd, int ack)
1788 {
1789         if (fd == -1) {
1790                 pr_debug("Control descriptor is not initialized\n");
1791                 return 0;
1792         }
1793
1794         evlist->ctl_fd.pos = perf_evlist__add_pollfd(&evlist->core, fd, NULL, POLLIN,
1795                                                      fdarray_flag__nonfilterable);
1796         if (evlist->ctl_fd.pos < 0) {
1797                 evlist->ctl_fd.pos = -1;
1798                 pr_err("Failed to add ctl fd entry: %m\n");
1799                 return -1;
1800         }
1801
1802         evlist->ctl_fd.fd = fd;
1803         evlist->ctl_fd.ack = ack;
1804
1805         return 0;
1806 }
1807
1808 bool evlist__ctlfd_initialized(struct evlist *evlist)
1809 {
1810         return evlist->ctl_fd.pos >= 0;
1811 }
1812
1813 int evlist__finalize_ctlfd(struct evlist *evlist)
1814 {
1815         struct pollfd *entries = evlist->core.pollfd.entries;
1816
1817         if (!evlist__ctlfd_initialized(evlist))
1818                 return 0;
1819
1820         entries[evlist->ctl_fd.pos].fd = -1;
1821         entries[evlist->ctl_fd.pos].events = 0;
1822         entries[evlist->ctl_fd.pos].revents = 0;
1823
1824         evlist->ctl_fd.pos = -1;
1825         evlist->ctl_fd.ack = -1;
1826         evlist->ctl_fd.fd = -1;
1827
1828         return 0;
1829 }
1830
1831 static int evlist__ctlfd_recv(struct evlist *evlist, enum evlist_ctl_cmd *cmd,
1832                               char *cmd_data, size_t data_size)
1833 {
1834         int err;
1835         char c;
1836         size_t bytes_read = 0;
1837
1838         *cmd = EVLIST_CTL_CMD_UNSUPPORTED;
1839         memset(cmd_data, 0, data_size);
1840         data_size--;
1841
1842         do {
1843                 err = read(evlist->ctl_fd.fd, &c, 1);
1844                 if (err > 0) {
1845                         if (c == '\n' || c == '\0')
1846                                 break;
1847                         cmd_data[bytes_read++] = c;
1848                         if (bytes_read == data_size)
1849                                 break;
1850                         continue;
1851                 } else if (err == -1) {
1852                         if (errno == EINTR)
1853                                 continue;
1854                         if (errno == EAGAIN || errno == EWOULDBLOCK)
1855                                 err = 0;
1856                         else
1857                                 pr_err("Failed to read from ctlfd %d: %m\n", evlist->ctl_fd.fd);
1858                 }
1859                 break;
1860         } while (1);
1861
1862         pr_debug("Message from ctl_fd: \"%s%s\"\n", cmd_data,
1863                  bytes_read == data_size ? "" : c == '\n' ? "\\n" : "\\0");
1864
1865         if (bytes_read > 0) {
1866                 if (!strncmp(cmd_data, EVLIST_CTL_CMD_ENABLE_TAG,
1867                              (sizeof(EVLIST_CTL_CMD_ENABLE_TAG)-1))) {
1868                         *cmd = EVLIST_CTL_CMD_ENABLE;
1869                 } else if (!strncmp(cmd_data, EVLIST_CTL_CMD_DISABLE_TAG,
1870                                     (sizeof(EVLIST_CTL_CMD_DISABLE_TAG)-1))) {
1871                         *cmd = EVLIST_CTL_CMD_DISABLE;
1872                 } else if (!strncmp(cmd_data, EVLIST_CTL_CMD_SNAPSHOT_TAG,
1873                                     (sizeof(EVLIST_CTL_CMD_SNAPSHOT_TAG)-1))) {
1874                         *cmd = EVLIST_CTL_CMD_SNAPSHOT;
1875                         pr_debug("is snapshot\n");
1876                 }
1877         }
1878
1879         return bytes_read ? (int)bytes_read : err;
1880 }
1881
1882 int evlist__ctlfd_ack(struct evlist *evlist)
1883 {
1884         int err;
1885
1886         if (evlist->ctl_fd.ack == -1)
1887                 return 0;
1888
1889         err = write(evlist->ctl_fd.ack, EVLIST_CTL_CMD_ACK_TAG,
1890                     sizeof(EVLIST_CTL_CMD_ACK_TAG));
1891         if (err == -1)
1892                 pr_err("failed to write to ctl_ack_fd %d: %m\n", evlist->ctl_fd.ack);
1893
1894         return err;
1895 }
1896
1897 int evlist__ctlfd_process(struct evlist *evlist, enum evlist_ctl_cmd *cmd)
1898 {
1899         int err = 0;
1900         char cmd_data[EVLIST_CTL_CMD_MAX_LEN];
1901         int ctlfd_pos = evlist->ctl_fd.pos;
1902         struct pollfd *entries = evlist->core.pollfd.entries;
1903
1904         if (!evlist__ctlfd_initialized(evlist) || !entries[ctlfd_pos].revents)
1905                 return 0;
1906
1907         if (entries[ctlfd_pos].revents & POLLIN) {
1908                 err = evlist__ctlfd_recv(evlist, cmd, cmd_data,
1909                                          EVLIST_CTL_CMD_MAX_LEN);
1910                 if (err > 0) {
1911                         switch (*cmd) {
1912                         case EVLIST_CTL_CMD_ENABLE:
1913                                 evlist__enable(evlist);
1914                                 break;
1915                         case EVLIST_CTL_CMD_DISABLE:
1916                                 evlist__disable(evlist);
1917                                 break;
1918                         case EVLIST_CTL_CMD_SNAPSHOT:
1919                                 break;
1920                         case EVLIST_CTL_CMD_ACK:
1921                         case EVLIST_CTL_CMD_UNSUPPORTED:
1922                         default:
1923                                 pr_debug("ctlfd: unsupported %d\n", *cmd);
1924                                 break;
1925                         }
1926                         if (!(*cmd == EVLIST_CTL_CMD_ACK || *cmd == EVLIST_CTL_CMD_UNSUPPORTED ||
1927                               *cmd == EVLIST_CTL_CMD_SNAPSHOT))
1928                                 evlist__ctlfd_ack(evlist);
1929                 }
1930         }
1931
1932         if (entries[ctlfd_pos].revents & (POLLHUP | POLLERR))
1933                 evlist__finalize_ctlfd(evlist);
1934         else
1935                 entries[ctlfd_pos].revents = 0;
1936
1937         return err;
1938 }
1939
1940 struct evsel *evlist__find_evsel(struct evlist *evlist, int idx)
1941 {
1942         struct evsel *evsel;
1943
1944         evlist__for_each_entry(evlist, evsel) {
1945                 if (evsel->idx == idx)
1946                         return evsel;
1947         }
1948         return NULL;
1949 }