perf evlist: Choose correct reading direction according to evlist->backward
[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_forward(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 union perf_event *perf_evlist__mmap_read(struct perf_evlist *evlist, int idx)
836 {
837         if (!evlist->backward)
838                 return perf_evlist__mmap_read_forward(evlist, idx);
839         return perf_evlist__mmap_read_backward(evlist, idx);
840 }
841
842 void perf_evlist__mmap_read_catchup(struct perf_evlist *evlist, int idx)
843 {
844         struct perf_mmap *md = &evlist->mmap[idx];
845         u64 head;
846
847         if (!atomic_read(&md->refcnt))
848                 return;
849
850         head = perf_mmap__read_head(md);
851         md->prev = head;
852 }
853
854 static bool perf_mmap__empty(struct perf_mmap *md)
855 {
856         return perf_mmap__read_head(md) == md->prev && !md->auxtrace_mmap.base;
857 }
858
859 static void perf_evlist__mmap_get(struct perf_evlist *evlist, int idx)
860 {
861         atomic_inc(&evlist->mmap[idx].refcnt);
862 }
863
864 static void perf_evlist__mmap_put(struct perf_evlist *evlist, int idx)
865 {
866         struct perf_mmap *md = &evlist->mmap[idx];
867
868         BUG_ON(md->base && atomic_read(&md->refcnt) == 0);
869
870         if (atomic_dec_and_test(&md->refcnt))
871                 __perf_evlist__munmap(evlist, idx);
872 }
873
874 void perf_evlist__mmap_consume(struct perf_evlist *evlist, int idx)
875 {
876         struct perf_mmap *md = &evlist->mmap[idx];
877
878         if (!evlist->overwrite) {
879                 u64 old = md->prev;
880
881                 perf_mmap__write_tail(md, old);
882         }
883
884         if (atomic_read(&md->refcnt) == 1 && perf_mmap__empty(md))
885                 perf_evlist__mmap_put(evlist, idx);
886 }
887
888 int __weak auxtrace_mmap__mmap(struct auxtrace_mmap *mm __maybe_unused,
889                                struct auxtrace_mmap_params *mp __maybe_unused,
890                                void *userpg __maybe_unused,
891                                int fd __maybe_unused)
892 {
893         return 0;
894 }
895
896 void __weak auxtrace_mmap__munmap(struct auxtrace_mmap *mm __maybe_unused)
897 {
898 }
899
900 void __weak auxtrace_mmap_params__init(
901                         struct auxtrace_mmap_params *mp __maybe_unused,
902                         off_t auxtrace_offset __maybe_unused,
903                         unsigned int auxtrace_pages __maybe_unused,
904                         bool auxtrace_overwrite __maybe_unused)
905 {
906 }
907
908 void __weak auxtrace_mmap_params__set_idx(
909                         struct auxtrace_mmap_params *mp __maybe_unused,
910                         struct perf_evlist *evlist __maybe_unused,
911                         int idx __maybe_unused,
912                         bool per_cpu __maybe_unused)
913 {
914 }
915
916 static void __perf_evlist__munmap(struct perf_evlist *evlist, int idx)
917 {
918         if (evlist->mmap[idx].base != NULL) {
919                 munmap(evlist->mmap[idx].base, evlist->mmap_len);
920                 evlist->mmap[idx].base = NULL;
921                 evlist->mmap[idx].fd = -1;
922                 atomic_set(&evlist->mmap[idx].refcnt, 0);
923         }
924         auxtrace_mmap__munmap(&evlist->mmap[idx].auxtrace_mmap);
925 }
926
927 void perf_evlist__munmap(struct perf_evlist *evlist)
928 {
929         int i;
930
931         if (evlist->mmap == NULL)
932                 return;
933
934         for (i = 0; i < evlist->nr_mmaps; i++)
935                 __perf_evlist__munmap(evlist, i);
936
937         zfree(&evlist->mmap);
938 }
939
940 static int perf_evlist__alloc_mmap(struct perf_evlist *evlist)
941 {
942         int i;
943
944         evlist->nr_mmaps = cpu_map__nr(evlist->cpus);
945         if (cpu_map__empty(evlist->cpus))
946                 evlist->nr_mmaps = thread_map__nr(evlist->threads);
947         evlist->mmap = zalloc(evlist->nr_mmaps * sizeof(struct perf_mmap));
948         for (i = 0; i < evlist->nr_mmaps; i++)
949                 evlist->mmap[i].fd = -1;
950         return evlist->mmap != NULL ? 0 : -ENOMEM;
951 }
952
953 struct mmap_params {
954         int prot;
955         int mask;
956         struct auxtrace_mmap_params auxtrace_mp;
957 };
958
959 static int __perf_evlist__mmap(struct perf_evlist *evlist, int idx,
960                                struct mmap_params *mp, int fd)
961 {
962         /*
963          * The last one will be done at perf_evlist__mmap_consume(), so that we
964          * make sure we don't prevent tools from consuming every last event in
965          * the ring buffer.
966          *
967          * I.e. we can get the POLLHUP meaning that the fd doesn't exist
968          * anymore, but the last events for it are still in the ring buffer,
969          * waiting to be consumed.
970          *
971          * Tools can chose to ignore this at their own discretion, but the
972          * evlist layer can't just drop it when filtering events in
973          * perf_evlist__filter_pollfd().
974          */
975         atomic_set(&evlist->mmap[idx].refcnt, 2);
976         evlist->mmap[idx].prev = 0;
977         evlist->mmap[idx].mask = mp->mask;
978         evlist->mmap[idx].base = mmap(NULL, evlist->mmap_len, mp->prot,
979                                       MAP_SHARED, fd, 0);
980         if (evlist->mmap[idx].base == MAP_FAILED) {
981                 pr_debug2("failed to mmap perf event ring buffer, error %d\n",
982                           errno);
983                 evlist->mmap[idx].base = NULL;
984                 return -1;
985         }
986         evlist->mmap[idx].fd = fd;
987
988         if (auxtrace_mmap__mmap(&evlist->mmap[idx].auxtrace_mmap,
989                                 &mp->auxtrace_mp, evlist->mmap[idx].base, fd))
990                 return -1;
991
992         return 0;
993 }
994
995 static bool
996 perf_evlist__should_poll(struct perf_evlist *evlist __maybe_unused,
997                          struct perf_evsel *evsel)
998 {
999         if (evsel->overwrite)
1000                 return false;
1001         return true;
1002 }
1003
1004 static int perf_evlist__mmap_per_evsel(struct perf_evlist *evlist, int idx,
1005                                        struct mmap_params *mp, int cpu,
1006                                        int thread, int *output)
1007 {
1008         struct perf_evsel *evsel;
1009         int revent;
1010
1011         evlist__for_each(evlist, evsel) {
1012                 int fd;
1013
1014                 if (evsel->overwrite != (evlist->overwrite && evlist->backward))
1015                         continue;
1016
1017                 if (evsel->system_wide && thread)
1018                         continue;
1019
1020                 fd = FD(evsel, cpu, thread);
1021
1022                 if (*output == -1) {
1023                         *output = fd;
1024                         if (__perf_evlist__mmap(evlist, idx, mp, *output) < 0)
1025                                 return -1;
1026                 } else {
1027                         if (ioctl(fd, PERF_EVENT_IOC_SET_OUTPUT, *output) != 0)
1028                                 return -1;
1029
1030                         perf_evlist__mmap_get(evlist, idx);
1031                 }
1032
1033                 revent = perf_evlist__should_poll(evlist, evsel) ? POLLIN : 0;
1034
1035                 /*
1036                  * The system_wide flag causes a selected event to be opened
1037                  * always without a pid.  Consequently it will never get a
1038                  * POLLHUP, but it is used for tracking in combination with
1039                  * other events, so it should not need to be polled anyway.
1040                  * Therefore don't add it for polling.
1041                  */
1042                 if (!evsel->system_wide &&
1043                     __perf_evlist__add_pollfd(evlist, fd, idx, revent) < 0) {
1044                         perf_evlist__mmap_put(evlist, idx);
1045                         return -1;
1046                 }
1047
1048                 if (evsel->attr.read_format & PERF_FORMAT_ID) {
1049                         if (perf_evlist__id_add_fd(evlist, evsel, cpu, thread,
1050                                                    fd) < 0)
1051                                 return -1;
1052                         perf_evlist__set_sid_idx(evlist, evsel, idx, cpu,
1053                                                  thread);
1054                 }
1055         }
1056
1057         return 0;
1058 }
1059
1060 static int perf_evlist__mmap_per_cpu(struct perf_evlist *evlist,
1061                                      struct mmap_params *mp)
1062 {
1063         int cpu, thread;
1064         int nr_cpus = cpu_map__nr(evlist->cpus);
1065         int nr_threads = thread_map__nr(evlist->threads);
1066
1067         pr_debug2("perf event ring buffer mmapped per cpu\n");
1068         for (cpu = 0; cpu < nr_cpus; cpu++) {
1069                 int output = -1;
1070
1071                 auxtrace_mmap_params__set_idx(&mp->auxtrace_mp, evlist, cpu,
1072                                               true);
1073
1074                 for (thread = 0; thread < nr_threads; thread++) {
1075                         if (perf_evlist__mmap_per_evsel(evlist, cpu, mp, cpu,
1076                                                         thread, &output))
1077                                 goto out_unmap;
1078                 }
1079         }
1080
1081         return 0;
1082
1083 out_unmap:
1084         for (cpu = 0; cpu < nr_cpus; cpu++)
1085                 __perf_evlist__munmap(evlist, cpu);
1086         return -1;
1087 }
1088
1089 static int perf_evlist__mmap_per_thread(struct perf_evlist *evlist,
1090                                         struct mmap_params *mp)
1091 {
1092         int thread;
1093         int nr_threads = thread_map__nr(evlist->threads);
1094
1095         pr_debug2("perf event ring buffer mmapped per thread\n");
1096         for (thread = 0; thread < nr_threads; thread++) {
1097                 int output = -1;
1098
1099                 auxtrace_mmap_params__set_idx(&mp->auxtrace_mp, evlist, thread,
1100                                               false);
1101
1102                 if (perf_evlist__mmap_per_evsel(evlist, thread, mp, 0, thread,
1103                                                 &output))
1104                         goto out_unmap;
1105         }
1106
1107         return 0;
1108
1109 out_unmap:
1110         for (thread = 0; thread < nr_threads; thread++)
1111                 __perf_evlist__munmap(evlist, thread);
1112         return -1;
1113 }
1114
1115 unsigned long perf_event_mlock_kb_in_pages(void)
1116 {
1117         unsigned long pages;
1118         int max;
1119
1120         if (sysctl__read_int("kernel/perf_event_mlock_kb", &max) < 0) {
1121                 /*
1122                  * Pick a once upon a time good value, i.e. things look
1123                  * strange since we can't read a sysctl value, but lets not
1124                  * die yet...
1125                  */
1126                 max = 512;
1127         } else {
1128                 max -= (page_size / 1024);
1129         }
1130
1131         pages = (max * 1024) / page_size;
1132         if (!is_power_of_2(pages))
1133                 pages = rounddown_pow_of_two(pages);
1134
1135         return pages;
1136 }
1137
1138 static size_t perf_evlist__mmap_size(unsigned long pages)
1139 {
1140         if (pages == UINT_MAX)
1141                 pages = perf_event_mlock_kb_in_pages();
1142         else if (!is_power_of_2(pages))
1143                 return 0;
1144
1145         return (pages + 1) * page_size;
1146 }
1147
1148 static long parse_pages_arg(const char *str, unsigned long min,
1149                             unsigned long max)
1150 {
1151         unsigned long pages, val;
1152         static struct parse_tag tags[] = {
1153                 { .tag  = 'B', .mult = 1       },
1154                 { .tag  = 'K', .mult = 1 << 10 },
1155                 { .tag  = 'M', .mult = 1 << 20 },
1156                 { .tag  = 'G', .mult = 1 << 30 },
1157                 { .tag  = 0 },
1158         };
1159
1160         if (str == NULL)
1161                 return -EINVAL;
1162
1163         val = parse_tag_value(str, tags);
1164         if (val != (unsigned long) -1) {
1165                 /* we got file size value */
1166                 pages = PERF_ALIGN(val, page_size) / page_size;
1167         } else {
1168                 /* we got pages count value */
1169                 char *eptr;
1170                 pages = strtoul(str, &eptr, 10);
1171                 if (*eptr != '\0')
1172                         return -EINVAL;
1173         }
1174
1175         if (pages == 0 && min == 0) {
1176                 /* leave number of pages at 0 */
1177         } else if (!is_power_of_2(pages)) {
1178                 /* round pages up to next power of 2 */
1179                 pages = roundup_pow_of_two(pages);
1180                 if (!pages)
1181                         return -EINVAL;
1182                 pr_info("rounding mmap pages size to %lu bytes (%lu pages)\n",
1183                         pages * page_size, pages);
1184         }
1185
1186         if (pages > max)
1187                 return -EINVAL;
1188
1189         return pages;
1190 }
1191
1192 int __perf_evlist__parse_mmap_pages(unsigned int *mmap_pages, const char *str)
1193 {
1194         unsigned long max = UINT_MAX;
1195         long pages;
1196
1197         if (max > SIZE_MAX / page_size)
1198                 max = SIZE_MAX / page_size;
1199
1200         pages = parse_pages_arg(str, 1, max);
1201         if (pages < 0) {
1202                 pr_err("Invalid argument for --mmap_pages/-m\n");
1203                 return -1;
1204         }
1205
1206         *mmap_pages = pages;
1207         return 0;
1208 }
1209
1210 int perf_evlist__parse_mmap_pages(const struct option *opt, const char *str,
1211                                   int unset __maybe_unused)
1212 {
1213         return __perf_evlist__parse_mmap_pages(opt->value, str);
1214 }
1215
1216 /**
1217  * perf_evlist__mmap_ex - Create mmaps to receive events.
1218  * @evlist: list of events
1219  * @pages: map length in pages
1220  * @overwrite: overwrite older events?
1221  * @auxtrace_pages - auxtrace map length in pages
1222  * @auxtrace_overwrite - overwrite older auxtrace data?
1223  *
1224  * If @overwrite is %false the user needs to signal event consumption using
1225  * perf_mmap__write_tail().  Using perf_evlist__mmap_read() does this
1226  * automatically.
1227  *
1228  * Similarly, if @auxtrace_overwrite is %false the user needs to signal data
1229  * consumption using auxtrace_mmap__write_tail().
1230  *
1231  * Return: %0 on success, negative error code otherwise.
1232  */
1233 int perf_evlist__mmap_ex(struct perf_evlist *evlist, unsigned int pages,
1234                          bool overwrite, unsigned int auxtrace_pages,
1235                          bool auxtrace_overwrite)
1236 {
1237         struct perf_evsel *evsel;
1238         const struct cpu_map *cpus = evlist->cpus;
1239         const struct thread_map *threads = evlist->threads;
1240         struct mmap_params mp = {
1241                 .prot = PROT_READ | (overwrite ? 0 : PROT_WRITE),
1242         };
1243
1244         if (evlist->mmap == NULL && perf_evlist__alloc_mmap(evlist) < 0)
1245                 return -ENOMEM;
1246
1247         if (evlist->pollfd.entries == NULL && perf_evlist__alloc_pollfd(evlist) < 0)
1248                 return -ENOMEM;
1249
1250         evlist->overwrite = overwrite;
1251         evlist->mmap_len = perf_evlist__mmap_size(pages);
1252         pr_debug("mmap size %zuB\n", evlist->mmap_len);
1253         mp.mask = evlist->mmap_len - page_size - 1;
1254
1255         auxtrace_mmap_params__init(&mp.auxtrace_mp, evlist->mmap_len,
1256                                    auxtrace_pages, auxtrace_overwrite);
1257
1258         evlist__for_each(evlist, evsel) {
1259                 if ((evsel->attr.read_format & PERF_FORMAT_ID) &&
1260                     evsel->sample_id == NULL &&
1261                     perf_evsel__alloc_id(evsel, cpu_map__nr(cpus), threads->nr) < 0)
1262                         return -ENOMEM;
1263         }
1264
1265         if (cpu_map__empty(cpus))
1266                 return perf_evlist__mmap_per_thread(evlist, &mp);
1267
1268         return perf_evlist__mmap_per_cpu(evlist, &mp);
1269 }
1270
1271 int perf_evlist__mmap(struct perf_evlist *evlist, unsigned int pages,
1272                       bool overwrite)
1273 {
1274         return perf_evlist__mmap_ex(evlist, pages, overwrite, 0, false);
1275 }
1276
1277 int perf_evlist__create_maps(struct perf_evlist *evlist, struct target *target)
1278 {
1279         struct cpu_map *cpus;
1280         struct thread_map *threads;
1281
1282         threads = thread_map__new_str(target->pid, target->tid, target->uid);
1283
1284         if (!threads)
1285                 return -1;
1286
1287         if (target__uses_dummy_map(target))
1288                 cpus = cpu_map__dummy_new();
1289         else
1290                 cpus = cpu_map__new(target->cpu_list);
1291
1292         if (!cpus)
1293                 goto out_delete_threads;
1294
1295         evlist->has_user_cpus = !!target->cpu_list;
1296
1297         perf_evlist__set_maps(evlist, cpus, threads);
1298
1299         return 0;
1300
1301 out_delete_threads:
1302         thread_map__put(threads);
1303         return -1;
1304 }
1305
1306 void perf_evlist__set_maps(struct perf_evlist *evlist, struct cpu_map *cpus,
1307                            struct thread_map *threads)
1308 {
1309         /*
1310          * Allow for the possibility that one or another of the maps isn't being
1311          * changed i.e. don't put it.  Note we are assuming the maps that are
1312          * being applied are brand new and evlist is taking ownership of the
1313          * original reference count of 1.  If that is not the case it is up to
1314          * the caller to increase the reference count.
1315          */
1316         if (cpus != evlist->cpus) {
1317                 cpu_map__put(evlist->cpus);
1318                 evlist->cpus = cpu_map__get(cpus);
1319         }
1320
1321         if (threads != evlist->threads) {
1322                 thread_map__put(evlist->threads);
1323                 evlist->threads = thread_map__get(threads);
1324         }
1325
1326         perf_evlist__propagate_maps(evlist);
1327 }
1328
1329 void __perf_evlist__set_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__set_sample_bit(evsel, bit);
1336 }
1337
1338 void __perf_evlist__reset_sample_bit(struct perf_evlist *evlist,
1339                                      enum perf_event_sample_format bit)
1340 {
1341         struct perf_evsel *evsel;
1342
1343         evlist__for_each(evlist, evsel)
1344                 __perf_evsel__reset_sample_bit(evsel, bit);
1345 }
1346
1347 int perf_evlist__apply_filters(struct perf_evlist *evlist, struct perf_evsel **err_evsel)
1348 {
1349         struct perf_evsel *evsel;
1350         int err = 0;
1351         const int ncpus = cpu_map__nr(evlist->cpus),
1352                   nthreads = thread_map__nr(evlist->threads);
1353
1354         evlist__for_each(evlist, evsel) {
1355                 if (evsel->filter == NULL)
1356                         continue;
1357
1358                 /*
1359                  * filters only work for tracepoint event, which doesn't have cpu limit.
1360                  * So evlist and evsel should always be same.
1361                  */
1362                 err = perf_evsel__apply_filter(evsel, ncpus, nthreads, evsel->filter);
1363                 if (err) {
1364                         *err_evsel = evsel;
1365                         break;
1366                 }
1367         }
1368
1369         return err;
1370 }
1371
1372 int perf_evlist__set_filter(struct perf_evlist *evlist, const char *filter)
1373 {
1374         struct perf_evsel *evsel;
1375         int err = 0;
1376
1377         evlist__for_each(evlist, evsel) {
1378                 if (evsel->attr.type != PERF_TYPE_TRACEPOINT)
1379                         continue;
1380
1381                 err = perf_evsel__set_filter(evsel, filter);
1382                 if (err)
1383                         break;
1384         }
1385
1386         return err;
1387 }
1388
1389 int perf_evlist__set_filter_pids(struct perf_evlist *evlist, size_t npids, pid_t *pids)
1390 {
1391         char *filter;
1392         int ret = -1;
1393         size_t i;
1394
1395         for (i = 0; i < npids; ++i) {
1396                 if (i == 0) {
1397                         if (asprintf(&filter, "common_pid != %d", pids[i]) < 0)
1398                                 return -1;
1399                 } else {
1400                         char *tmp;
1401
1402                         if (asprintf(&tmp, "%s && common_pid != %d", filter, pids[i]) < 0)
1403                                 goto out_free;
1404
1405                         free(filter);
1406                         filter = tmp;
1407                 }
1408         }
1409
1410         ret = perf_evlist__set_filter(evlist, filter);
1411 out_free:
1412         free(filter);
1413         return ret;
1414 }
1415
1416 int perf_evlist__set_filter_pid(struct perf_evlist *evlist, pid_t pid)
1417 {
1418         return perf_evlist__set_filter_pids(evlist, 1, &pid);
1419 }
1420
1421 bool perf_evlist__valid_sample_type(struct perf_evlist *evlist)
1422 {
1423         struct perf_evsel *pos;
1424
1425         if (evlist->nr_entries == 1)
1426                 return true;
1427
1428         if (evlist->id_pos < 0 || evlist->is_pos < 0)
1429                 return false;
1430
1431         evlist__for_each(evlist, pos) {
1432                 if (pos->id_pos != evlist->id_pos ||
1433                     pos->is_pos != evlist->is_pos)
1434                         return false;
1435         }
1436
1437         return true;
1438 }
1439
1440 u64 __perf_evlist__combined_sample_type(struct perf_evlist *evlist)
1441 {
1442         struct perf_evsel *evsel;
1443
1444         if (evlist->combined_sample_type)
1445                 return evlist->combined_sample_type;
1446
1447         evlist__for_each(evlist, evsel)
1448                 evlist->combined_sample_type |= evsel->attr.sample_type;
1449
1450         return evlist->combined_sample_type;
1451 }
1452
1453 u64 perf_evlist__combined_sample_type(struct perf_evlist *evlist)
1454 {
1455         evlist->combined_sample_type = 0;
1456         return __perf_evlist__combined_sample_type(evlist);
1457 }
1458
1459 u64 perf_evlist__combined_branch_type(struct perf_evlist *evlist)
1460 {
1461         struct perf_evsel *evsel;
1462         u64 branch_type = 0;
1463
1464         evlist__for_each(evlist, evsel)
1465                 branch_type |= evsel->attr.branch_sample_type;
1466         return branch_type;
1467 }
1468
1469 bool perf_evlist__valid_read_format(struct perf_evlist *evlist)
1470 {
1471         struct perf_evsel *first = perf_evlist__first(evlist), *pos = first;
1472         u64 read_format = first->attr.read_format;
1473         u64 sample_type = first->attr.sample_type;
1474
1475         evlist__for_each(evlist, pos) {
1476                 if (read_format != pos->attr.read_format)
1477                         return false;
1478         }
1479
1480         /* PERF_SAMPLE_READ imples PERF_FORMAT_ID. */
1481         if ((sample_type & PERF_SAMPLE_READ) &&
1482             !(read_format & PERF_FORMAT_ID)) {
1483                 return false;
1484         }
1485
1486         return true;
1487 }
1488
1489 u64 perf_evlist__read_format(struct perf_evlist *evlist)
1490 {
1491         struct perf_evsel *first = perf_evlist__first(evlist);
1492         return first->attr.read_format;
1493 }
1494
1495 u16 perf_evlist__id_hdr_size(struct perf_evlist *evlist)
1496 {
1497         struct perf_evsel *first = perf_evlist__first(evlist);
1498         struct perf_sample *data;
1499         u64 sample_type;
1500         u16 size = 0;
1501
1502         if (!first->attr.sample_id_all)
1503                 goto out;
1504
1505         sample_type = first->attr.sample_type;
1506
1507         if (sample_type & PERF_SAMPLE_TID)
1508                 size += sizeof(data->tid) * 2;
1509
1510        if (sample_type & PERF_SAMPLE_TIME)
1511                 size += sizeof(data->time);
1512
1513         if (sample_type & PERF_SAMPLE_ID)
1514                 size += sizeof(data->id);
1515
1516         if (sample_type & PERF_SAMPLE_STREAM_ID)
1517                 size += sizeof(data->stream_id);
1518
1519         if (sample_type & PERF_SAMPLE_CPU)
1520                 size += sizeof(data->cpu) * 2;
1521
1522         if (sample_type & PERF_SAMPLE_IDENTIFIER)
1523                 size += sizeof(data->id);
1524 out:
1525         return size;
1526 }
1527
1528 bool perf_evlist__valid_sample_id_all(struct perf_evlist *evlist)
1529 {
1530         struct perf_evsel *first = perf_evlist__first(evlist), *pos = first;
1531
1532         evlist__for_each_continue(evlist, pos) {
1533                 if (first->attr.sample_id_all != pos->attr.sample_id_all)
1534                         return false;
1535         }
1536
1537         return true;
1538 }
1539
1540 bool perf_evlist__sample_id_all(struct perf_evlist *evlist)
1541 {
1542         struct perf_evsel *first = perf_evlist__first(evlist);
1543         return first->attr.sample_id_all;
1544 }
1545
1546 void perf_evlist__set_selected(struct perf_evlist *evlist,
1547                                struct perf_evsel *evsel)
1548 {
1549         evlist->selected = evsel;
1550 }
1551
1552 void perf_evlist__close(struct perf_evlist *evlist)
1553 {
1554         struct perf_evsel *evsel;
1555         int ncpus = cpu_map__nr(evlist->cpus);
1556         int nthreads = thread_map__nr(evlist->threads);
1557         int n;
1558
1559         evlist__for_each_reverse(evlist, evsel) {
1560                 n = evsel->cpus ? evsel->cpus->nr : ncpus;
1561                 perf_evsel__close(evsel, n, nthreads);
1562         }
1563 }
1564
1565 static int perf_evlist__create_syswide_maps(struct perf_evlist *evlist)
1566 {
1567         struct cpu_map    *cpus;
1568         struct thread_map *threads;
1569         int err = -ENOMEM;
1570
1571         /*
1572          * Try reading /sys/devices/system/cpu/online to get
1573          * an all cpus map.
1574          *
1575          * FIXME: -ENOMEM is the best we can do here, the cpu_map
1576          * code needs an overhaul to properly forward the
1577          * error, and we may not want to do that fallback to a
1578          * default cpu identity map :-\
1579          */
1580         cpus = cpu_map__new(NULL);
1581         if (!cpus)
1582                 goto out;
1583
1584         threads = thread_map__new_dummy();
1585         if (!threads)
1586                 goto out_put;
1587
1588         perf_evlist__set_maps(evlist, cpus, threads);
1589 out:
1590         return err;
1591 out_put:
1592         cpu_map__put(cpus);
1593         goto out;
1594 }
1595
1596 int perf_evlist__open(struct perf_evlist *evlist)
1597 {
1598         struct perf_evsel *evsel;
1599         int err;
1600
1601         /*
1602          * Default: one fd per CPU, all threads, aka systemwide
1603          * as sys_perf_event_open(cpu = -1, thread = -1) is EINVAL
1604          */
1605         if (evlist->threads == NULL && evlist->cpus == NULL) {
1606                 err = perf_evlist__create_syswide_maps(evlist);
1607                 if (err < 0)
1608                         goto out_err;
1609         }
1610
1611         perf_evlist__update_id_pos(evlist);
1612
1613         evlist__for_each(evlist, evsel) {
1614                 err = perf_evsel__open(evsel, evsel->cpus, evsel->threads);
1615                 if (err < 0)
1616                         goto out_err;
1617         }
1618
1619         return 0;
1620 out_err:
1621         perf_evlist__close(evlist);
1622         errno = -err;
1623         return err;
1624 }
1625
1626 int perf_evlist__prepare_workload(struct perf_evlist *evlist, struct target *target,
1627                                   const char *argv[], bool pipe_output,
1628                                   void (*exec_error)(int signo, siginfo_t *info, void *ucontext))
1629 {
1630         int child_ready_pipe[2], go_pipe[2];
1631         char bf;
1632
1633         if (pipe(child_ready_pipe) < 0) {
1634                 perror("failed to create 'ready' pipe");
1635                 return -1;
1636         }
1637
1638         if (pipe(go_pipe) < 0) {
1639                 perror("failed to create 'go' pipe");
1640                 goto out_close_ready_pipe;
1641         }
1642
1643         evlist->workload.pid = fork();
1644         if (evlist->workload.pid < 0) {
1645                 perror("failed to fork");
1646                 goto out_close_pipes;
1647         }
1648
1649         if (!evlist->workload.pid) {
1650                 int ret;
1651
1652                 if (pipe_output)
1653                         dup2(2, 1);
1654
1655                 signal(SIGTERM, SIG_DFL);
1656
1657                 close(child_ready_pipe[0]);
1658                 close(go_pipe[1]);
1659                 fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC);
1660
1661                 /*
1662                  * Tell the parent we're ready to go
1663                  */
1664                 close(child_ready_pipe[1]);
1665
1666                 /*
1667                  * Wait until the parent tells us to go.
1668                  */
1669                 ret = read(go_pipe[0], &bf, 1);
1670                 /*
1671                  * The parent will ask for the execvp() to be performed by
1672                  * writing exactly one byte, in workload.cork_fd, usually via
1673                  * perf_evlist__start_workload().
1674                  *
1675                  * For cancelling the workload without actually running it,
1676                  * the parent will just close workload.cork_fd, without writing
1677                  * anything, i.e. read will return zero and we just exit()
1678                  * here.
1679                  */
1680                 if (ret != 1) {
1681                         if (ret == -1)
1682                                 perror("unable to read pipe");
1683                         exit(ret);
1684                 }
1685
1686                 execvp(argv[0], (char **)argv);
1687
1688                 if (exec_error) {
1689                         union sigval val;
1690
1691                         val.sival_int = errno;
1692                         if (sigqueue(getppid(), SIGUSR1, val))
1693                                 perror(argv[0]);
1694                 } else
1695                         perror(argv[0]);
1696                 exit(-1);
1697         }
1698
1699         if (exec_error) {
1700                 struct sigaction act = {
1701                         .sa_flags     = SA_SIGINFO,
1702                         .sa_sigaction = exec_error,
1703                 };
1704                 sigaction(SIGUSR1, &act, NULL);
1705         }
1706
1707         if (target__none(target)) {
1708                 if (evlist->threads == NULL) {
1709                         fprintf(stderr, "FATAL: evlist->threads need to be set at this point (%s:%d).\n",
1710                                 __func__, __LINE__);
1711                         goto out_close_pipes;
1712                 }
1713                 thread_map__set_pid(evlist->threads, 0, evlist->workload.pid);
1714         }
1715
1716         close(child_ready_pipe[1]);
1717         close(go_pipe[0]);
1718         /*
1719          * wait for child to settle
1720          */
1721         if (read(child_ready_pipe[0], &bf, 1) == -1) {
1722                 perror("unable to read pipe");
1723                 goto out_close_pipes;
1724         }
1725
1726         fcntl(go_pipe[1], F_SETFD, FD_CLOEXEC);
1727         evlist->workload.cork_fd = go_pipe[1];
1728         close(child_ready_pipe[0]);
1729         return 0;
1730
1731 out_close_pipes:
1732         close(go_pipe[0]);
1733         close(go_pipe[1]);
1734 out_close_ready_pipe:
1735         close(child_ready_pipe[0]);
1736         close(child_ready_pipe[1]);
1737         return -1;
1738 }
1739
1740 int perf_evlist__start_workload(struct perf_evlist *evlist)
1741 {
1742         if (evlist->workload.cork_fd > 0) {
1743                 char bf = 0;
1744                 int ret;
1745                 /*
1746                  * Remove the cork, let it rip!
1747                  */
1748                 ret = write(evlist->workload.cork_fd, &bf, 1);
1749                 if (ret < 0)
1750                         perror("enable to write to pipe");
1751
1752                 close(evlist->workload.cork_fd);
1753                 return ret;
1754         }
1755
1756         return 0;
1757 }
1758
1759 int perf_evlist__parse_sample(struct perf_evlist *evlist, union perf_event *event,
1760                               struct perf_sample *sample)
1761 {
1762         struct perf_evsel *evsel = perf_evlist__event2evsel(evlist, event);
1763
1764         if (!evsel)
1765                 return -EFAULT;
1766         return perf_evsel__parse_sample(evsel, event, sample);
1767 }
1768
1769 size_t perf_evlist__fprintf(struct perf_evlist *evlist, FILE *fp)
1770 {
1771         struct perf_evsel *evsel;
1772         size_t printed = 0;
1773
1774         evlist__for_each(evlist, evsel) {
1775                 printed += fprintf(fp, "%s%s", evsel->idx ? ", " : "",
1776                                    perf_evsel__name(evsel));
1777         }
1778
1779         return printed + fprintf(fp, "\n");
1780 }
1781
1782 int perf_evlist__strerror_open(struct perf_evlist *evlist,
1783                                int err, char *buf, size_t size)
1784 {
1785         int printed, value;
1786         char sbuf[STRERR_BUFSIZE], *emsg = strerror_r(err, sbuf, sizeof(sbuf));
1787
1788         switch (err) {
1789         case EACCES:
1790         case EPERM:
1791                 printed = scnprintf(buf, size,
1792                                     "Error:\t%s.\n"
1793                                     "Hint:\tCheck /proc/sys/kernel/perf_event_paranoid setting.", emsg);
1794
1795                 value = perf_event_paranoid();
1796
1797                 printed += scnprintf(buf + printed, size - printed, "\nHint:\t");
1798
1799                 if (value >= 2) {
1800                         printed += scnprintf(buf + printed, size - printed,
1801                                              "For your workloads it needs to be <= 1\nHint:\t");
1802                 }
1803                 printed += scnprintf(buf + printed, size - printed,
1804                                      "For system wide tracing it needs to be set to -1.\n");
1805
1806                 printed += scnprintf(buf + printed, size - printed,
1807                                     "Hint:\tTry: 'sudo sh -c \"echo -1 > /proc/sys/kernel/perf_event_paranoid\"'\n"
1808                                     "Hint:\tThe current value is %d.", value);
1809                 break;
1810         case EINVAL: {
1811                 struct perf_evsel *first = perf_evlist__first(evlist);
1812                 int max_freq;
1813
1814                 if (sysctl__read_int("kernel/perf_event_max_sample_rate", &max_freq) < 0)
1815                         goto out_default;
1816
1817                 if (first->attr.sample_freq < (u64)max_freq)
1818                         goto out_default;
1819
1820                 printed = scnprintf(buf, size,
1821                                     "Error:\t%s.\n"
1822                                     "Hint:\tCheck /proc/sys/kernel/perf_event_max_sample_rate.\n"
1823                                     "Hint:\tThe current value is %d and %" PRIu64 " is being requested.",
1824                                     emsg, max_freq, first->attr.sample_freq);
1825                 break;
1826         }
1827         default:
1828 out_default:
1829                 scnprintf(buf, size, "%s", emsg);
1830                 break;
1831         }
1832
1833         return 0;
1834 }
1835
1836 int perf_evlist__strerror_mmap(struct perf_evlist *evlist, int err, char *buf, size_t size)
1837 {
1838         char sbuf[STRERR_BUFSIZE], *emsg = strerror_r(err, sbuf, sizeof(sbuf));
1839         int pages_attempted = evlist->mmap_len / 1024, pages_max_per_user, printed = 0;
1840
1841         switch (err) {
1842         case EPERM:
1843                 sysctl__read_int("kernel/perf_event_mlock_kb", &pages_max_per_user);
1844                 printed += scnprintf(buf + printed, size - printed,
1845                                      "Error:\t%s.\n"
1846                                      "Hint:\tCheck /proc/sys/kernel/perf_event_mlock_kb (%d kB) setting.\n"
1847                                      "Hint:\tTried using %zd kB.\n",
1848                                      emsg, pages_max_per_user, pages_attempted);
1849
1850                 if (pages_attempted >= pages_max_per_user) {
1851                         printed += scnprintf(buf + printed, size - printed,
1852                                              "Hint:\tTry 'sudo sh -c \"echo %d > /proc/sys/kernel/perf_event_mlock_kb\"', or\n",
1853                                              pages_max_per_user + pages_attempted);
1854                 }
1855
1856                 printed += scnprintf(buf + printed, size - printed,
1857                                      "Hint:\tTry using a smaller -m/--mmap-pages value.");
1858                 break;
1859         default:
1860                 scnprintf(buf, size, "%s", emsg);
1861                 break;
1862         }
1863
1864         return 0;
1865 }
1866
1867 void perf_evlist__to_front(struct perf_evlist *evlist,
1868                            struct perf_evsel *move_evsel)
1869 {
1870         struct perf_evsel *evsel, *n;
1871         LIST_HEAD(move);
1872
1873         if (move_evsel == perf_evlist__first(evlist))
1874                 return;
1875
1876         evlist__for_each_safe(evlist, n, evsel) {
1877                 if (evsel->leader == move_evsel->leader)
1878                         list_move_tail(&evsel->node, &move);
1879         }
1880
1881         list_splice(&move, &evlist->entries);
1882 }
1883
1884 void perf_evlist__set_tracking_event(struct perf_evlist *evlist,
1885                                      struct perf_evsel *tracking_evsel)
1886 {
1887         struct perf_evsel *evsel;
1888
1889         if (tracking_evsel->tracking)
1890                 return;
1891
1892         evlist__for_each(evlist, evsel) {
1893                 if (evsel != tracking_evsel)
1894                         evsel->tracking = false;
1895         }
1896
1897         tracking_evsel->tracking = true;
1898 }
1899
1900 struct perf_evsel *
1901 perf_evlist__find_evsel_by_str(struct perf_evlist *evlist,
1902                                const char *str)
1903 {
1904         struct perf_evsel *evsel;
1905
1906         evlist__for_each(evlist, evsel) {
1907                 if (!evsel->name)
1908                         continue;
1909                 if (strcmp(str, evsel->name) == 0)
1910                         return evsel;
1911         }
1912
1913         return NULL;
1914 }