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