libperf: Add perf_evsel__alloc_id/perf_evsel__free_id functions
[linux-2.6-microblaze.git] / tools / perf / util / evsel.c
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
4  *
5  * Parts came from builtin-{top,stat,record}.c, see those files for further
6  * copyright notes.
7  */
8
9 #include <byteswap.h>
10 #include <errno.h>
11 #include <inttypes.h>
12 #include <linux/bitops.h>
13 #include <api/fs/fs.h>
14 #include <api/fs/tracing_path.h>
15 #include <traceevent/event-parse.h>
16 #include <linux/hw_breakpoint.h>
17 #include <linux/perf_event.h>
18 #include <linux/compiler.h>
19 #include <linux/err.h>
20 #include <linux/zalloc.h>
21 #include <sys/ioctl.h>
22 #include <sys/resource.h>
23 #include <sys/types.h>
24 #include <dirent.h>
25 #include <stdlib.h>
26 #include <perf/evsel.h>
27 #include "asm/bug.h"
28 #include "callchain.h"
29 #include "cgroup.h"
30 #include "counts.h"
31 #include "event.h"
32 #include "evsel.h"
33 #include "evlist.h"
34 #include <perf/cpumap.h>
35 #include "thread_map.h"
36 #include "target.h"
37 #include "perf_regs.h"
38 #include "record.h"
39 #include "debug.h"
40 #include "trace-event.h"
41 #include "stat.h"
42 #include "string2.h"
43 #include "memswap.h"
44 #include "util.h"
45 #include "../perf-sys.h"
46 #include "util/parse-branch-options.h"
47 #include <internal/xyarray.h>
48 #include <internal/lib.h>
49
50 #include <linux/ctype.h>
51
52 struct perf_missing_features perf_missing_features;
53
54 static clockid_t clockid;
55
56 static int perf_evsel__no_extra_init(struct evsel *evsel __maybe_unused)
57 {
58         return 0;
59 }
60
61 void __weak test_attr__ready(void) { }
62
63 static void perf_evsel__no_extra_fini(struct evsel *evsel __maybe_unused)
64 {
65 }
66
67 static struct {
68         size_t  size;
69         int     (*init)(struct evsel *evsel);
70         void    (*fini)(struct evsel *evsel);
71 } perf_evsel__object = {
72         .size = sizeof(struct evsel),
73         .init = perf_evsel__no_extra_init,
74         .fini = perf_evsel__no_extra_fini,
75 };
76
77 int perf_evsel__object_config(size_t object_size,
78                               int (*init)(struct evsel *evsel),
79                               void (*fini)(struct evsel *evsel))
80 {
81
82         if (object_size == 0)
83                 goto set_methods;
84
85         if (perf_evsel__object.size > object_size)
86                 return -EINVAL;
87
88         perf_evsel__object.size = object_size;
89
90 set_methods:
91         if (init != NULL)
92                 perf_evsel__object.init = init;
93
94         if (fini != NULL)
95                 perf_evsel__object.fini = fini;
96
97         return 0;
98 }
99
100 #define FD(e, x, y) (*(int *)xyarray__entry(e->core.fd, x, y))
101
102 int __perf_evsel__sample_size(u64 sample_type)
103 {
104         u64 mask = sample_type & PERF_SAMPLE_MASK;
105         int size = 0;
106         int i;
107
108         for (i = 0; i < 64; i++) {
109                 if (mask & (1ULL << i))
110                         size++;
111         }
112
113         size *= sizeof(u64);
114
115         return size;
116 }
117
118 /**
119  * __perf_evsel__calc_id_pos - calculate id_pos.
120  * @sample_type: sample type
121  *
122  * This function returns the position of the event id (PERF_SAMPLE_ID or
123  * PERF_SAMPLE_IDENTIFIER) in a sample event i.e. in the array of struct
124  * perf_record_sample.
125  */
126 static int __perf_evsel__calc_id_pos(u64 sample_type)
127 {
128         int idx = 0;
129
130         if (sample_type & PERF_SAMPLE_IDENTIFIER)
131                 return 0;
132
133         if (!(sample_type & PERF_SAMPLE_ID))
134                 return -1;
135
136         if (sample_type & PERF_SAMPLE_IP)
137                 idx += 1;
138
139         if (sample_type & PERF_SAMPLE_TID)
140                 idx += 1;
141
142         if (sample_type & PERF_SAMPLE_TIME)
143                 idx += 1;
144
145         if (sample_type & PERF_SAMPLE_ADDR)
146                 idx += 1;
147
148         return idx;
149 }
150
151 /**
152  * __perf_evsel__calc_is_pos - calculate is_pos.
153  * @sample_type: sample type
154  *
155  * This function returns the position (counting backwards) of the event id
156  * (PERF_SAMPLE_ID or PERF_SAMPLE_IDENTIFIER) in a non-sample event i.e. if
157  * sample_id_all is used there is an id sample appended to non-sample events.
158  */
159 static int __perf_evsel__calc_is_pos(u64 sample_type)
160 {
161         int idx = 1;
162
163         if (sample_type & PERF_SAMPLE_IDENTIFIER)
164                 return 1;
165
166         if (!(sample_type & PERF_SAMPLE_ID))
167                 return -1;
168
169         if (sample_type & PERF_SAMPLE_CPU)
170                 idx += 1;
171
172         if (sample_type & PERF_SAMPLE_STREAM_ID)
173                 idx += 1;
174
175         return idx;
176 }
177
178 void perf_evsel__calc_id_pos(struct evsel *evsel)
179 {
180         evsel->id_pos = __perf_evsel__calc_id_pos(evsel->core.attr.sample_type);
181         evsel->is_pos = __perf_evsel__calc_is_pos(evsel->core.attr.sample_type);
182 }
183
184 void __perf_evsel__set_sample_bit(struct evsel *evsel,
185                                   enum perf_event_sample_format bit)
186 {
187         if (!(evsel->core.attr.sample_type & bit)) {
188                 evsel->core.attr.sample_type |= bit;
189                 evsel->sample_size += sizeof(u64);
190                 perf_evsel__calc_id_pos(evsel);
191         }
192 }
193
194 void __perf_evsel__reset_sample_bit(struct evsel *evsel,
195                                     enum perf_event_sample_format bit)
196 {
197         if (evsel->core.attr.sample_type & bit) {
198                 evsel->core.attr.sample_type &= ~bit;
199                 evsel->sample_size -= sizeof(u64);
200                 perf_evsel__calc_id_pos(evsel);
201         }
202 }
203
204 void perf_evsel__set_sample_id(struct evsel *evsel,
205                                bool can_sample_identifier)
206 {
207         if (can_sample_identifier) {
208                 perf_evsel__reset_sample_bit(evsel, ID);
209                 perf_evsel__set_sample_bit(evsel, IDENTIFIER);
210         } else {
211                 perf_evsel__set_sample_bit(evsel, ID);
212         }
213         evsel->core.attr.read_format |= PERF_FORMAT_ID;
214 }
215
216 /**
217  * perf_evsel__is_function_event - Return whether given evsel is a function
218  * trace event
219  *
220  * @evsel - evsel selector to be tested
221  *
222  * Return %true if event is function trace event
223  */
224 bool perf_evsel__is_function_event(struct evsel *evsel)
225 {
226 #define FUNCTION_EVENT "ftrace:function"
227
228         return evsel->name &&
229                !strncmp(FUNCTION_EVENT, evsel->name, sizeof(FUNCTION_EVENT));
230
231 #undef FUNCTION_EVENT
232 }
233
234 void evsel__init(struct evsel *evsel,
235                  struct perf_event_attr *attr, int idx)
236 {
237         perf_evsel__init(&evsel->core, attr);
238         evsel->idx         = idx;
239         evsel->tracking    = !idx;
240         evsel->leader      = evsel;
241         evsel->unit        = "";
242         evsel->scale       = 1.0;
243         evsel->max_events  = ULONG_MAX;
244         evsel->evlist      = NULL;
245         evsel->bpf_obj     = NULL;
246         evsel->bpf_fd      = -1;
247         INIT_LIST_HEAD(&evsel->config_terms);
248         perf_evsel__object.init(evsel);
249         evsel->sample_size = __perf_evsel__sample_size(attr->sample_type);
250         perf_evsel__calc_id_pos(evsel);
251         evsel->cmdline_group_boundary = false;
252         evsel->metric_expr   = NULL;
253         evsel->metric_name   = NULL;
254         evsel->metric_events = NULL;
255         evsel->collect_stat  = false;
256         evsel->pmu_name      = NULL;
257 }
258
259 struct evsel *perf_evsel__new_idx(struct perf_event_attr *attr, int idx)
260 {
261         struct evsel *evsel = zalloc(perf_evsel__object.size);
262
263         if (!evsel)
264                 return NULL;
265         evsel__init(evsel, attr, idx);
266
267         if (perf_evsel__is_bpf_output(evsel)) {
268                 evsel->core.attr.sample_type |= (PERF_SAMPLE_RAW | PERF_SAMPLE_TIME |
269                                             PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD),
270                 evsel->core.attr.sample_period = 1;
271         }
272
273         if (perf_evsel__is_clock(evsel)) {
274                 /*
275                  * The evsel->unit points to static alias->unit
276                  * so it's ok to use static string in here.
277                  */
278                 static const char *unit = "msec";
279
280                 evsel->unit = unit;
281                 evsel->scale = 1e-6;
282         }
283
284         return evsel;
285 }
286
287 static bool perf_event_can_profile_kernel(void)
288 {
289         return perf_event_paranoid_check(1);
290 }
291
292 struct evsel *perf_evsel__new_cycles(bool precise)
293 {
294         struct perf_event_attr attr = {
295                 .type   = PERF_TYPE_HARDWARE,
296                 .config = PERF_COUNT_HW_CPU_CYCLES,
297                 .exclude_kernel = !perf_event_can_profile_kernel(),
298         };
299         struct evsel *evsel;
300
301         event_attr_init(&attr);
302
303         if (!precise)
304                 goto new_event;
305
306         /*
307          * Now let the usual logic to set up the perf_event_attr defaults
308          * to kick in when we return and before perf_evsel__open() is called.
309          */
310 new_event:
311         evsel = evsel__new(&attr);
312         if (evsel == NULL)
313                 goto out;
314
315         evsel->precise_max = true;
316
317         /* use asprintf() because free(evsel) assumes name is allocated */
318         if (asprintf(&evsel->name, "cycles%s%s%.*s",
319                      (attr.precise_ip || attr.exclude_kernel) ? ":" : "",
320                      attr.exclude_kernel ? "u" : "",
321                      attr.precise_ip ? attr.precise_ip + 1 : 0, "ppp") < 0)
322                 goto error_free;
323 out:
324         return evsel;
325 error_free:
326         evsel__delete(evsel);
327         evsel = NULL;
328         goto out;
329 }
330
331 /*
332  * Returns pointer with encoded error via <linux/err.h> interface.
333  */
334 struct evsel *perf_evsel__newtp_idx(const char *sys, const char *name, int idx)
335 {
336         struct evsel *evsel = zalloc(perf_evsel__object.size);
337         int err = -ENOMEM;
338
339         if (evsel == NULL) {
340                 goto out_err;
341         } else {
342                 struct perf_event_attr attr = {
343                         .type          = PERF_TYPE_TRACEPOINT,
344                         .sample_type   = (PERF_SAMPLE_RAW | PERF_SAMPLE_TIME |
345                                           PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD),
346                 };
347
348                 if (asprintf(&evsel->name, "%s:%s", sys, name) < 0)
349                         goto out_free;
350
351                 evsel->tp_format = trace_event__tp_format(sys, name);
352                 if (IS_ERR(evsel->tp_format)) {
353                         err = PTR_ERR(evsel->tp_format);
354                         goto out_free;
355                 }
356
357                 event_attr_init(&attr);
358                 attr.config = evsel->tp_format->id;
359                 attr.sample_period = 1;
360                 evsel__init(evsel, &attr, idx);
361         }
362
363         return evsel;
364
365 out_free:
366         zfree(&evsel->name);
367         free(evsel);
368 out_err:
369         return ERR_PTR(err);
370 }
371
372 const char *perf_evsel__hw_names[PERF_COUNT_HW_MAX] = {
373         "cycles",
374         "instructions",
375         "cache-references",
376         "cache-misses",
377         "branches",
378         "branch-misses",
379         "bus-cycles",
380         "stalled-cycles-frontend",
381         "stalled-cycles-backend",
382         "ref-cycles",
383 };
384
385 static const char *__perf_evsel__hw_name(u64 config)
386 {
387         if (config < PERF_COUNT_HW_MAX && perf_evsel__hw_names[config])
388                 return perf_evsel__hw_names[config];
389
390         return "unknown-hardware";
391 }
392
393 static int perf_evsel__add_modifiers(struct evsel *evsel, char *bf, size_t size)
394 {
395         int colon = 0, r = 0;
396         struct perf_event_attr *attr = &evsel->core.attr;
397         bool exclude_guest_default = false;
398
399 #define MOD_PRINT(context, mod) do {                                    \
400                 if (!attr->exclude_##context) {                         \
401                         if (!colon) colon = ++r;                        \
402                         r += scnprintf(bf + r, size - r, "%c", mod);    \
403                 } } while(0)
404
405         if (attr->exclude_kernel || attr->exclude_user || attr->exclude_hv) {
406                 MOD_PRINT(kernel, 'k');
407                 MOD_PRINT(user, 'u');
408                 MOD_PRINT(hv, 'h');
409                 exclude_guest_default = true;
410         }
411
412         if (attr->precise_ip) {
413                 if (!colon)
414                         colon = ++r;
415                 r += scnprintf(bf + r, size - r, "%.*s", attr->precise_ip, "ppp");
416                 exclude_guest_default = true;
417         }
418
419         if (attr->exclude_host || attr->exclude_guest == exclude_guest_default) {
420                 MOD_PRINT(host, 'H');
421                 MOD_PRINT(guest, 'G');
422         }
423 #undef MOD_PRINT
424         if (colon)
425                 bf[colon - 1] = ':';
426         return r;
427 }
428
429 static int perf_evsel__hw_name(struct evsel *evsel, char *bf, size_t size)
430 {
431         int r = scnprintf(bf, size, "%s", __perf_evsel__hw_name(evsel->core.attr.config));
432         return r + perf_evsel__add_modifiers(evsel, bf + r, size - r);
433 }
434
435 const char *perf_evsel__sw_names[PERF_COUNT_SW_MAX] = {
436         "cpu-clock",
437         "task-clock",
438         "page-faults",
439         "context-switches",
440         "cpu-migrations",
441         "minor-faults",
442         "major-faults",
443         "alignment-faults",
444         "emulation-faults",
445         "dummy",
446 };
447
448 static const char *__perf_evsel__sw_name(u64 config)
449 {
450         if (config < PERF_COUNT_SW_MAX && perf_evsel__sw_names[config])
451                 return perf_evsel__sw_names[config];
452         return "unknown-software";
453 }
454
455 static int perf_evsel__sw_name(struct evsel *evsel, char *bf, size_t size)
456 {
457         int r = scnprintf(bf, size, "%s", __perf_evsel__sw_name(evsel->core.attr.config));
458         return r + perf_evsel__add_modifiers(evsel, bf + r, size - r);
459 }
460
461 static int __perf_evsel__bp_name(char *bf, size_t size, u64 addr, u64 type)
462 {
463         int r;
464
465         r = scnprintf(bf, size, "mem:0x%" PRIx64 ":", addr);
466
467         if (type & HW_BREAKPOINT_R)
468                 r += scnprintf(bf + r, size - r, "r");
469
470         if (type & HW_BREAKPOINT_W)
471                 r += scnprintf(bf + r, size - r, "w");
472
473         if (type & HW_BREAKPOINT_X)
474                 r += scnprintf(bf + r, size - r, "x");
475
476         return r;
477 }
478
479 static int perf_evsel__bp_name(struct evsel *evsel, char *bf, size_t size)
480 {
481         struct perf_event_attr *attr = &evsel->core.attr;
482         int r = __perf_evsel__bp_name(bf, size, attr->bp_addr, attr->bp_type);
483         return r + perf_evsel__add_modifiers(evsel, bf + r, size - r);
484 }
485
486 const char *perf_evsel__hw_cache[PERF_COUNT_HW_CACHE_MAX]
487                                 [PERF_EVSEL__MAX_ALIASES] = {
488  { "L1-dcache", "l1-d",         "l1d",          "L1-data",              },
489  { "L1-icache", "l1-i",         "l1i",          "L1-instruction",       },
490  { "LLC",       "L2",                                                   },
491  { "dTLB",      "d-tlb",        "Data-TLB",                             },
492  { "iTLB",      "i-tlb",        "Instruction-TLB",                      },
493  { "branch",    "branches",     "bpu",          "btb",          "bpc",  },
494  { "node",                                                              },
495 };
496
497 const char *perf_evsel__hw_cache_op[PERF_COUNT_HW_CACHE_OP_MAX]
498                                    [PERF_EVSEL__MAX_ALIASES] = {
499  { "load",      "loads",        "read",                                 },
500  { "store",     "stores",       "write",                                },
501  { "prefetch",  "prefetches",   "speculative-read", "speculative-load", },
502 };
503
504 const char *perf_evsel__hw_cache_result[PERF_COUNT_HW_CACHE_RESULT_MAX]
505                                        [PERF_EVSEL__MAX_ALIASES] = {
506  { "refs",      "Reference",    "ops",          "access",               },
507  { "misses",    "miss",                                                 },
508 };
509
510 #define C(x)            PERF_COUNT_HW_CACHE_##x
511 #define CACHE_READ      (1 << C(OP_READ))
512 #define CACHE_WRITE     (1 << C(OP_WRITE))
513 #define CACHE_PREFETCH  (1 << C(OP_PREFETCH))
514 #define COP(x)          (1 << x)
515
516 /*
517  * cache operartion stat
518  * L1I : Read and prefetch only
519  * ITLB and BPU : Read-only
520  */
521 static unsigned long perf_evsel__hw_cache_stat[C(MAX)] = {
522  [C(L1D)]       = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
523  [C(L1I)]       = (CACHE_READ | CACHE_PREFETCH),
524  [C(LL)]        = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
525  [C(DTLB)]      = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
526  [C(ITLB)]      = (CACHE_READ),
527  [C(BPU)]       = (CACHE_READ),
528  [C(NODE)]      = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
529 };
530
531 bool perf_evsel__is_cache_op_valid(u8 type, u8 op)
532 {
533         if (perf_evsel__hw_cache_stat[type] & COP(op))
534                 return true;    /* valid */
535         else
536                 return false;   /* invalid */
537 }
538
539 int __perf_evsel__hw_cache_type_op_res_name(u8 type, u8 op, u8 result,
540                                             char *bf, size_t size)
541 {
542         if (result) {
543                 return scnprintf(bf, size, "%s-%s-%s", perf_evsel__hw_cache[type][0],
544                                  perf_evsel__hw_cache_op[op][0],
545                                  perf_evsel__hw_cache_result[result][0]);
546         }
547
548         return scnprintf(bf, size, "%s-%s", perf_evsel__hw_cache[type][0],
549                          perf_evsel__hw_cache_op[op][1]);
550 }
551
552 static int __perf_evsel__hw_cache_name(u64 config, char *bf, size_t size)
553 {
554         u8 op, result, type = (config >>  0) & 0xff;
555         const char *err = "unknown-ext-hardware-cache-type";
556
557         if (type >= PERF_COUNT_HW_CACHE_MAX)
558                 goto out_err;
559
560         op = (config >>  8) & 0xff;
561         err = "unknown-ext-hardware-cache-op";
562         if (op >= PERF_COUNT_HW_CACHE_OP_MAX)
563                 goto out_err;
564
565         result = (config >> 16) & 0xff;
566         err = "unknown-ext-hardware-cache-result";
567         if (result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
568                 goto out_err;
569
570         err = "invalid-cache";
571         if (!perf_evsel__is_cache_op_valid(type, op))
572                 goto out_err;
573
574         return __perf_evsel__hw_cache_type_op_res_name(type, op, result, bf, size);
575 out_err:
576         return scnprintf(bf, size, "%s", err);
577 }
578
579 static int perf_evsel__hw_cache_name(struct evsel *evsel, char *bf, size_t size)
580 {
581         int ret = __perf_evsel__hw_cache_name(evsel->core.attr.config, bf, size);
582         return ret + perf_evsel__add_modifiers(evsel, bf + ret, size - ret);
583 }
584
585 static int perf_evsel__raw_name(struct evsel *evsel, char *bf, size_t size)
586 {
587         int ret = scnprintf(bf, size, "raw 0x%" PRIx64, evsel->core.attr.config);
588         return ret + perf_evsel__add_modifiers(evsel, bf + ret, size - ret);
589 }
590
591 static int perf_evsel__tool_name(char *bf, size_t size)
592 {
593         int ret = scnprintf(bf, size, "duration_time");
594         return ret;
595 }
596
597 const char *perf_evsel__name(struct evsel *evsel)
598 {
599         char bf[128];
600
601         if (!evsel)
602                 goto out_unknown;
603
604         if (evsel->name)
605                 return evsel->name;
606
607         switch (evsel->core.attr.type) {
608         case PERF_TYPE_RAW:
609                 perf_evsel__raw_name(evsel, bf, sizeof(bf));
610                 break;
611
612         case PERF_TYPE_HARDWARE:
613                 perf_evsel__hw_name(evsel, bf, sizeof(bf));
614                 break;
615
616         case PERF_TYPE_HW_CACHE:
617                 perf_evsel__hw_cache_name(evsel, bf, sizeof(bf));
618                 break;
619
620         case PERF_TYPE_SOFTWARE:
621                 if (evsel->tool_event)
622                         perf_evsel__tool_name(bf, sizeof(bf));
623                 else
624                         perf_evsel__sw_name(evsel, bf, sizeof(bf));
625                 break;
626
627         case PERF_TYPE_TRACEPOINT:
628                 scnprintf(bf, sizeof(bf), "%s", "unknown tracepoint");
629                 break;
630
631         case PERF_TYPE_BREAKPOINT:
632                 perf_evsel__bp_name(evsel, bf, sizeof(bf));
633                 break;
634
635         default:
636                 scnprintf(bf, sizeof(bf), "unknown attr type: %d",
637                           evsel->core.attr.type);
638                 break;
639         }
640
641         evsel->name = strdup(bf);
642
643         if (evsel->name)
644                 return evsel->name;
645 out_unknown:
646         return "unknown";
647 }
648
649 const char *perf_evsel__group_name(struct evsel *evsel)
650 {
651         return evsel->group_name ?: "anon group";
652 }
653
654 /*
655  * Returns the group details for the specified leader,
656  * with following rules.
657  *
658  *  For record -e '{cycles,instructions}'
659  *    'anon group { cycles:u, instructions:u }'
660  *
661  *  For record -e 'cycles,instructions' and report --group
662  *    'cycles:u, instructions:u'
663  */
664 int perf_evsel__group_desc(struct evsel *evsel, char *buf, size_t size)
665 {
666         int ret = 0;
667         struct evsel *pos;
668         const char *group_name = perf_evsel__group_name(evsel);
669
670         if (!evsel->forced_leader)
671                 ret = scnprintf(buf, size, "%s { ", group_name);
672
673         ret += scnprintf(buf + ret, size - ret, "%s",
674                          perf_evsel__name(evsel));
675
676         for_each_group_member(pos, evsel)
677                 ret += scnprintf(buf + ret, size - ret, ", %s",
678                                  perf_evsel__name(pos));
679
680         if (!evsel->forced_leader)
681                 ret += scnprintf(buf + ret, size - ret, " }");
682
683         return ret;
684 }
685
686 static void __perf_evsel__config_callchain(struct evsel *evsel,
687                                            struct record_opts *opts,
688                                            struct callchain_param *param)
689 {
690         bool function = perf_evsel__is_function_event(evsel);
691         struct perf_event_attr *attr = &evsel->core.attr;
692
693         perf_evsel__set_sample_bit(evsel, CALLCHAIN);
694
695         attr->sample_max_stack = param->max_stack;
696
697         if (opts->kernel_callchains)
698                 attr->exclude_callchain_user = 1;
699         if (opts->user_callchains)
700                 attr->exclude_callchain_kernel = 1;
701         if (param->record_mode == CALLCHAIN_LBR) {
702                 if (!opts->branch_stack) {
703                         if (attr->exclude_user) {
704                                 pr_warning("LBR callstack option is only available "
705                                            "to get user callchain information. "
706                                            "Falling back to framepointers.\n");
707                         } else {
708                                 perf_evsel__set_sample_bit(evsel, BRANCH_STACK);
709                                 attr->branch_sample_type = PERF_SAMPLE_BRANCH_USER |
710                                                         PERF_SAMPLE_BRANCH_CALL_STACK |
711                                                         PERF_SAMPLE_BRANCH_NO_CYCLES |
712                                                         PERF_SAMPLE_BRANCH_NO_FLAGS;
713                         }
714                 } else
715                          pr_warning("Cannot use LBR callstack with branch stack. "
716                                     "Falling back to framepointers.\n");
717         }
718
719         if (param->record_mode == CALLCHAIN_DWARF) {
720                 if (!function) {
721                         perf_evsel__set_sample_bit(evsel, REGS_USER);
722                         perf_evsel__set_sample_bit(evsel, STACK_USER);
723                         if (opts->sample_user_regs && DWARF_MINIMAL_REGS != PERF_REGS_MASK) {
724                                 attr->sample_regs_user |= DWARF_MINIMAL_REGS;
725                                 pr_warning("WARNING: The use of --call-graph=dwarf may require all the user registers, "
726                                            "specifying a subset with --user-regs may render DWARF unwinding unreliable, "
727                                            "so the minimal registers set (IP, SP) is explicitly forced.\n");
728                         } else {
729                                 attr->sample_regs_user |= PERF_REGS_MASK;
730                         }
731                         attr->sample_stack_user = param->dump_size;
732                         attr->exclude_callchain_user = 1;
733                 } else {
734                         pr_info("Cannot use DWARF unwind for function trace event,"
735                                 " falling back to framepointers.\n");
736                 }
737         }
738
739         if (function) {
740                 pr_info("Disabling user space callchains for function trace event.\n");
741                 attr->exclude_callchain_user = 1;
742         }
743 }
744
745 void perf_evsel__config_callchain(struct evsel *evsel,
746                                   struct record_opts *opts,
747                                   struct callchain_param *param)
748 {
749         if (param->enabled)
750                 return __perf_evsel__config_callchain(evsel, opts, param);
751 }
752
753 static void
754 perf_evsel__reset_callgraph(struct evsel *evsel,
755                             struct callchain_param *param)
756 {
757         struct perf_event_attr *attr = &evsel->core.attr;
758
759         perf_evsel__reset_sample_bit(evsel, CALLCHAIN);
760         if (param->record_mode == CALLCHAIN_LBR) {
761                 perf_evsel__reset_sample_bit(evsel, BRANCH_STACK);
762                 attr->branch_sample_type &= ~(PERF_SAMPLE_BRANCH_USER |
763                                               PERF_SAMPLE_BRANCH_CALL_STACK);
764         }
765         if (param->record_mode == CALLCHAIN_DWARF) {
766                 perf_evsel__reset_sample_bit(evsel, REGS_USER);
767                 perf_evsel__reset_sample_bit(evsel, STACK_USER);
768         }
769 }
770
771 static void apply_config_terms(struct evsel *evsel,
772                                struct record_opts *opts, bool track)
773 {
774         struct perf_evsel_config_term *term;
775         struct list_head *config_terms = &evsel->config_terms;
776         struct perf_event_attr *attr = &evsel->core.attr;
777         /* callgraph default */
778         struct callchain_param param = {
779                 .record_mode = callchain_param.record_mode,
780         };
781         u32 dump_size = 0;
782         int max_stack = 0;
783         const char *callgraph_buf = NULL;
784
785         list_for_each_entry(term, config_terms, list) {
786                 switch (term->type) {
787                 case PERF_EVSEL__CONFIG_TERM_PERIOD:
788                         if (!(term->weak && opts->user_interval != ULLONG_MAX)) {
789                                 attr->sample_period = term->val.period;
790                                 attr->freq = 0;
791                                 perf_evsel__reset_sample_bit(evsel, PERIOD);
792                         }
793                         break;
794                 case PERF_EVSEL__CONFIG_TERM_FREQ:
795                         if (!(term->weak && opts->user_freq != UINT_MAX)) {
796                                 attr->sample_freq = term->val.freq;
797                                 attr->freq = 1;
798                                 perf_evsel__set_sample_bit(evsel, PERIOD);
799                         }
800                         break;
801                 case PERF_EVSEL__CONFIG_TERM_TIME:
802                         if (term->val.time)
803                                 perf_evsel__set_sample_bit(evsel, TIME);
804                         else
805                                 perf_evsel__reset_sample_bit(evsel, TIME);
806                         break;
807                 case PERF_EVSEL__CONFIG_TERM_CALLGRAPH:
808                         callgraph_buf = term->val.callgraph;
809                         break;
810                 case PERF_EVSEL__CONFIG_TERM_BRANCH:
811                         if (term->val.branch && strcmp(term->val.branch, "no")) {
812                                 perf_evsel__set_sample_bit(evsel, BRANCH_STACK);
813                                 parse_branch_str(term->val.branch,
814                                                  &attr->branch_sample_type);
815                         } else
816                                 perf_evsel__reset_sample_bit(evsel, BRANCH_STACK);
817                         break;
818                 case PERF_EVSEL__CONFIG_TERM_STACK_USER:
819                         dump_size = term->val.stack_user;
820                         break;
821                 case PERF_EVSEL__CONFIG_TERM_MAX_STACK:
822                         max_stack = term->val.max_stack;
823                         break;
824                 case PERF_EVSEL__CONFIG_TERM_MAX_EVENTS:
825                         evsel->max_events = term->val.max_events;
826                         break;
827                 case PERF_EVSEL__CONFIG_TERM_INHERIT:
828                         /*
829                          * attr->inherit should has already been set by
830                          * perf_evsel__config. If user explicitly set
831                          * inherit using config terms, override global
832                          * opt->no_inherit setting.
833                          */
834                         attr->inherit = term->val.inherit ? 1 : 0;
835                         break;
836                 case PERF_EVSEL__CONFIG_TERM_OVERWRITE:
837                         attr->write_backward = term->val.overwrite ? 1 : 0;
838                         break;
839                 case PERF_EVSEL__CONFIG_TERM_DRV_CFG:
840                         break;
841                 case PERF_EVSEL__CONFIG_TERM_PERCORE:
842                         break;
843                 case PERF_EVSEL__CONFIG_TERM_AUX_OUTPUT:
844                         attr->aux_output = term->val.aux_output ? 1 : 0;
845                         break;
846                 default:
847                         break;
848                 }
849         }
850
851         /* User explicitly set per-event callgraph, clear the old setting and reset. */
852         if ((callgraph_buf != NULL) || (dump_size > 0) || max_stack) {
853                 bool sample_address = false;
854
855                 if (max_stack) {
856                         param.max_stack = max_stack;
857                         if (callgraph_buf == NULL)
858                                 callgraph_buf = "fp";
859                 }
860
861                 /* parse callgraph parameters */
862                 if (callgraph_buf != NULL) {
863                         if (!strcmp(callgraph_buf, "no")) {
864                                 param.enabled = false;
865                                 param.record_mode = CALLCHAIN_NONE;
866                         } else {
867                                 param.enabled = true;
868                                 if (parse_callchain_record(callgraph_buf, &param)) {
869                                         pr_err("per-event callgraph setting for %s failed. "
870                                                "Apply callgraph global setting for it\n",
871                                                evsel->name);
872                                         return;
873                                 }
874                                 if (param.record_mode == CALLCHAIN_DWARF)
875                                         sample_address = true;
876                         }
877                 }
878                 if (dump_size > 0) {
879                         dump_size = round_up(dump_size, sizeof(u64));
880                         param.dump_size = dump_size;
881                 }
882
883                 /* If global callgraph set, clear it */
884                 if (callchain_param.enabled)
885                         perf_evsel__reset_callgraph(evsel, &callchain_param);
886
887                 /* set perf-event callgraph */
888                 if (param.enabled) {
889                         if (sample_address) {
890                                 perf_evsel__set_sample_bit(evsel, ADDR);
891                                 perf_evsel__set_sample_bit(evsel, DATA_SRC);
892                                 evsel->core.attr.mmap_data = track;
893                         }
894                         perf_evsel__config_callchain(evsel, opts, &param);
895                 }
896         }
897 }
898
899 static bool is_dummy_event(struct evsel *evsel)
900 {
901         return (evsel->core.attr.type == PERF_TYPE_SOFTWARE) &&
902                (evsel->core.attr.config == PERF_COUNT_SW_DUMMY);
903 }
904
905 /*
906  * The enable_on_exec/disabled value strategy:
907  *
908  *  1) For any type of traced program:
909  *    - all independent events and group leaders are disabled
910  *    - all group members are enabled
911  *
912  *     Group members are ruled by group leaders. They need to
913  *     be enabled, because the group scheduling relies on that.
914  *
915  *  2) For traced programs executed by perf:
916  *     - all independent events and group leaders have
917  *       enable_on_exec set
918  *     - we don't specifically enable or disable any event during
919  *       the record command
920  *
921  *     Independent events and group leaders are initially disabled
922  *     and get enabled by exec. Group members are ruled by group
923  *     leaders as stated in 1).
924  *
925  *  3) For traced programs attached by perf (pid/tid):
926  *     - we specifically enable or disable all events during
927  *       the record command
928  *
929  *     When attaching events to already running traced we
930  *     enable/disable events specifically, as there's no
931  *     initial traced exec call.
932  */
933 void perf_evsel__config(struct evsel *evsel, struct record_opts *opts,
934                         struct callchain_param *callchain)
935 {
936         struct evsel *leader = evsel->leader;
937         struct perf_event_attr *attr = &evsel->core.attr;
938         int track = evsel->tracking;
939         bool per_cpu = opts->target.default_per_cpu && !opts->target.per_thread;
940
941         attr->sample_id_all = perf_missing_features.sample_id_all ? 0 : 1;
942         attr->inherit       = !opts->no_inherit;
943         attr->write_backward = opts->overwrite ? 1 : 0;
944
945         perf_evsel__set_sample_bit(evsel, IP);
946         perf_evsel__set_sample_bit(evsel, TID);
947
948         if (evsel->sample_read) {
949                 perf_evsel__set_sample_bit(evsel, READ);
950
951                 /*
952                  * We need ID even in case of single event, because
953                  * PERF_SAMPLE_READ process ID specific data.
954                  */
955                 perf_evsel__set_sample_id(evsel, false);
956
957                 /*
958                  * Apply group format only if we belong to group
959                  * with more than one members.
960                  */
961                 if (leader->core.nr_members > 1) {
962                         attr->read_format |= PERF_FORMAT_GROUP;
963                         attr->inherit = 0;
964                 }
965         }
966
967         /*
968          * We default some events to have a default interval. But keep
969          * it a weak assumption overridable by the user.
970          */
971         if (!attr->sample_period || (opts->user_freq != UINT_MAX ||
972                                      opts->user_interval != ULLONG_MAX)) {
973                 if (opts->freq) {
974                         perf_evsel__set_sample_bit(evsel, PERIOD);
975                         attr->freq              = 1;
976                         attr->sample_freq       = opts->freq;
977                 } else {
978                         attr->sample_period = opts->default_interval;
979                 }
980         }
981
982         /*
983          * Disable sampling for all group members other
984          * than leader in case leader 'leads' the sampling.
985          */
986         if ((leader != evsel) && leader->sample_read) {
987                 attr->freq           = 0;
988                 attr->sample_freq    = 0;
989                 attr->sample_period  = 0;
990                 attr->write_backward = 0;
991
992                 /*
993                  * We don't get sample for slave events, we make them
994                  * when delivering group leader sample. Set the slave
995                  * event to follow the master sample_type to ease up
996                  * report.
997                  */
998                 attr->sample_type = leader->core.attr.sample_type;
999         }
1000
1001         if (opts->no_samples)
1002                 attr->sample_freq = 0;
1003
1004         if (opts->inherit_stat) {
1005                 evsel->core.attr.read_format |=
1006                         PERF_FORMAT_TOTAL_TIME_ENABLED |
1007                         PERF_FORMAT_TOTAL_TIME_RUNNING |
1008                         PERF_FORMAT_ID;
1009                 attr->inherit_stat = 1;
1010         }
1011
1012         if (opts->sample_address) {
1013                 perf_evsel__set_sample_bit(evsel, ADDR);
1014                 attr->mmap_data = track;
1015         }
1016
1017         /*
1018          * We don't allow user space callchains for  function trace
1019          * event, due to issues with page faults while tracing page
1020          * fault handler and its overall trickiness nature.
1021          */
1022         if (perf_evsel__is_function_event(evsel))
1023                 evsel->core.attr.exclude_callchain_user = 1;
1024
1025         if (callchain && callchain->enabled && !evsel->no_aux_samples)
1026                 perf_evsel__config_callchain(evsel, opts, callchain);
1027
1028         if (opts->sample_intr_regs) {
1029                 attr->sample_regs_intr = opts->sample_intr_regs;
1030                 perf_evsel__set_sample_bit(evsel, REGS_INTR);
1031         }
1032
1033         if (opts->sample_user_regs) {
1034                 attr->sample_regs_user |= opts->sample_user_regs;
1035                 perf_evsel__set_sample_bit(evsel, REGS_USER);
1036         }
1037
1038         if (target__has_cpu(&opts->target) || opts->sample_cpu)
1039                 perf_evsel__set_sample_bit(evsel, CPU);
1040
1041         /*
1042          * When the user explicitly disabled time don't force it here.
1043          */
1044         if (opts->sample_time &&
1045             (!perf_missing_features.sample_id_all &&
1046             (!opts->no_inherit || target__has_cpu(&opts->target) || per_cpu ||
1047              opts->sample_time_set)))
1048                 perf_evsel__set_sample_bit(evsel, TIME);
1049
1050         if (opts->raw_samples && !evsel->no_aux_samples) {
1051                 perf_evsel__set_sample_bit(evsel, TIME);
1052                 perf_evsel__set_sample_bit(evsel, RAW);
1053                 perf_evsel__set_sample_bit(evsel, CPU);
1054         }
1055
1056         if (opts->sample_address)
1057                 perf_evsel__set_sample_bit(evsel, DATA_SRC);
1058
1059         if (opts->sample_phys_addr)
1060                 perf_evsel__set_sample_bit(evsel, PHYS_ADDR);
1061
1062         if (opts->no_buffering) {
1063                 attr->watermark = 0;
1064                 attr->wakeup_events = 1;
1065         }
1066         if (opts->branch_stack && !evsel->no_aux_samples) {
1067                 perf_evsel__set_sample_bit(evsel, BRANCH_STACK);
1068                 attr->branch_sample_type = opts->branch_stack;
1069         }
1070
1071         if (opts->sample_weight)
1072                 perf_evsel__set_sample_bit(evsel, WEIGHT);
1073
1074         attr->task  = track;
1075         attr->mmap  = track;
1076         attr->mmap2 = track && !perf_missing_features.mmap2;
1077         attr->comm  = track;
1078         attr->ksymbol = track && !perf_missing_features.ksymbol;
1079         attr->bpf_event = track && !opts->no_bpf_event && !perf_missing_features.bpf;
1080
1081         if (opts->record_namespaces)
1082                 attr->namespaces  = track;
1083
1084         if (opts->record_switch_events)
1085                 attr->context_switch = track;
1086
1087         if (opts->sample_transaction)
1088                 perf_evsel__set_sample_bit(evsel, TRANSACTION);
1089
1090         if (opts->running_time) {
1091                 evsel->core.attr.read_format |=
1092                         PERF_FORMAT_TOTAL_TIME_ENABLED |
1093                         PERF_FORMAT_TOTAL_TIME_RUNNING;
1094         }
1095
1096         /*
1097          * XXX see the function comment above
1098          *
1099          * Disabling only independent events or group leaders,
1100          * keeping group members enabled.
1101          */
1102         if (perf_evsel__is_group_leader(evsel))
1103                 attr->disabled = 1;
1104
1105         /*
1106          * Setting enable_on_exec for independent events and
1107          * group leaders for traced executed by perf.
1108          */
1109         if (target__none(&opts->target) && perf_evsel__is_group_leader(evsel) &&
1110                 !opts->initial_delay)
1111                 attr->enable_on_exec = 1;
1112
1113         if (evsel->immediate) {
1114                 attr->disabled = 0;
1115                 attr->enable_on_exec = 0;
1116         }
1117
1118         clockid = opts->clockid;
1119         if (opts->use_clockid) {
1120                 attr->use_clockid = 1;
1121                 attr->clockid = opts->clockid;
1122         }
1123
1124         if (evsel->precise_max)
1125                 attr->precise_ip = 3;
1126
1127         if (opts->all_user) {
1128                 attr->exclude_kernel = 1;
1129                 attr->exclude_user   = 0;
1130         }
1131
1132         if (opts->all_kernel) {
1133                 attr->exclude_kernel = 0;
1134                 attr->exclude_user   = 1;
1135         }
1136
1137         if (evsel->core.own_cpus || evsel->unit)
1138                 evsel->core.attr.read_format |= PERF_FORMAT_ID;
1139
1140         /*
1141          * Apply event specific term settings,
1142          * it overloads any global configuration.
1143          */
1144         apply_config_terms(evsel, opts, track);
1145
1146         evsel->ignore_missing_thread = opts->ignore_missing_thread;
1147
1148         /* The --period option takes the precedence. */
1149         if (opts->period_set) {
1150                 if (opts->period)
1151                         perf_evsel__set_sample_bit(evsel, PERIOD);
1152                 else
1153                         perf_evsel__reset_sample_bit(evsel, PERIOD);
1154         }
1155
1156         /*
1157          * For initial_delay, a dummy event is added implicitly.
1158          * The software event will trigger -EOPNOTSUPP error out,
1159          * if BRANCH_STACK bit is set.
1160          */
1161         if (opts->initial_delay && is_dummy_event(evsel))
1162                 perf_evsel__reset_sample_bit(evsel, BRANCH_STACK);
1163 }
1164
1165 int perf_evsel__set_filter(struct evsel *evsel, const char *filter)
1166 {
1167         char *new_filter = strdup(filter);
1168
1169         if (new_filter != NULL) {
1170                 free(evsel->filter);
1171                 evsel->filter = new_filter;
1172                 return 0;
1173         }
1174
1175         return -1;
1176 }
1177
1178 static int perf_evsel__append_filter(struct evsel *evsel,
1179                                      const char *fmt, const char *filter)
1180 {
1181         char *new_filter;
1182
1183         if (evsel->filter == NULL)
1184                 return perf_evsel__set_filter(evsel, filter);
1185
1186         if (asprintf(&new_filter, fmt, evsel->filter, filter) > 0) {
1187                 free(evsel->filter);
1188                 evsel->filter = new_filter;
1189                 return 0;
1190         }
1191
1192         return -1;
1193 }
1194
1195 int perf_evsel__append_tp_filter(struct evsel *evsel, const char *filter)
1196 {
1197         return perf_evsel__append_filter(evsel, "(%s) && (%s)", filter);
1198 }
1199
1200 int perf_evsel__append_addr_filter(struct evsel *evsel, const char *filter)
1201 {
1202         return perf_evsel__append_filter(evsel, "%s,%s", filter);
1203 }
1204
1205 int evsel__enable(struct evsel *evsel)
1206 {
1207         int err = perf_evsel__enable(&evsel->core);
1208
1209         if (!err)
1210                 evsel->disabled = false;
1211
1212         return err;
1213 }
1214
1215 int evsel__disable(struct evsel *evsel)
1216 {
1217         int err = perf_evsel__disable(&evsel->core);
1218         /*
1219          * We mark it disabled here so that tools that disable a event can
1220          * ignore events after they disable it. I.e. the ring buffer may have
1221          * already a few more events queued up before the kernel got the stop
1222          * request.
1223          */
1224         if (!err)
1225                 evsel->disabled = true;
1226
1227         return err;
1228 }
1229
1230 static void perf_evsel__free_config_terms(struct evsel *evsel)
1231 {
1232         struct perf_evsel_config_term *term, *h;
1233
1234         list_for_each_entry_safe(term, h, &evsel->config_terms, list) {
1235                 list_del_init(&term->list);
1236                 free(term);
1237         }
1238 }
1239
1240 void perf_evsel__exit(struct evsel *evsel)
1241 {
1242         assert(list_empty(&evsel->core.node));
1243         assert(evsel->evlist == NULL);
1244         perf_evsel__free_counts(evsel);
1245         perf_evsel__free_fd(&evsel->core);
1246         perf_evsel__free_id(&evsel->core);
1247         perf_evsel__free_config_terms(evsel);
1248         cgroup__put(evsel->cgrp);
1249         perf_cpu_map__put(evsel->core.cpus);
1250         perf_cpu_map__put(evsel->core.own_cpus);
1251         perf_thread_map__put(evsel->core.threads);
1252         zfree(&evsel->group_name);
1253         zfree(&evsel->name);
1254         perf_evsel__object.fini(evsel);
1255 }
1256
1257 void evsel__delete(struct evsel *evsel)
1258 {
1259         perf_evsel__exit(evsel);
1260         free(evsel);
1261 }
1262
1263 void perf_evsel__compute_deltas(struct evsel *evsel, int cpu, int thread,
1264                                 struct perf_counts_values *count)
1265 {
1266         struct perf_counts_values tmp;
1267
1268         if (!evsel->prev_raw_counts)
1269                 return;
1270
1271         if (cpu == -1) {
1272                 tmp = evsel->prev_raw_counts->aggr;
1273                 evsel->prev_raw_counts->aggr = *count;
1274         } else {
1275                 tmp = *perf_counts(evsel->prev_raw_counts, cpu, thread);
1276                 *perf_counts(evsel->prev_raw_counts, cpu, thread) = *count;
1277         }
1278
1279         count->val = count->val - tmp.val;
1280         count->ena = count->ena - tmp.ena;
1281         count->run = count->run - tmp.run;
1282 }
1283
1284 void perf_counts_values__scale(struct perf_counts_values *count,
1285                                bool scale, s8 *pscaled)
1286 {
1287         s8 scaled = 0;
1288
1289         if (scale) {
1290                 if (count->run == 0) {
1291                         scaled = -1;
1292                         count->val = 0;
1293                 } else if (count->run < count->ena) {
1294                         scaled = 1;
1295                         count->val = (u64)((double) count->val * count->ena / count->run);
1296                 }
1297         }
1298
1299         if (pscaled)
1300                 *pscaled = scaled;
1301 }
1302
1303 static int
1304 perf_evsel__read_one(struct evsel *evsel, int cpu, int thread)
1305 {
1306         struct perf_counts_values *count = perf_counts(evsel->counts, cpu, thread);
1307
1308         return perf_evsel__read(&evsel->core, cpu, thread, count);
1309 }
1310
1311 static void
1312 perf_evsel__set_count(struct evsel *counter, int cpu, int thread,
1313                       u64 val, u64 ena, u64 run)
1314 {
1315         struct perf_counts_values *count;
1316
1317         count = perf_counts(counter->counts, cpu, thread);
1318
1319         count->val    = val;
1320         count->ena    = ena;
1321         count->run    = run;
1322
1323         perf_counts__set_loaded(counter->counts, cpu, thread, true);
1324 }
1325
1326 static int
1327 perf_evsel__process_group_data(struct evsel *leader,
1328                                int cpu, int thread, u64 *data)
1329 {
1330         u64 read_format = leader->core.attr.read_format;
1331         struct sample_read_value *v;
1332         u64 nr, ena = 0, run = 0, i;
1333
1334         nr = *data++;
1335
1336         if (nr != (u64) leader->core.nr_members)
1337                 return -EINVAL;
1338
1339         if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1340                 ena = *data++;
1341
1342         if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1343                 run = *data++;
1344
1345         v = (struct sample_read_value *) data;
1346
1347         perf_evsel__set_count(leader, cpu, thread,
1348                               v[0].value, ena, run);
1349
1350         for (i = 1; i < nr; i++) {
1351                 struct evsel *counter;
1352
1353                 counter = perf_evlist__id2evsel(leader->evlist, v[i].id);
1354                 if (!counter)
1355                         return -EINVAL;
1356
1357                 perf_evsel__set_count(counter, cpu, thread,
1358                                       v[i].value, ena, run);
1359         }
1360
1361         return 0;
1362 }
1363
1364 static int
1365 perf_evsel__read_group(struct evsel *leader, int cpu, int thread)
1366 {
1367         struct perf_stat_evsel *ps = leader->stats;
1368         u64 read_format = leader->core.attr.read_format;
1369         int size = perf_evsel__read_size(&leader->core);
1370         u64 *data = ps->group_data;
1371
1372         if (!(read_format & PERF_FORMAT_ID))
1373                 return -EINVAL;
1374
1375         if (!perf_evsel__is_group_leader(leader))
1376                 return -EINVAL;
1377
1378         if (!data) {
1379                 data = zalloc(size);
1380                 if (!data)
1381                         return -ENOMEM;
1382
1383                 ps->group_data = data;
1384         }
1385
1386         if (FD(leader, cpu, thread) < 0)
1387                 return -EINVAL;
1388
1389         if (readn(FD(leader, cpu, thread), data, size) <= 0)
1390                 return -errno;
1391
1392         return perf_evsel__process_group_data(leader, cpu, thread, data);
1393 }
1394
1395 int perf_evsel__read_counter(struct evsel *evsel, int cpu, int thread)
1396 {
1397         u64 read_format = evsel->core.attr.read_format;
1398
1399         if (read_format & PERF_FORMAT_GROUP)
1400                 return perf_evsel__read_group(evsel, cpu, thread);
1401         else
1402                 return perf_evsel__read_one(evsel, cpu, thread);
1403 }
1404
1405 int __perf_evsel__read_on_cpu(struct evsel *evsel,
1406                               int cpu, int thread, bool scale)
1407 {
1408         struct perf_counts_values count;
1409         size_t nv = scale ? 3 : 1;
1410
1411         if (FD(evsel, cpu, thread) < 0)
1412                 return -EINVAL;
1413
1414         if (evsel->counts == NULL && perf_evsel__alloc_counts(evsel, cpu + 1, thread + 1) < 0)
1415                 return -ENOMEM;
1416
1417         if (readn(FD(evsel, cpu, thread), &count, nv * sizeof(u64)) <= 0)
1418                 return -errno;
1419
1420         perf_evsel__compute_deltas(evsel, cpu, thread, &count);
1421         perf_counts_values__scale(&count, scale, NULL);
1422         *perf_counts(evsel->counts, cpu, thread) = count;
1423         return 0;
1424 }
1425
1426 static int get_group_fd(struct evsel *evsel, int cpu, int thread)
1427 {
1428         struct evsel *leader = evsel->leader;
1429         int fd;
1430
1431         if (perf_evsel__is_group_leader(evsel))
1432                 return -1;
1433
1434         /*
1435          * Leader must be already processed/open,
1436          * if not it's a bug.
1437          */
1438         BUG_ON(!leader->core.fd);
1439
1440         fd = FD(leader, cpu, thread);
1441         BUG_ON(fd == -1);
1442
1443         return fd;
1444 }
1445
1446 struct bit_names {
1447         int bit;
1448         const char *name;
1449 };
1450
1451 static void __p_bits(char *buf, size_t size, u64 value, struct bit_names *bits)
1452 {
1453         bool first_bit = true;
1454         int i = 0;
1455
1456         do {
1457                 if (value & bits[i].bit) {
1458                         buf += scnprintf(buf, size, "%s%s", first_bit ? "" : "|", bits[i].name);
1459                         first_bit = false;
1460                 }
1461         } while (bits[++i].name != NULL);
1462 }
1463
1464 static void __p_sample_type(char *buf, size_t size, u64 value)
1465 {
1466 #define bit_name(n) { PERF_SAMPLE_##n, #n }
1467         struct bit_names bits[] = {
1468                 bit_name(IP), bit_name(TID), bit_name(TIME), bit_name(ADDR),
1469                 bit_name(READ), bit_name(CALLCHAIN), bit_name(ID), bit_name(CPU),
1470                 bit_name(PERIOD), bit_name(STREAM_ID), bit_name(RAW),
1471                 bit_name(BRANCH_STACK), bit_name(REGS_USER), bit_name(STACK_USER),
1472                 bit_name(IDENTIFIER), bit_name(REGS_INTR), bit_name(DATA_SRC),
1473                 bit_name(WEIGHT), bit_name(PHYS_ADDR),
1474                 { .name = NULL, }
1475         };
1476 #undef bit_name
1477         __p_bits(buf, size, value, bits);
1478 }
1479
1480 static void __p_branch_sample_type(char *buf, size_t size, u64 value)
1481 {
1482 #define bit_name(n) { PERF_SAMPLE_BRANCH_##n, #n }
1483         struct bit_names bits[] = {
1484                 bit_name(USER), bit_name(KERNEL), bit_name(HV), bit_name(ANY),
1485                 bit_name(ANY_CALL), bit_name(ANY_RETURN), bit_name(IND_CALL),
1486                 bit_name(ABORT_TX), bit_name(IN_TX), bit_name(NO_TX),
1487                 bit_name(COND), bit_name(CALL_STACK), bit_name(IND_JUMP),
1488                 bit_name(CALL), bit_name(NO_FLAGS), bit_name(NO_CYCLES),
1489                 { .name = NULL, }
1490         };
1491 #undef bit_name
1492         __p_bits(buf, size, value, bits);
1493 }
1494
1495 static void __p_read_format(char *buf, size_t size, u64 value)
1496 {
1497 #define bit_name(n) { PERF_FORMAT_##n, #n }
1498         struct bit_names bits[] = {
1499                 bit_name(TOTAL_TIME_ENABLED), bit_name(TOTAL_TIME_RUNNING),
1500                 bit_name(ID), bit_name(GROUP),
1501                 { .name = NULL, }
1502         };
1503 #undef bit_name
1504         __p_bits(buf, size, value, bits);
1505 }
1506
1507 #define BUF_SIZE                1024
1508
1509 #define p_hex(val)              snprintf(buf, BUF_SIZE, "%#"PRIx64, (uint64_t)(val))
1510 #define p_unsigned(val)         snprintf(buf, BUF_SIZE, "%"PRIu64, (uint64_t)(val))
1511 #define p_signed(val)           snprintf(buf, BUF_SIZE, "%"PRId64, (int64_t)(val))
1512 #define p_sample_type(val)      __p_sample_type(buf, BUF_SIZE, val)
1513 #define p_branch_sample_type(val) __p_branch_sample_type(buf, BUF_SIZE, val)
1514 #define p_read_format(val)      __p_read_format(buf, BUF_SIZE, val)
1515
1516 #define PRINT_ATTRn(_n, _f, _p)                         \
1517 do {                                                    \
1518         if (attr->_f) {                                 \
1519                 _p(attr->_f);                           \
1520                 ret += attr__fprintf(fp, _n, buf, priv);\
1521         }                                               \
1522 } while (0)
1523
1524 #define PRINT_ATTRf(_f, _p)     PRINT_ATTRn(#_f, _f, _p)
1525
1526 int perf_event_attr__fprintf(FILE *fp, struct perf_event_attr *attr,
1527                              attr__fprintf_f attr__fprintf, void *priv)
1528 {
1529         char buf[BUF_SIZE];
1530         int ret = 0;
1531
1532         PRINT_ATTRf(type, p_unsigned);
1533         PRINT_ATTRf(size, p_unsigned);
1534         PRINT_ATTRf(config, p_hex);
1535         PRINT_ATTRn("{ sample_period, sample_freq }", sample_period, p_unsigned);
1536         PRINT_ATTRf(sample_type, p_sample_type);
1537         PRINT_ATTRf(read_format, p_read_format);
1538
1539         PRINT_ATTRf(disabled, p_unsigned);
1540         PRINT_ATTRf(inherit, p_unsigned);
1541         PRINT_ATTRf(pinned, p_unsigned);
1542         PRINT_ATTRf(exclusive, p_unsigned);
1543         PRINT_ATTRf(exclude_user, p_unsigned);
1544         PRINT_ATTRf(exclude_kernel, p_unsigned);
1545         PRINT_ATTRf(exclude_hv, p_unsigned);
1546         PRINT_ATTRf(exclude_idle, p_unsigned);
1547         PRINT_ATTRf(mmap, p_unsigned);
1548         PRINT_ATTRf(comm, p_unsigned);
1549         PRINT_ATTRf(freq, p_unsigned);
1550         PRINT_ATTRf(inherit_stat, p_unsigned);
1551         PRINT_ATTRf(enable_on_exec, p_unsigned);
1552         PRINT_ATTRf(task, p_unsigned);
1553         PRINT_ATTRf(watermark, p_unsigned);
1554         PRINT_ATTRf(precise_ip, p_unsigned);
1555         PRINT_ATTRf(mmap_data, p_unsigned);
1556         PRINT_ATTRf(sample_id_all, p_unsigned);
1557         PRINT_ATTRf(exclude_host, p_unsigned);
1558         PRINT_ATTRf(exclude_guest, p_unsigned);
1559         PRINT_ATTRf(exclude_callchain_kernel, p_unsigned);
1560         PRINT_ATTRf(exclude_callchain_user, p_unsigned);
1561         PRINT_ATTRf(mmap2, p_unsigned);
1562         PRINT_ATTRf(comm_exec, p_unsigned);
1563         PRINT_ATTRf(use_clockid, p_unsigned);
1564         PRINT_ATTRf(context_switch, p_unsigned);
1565         PRINT_ATTRf(write_backward, p_unsigned);
1566         PRINT_ATTRf(namespaces, p_unsigned);
1567         PRINT_ATTRf(ksymbol, p_unsigned);
1568         PRINT_ATTRf(bpf_event, p_unsigned);
1569         PRINT_ATTRf(aux_output, p_unsigned);
1570
1571         PRINT_ATTRn("{ wakeup_events, wakeup_watermark }", wakeup_events, p_unsigned);
1572         PRINT_ATTRf(bp_type, p_unsigned);
1573         PRINT_ATTRn("{ bp_addr, config1 }", bp_addr, p_hex);
1574         PRINT_ATTRn("{ bp_len, config2 }", bp_len, p_hex);
1575         PRINT_ATTRf(branch_sample_type, p_branch_sample_type);
1576         PRINT_ATTRf(sample_regs_user, p_hex);
1577         PRINT_ATTRf(sample_stack_user, p_unsigned);
1578         PRINT_ATTRf(clockid, p_signed);
1579         PRINT_ATTRf(sample_regs_intr, p_hex);
1580         PRINT_ATTRf(aux_watermark, p_unsigned);
1581         PRINT_ATTRf(sample_max_stack, p_unsigned);
1582
1583         return ret;
1584 }
1585
1586 static int __open_attr__fprintf(FILE *fp, const char *name, const char *val,
1587                                 void *priv __maybe_unused)
1588 {
1589         return fprintf(fp, "  %-32s %s\n", name, val);
1590 }
1591
1592 static void perf_evsel__remove_fd(struct evsel *pos,
1593                                   int nr_cpus, int nr_threads,
1594                                   int thread_idx)
1595 {
1596         for (int cpu = 0; cpu < nr_cpus; cpu++)
1597                 for (int thread = thread_idx; thread < nr_threads - 1; thread++)
1598                         FD(pos, cpu, thread) = FD(pos, cpu, thread + 1);
1599 }
1600
1601 static int update_fds(struct evsel *evsel,
1602                       int nr_cpus, int cpu_idx,
1603                       int nr_threads, int thread_idx)
1604 {
1605         struct evsel *pos;
1606
1607         if (cpu_idx >= nr_cpus || thread_idx >= nr_threads)
1608                 return -EINVAL;
1609
1610         evlist__for_each_entry(evsel->evlist, pos) {
1611                 nr_cpus = pos != evsel ? nr_cpus : cpu_idx;
1612
1613                 perf_evsel__remove_fd(pos, nr_cpus, nr_threads, thread_idx);
1614
1615                 /*
1616                  * Since fds for next evsel has not been created,
1617                  * there is no need to iterate whole event list.
1618                  */
1619                 if (pos == evsel)
1620                         break;
1621         }
1622         return 0;
1623 }
1624
1625 static bool ignore_missing_thread(struct evsel *evsel,
1626                                   int nr_cpus, int cpu,
1627                                   struct perf_thread_map *threads,
1628                                   int thread, int err)
1629 {
1630         pid_t ignore_pid = perf_thread_map__pid(threads, thread);
1631
1632         if (!evsel->ignore_missing_thread)
1633                 return false;
1634
1635         /* The system wide setup does not work with threads. */
1636         if (evsel->core.system_wide)
1637                 return false;
1638
1639         /* The -ESRCH is perf event syscall errno for pid's not found. */
1640         if (err != -ESRCH)
1641                 return false;
1642
1643         /* If there's only one thread, let it fail. */
1644         if (threads->nr == 1)
1645                 return false;
1646
1647         /*
1648          * We should remove fd for missing_thread first
1649          * because thread_map__remove() will decrease threads->nr.
1650          */
1651         if (update_fds(evsel, nr_cpus, cpu, threads->nr, thread))
1652                 return false;
1653
1654         if (thread_map__remove(threads, thread))
1655                 return false;
1656
1657         pr_warning("WARNING: Ignored open failure for pid %d\n",
1658                    ignore_pid);
1659         return true;
1660 }
1661
1662 static void display_attr(struct perf_event_attr *attr)
1663 {
1664         if (verbose >= 2) {
1665                 fprintf(stderr, "%.60s\n", graph_dotted_line);
1666                 fprintf(stderr, "perf_event_attr:\n");
1667                 perf_event_attr__fprintf(stderr, attr, __open_attr__fprintf, NULL);
1668                 fprintf(stderr, "%.60s\n", graph_dotted_line);
1669         }
1670 }
1671
1672 static int perf_event_open(struct evsel *evsel,
1673                            pid_t pid, int cpu, int group_fd,
1674                            unsigned long flags)
1675 {
1676         int precise_ip = evsel->core.attr.precise_ip;
1677         int fd;
1678
1679         while (1) {
1680                 pr_debug2("sys_perf_event_open: pid %d  cpu %d  group_fd %d  flags %#lx",
1681                           pid, cpu, group_fd, flags);
1682
1683                 fd = sys_perf_event_open(&evsel->core.attr, pid, cpu, group_fd, flags);
1684                 if (fd >= 0)
1685                         break;
1686
1687                 /* Do not try less precise if not requested. */
1688                 if (!evsel->precise_max)
1689                         break;
1690
1691                 /*
1692                  * We tried all the precise_ip values, and it's
1693                  * still failing, so leave it to standard fallback.
1694                  */
1695                 if (!evsel->core.attr.precise_ip) {
1696                         evsel->core.attr.precise_ip = precise_ip;
1697                         break;
1698                 }
1699
1700                 pr_debug2("\nsys_perf_event_open failed, error %d\n", -ENOTSUP);
1701                 evsel->core.attr.precise_ip--;
1702                 pr_debug2("decreasing precise_ip by one (%d)\n", evsel->core.attr.precise_ip);
1703                 display_attr(&evsel->core.attr);
1704         }
1705
1706         return fd;
1707 }
1708
1709 int evsel__open(struct evsel *evsel, struct perf_cpu_map *cpus,
1710                 struct perf_thread_map *threads)
1711 {
1712         int cpu, thread, nthreads;
1713         unsigned long flags = PERF_FLAG_FD_CLOEXEC;
1714         int pid = -1, err;
1715         enum { NO_CHANGE, SET_TO_MAX, INCREASED_MAX } set_rlimit = NO_CHANGE;
1716
1717         if ((perf_missing_features.write_backward && evsel->core.attr.write_backward) ||
1718             (perf_missing_features.aux_output     && evsel->core.attr.aux_output))
1719                 return -EINVAL;
1720
1721         if (cpus == NULL) {
1722                 static struct perf_cpu_map *empty_cpu_map;
1723
1724                 if (empty_cpu_map == NULL) {
1725                         empty_cpu_map = perf_cpu_map__dummy_new();
1726                         if (empty_cpu_map == NULL)
1727                                 return -ENOMEM;
1728                 }
1729
1730                 cpus = empty_cpu_map;
1731         }
1732
1733         if (threads == NULL) {
1734                 static struct perf_thread_map *empty_thread_map;
1735
1736                 if (empty_thread_map == NULL) {
1737                         empty_thread_map = thread_map__new_by_tid(-1);
1738                         if (empty_thread_map == NULL)
1739                                 return -ENOMEM;
1740                 }
1741
1742                 threads = empty_thread_map;
1743         }
1744
1745         if (evsel->core.system_wide)
1746                 nthreads = 1;
1747         else
1748                 nthreads = threads->nr;
1749
1750         if (evsel->core.fd == NULL &&
1751             perf_evsel__alloc_fd(&evsel->core, cpus->nr, nthreads) < 0)
1752                 return -ENOMEM;
1753
1754         if (evsel->cgrp) {
1755                 flags |= PERF_FLAG_PID_CGROUP;
1756                 pid = evsel->cgrp->fd;
1757         }
1758
1759 fallback_missing_features:
1760         if (perf_missing_features.clockid_wrong)
1761                 evsel->core.attr.clockid = CLOCK_MONOTONIC; /* should always work */
1762         if (perf_missing_features.clockid) {
1763                 evsel->core.attr.use_clockid = 0;
1764                 evsel->core.attr.clockid = 0;
1765         }
1766         if (perf_missing_features.cloexec)
1767                 flags &= ~(unsigned long)PERF_FLAG_FD_CLOEXEC;
1768         if (perf_missing_features.mmap2)
1769                 evsel->core.attr.mmap2 = 0;
1770         if (perf_missing_features.exclude_guest)
1771                 evsel->core.attr.exclude_guest = evsel->core.attr.exclude_host = 0;
1772         if (perf_missing_features.lbr_flags)
1773                 evsel->core.attr.branch_sample_type &= ~(PERF_SAMPLE_BRANCH_NO_FLAGS |
1774                                      PERF_SAMPLE_BRANCH_NO_CYCLES);
1775         if (perf_missing_features.group_read && evsel->core.attr.inherit)
1776                 evsel->core.attr.read_format &= ~(PERF_FORMAT_GROUP|PERF_FORMAT_ID);
1777         if (perf_missing_features.ksymbol)
1778                 evsel->core.attr.ksymbol = 0;
1779         if (perf_missing_features.bpf)
1780                 evsel->core.attr.bpf_event = 0;
1781 retry_sample_id:
1782         if (perf_missing_features.sample_id_all)
1783                 evsel->core.attr.sample_id_all = 0;
1784
1785         display_attr(&evsel->core.attr);
1786
1787         for (cpu = 0; cpu < cpus->nr; cpu++) {
1788
1789                 for (thread = 0; thread < nthreads; thread++) {
1790                         int fd, group_fd;
1791
1792                         if (!evsel->cgrp && !evsel->core.system_wide)
1793                                 pid = perf_thread_map__pid(threads, thread);
1794
1795                         group_fd = get_group_fd(evsel, cpu, thread);
1796 retry_open:
1797                         test_attr__ready();
1798
1799                         fd = perf_event_open(evsel, pid, cpus->map[cpu],
1800                                              group_fd, flags);
1801
1802                         FD(evsel, cpu, thread) = fd;
1803
1804                         if (fd < 0) {
1805                                 err = -errno;
1806
1807                                 if (ignore_missing_thread(evsel, cpus->nr, cpu, threads, thread, err)) {
1808                                         /*
1809                                          * We just removed 1 thread, so take a step
1810                                          * back on thread index and lower the upper
1811                                          * nthreads limit.
1812                                          */
1813                                         nthreads--;
1814                                         thread--;
1815
1816                                         /* ... and pretend like nothing have happened. */
1817                                         err = 0;
1818                                         continue;
1819                                 }
1820
1821                                 pr_debug2("\nsys_perf_event_open failed, error %d\n",
1822                                           err);
1823                                 goto try_fallback;
1824                         }
1825
1826                         pr_debug2(" = %d\n", fd);
1827
1828                         if (evsel->bpf_fd >= 0) {
1829                                 int evt_fd = fd;
1830                                 int bpf_fd = evsel->bpf_fd;
1831
1832                                 err = ioctl(evt_fd,
1833                                             PERF_EVENT_IOC_SET_BPF,
1834                                             bpf_fd);
1835                                 if (err && errno != EEXIST) {
1836                                         pr_err("failed to attach bpf fd %d: %s\n",
1837                                                bpf_fd, strerror(errno));
1838                                         err = -EINVAL;
1839                                         goto out_close;
1840                                 }
1841                         }
1842
1843                         set_rlimit = NO_CHANGE;
1844
1845                         /*
1846                          * If we succeeded but had to kill clockid, fail and
1847                          * have perf_evsel__open_strerror() print us a nice
1848                          * error.
1849                          */
1850                         if (perf_missing_features.clockid ||
1851                             perf_missing_features.clockid_wrong) {
1852                                 err = -EINVAL;
1853                                 goto out_close;
1854                         }
1855                 }
1856         }
1857
1858         return 0;
1859
1860 try_fallback:
1861         /*
1862          * perf stat needs between 5 and 22 fds per CPU. When we run out
1863          * of them try to increase the limits.
1864          */
1865         if (err == -EMFILE && set_rlimit < INCREASED_MAX) {
1866                 struct rlimit l;
1867                 int old_errno = errno;
1868
1869                 if (getrlimit(RLIMIT_NOFILE, &l) == 0) {
1870                         if (set_rlimit == NO_CHANGE)
1871                                 l.rlim_cur = l.rlim_max;
1872                         else {
1873                                 l.rlim_cur = l.rlim_max + 1000;
1874                                 l.rlim_max = l.rlim_cur;
1875                         }
1876                         if (setrlimit(RLIMIT_NOFILE, &l) == 0) {
1877                                 set_rlimit++;
1878                                 errno = old_errno;
1879                                 goto retry_open;
1880                         }
1881                 }
1882                 errno = old_errno;
1883         }
1884
1885         if (err != -EINVAL || cpu > 0 || thread > 0)
1886                 goto out_close;
1887
1888         /*
1889          * Must probe features in the order they were added to the
1890          * perf_event_attr interface.
1891          */
1892         if (!perf_missing_features.aux_output && evsel->core.attr.aux_output) {
1893                 perf_missing_features.aux_output = true;
1894                 pr_debug2("Kernel has no attr.aux_output support, bailing out\n");
1895                 goto out_close;
1896         } else if (!perf_missing_features.bpf && evsel->core.attr.bpf_event) {
1897                 perf_missing_features.bpf = true;
1898                 pr_debug2("switching off bpf_event\n");
1899                 goto fallback_missing_features;
1900         } else if (!perf_missing_features.ksymbol && evsel->core.attr.ksymbol) {
1901                 perf_missing_features.ksymbol = true;
1902                 pr_debug2("switching off ksymbol\n");
1903                 goto fallback_missing_features;
1904         } else if (!perf_missing_features.write_backward && evsel->core.attr.write_backward) {
1905                 perf_missing_features.write_backward = true;
1906                 pr_debug2("switching off write_backward\n");
1907                 goto out_close;
1908         } else if (!perf_missing_features.clockid_wrong && evsel->core.attr.use_clockid) {
1909                 perf_missing_features.clockid_wrong = true;
1910                 pr_debug2("switching off clockid\n");
1911                 goto fallback_missing_features;
1912         } else if (!perf_missing_features.clockid && evsel->core.attr.use_clockid) {
1913                 perf_missing_features.clockid = true;
1914                 pr_debug2("switching off use_clockid\n");
1915                 goto fallback_missing_features;
1916         } else if (!perf_missing_features.cloexec && (flags & PERF_FLAG_FD_CLOEXEC)) {
1917                 perf_missing_features.cloexec = true;
1918                 pr_debug2("switching off cloexec flag\n");
1919                 goto fallback_missing_features;
1920         } else if (!perf_missing_features.mmap2 && evsel->core.attr.mmap2) {
1921                 perf_missing_features.mmap2 = true;
1922                 pr_debug2("switching off mmap2\n");
1923                 goto fallback_missing_features;
1924         } else if (!perf_missing_features.exclude_guest &&
1925                    (evsel->core.attr.exclude_guest || evsel->core.attr.exclude_host)) {
1926                 perf_missing_features.exclude_guest = true;
1927                 pr_debug2("switching off exclude_guest, exclude_host\n");
1928                 goto fallback_missing_features;
1929         } else if (!perf_missing_features.sample_id_all) {
1930                 perf_missing_features.sample_id_all = true;
1931                 pr_debug2("switching off sample_id_all\n");
1932                 goto retry_sample_id;
1933         } else if (!perf_missing_features.lbr_flags &&
1934                         (evsel->core.attr.branch_sample_type &
1935                          (PERF_SAMPLE_BRANCH_NO_CYCLES |
1936                           PERF_SAMPLE_BRANCH_NO_FLAGS))) {
1937                 perf_missing_features.lbr_flags = true;
1938                 pr_debug2("switching off branch sample type no (cycles/flags)\n");
1939                 goto fallback_missing_features;
1940         } else if (!perf_missing_features.group_read &&
1941                     evsel->core.attr.inherit &&
1942                    (evsel->core.attr.read_format & PERF_FORMAT_GROUP) &&
1943                    perf_evsel__is_group_leader(evsel)) {
1944                 perf_missing_features.group_read = true;
1945                 pr_debug2("switching off group read\n");
1946                 goto fallback_missing_features;
1947         }
1948 out_close:
1949         if (err)
1950                 threads->err_thread = thread;
1951
1952         do {
1953                 while (--thread >= 0) {
1954                         close(FD(evsel, cpu, thread));
1955                         FD(evsel, cpu, thread) = -1;
1956                 }
1957                 thread = nthreads;
1958         } while (--cpu >= 0);
1959         return err;
1960 }
1961
1962 void evsel__close(struct evsel *evsel)
1963 {
1964         perf_evsel__close(&evsel->core);
1965         perf_evsel__free_id(&evsel->core);
1966 }
1967
1968 int perf_evsel__open_per_cpu(struct evsel *evsel,
1969                              struct perf_cpu_map *cpus)
1970 {
1971         return evsel__open(evsel, cpus, NULL);
1972 }
1973
1974 int perf_evsel__open_per_thread(struct evsel *evsel,
1975                                 struct perf_thread_map *threads)
1976 {
1977         return evsel__open(evsel, NULL, threads);
1978 }
1979
1980 static int perf_evsel__parse_id_sample(const struct evsel *evsel,
1981                                        const union perf_event *event,
1982                                        struct perf_sample *sample)
1983 {
1984         u64 type = evsel->core.attr.sample_type;
1985         const __u64 *array = event->sample.array;
1986         bool swapped = evsel->needs_swap;
1987         union u64_swap u;
1988
1989         array += ((event->header.size -
1990                    sizeof(event->header)) / sizeof(u64)) - 1;
1991
1992         if (type & PERF_SAMPLE_IDENTIFIER) {
1993                 sample->id = *array;
1994                 array--;
1995         }
1996
1997         if (type & PERF_SAMPLE_CPU) {
1998                 u.val64 = *array;
1999                 if (swapped) {
2000                         /* undo swap of u64, then swap on individual u32s */
2001                         u.val64 = bswap_64(u.val64);
2002                         u.val32[0] = bswap_32(u.val32[0]);
2003                 }
2004
2005                 sample->cpu = u.val32[0];
2006                 array--;
2007         }
2008
2009         if (type & PERF_SAMPLE_STREAM_ID) {
2010                 sample->stream_id = *array;
2011                 array--;
2012         }
2013
2014         if (type & PERF_SAMPLE_ID) {
2015                 sample->id = *array;
2016                 array--;
2017         }
2018
2019         if (type & PERF_SAMPLE_TIME) {
2020                 sample->time = *array;
2021                 array--;
2022         }
2023
2024         if (type & PERF_SAMPLE_TID) {
2025                 u.val64 = *array;
2026                 if (swapped) {
2027                         /* undo swap of u64, then swap on individual u32s */
2028                         u.val64 = bswap_64(u.val64);
2029                         u.val32[0] = bswap_32(u.val32[0]);
2030                         u.val32[1] = bswap_32(u.val32[1]);
2031                 }
2032
2033                 sample->pid = u.val32[0];
2034                 sample->tid = u.val32[1];
2035                 array--;
2036         }
2037
2038         return 0;
2039 }
2040
2041 static inline bool overflow(const void *endp, u16 max_size, const void *offset,
2042                             u64 size)
2043 {
2044         return size > max_size || offset + size > endp;
2045 }
2046
2047 #define OVERFLOW_CHECK(offset, size, max_size)                          \
2048         do {                                                            \
2049                 if (overflow(endp, (max_size), (offset), (size)))       \
2050                         return -EFAULT;                                 \
2051         } while (0)
2052
2053 #define OVERFLOW_CHECK_u64(offset) \
2054         OVERFLOW_CHECK(offset, sizeof(u64), sizeof(u64))
2055
2056 static int
2057 perf_event__check_size(union perf_event *event, unsigned int sample_size)
2058 {
2059         /*
2060          * The evsel's sample_size is based on PERF_SAMPLE_MASK which includes
2061          * up to PERF_SAMPLE_PERIOD.  After that overflow() must be used to
2062          * check the format does not go past the end of the event.
2063          */
2064         if (sample_size + sizeof(event->header) > event->header.size)
2065                 return -EFAULT;
2066
2067         return 0;
2068 }
2069
2070 int perf_evsel__parse_sample(struct evsel *evsel, union perf_event *event,
2071                              struct perf_sample *data)
2072 {
2073         u64 type = evsel->core.attr.sample_type;
2074         bool swapped = evsel->needs_swap;
2075         const __u64 *array;
2076         u16 max_size = event->header.size;
2077         const void *endp = (void *)event + max_size;
2078         u64 sz;
2079
2080         /*
2081          * used for cross-endian analysis. See git commit 65014ab3
2082          * for why this goofiness is needed.
2083          */
2084         union u64_swap u;
2085
2086         memset(data, 0, sizeof(*data));
2087         data->cpu = data->pid = data->tid = -1;
2088         data->stream_id = data->id = data->time = -1ULL;
2089         data->period = evsel->core.attr.sample_period;
2090         data->cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
2091         data->misc    = event->header.misc;
2092         data->id = -1ULL;
2093         data->data_src = PERF_MEM_DATA_SRC_NONE;
2094
2095         if (event->header.type != PERF_RECORD_SAMPLE) {
2096                 if (!evsel->core.attr.sample_id_all)
2097                         return 0;
2098                 return perf_evsel__parse_id_sample(evsel, event, data);
2099         }
2100
2101         array = event->sample.array;
2102
2103         if (perf_event__check_size(event, evsel->sample_size))
2104                 return -EFAULT;
2105
2106         if (type & PERF_SAMPLE_IDENTIFIER) {
2107                 data->id = *array;
2108                 array++;
2109         }
2110
2111         if (type & PERF_SAMPLE_IP) {
2112                 data->ip = *array;
2113                 array++;
2114         }
2115
2116         if (type & PERF_SAMPLE_TID) {
2117                 u.val64 = *array;
2118                 if (swapped) {
2119                         /* undo swap of u64, then swap on individual u32s */
2120                         u.val64 = bswap_64(u.val64);
2121                         u.val32[0] = bswap_32(u.val32[0]);
2122                         u.val32[1] = bswap_32(u.val32[1]);
2123                 }
2124
2125                 data->pid = u.val32[0];
2126                 data->tid = u.val32[1];
2127                 array++;
2128         }
2129
2130         if (type & PERF_SAMPLE_TIME) {
2131                 data->time = *array;
2132                 array++;
2133         }
2134
2135         if (type & PERF_SAMPLE_ADDR) {
2136                 data->addr = *array;
2137                 array++;
2138         }
2139
2140         if (type & PERF_SAMPLE_ID) {
2141                 data->id = *array;
2142                 array++;
2143         }
2144
2145         if (type & PERF_SAMPLE_STREAM_ID) {
2146                 data->stream_id = *array;
2147                 array++;
2148         }
2149
2150         if (type & PERF_SAMPLE_CPU) {
2151
2152                 u.val64 = *array;
2153                 if (swapped) {
2154                         /* undo swap of u64, then swap on individual u32s */
2155                         u.val64 = bswap_64(u.val64);
2156                         u.val32[0] = bswap_32(u.val32[0]);
2157                 }
2158
2159                 data->cpu = u.val32[0];
2160                 array++;
2161         }
2162
2163         if (type & PERF_SAMPLE_PERIOD) {
2164                 data->period = *array;
2165                 array++;
2166         }
2167
2168         if (type & PERF_SAMPLE_READ) {
2169                 u64 read_format = evsel->core.attr.read_format;
2170
2171                 OVERFLOW_CHECK_u64(array);
2172                 if (read_format & PERF_FORMAT_GROUP)
2173                         data->read.group.nr = *array;
2174                 else
2175                         data->read.one.value = *array;
2176
2177                 array++;
2178
2179                 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2180                         OVERFLOW_CHECK_u64(array);
2181                         data->read.time_enabled = *array;
2182                         array++;
2183                 }
2184
2185                 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2186                         OVERFLOW_CHECK_u64(array);
2187                         data->read.time_running = *array;
2188                         array++;
2189                 }
2190
2191                 /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
2192                 if (read_format & PERF_FORMAT_GROUP) {
2193                         const u64 max_group_nr = UINT64_MAX /
2194                                         sizeof(struct sample_read_value);
2195
2196                         if (data->read.group.nr > max_group_nr)
2197                                 return -EFAULT;
2198                         sz = data->read.group.nr *
2199                              sizeof(struct sample_read_value);
2200                         OVERFLOW_CHECK(array, sz, max_size);
2201                         data->read.group.values =
2202                                         (struct sample_read_value *)array;
2203                         array = (void *)array + sz;
2204                 } else {
2205                         OVERFLOW_CHECK_u64(array);
2206                         data->read.one.id = *array;
2207                         array++;
2208                 }
2209         }
2210
2211         if (evsel__has_callchain(evsel)) {
2212                 const u64 max_callchain_nr = UINT64_MAX / sizeof(u64);
2213
2214                 OVERFLOW_CHECK_u64(array);
2215                 data->callchain = (struct ip_callchain *)array++;
2216                 if (data->callchain->nr > max_callchain_nr)
2217                         return -EFAULT;
2218                 sz = data->callchain->nr * sizeof(u64);
2219                 OVERFLOW_CHECK(array, sz, max_size);
2220                 array = (void *)array + sz;
2221         }
2222
2223         if (type & PERF_SAMPLE_RAW) {
2224                 OVERFLOW_CHECK_u64(array);
2225                 u.val64 = *array;
2226
2227                 /*
2228                  * Undo swap of u64, then swap on individual u32s,
2229                  * get the size of the raw area and undo all of the
2230                  * swap. The pevent interface handles endianity by
2231                  * itself.
2232                  */
2233                 if (swapped) {
2234                         u.val64 = bswap_64(u.val64);
2235                         u.val32[0] = bswap_32(u.val32[0]);
2236                         u.val32[1] = bswap_32(u.val32[1]);
2237                 }
2238                 data->raw_size = u.val32[0];
2239
2240                 /*
2241                  * The raw data is aligned on 64bits including the
2242                  * u32 size, so it's safe to use mem_bswap_64.
2243                  */
2244                 if (swapped)
2245                         mem_bswap_64((void *) array, data->raw_size);
2246
2247                 array = (void *)array + sizeof(u32);
2248
2249                 OVERFLOW_CHECK(array, data->raw_size, max_size);
2250                 data->raw_data = (void *)array;
2251                 array = (void *)array + data->raw_size;
2252         }
2253
2254         if (type & PERF_SAMPLE_BRANCH_STACK) {
2255                 const u64 max_branch_nr = UINT64_MAX /
2256                                           sizeof(struct branch_entry);
2257
2258                 OVERFLOW_CHECK_u64(array);
2259                 data->branch_stack = (struct branch_stack *)array++;
2260
2261                 if (data->branch_stack->nr > max_branch_nr)
2262                         return -EFAULT;
2263                 sz = data->branch_stack->nr * sizeof(struct branch_entry);
2264                 OVERFLOW_CHECK(array, sz, max_size);
2265                 array = (void *)array + sz;
2266         }
2267
2268         if (type & PERF_SAMPLE_REGS_USER) {
2269                 OVERFLOW_CHECK_u64(array);
2270                 data->user_regs.abi = *array;
2271                 array++;
2272
2273                 if (data->user_regs.abi) {
2274                         u64 mask = evsel->core.attr.sample_regs_user;
2275
2276                         sz = hweight64(mask) * sizeof(u64);
2277                         OVERFLOW_CHECK(array, sz, max_size);
2278                         data->user_regs.mask = mask;
2279                         data->user_regs.regs = (u64 *)array;
2280                         array = (void *)array + sz;
2281                 }
2282         }
2283
2284         if (type & PERF_SAMPLE_STACK_USER) {
2285                 OVERFLOW_CHECK_u64(array);
2286                 sz = *array++;
2287
2288                 data->user_stack.offset = ((char *)(array - 1)
2289                                           - (char *) event);
2290
2291                 if (!sz) {
2292                         data->user_stack.size = 0;
2293                 } else {
2294                         OVERFLOW_CHECK(array, sz, max_size);
2295                         data->user_stack.data = (char *)array;
2296                         array = (void *)array + sz;
2297                         OVERFLOW_CHECK_u64(array);
2298                         data->user_stack.size = *array++;
2299                         if (WARN_ONCE(data->user_stack.size > sz,
2300                                       "user stack dump failure\n"))
2301                                 return -EFAULT;
2302                 }
2303         }
2304
2305         if (type & PERF_SAMPLE_WEIGHT) {
2306                 OVERFLOW_CHECK_u64(array);
2307                 data->weight = *array;
2308                 array++;
2309         }
2310
2311         if (type & PERF_SAMPLE_DATA_SRC) {
2312                 OVERFLOW_CHECK_u64(array);
2313                 data->data_src = *array;
2314                 array++;
2315         }
2316
2317         if (type & PERF_SAMPLE_TRANSACTION) {
2318                 OVERFLOW_CHECK_u64(array);
2319                 data->transaction = *array;
2320                 array++;
2321         }
2322
2323         data->intr_regs.abi = PERF_SAMPLE_REGS_ABI_NONE;
2324         if (type & PERF_SAMPLE_REGS_INTR) {
2325                 OVERFLOW_CHECK_u64(array);
2326                 data->intr_regs.abi = *array;
2327                 array++;
2328
2329                 if (data->intr_regs.abi != PERF_SAMPLE_REGS_ABI_NONE) {
2330                         u64 mask = evsel->core.attr.sample_regs_intr;
2331
2332                         sz = hweight64(mask) * sizeof(u64);
2333                         OVERFLOW_CHECK(array, sz, max_size);
2334                         data->intr_regs.mask = mask;
2335                         data->intr_regs.regs = (u64 *)array;
2336                         array = (void *)array + sz;
2337                 }
2338         }
2339
2340         data->phys_addr = 0;
2341         if (type & PERF_SAMPLE_PHYS_ADDR) {
2342                 data->phys_addr = *array;
2343                 array++;
2344         }
2345
2346         return 0;
2347 }
2348
2349 int perf_evsel__parse_sample_timestamp(struct evsel *evsel,
2350                                        union perf_event *event,
2351                                        u64 *timestamp)
2352 {
2353         u64 type = evsel->core.attr.sample_type;
2354         const __u64 *array;
2355
2356         if (!(type & PERF_SAMPLE_TIME))
2357                 return -1;
2358
2359         if (event->header.type != PERF_RECORD_SAMPLE) {
2360                 struct perf_sample data = {
2361                         .time = -1ULL,
2362                 };
2363
2364                 if (!evsel->core.attr.sample_id_all)
2365                         return -1;
2366                 if (perf_evsel__parse_id_sample(evsel, event, &data))
2367                         return -1;
2368
2369                 *timestamp = data.time;
2370                 return 0;
2371         }
2372
2373         array = event->sample.array;
2374
2375         if (perf_event__check_size(event, evsel->sample_size))
2376                 return -EFAULT;
2377
2378         if (type & PERF_SAMPLE_IDENTIFIER)
2379                 array++;
2380
2381         if (type & PERF_SAMPLE_IP)
2382                 array++;
2383
2384         if (type & PERF_SAMPLE_TID)
2385                 array++;
2386
2387         if (type & PERF_SAMPLE_TIME)
2388                 *timestamp = *array;
2389
2390         return 0;
2391 }
2392
2393 struct tep_format_field *perf_evsel__field(struct evsel *evsel, const char *name)
2394 {
2395         return tep_find_field(evsel->tp_format, name);
2396 }
2397
2398 void *perf_evsel__rawptr(struct evsel *evsel, struct perf_sample *sample,
2399                          const char *name)
2400 {
2401         struct tep_format_field *field = perf_evsel__field(evsel, name);
2402         int offset;
2403
2404         if (!field)
2405                 return NULL;
2406
2407         offset = field->offset;
2408
2409         if (field->flags & TEP_FIELD_IS_DYNAMIC) {
2410                 offset = *(int *)(sample->raw_data + field->offset);
2411                 offset &= 0xffff;
2412         }
2413
2414         return sample->raw_data + offset;
2415 }
2416
2417 u64 format_field__intval(struct tep_format_field *field, struct perf_sample *sample,
2418                          bool needs_swap)
2419 {
2420         u64 value;
2421         void *ptr = sample->raw_data + field->offset;
2422
2423         switch (field->size) {
2424         case 1:
2425                 return *(u8 *)ptr;
2426         case 2:
2427                 value = *(u16 *)ptr;
2428                 break;
2429         case 4:
2430                 value = *(u32 *)ptr;
2431                 break;
2432         case 8:
2433                 memcpy(&value, ptr, sizeof(u64));
2434                 break;
2435         default:
2436                 return 0;
2437         }
2438
2439         if (!needs_swap)
2440                 return value;
2441
2442         switch (field->size) {
2443         case 2:
2444                 return bswap_16(value);
2445         case 4:
2446                 return bswap_32(value);
2447         case 8:
2448                 return bswap_64(value);
2449         default:
2450                 return 0;
2451         }
2452
2453         return 0;
2454 }
2455
2456 u64 perf_evsel__intval(struct evsel *evsel, struct perf_sample *sample,
2457                        const char *name)
2458 {
2459         struct tep_format_field *field = perf_evsel__field(evsel, name);
2460
2461         if (!field)
2462                 return 0;
2463
2464         return field ? format_field__intval(field, sample, evsel->needs_swap) : 0;
2465 }
2466
2467 bool perf_evsel__fallback(struct evsel *evsel, int err,
2468                           char *msg, size_t msgsize)
2469 {
2470         int paranoid;
2471
2472         if ((err == ENOENT || err == ENXIO || err == ENODEV) &&
2473             evsel->core.attr.type   == PERF_TYPE_HARDWARE &&
2474             evsel->core.attr.config == PERF_COUNT_HW_CPU_CYCLES) {
2475                 /*
2476                  * If it's cycles then fall back to hrtimer based
2477                  * cpu-clock-tick sw counter, which is always available even if
2478                  * no PMU support.
2479                  *
2480                  * PPC returns ENXIO until 2.6.37 (behavior changed with commit
2481                  * b0a873e).
2482                  */
2483                 scnprintf(msg, msgsize, "%s",
2484 "The cycles event is not supported, trying to fall back to cpu-clock-ticks");
2485
2486                 evsel->core.attr.type   = PERF_TYPE_SOFTWARE;
2487                 evsel->core.attr.config = PERF_COUNT_SW_CPU_CLOCK;
2488
2489                 zfree(&evsel->name);
2490                 return true;
2491         } else if (err == EACCES && !evsel->core.attr.exclude_kernel &&
2492                    (paranoid = perf_event_paranoid()) > 1) {
2493                 const char *name = perf_evsel__name(evsel);
2494                 char *new_name;
2495                 const char *sep = ":";
2496
2497                 /* Is there already the separator in the name. */
2498                 if (strchr(name, '/') ||
2499                     strchr(name, ':'))
2500                         sep = "";
2501
2502                 if (asprintf(&new_name, "%s%su", name, sep) < 0)
2503                         return false;
2504
2505                 if (evsel->name)
2506                         free(evsel->name);
2507                 evsel->name = new_name;
2508                 scnprintf(msg, msgsize, "kernel.perf_event_paranoid=%d, trying "
2509                           "to fall back to excluding kernel and hypervisor "
2510                           " samples", paranoid);
2511                 evsel->core.attr.exclude_kernel = 1;
2512                 evsel->core.attr.exclude_hv     = 1;
2513
2514                 return true;
2515         }
2516
2517         return false;
2518 }
2519
2520 static bool find_process(const char *name)
2521 {
2522         size_t len = strlen(name);
2523         DIR *dir;
2524         struct dirent *d;
2525         int ret = -1;
2526
2527         dir = opendir(procfs__mountpoint());
2528         if (!dir)
2529                 return false;
2530
2531         /* Walk through the directory. */
2532         while (ret && (d = readdir(dir)) != NULL) {
2533                 char path[PATH_MAX];
2534                 char *data;
2535                 size_t size;
2536
2537                 if ((d->d_type != DT_DIR) ||
2538                      !strcmp(".", d->d_name) ||
2539                      !strcmp("..", d->d_name))
2540                         continue;
2541
2542                 scnprintf(path, sizeof(path), "%s/%s/comm",
2543                           procfs__mountpoint(), d->d_name);
2544
2545                 if (filename__read_str(path, &data, &size))
2546                         continue;
2547
2548                 ret = strncmp(name, data, len);
2549                 free(data);
2550         }
2551
2552         closedir(dir);
2553         return ret ? false : true;
2554 }
2555
2556 int perf_evsel__open_strerror(struct evsel *evsel, struct target *target,
2557                               int err, char *msg, size_t size)
2558 {
2559         char sbuf[STRERR_BUFSIZE];
2560         int printed = 0;
2561
2562         switch (err) {
2563         case EPERM:
2564         case EACCES:
2565                 if (err == EPERM)
2566                         printed = scnprintf(msg, size,
2567                                 "No permission to enable %s event.\n\n",
2568                                 perf_evsel__name(evsel));
2569
2570                 return scnprintf(msg + printed, size - printed,
2571                  "You may not have permission to collect %sstats.\n\n"
2572                  "Consider tweaking /proc/sys/kernel/perf_event_paranoid,\n"
2573                  "which controls use of the performance events system by\n"
2574                  "unprivileged users (without CAP_SYS_ADMIN).\n\n"
2575                  "The current value is %d:\n\n"
2576                  "  -1: Allow use of (almost) all events by all users\n"
2577                  "      Ignore mlock limit after perf_event_mlock_kb without CAP_IPC_LOCK\n"
2578                  ">= 0: Disallow ftrace function tracepoint by users without CAP_SYS_ADMIN\n"
2579                  "      Disallow raw tracepoint access by users without CAP_SYS_ADMIN\n"
2580                  ">= 1: Disallow CPU event access by users without CAP_SYS_ADMIN\n"
2581                  ">= 2: Disallow kernel profiling by users without CAP_SYS_ADMIN\n\n"
2582                  "To make this setting permanent, edit /etc/sysctl.conf too, e.g.:\n\n"
2583                  "      kernel.perf_event_paranoid = -1\n" ,
2584                                  target->system_wide ? "system-wide " : "",
2585                                  perf_event_paranoid());
2586         case ENOENT:
2587                 return scnprintf(msg, size, "The %s event is not supported.",
2588                                  perf_evsel__name(evsel));
2589         case EMFILE:
2590                 return scnprintf(msg, size, "%s",
2591                          "Too many events are opened.\n"
2592                          "Probably the maximum number of open file descriptors has been reached.\n"
2593                          "Hint: Try again after reducing the number of events.\n"
2594                          "Hint: Try increasing the limit with 'ulimit -n <limit>'");
2595         case ENOMEM:
2596                 if (evsel__has_callchain(evsel) &&
2597                     access("/proc/sys/kernel/perf_event_max_stack", F_OK) == 0)
2598                         return scnprintf(msg, size,
2599                                          "Not enough memory to setup event with callchain.\n"
2600                                          "Hint: Try tweaking /proc/sys/kernel/perf_event_max_stack\n"
2601                                          "Hint: Current value: %d", sysctl__max_stack());
2602                 break;
2603         case ENODEV:
2604                 if (target->cpu_list)
2605                         return scnprintf(msg, size, "%s",
2606          "No such device - did you specify an out-of-range profile CPU?");
2607                 break;
2608         case EOPNOTSUPP:
2609                 if (evsel->core.attr.sample_period != 0)
2610                         return scnprintf(msg, size,
2611         "%s: PMU Hardware doesn't support sampling/overflow-interrupts. Try 'perf stat'",
2612                                          perf_evsel__name(evsel));
2613                 if (evsel->core.attr.precise_ip)
2614                         return scnprintf(msg, size, "%s",
2615         "\'precise\' request may not be supported. Try removing 'p' modifier.");
2616 #if defined(__i386__) || defined(__x86_64__)
2617                 if (evsel->core.attr.type == PERF_TYPE_HARDWARE)
2618                         return scnprintf(msg, size, "%s",
2619         "No hardware sampling interrupt available.\n");
2620 #endif
2621                 break;
2622         case EBUSY:
2623                 if (find_process("oprofiled"))
2624                         return scnprintf(msg, size,
2625         "The PMU counters are busy/taken by another profiler.\n"
2626         "We found oprofile daemon running, please stop it and try again.");
2627                 break;
2628         case EINVAL:
2629                 if (evsel->core.attr.write_backward && perf_missing_features.write_backward)
2630                         return scnprintf(msg, size, "Reading from overwrite event is not supported by this kernel.");
2631                 if (perf_missing_features.clockid)
2632                         return scnprintf(msg, size, "clockid feature not supported.");
2633                 if (perf_missing_features.clockid_wrong)
2634                         return scnprintf(msg, size, "wrong clockid (%d).", clockid);
2635                 if (perf_missing_features.aux_output)
2636                         return scnprintf(msg, size, "The 'aux_output' feature is not supported, update the kernel.");
2637                 break;
2638         default:
2639                 break;
2640         }
2641
2642         return scnprintf(msg, size,
2643         "The sys_perf_event_open() syscall returned with %d (%s) for event (%s).\n"
2644         "/bin/dmesg | grep -i perf may provide additional information.\n",
2645                          err, str_error_r(err, sbuf, sizeof(sbuf)),
2646                          perf_evsel__name(evsel));
2647 }
2648
2649 struct perf_env *perf_evsel__env(struct evsel *evsel)
2650 {
2651         if (evsel && evsel->evlist)
2652                 return evsel->evlist->env;
2653         return NULL;
2654 }
2655
2656 static int store_evsel_ids(struct evsel *evsel, struct evlist *evlist)
2657 {
2658         int cpu, thread;
2659
2660         for (cpu = 0; cpu < xyarray__max_x(evsel->core.fd); cpu++) {
2661                 for (thread = 0; thread < xyarray__max_y(evsel->core.fd);
2662                      thread++) {
2663                         int fd = FD(evsel, cpu, thread);
2664
2665                         if (perf_evlist__id_add_fd(evlist, evsel,
2666                                                    cpu, thread, fd) < 0)
2667                                 return -1;
2668                 }
2669         }
2670
2671         return 0;
2672 }
2673
2674 int perf_evsel__store_ids(struct evsel *evsel, struct evlist *evlist)
2675 {
2676         struct perf_cpu_map *cpus = evsel->core.cpus;
2677         struct perf_thread_map *threads = evsel->core.threads;
2678
2679         if (perf_evsel__alloc_id(&evsel->core, cpus->nr, threads->nr))
2680                 return -ENOMEM;
2681
2682         return store_evsel_ids(evsel, evlist);
2683 }