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