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