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