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