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