perf evsel: Introduce append_filter() method
[cascardo/linux.git] / tools / perf / util / evsel.c
1 /*
2  * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
3  *
4  * Parts came from builtin-{top,stat,record}.c, see those files for further
5  * copyright notes.
6  *
7  * Released under the GPL v2. (and only v2, not any later version)
8  */
9
10 #include <byteswap.h>
11 #include <linux/bitops.h>
12 #include <api/fs/debugfs.h>
13 #include <traceevent/event-parse.h>
14 #include <linux/hw_breakpoint.h>
15 #include <linux/perf_event.h>
16 #include <sys/resource.h>
17 #include "asm/bug.h"
18 #include "callchain.h"
19 #include "cgroup.h"
20 #include "evsel.h"
21 #include "evlist.h"
22 #include "util.h"
23 #include "cpumap.h"
24 #include "thread_map.h"
25 #include "target.h"
26 #include "perf_regs.h"
27 #include "debug.h"
28 #include "trace-event.h"
29 #include "stat.h"
30
31 static struct {
32         bool sample_id_all;
33         bool exclude_guest;
34         bool mmap2;
35         bool cloexec;
36         bool clockid;
37         bool clockid_wrong;
38 } perf_missing_features;
39
40 static clockid_t clockid;
41
42 static int perf_evsel__no_extra_init(struct perf_evsel *evsel __maybe_unused)
43 {
44         return 0;
45 }
46
47 static void perf_evsel__no_extra_fini(struct perf_evsel *evsel __maybe_unused)
48 {
49 }
50
51 static struct {
52         size_t  size;
53         int     (*init)(struct perf_evsel *evsel);
54         void    (*fini)(struct perf_evsel *evsel);
55 } perf_evsel__object = {
56         .size = sizeof(struct perf_evsel),
57         .init = perf_evsel__no_extra_init,
58         .fini = perf_evsel__no_extra_fini,
59 };
60
61 int perf_evsel__object_config(size_t object_size,
62                               int (*init)(struct perf_evsel *evsel),
63                               void (*fini)(struct perf_evsel *evsel))
64 {
65
66         if (object_size == 0)
67                 goto set_methods;
68
69         if (perf_evsel__object.size > object_size)
70                 return -EINVAL;
71
72         perf_evsel__object.size = object_size;
73
74 set_methods:
75         if (init != NULL)
76                 perf_evsel__object.init = init;
77
78         if (fini != NULL)
79                 perf_evsel__object.fini = fini;
80
81         return 0;
82 }
83
84 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y))
85
86 int __perf_evsel__sample_size(u64 sample_type)
87 {
88         u64 mask = sample_type & PERF_SAMPLE_MASK;
89         int size = 0;
90         int i;
91
92         for (i = 0; i < 64; i++) {
93                 if (mask & (1ULL << i))
94                         size++;
95         }
96
97         size *= sizeof(u64);
98
99         return size;
100 }
101
102 /**
103  * __perf_evsel__calc_id_pos - calculate id_pos.
104  * @sample_type: sample type
105  *
106  * This function returns the position of the event id (PERF_SAMPLE_ID or
107  * PERF_SAMPLE_IDENTIFIER) in a sample event i.e. in the array of struct
108  * sample_event.
109  */
110 static int __perf_evsel__calc_id_pos(u64 sample_type)
111 {
112         int idx = 0;
113
114         if (sample_type & PERF_SAMPLE_IDENTIFIER)
115                 return 0;
116
117         if (!(sample_type & PERF_SAMPLE_ID))
118                 return -1;
119
120         if (sample_type & PERF_SAMPLE_IP)
121                 idx += 1;
122
123         if (sample_type & PERF_SAMPLE_TID)
124                 idx += 1;
125
126         if (sample_type & PERF_SAMPLE_TIME)
127                 idx += 1;
128
129         if (sample_type & PERF_SAMPLE_ADDR)
130                 idx += 1;
131
132         return idx;
133 }
134
135 /**
136  * __perf_evsel__calc_is_pos - calculate is_pos.
137  * @sample_type: sample type
138  *
139  * This function returns the position (counting backwards) of the event id
140  * (PERF_SAMPLE_ID or PERF_SAMPLE_IDENTIFIER) in a non-sample event i.e. if
141  * sample_id_all is used there is an id sample appended to non-sample events.
142  */
143 static int __perf_evsel__calc_is_pos(u64 sample_type)
144 {
145         int idx = 1;
146
147         if (sample_type & PERF_SAMPLE_IDENTIFIER)
148                 return 1;
149
150         if (!(sample_type & PERF_SAMPLE_ID))
151                 return -1;
152
153         if (sample_type & PERF_SAMPLE_CPU)
154                 idx += 1;
155
156         if (sample_type & PERF_SAMPLE_STREAM_ID)
157                 idx += 1;
158
159         return idx;
160 }
161
162 void perf_evsel__calc_id_pos(struct perf_evsel *evsel)
163 {
164         evsel->id_pos = __perf_evsel__calc_id_pos(evsel->attr.sample_type);
165         evsel->is_pos = __perf_evsel__calc_is_pos(evsel->attr.sample_type);
166 }
167
168 void __perf_evsel__set_sample_bit(struct perf_evsel *evsel,
169                                   enum perf_event_sample_format bit)
170 {
171         if (!(evsel->attr.sample_type & bit)) {
172                 evsel->attr.sample_type |= bit;
173                 evsel->sample_size += sizeof(u64);
174                 perf_evsel__calc_id_pos(evsel);
175         }
176 }
177
178 void __perf_evsel__reset_sample_bit(struct perf_evsel *evsel,
179                                     enum perf_event_sample_format bit)
180 {
181         if (evsel->attr.sample_type & bit) {
182                 evsel->attr.sample_type &= ~bit;
183                 evsel->sample_size -= sizeof(u64);
184                 perf_evsel__calc_id_pos(evsel);
185         }
186 }
187
188 void perf_evsel__set_sample_id(struct perf_evsel *evsel,
189                                bool can_sample_identifier)
190 {
191         if (can_sample_identifier) {
192                 perf_evsel__reset_sample_bit(evsel, ID);
193                 perf_evsel__set_sample_bit(evsel, IDENTIFIER);
194         } else {
195                 perf_evsel__set_sample_bit(evsel, ID);
196         }
197         evsel->attr.read_format |= PERF_FORMAT_ID;
198 }
199
200 void perf_evsel__init(struct perf_evsel *evsel,
201                       struct perf_event_attr *attr, int idx)
202 {
203         evsel->idx         = idx;
204         evsel->tracking    = !idx;
205         evsel->attr        = *attr;
206         evsel->leader      = evsel;
207         evsel->unit        = "";
208         evsel->scale       = 1.0;
209         INIT_LIST_HEAD(&evsel->node);
210         perf_evsel__object.init(evsel);
211         evsel->sample_size = __perf_evsel__sample_size(attr->sample_type);
212         perf_evsel__calc_id_pos(evsel);
213 }
214
215 struct perf_evsel *perf_evsel__new_idx(struct perf_event_attr *attr, int idx)
216 {
217         struct perf_evsel *evsel = zalloc(perf_evsel__object.size);
218
219         if (evsel != NULL)
220                 perf_evsel__init(evsel, attr, idx);
221
222         return evsel;
223 }
224
225 struct perf_evsel *perf_evsel__newtp_idx(const char *sys, const char *name, int idx)
226 {
227         struct perf_evsel *evsel = zalloc(perf_evsel__object.size);
228
229         if (evsel != NULL) {
230                 struct perf_event_attr attr = {
231                         .type          = PERF_TYPE_TRACEPOINT,
232                         .sample_type   = (PERF_SAMPLE_RAW | PERF_SAMPLE_TIME |
233                                           PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD),
234                 };
235
236                 if (asprintf(&evsel->name, "%s:%s", sys, name) < 0)
237                         goto out_free;
238
239                 evsel->tp_format = trace_event__tp_format(sys, name);
240                 if (evsel->tp_format == NULL)
241                         goto out_free;
242
243                 event_attr_init(&attr);
244                 attr.config = evsel->tp_format->id;
245                 attr.sample_period = 1;
246                 perf_evsel__init(evsel, &attr, idx);
247         }
248
249         return evsel;
250
251 out_free:
252         zfree(&evsel->name);
253         free(evsel);
254         return NULL;
255 }
256
257 const char *perf_evsel__hw_names[PERF_COUNT_HW_MAX] = {
258         "cycles",
259         "instructions",
260         "cache-references",
261         "cache-misses",
262         "branches",
263         "branch-misses",
264         "bus-cycles",
265         "stalled-cycles-frontend",
266         "stalled-cycles-backend",
267         "ref-cycles",
268 };
269
270 static const char *__perf_evsel__hw_name(u64 config)
271 {
272         if (config < PERF_COUNT_HW_MAX && perf_evsel__hw_names[config])
273                 return perf_evsel__hw_names[config];
274
275         return "unknown-hardware";
276 }
277
278 static int perf_evsel__add_modifiers(struct perf_evsel *evsel, char *bf, size_t size)
279 {
280         int colon = 0, r = 0;
281         struct perf_event_attr *attr = &evsel->attr;
282         bool exclude_guest_default = false;
283
284 #define MOD_PRINT(context, mod) do {                                    \
285                 if (!attr->exclude_##context) {                         \
286                         if (!colon) colon = ++r;                        \
287                         r += scnprintf(bf + r, size - r, "%c", mod);    \
288                 } } while(0)
289
290         if (attr->exclude_kernel || attr->exclude_user || attr->exclude_hv) {
291                 MOD_PRINT(kernel, 'k');
292                 MOD_PRINT(user, 'u');
293                 MOD_PRINT(hv, 'h');
294                 exclude_guest_default = true;
295         }
296
297         if (attr->precise_ip) {
298                 if (!colon)
299                         colon = ++r;
300                 r += scnprintf(bf + r, size - r, "%.*s", attr->precise_ip, "ppp");
301                 exclude_guest_default = true;
302         }
303
304         if (attr->exclude_host || attr->exclude_guest == exclude_guest_default) {
305                 MOD_PRINT(host, 'H');
306                 MOD_PRINT(guest, 'G');
307         }
308 #undef MOD_PRINT
309         if (colon)
310                 bf[colon - 1] = ':';
311         return r;
312 }
313
314 static int perf_evsel__hw_name(struct perf_evsel *evsel, char *bf, size_t size)
315 {
316         int r = scnprintf(bf, size, "%s", __perf_evsel__hw_name(evsel->attr.config));
317         return r + perf_evsel__add_modifiers(evsel, bf + r, size - r);
318 }
319
320 const char *perf_evsel__sw_names[PERF_COUNT_SW_MAX] = {
321         "cpu-clock",
322         "task-clock",
323         "page-faults",
324         "context-switches",
325         "cpu-migrations",
326         "minor-faults",
327         "major-faults",
328         "alignment-faults",
329         "emulation-faults",
330         "dummy",
331 };
332
333 static const char *__perf_evsel__sw_name(u64 config)
334 {
335         if (config < PERF_COUNT_SW_MAX && perf_evsel__sw_names[config])
336                 return perf_evsel__sw_names[config];
337         return "unknown-software";
338 }
339
340 static int perf_evsel__sw_name(struct perf_evsel *evsel, char *bf, size_t size)
341 {
342         int r = scnprintf(bf, size, "%s", __perf_evsel__sw_name(evsel->attr.config));
343         return r + perf_evsel__add_modifiers(evsel, bf + r, size - r);
344 }
345
346 static int __perf_evsel__bp_name(char *bf, size_t size, u64 addr, u64 type)
347 {
348         int r;
349
350         r = scnprintf(bf, size, "mem:0x%" PRIx64 ":", addr);
351
352         if (type & HW_BREAKPOINT_R)
353                 r += scnprintf(bf + r, size - r, "r");
354
355         if (type & HW_BREAKPOINT_W)
356                 r += scnprintf(bf + r, size - r, "w");
357
358         if (type & HW_BREAKPOINT_X)
359                 r += scnprintf(bf + r, size - r, "x");
360
361         return r;
362 }
363
364 static int perf_evsel__bp_name(struct perf_evsel *evsel, char *bf, size_t size)
365 {
366         struct perf_event_attr *attr = &evsel->attr;
367         int r = __perf_evsel__bp_name(bf, size, attr->bp_addr, attr->bp_type);
368         return r + perf_evsel__add_modifiers(evsel, bf + r, size - r);
369 }
370
371 const char *perf_evsel__hw_cache[PERF_COUNT_HW_CACHE_MAX]
372                                 [PERF_EVSEL__MAX_ALIASES] = {
373  { "L1-dcache", "l1-d",         "l1d",          "L1-data",              },
374  { "L1-icache", "l1-i",         "l1i",          "L1-instruction",       },
375  { "LLC",       "L2",                                                   },
376  { "dTLB",      "d-tlb",        "Data-TLB",                             },
377  { "iTLB",      "i-tlb",        "Instruction-TLB",                      },
378  { "branch",    "branches",     "bpu",          "btb",          "bpc",  },
379  { "node",                                                              },
380 };
381
382 const char *perf_evsel__hw_cache_op[PERF_COUNT_HW_CACHE_OP_MAX]
383                                    [PERF_EVSEL__MAX_ALIASES] = {
384  { "load",      "loads",        "read",                                 },
385  { "store",     "stores",       "write",                                },
386  { "prefetch",  "prefetches",   "speculative-read", "speculative-load", },
387 };
388
389 const char *perf_evsel__hw_cache_result[PERF_COUNT_HW_CACHE_RESULT_MAX]
390                                        [PERF_EVSEL__MAX_ALIASES] = {
391  { "refs",      "Reference",    "ops",          "access",               },
392  { "misses",    "miss",                                                 },
393 };
394
395 #define C(x)            PERF_COUNT_HW_CACHE_##x
396 #define CACHE_READ      (1 << C(OP_READ))
397 #define CACHE_WRITE     (1 << C(OP_WRITE))
398 #define CACHE_PREFETCH  (1 << C(OP_PREFETCH))
399 #define COP(x)          (1 << x)
400
401 /*
402  * cache operartion stat
403  * L1I : Read and prefetch only
404  * ITLB and BPU : Read-only
405  */
406 static unsigned long perf_evsel__hw_cache_stat[C(MAX)] = {
407  [C(L1D)]       = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
408  [C(L1I)]       = (CACHE_READ | CACHE_PREFETCH),
409  [C(LL)]        = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
410  [C(DTLB)]      = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
411  [C(ITLB)]      = (CACHE_READ),
412  [C(BPU)]       = (CACHE_READ),
413  [C(NODE)]      = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
414 };
415
416 bool perf_evsel__is_cache_op_valid(u8 type, u8 op)
417 {
418         if (perf_evsel__hw_cache_stat[type] & COP(op))
419                 return true;    /* valid */
420         else
421                 return false;   /* invalid */
422 }
423
424 int __perf_evsel__hw_cache_type_op_res_name(u8 type, u8 op, u8 result,
425                                             char *bf, size_t size)
426 {
427         if (result) {
428                 return scnprintf(bf, size, "%s-%s-%s", perf_evsel__hw_cache[type][0],
429                                  perf_evsel__hw_cache_op[op][0],
430                                  perf_evsel__hw_cache_result[result][0]);
431         }
432
433         return scnprintf(bf, size, "%s-%s", perf_evsel__hw_cache[type][0],
434                          perf_evsel__hw_cache_op[op][1]);
435 }
436
437 static int __perf_evsel__hw_cache_name(u64 config, char *bf, size_t size)
438 {
439         u8 op, result, type = (config >>  0) & 0xff;
440         const char *err = "unknown-ext-hardware-cache-type";
441
442         if (type > PERF_COUNT_HW_CACHE_MAX)
443                 goto out_err;
444
445         op = (config >>  8) & 0xff;
446         err = "unknown-ext-hardware-cache-op";
447         if (op > PERF_COUNT_HW_CACHE_OP_MAX)
448                 goto out_err;
449
450         result = (config >> 16) & 0xff;
451         err = "unknown-ext-hardware-cache-result";
452         if (result > PERF_COUNT_HW_CACHE_RESULT_MAX)
453                 goto out_err;
454
455         err = "invalid-cache";
456         if (!perf_evsel__is_cache_op_valid(type, op))
457                 goto out_err;
458
459         return __perf_evsel__hw_cache_type_op_res_name(type, op, result, bf, size);
460 out_err:
461         return scnprintf(bf, size, "%s", err);
462 }
463
464 static int perf_evsel__hw_cache_name(struct perf_evsel *evsel, char *bf, size_t size)
465 {
466         int ret = __perf_evsel__hw_cache_name(evsel->attr.config, bf, size);
467         return ret + perf_evsel__add_modifiers(evsel, bf + ret, size - ret);
468 }
469
470 static int perf_evsel__raw_name(struct perf_evsel *evsel, char *bf, size_t size)
471 {
472         int ret = scnprintf(bf, size, "raw 0x%" PRIx64, evsel->attr.config);
473         return ret + perf_evsel__add_modifiers(evsel, bf + ret, size - ret);
474 }
475
476 const char *perf_evsel__name(struct perf_evsel *evsel)
477 {
478         char bf[128];
479
480         if (evsel->name)
481                 return evsel->name;
482
483         switch (evsel->attr.type) {
484         case PERF_TYPE_RAW:
485                 perf_evsel__raw_name(evsel, bf, sizeof(bf));
486                 break;
487
488         case PERF_TYPE_HARDWARE:
489                 perf_evsel__hw_name(evsel, bf, sizeof(bf));
490                 break;
491
492         case PERF_TYPE_HW_CACHE:
493                 perf_evsel__hw_cache_name(evsel, bf, sizeof(bf));
494                 break;
495
496         case PERF_TYPE_SOFTWARE:
497                 perf_evsel__sw_name(evsel, bf, sizeof(bf));
498                 break;
499
500         case PERF_TYPE_TRACEPOINT:
501                 scnprintf(bf, sizeof(bf), "%s", "unknown tracepoint");
502                 break;
503
504         case PERF_TYPE_BREAKPOINT:
505                 perf_evsel__bp_name(evsel, bf, sizeof(bf));
506                 break;
507
508         default:
509                 scnprintf(bf, sizeof(bf), "unknown attr type: %d",
510                           evsel->attr.type);
511                 break;
512         }
513
514         evsel->name = strdup(bf);
515
516         return evsel->name ?: "unknown";
517 }
518
519 const char *perf_evsel__group_name(struct perf_evsel *evsel)
520 {
521         return evsel->group_name ?: "anon group";
522 }
523
524 int perf_evsel__group_desc(struct perf_evsel *evsel, char *buf, size_t size)
525 {
526         int ret;
527         struct perf_evsel *pos;
528         const char *group_name = perf_evsel__group_name(evsel);
529
530         ret = scnprintf(buf, size, "%s", group_name);
531
532         ret += scnprintf(buf + ret, size - ret, " { %s",
533                          perf_evsel__name(evsel));
534
535         for_each_group_member(pos, evsel)
536                 ret += scnprintf(buf + ret, size - ret, ", %s",
537                                  perf_evsel__name(pos));
538
539         ret += scnprintf(buf + ret, size - ret, " }");
540
541         return ret;
542 }
543
544 static void
545 perf_evsel__config_callgraph(struct perf_evsel *evsel,
546                              struct record_opts *opts)
547 {
548         bool function = perf_evsel__is_function_event(evsel);
549         struct perf_event_attr *attr = &evsel->attr;
550
551         perf_evsel__set_sample_bit(evsel, CALLCHAIN);
552
553         if (callchain_param.record_mode == CALLCHAIN_LBR) {
554                 if (!opts->branch_stack) {
555                         if (attr->exclude_user) {
556                                 pr_warning("LBR callstack option is only available "
557                                            "to get user callchain information. "
558                                            "Falling back to framepointers.\n");
559                         } else {
560                                 perf_evsel__set_sample_bit(evsel, BRANCH_STACK);
561                                 attr->branch_sample_type = PERF_SAMPLE_BRANCH_USER |
562                                                         PERF_SAMPLE_BRANCH_CALL_STACK;
563                         }
564                 } else
565                          pr_warning("Cannot use LBR callstack with branch stack. "
566                                     "Falling back to framepointers.\n");
567         }
568
569         if (callchain_param.record_mode == CALLCHAIN_DWARF) {
570                 if (!function) {
571                         perf_evsel__set_sample_bit(evsel, REGS_USER);
572                         perf_evsel__set_sample_bit(evsel, STACK_USER);
573                         attr->sample_regs_user = PERF_REGS_MASK;
574                         attr->sample_stack_user = callchain_param.dump_size;
575                         attr->exclude_callchain_user = 1;
576                 } else {
577                         pr_info("Cannot use DWARF unwind for function trace event,"
578                                 " falling back to framepointers.\n");
579                 }
580         }
581
582         if (function) {
583                 pr_info("Disabling user space callchains for function trace event.\n");
584                 attr->exclude_callchain_user = 1;
585         }
586 }
587
588 /*
589  * The enable_on_exec/disabled value strategy:
590  *
591  *  1) For any type of traced program:
592  *    - all independent events and group leaders are disabled
593  *    - all group members are enabled
594  *
595  *     Group members are ruled by group leaders. They need to
596  *     be enabled, because the group scheduling relies on that.
597  *
598  *  2) For traced programs executed by perf:
599  *     - all independent events and group leaders have
600  *       enable_on_exec set
601  *     - we don't specifically enable or disable any event during
602  *       the record command
603  *
604  *     Independent events and group leaders are initially disabled
605  *     and get enabled by exec. Group members are ruled by group
606  *     leaders as stated in 1).
607  *
608  *  3) For traced programs attached by perf (pid/tid):
609  *     - we specifically enable or disable all events during
610  *       the record command
611  *
612  *     When attaching events to already running traced we
613  *     enable/disable events specifically, as there's no
614  *     initial traced exec call.
615  */
616 void perf_evsel__config(struct perf_evsel *evsel, struct record_opts *opts)
617 {
618         struct perf_evsel *leader = evsel->leader;
619         struct perf_event_attr *attr = &evsel->attr;
620         int track = evsel->tracking;
621         bool per_cpu = opts->target.default_per_cpu && !opts->target.per_thread;
622
623         attr->sample_id_all = perf_missing_features.sample_id_all ? 0 : 1;
624         attr->inherit       = !opts->no_inherit;
625
626         perf_evsel__set_sample_bit(evsel, IP);
627         perf_evsel__set_sample_bit(evsel, TID);
628
629         if (evsel->sample_read) {
630                 perf_evsel__set_sample_bit(evsel, READ);
631
632                 /*
633                  * We need ID even in case of single event, because
634                  * PERF_SAMPLE_READ process ID specific data.
635                  */
636                 perf_evsel__set_sample_id(evsel, false);
637
638                 /*
639                  * Apply group format only if we belong to group
640                  * with more than one members.
641                  */
642                 if (leader->nr_members > 1) {
643                         attr->read_format |= PERF_FORMAT_GROUP;
644                         attr->inherit = 0;
645                 }
646         }
647
648         /*
649          * We default some events to have a default interval. But keep
650          * it a weak assumption overridable by the user.
651          */
652         if (!attr->sample_period || (opts->user_freq != UINT_MAX ||
653                                      opts->user_interval != ULLONG_MAX)) {
654                 if (opts->freq) {
655                         perf_evsel__set_sample_bit(evsel, PERIOD);
656                         attr->freq              = 1;
657                         attr->sample_freq       = opts->freq;
658                 } else {
659                         attr->sample_period = opts->default_interval;
660                 }
661         }
662
663         /*
664          * Disable sampling for all group members other
665          * than leader in case leader 'leads' the sampling.
666          */
667         if ((leader != evsel) && leader->sample_read) {
668                 attr->sample_freq   = 0;
669                 attr->sample_period = 0;
670         }
671
672         if (opts->no_samples)
673                 attr->sample_freq = 0;
674
675         if (opts->inherit_stat)
676                 attr->inherit_stat = 1;
677
678         if (opts->sample_address) {
679                 perf_evsel__set_sample_bit(evsel, ADDR);
680                 attr->mmap_data = track;
681         }
682
683         /*
684          * We don't allow user space callchains for  function trace
685          * event, due to issues with page faults while tracing page
686          * fault handler and its overall trickiness nature.
687          */
688         if (perf_evsel__is_function_event(evsel))
689                 evsel->attr.exclude_callchain_user = 1;
690
691         if (callchain_param.enabled && !evsel->no_aux_samples)
692                 perf_evsel__config_callgraph(evsel, opts);
693
694         if (opts->sample_intr_regs) {
695                 attr->sample_regs_intr = PERF_REGS_MASK;
696                 perf_evsel__set_sample_bit(evsel, REGS_INTR);
697         }
698
699         if (target__has_cpu(&opts->target))
700                 perf_evsel__set_sample_bit(evsel, CPU);
701
702         if (opts->period)
703                 perf_evsel__set_sample_bit(evsel, PERIOD);
704
705         /*
706          * When the user explicitely disabled time don't force it here.
707          */
708         if (opts->sample_time &&
709             (!perf_missing_features.sample_id_all &&
710             (!opts->no_inherit || target__has_cpu(&opts->target) || per_cpu)))
711                 perf_evsel__set_sample_bit(evsel, TIME);
712
713         if (opts->raw_samples && !evsel->no_aux_samples) {
714                 perf_evsel__set_sample_bit(evsel, TIME);
715                 perf_evsel__set_sample_bit(evsel, RAW);
716                 perf_evsel__set_sample_bit(evsel, CPU);
717         }
718
719         if (opts->sample_address)
720                 perf_evsel__set_sample_bit(evsel, DATA_SRC);
721
722         if (opts->no_buffering) {
723                 attr->watermark = 0;
724                 attr->wakeup_events = 1;
725         }
726         if (opts->branch_stack && !evsel->no_aux_samples) {
727                 perf_evsel__set_sample_bit(evsel, BRANCH_STACK);
728                 attr->branch_sample_type = opts->branch_stack;
729         }
730
731         if (opts->sample_weight)
732                 perf_evsel__set_sample_bit(evsel, WEIGHT);
733
734         attr->task  = track;
735         attr->mmap  = track;
736         attr->mmap2 = track && !perf_missing_features.mmap2;
737         attr->comm  = track;
738
739         if (opts->sample_transaction)
740                 perf_evsel__set_sample_bit(evsel, TRANSACTION);
741
742         if (opts->running_time) {
743                 evsel->attr.read_format |=
744                         PERF_FORMAT_TOTAL_TIME_ENABLED |
745                         PERF_FORMAT_TOTAL_TIME_RUNNING;
746         }
747
748         /*
749          * XXX see the function comment above
750          *
751          * Disabling only independent events or group leaders,
752          * keeping group members enabled.
753          */
754         if (perf_evsel__is_group_leader(evsel))
755                 attr->disabled = 1;
756
757         /*
758          * Setting enable_on_exec for independent events and
759          * group leaders for traced executed by perf.
760          */
761         if (target__none(&opts->target) && perf_evsel__is_group_leader(evsel) &&
762                 !opts->initial_delay)
763                 attr->enable_on_exec = 1;
764
765         if (evsel->immediate) {
766                 attr->disabled = 0;
767                 attr->enable_on_exec = 0;
768         }
769
770         clockid = opts->clockid;
771         if (opts->use_clockid) {
772                 attr->use_clockid = 1;
773                 attr->clockid = opts->clockid;
774         }
775 }
776
777 static int perf_evsel__alloc_fd(struct perf_evsel *evsel, int ncpus, int nthreads)
778 {
779         int cpu, thread;
780
781         if (evsel->system_wide)
782                 nthreads = 1;
783
784         evsel->fd = xyarray__new(ncpus, nthreads, sizeof(int));
785
786         if (evsel->fd) {
787                 for (cpu = 0; cpu < ncpus; cpu++) {
788                         for (thread = 0; thread < nthreads; thread++) {
789                                 FD(evsel, cpu, thread) = -1;
790                         }
791                 }
792         }
793
794         return evsel->fd != NULL ? 0 : -ENOMEM;
795 }
796
797 static int perf_evsel__run_ioctl(struct perf_evsel *evsel, int ncpus, int nthreads,
798                           int ioc,  void *arg)
799 {
800         int cpu, thread;
801
802         if (evsel->system_wide)
803                 nthreads = 1;
804
805         for (cpu = 0; cpu < ncpus; cpu++) {
806                 for (thread = 0; thread < nthreads; thread++) {
807                         int fd = FD(evsel, cpu, thread),
808                             err = ioctl(fd, ioc, arg);
809
810                         if (err)
811                                 return err;
812                 }
813         }
814
815         return 0;
816 }
817
818 int perf_evsel__apply_filter(struct perf_evsel *evsel, int ncpus, int nthreads,
819                              const char *filter)
820 {
821         return perf_evsel__run_ioctl(evsel, ncpus, nthreads,
822                                      PERF_EVENT_IOC_SET_FILTER,
823                                      (void *)filter);
824 }
825
826 int perf_evsel__set_filter(struct perf_evsel *evsel, const char *filter)
827 {
828         char *new_filter = strdup(filter);
829
830         if (new_filter != NULL) {
831                 free(evsel->filter);
832                 evsel->filter = new_filter;
833                 return 0;
834         }
835
836         return -1;
837 }
838
839 int perf_evsel__append_filter(struct perf_evsel *evsel,
840                               const char *op, const char *filter)
841 {
842         char *new_filter;
843
844         if (evsel->filter == NULL)
845                 return perf_evsel__set_filter(evsel, filter);
846
847         if (asprintf(&new_filter,"(%s) %s (%s)", evsel->filter, op, filter) > 0) {
848                 free(evsel->filter);
849                 evsel->filter = new_filter;
850                 return 0;
851         }
852
853         return -1;
854 }
855
856 int perf_evsel__enable(struct perf_evsel *evsel, int ncpus, int nthreads)
857 {
858         return perf_evsel__run_ioctl(evsel, ncpus, nthreads,
859                                      PERF_EVENT_IOC_ENABLE,
860                                      0);
861 }
862
863 int perf_evsel__alloc_id(struct perf_evsel *evsel, int ncpus, int nthreads)
864 {
865         if (ncpus == 0 || nthreads == 0)
866                 return 0;
867
868         if (evsel->system_wide)
869                 nthreads = 1;
870
871         evsel->sample_id = xyarray__new(ncpus, nthreads, sizeof(struct perf_sample_id));
872         if (evsel->sample_id == NULL)
873                 return -ENOMEM;
874
875         evsel->id = zalloc(ncpus * nthreads * sizeof(u64));
876         if (evsel->id == NULL) {
877                 xyarray__delete(evsel->sample_id);
878                 evsel->sample_id = NULL;
879                 return -ENOMEM;
880         }
881
882         return 0;
883 }
884
885 static void perf_evsel__free_fd(struct perf_evsel *evsel)
886 {
887         xyarray__delete(evsel->fd);
888         evsel->fd = NULL;
889 }
890
891 static void perf_evsel__free_id(struct perf_evsel *evsel)
892 {
893         xyarray__delete(evsel->sample_id);
894         evsel->sample_id = NULL;
895         zfree(&evsel->id);
896 }
897
898 void perf_evsel__close_fd(struct perf_evsel *evsel, int ncpus, int nthreads)
899 {
900         int cpu, thread;
901
902         if (evsel->system_wide)
903                 nthreads = 1;
904
905         for (cpu = 0; cpu < ncpus; cpu++)
906                 for (thread = 0; thread < nthreads; ++thread) {
907                         close(FD(evsel, cpu, thread));
908                         FD(evsel, cpu, thread) = -1;
909                 }
910 }
911
912 void perf_evsel__exit(struct perf_evsel *evsel)
913 {
914         assert(list_empty(&evsel->node));
915         perf_evsel__free_fd(evsel);
916         perf_evsel__free_id(evsel);
917         close_cgroup(evsel->cgrp);
918         cpu_map__put(evsel->cpus);
919         thread_map__put(evsel->threads);
920         zfree(&evsel->group_name);
921         zfree(&evsel->name);
922         perf_evsel__object.fini(evsel);
923 }
924
925 void perf_evsel__delete(struct perf_evsel *evsel)
926 {
927         perf_evsel__exit(evsel);
928         free(evsel);
929 }
930
931 void perf_evsel__compute_deltas(struct perf_evsel *evsel, int cpu, int thread,
932                                 struct perf_counts_values *count)
933 {
934         struct perf_counts_values tmp;
935
936         if (!evsel->prev_raw_counts)
937                 return;
938
939         if (cpu == -1) {
940                 tmp = evsel->prev_raw_counts->aggr;
941                 evsel->prev_raw_counts->aggr = *count;
942         } else {
943                 tmp = *perf_counts(evsel->prev_raw_counts, cpu, thread);
944                 *perf_counts(evsel->prev_raw_counts, cpu, thread) = *count;
945         }
946
947         count->val = count->val - tmp.val;
948         count->ena = count->ena - tmp.ena;
949         count->run = count->run - tmp.run;
950 }
951
952 void perf_counts_values__scale(struct perf_counts_values *count,
953                                bool scale, s8 *pscaled)
954 {
955         s8 scaled = 0;
956
957         if (scale) {
958                 if (count->run == 0) {
959                         scaled = -1;
960                         count->val = 0;
961                 } else if (count->run < count->ena) {
962                         scaled = 1;
963                         count->val = (u64)((double) count->val * count->ena / count->run + 0.5);
964                 }
965         } else
966                 count->ena = count->run = 0;
967
968         if (pscaled)
969                 *pscaled = scaled;
970 }
971
972 int perf_evsel__read(struct perf_evsel *evsel, int cpu, int thread,
973                      struct perf_counts_values *count)
974 {
975         memset(count, 0, sizeof(*count));
976
977         if (FD(evsel, cpu, thread) < 0)
978                 return -EINVAL;
979
980         if (readn(FD(evsel, cpu, thread), count, sizeof(*count)) < 0)
981                 return -errno;
982
983         return 0;
984 }
985
986 int __perf_evsel__read_on_cpu(struct perf_evsel *evsel,
987                               int cpu, int thread, bool scale)
988 {
989         struct perf_counts_values count;
990         size_t nv = scale ? 3 : 1;
991
992         if (FD(evsel, cpu, thread) < 0)
993                 return -EINVAL;
994
995         if (evsel->counts == NULL && perf_evsel__alloc_counts(evsel, cpu + 1, thread + 1) < 0)
996                 return -ENOMEM;
997
998         if (readn(FD(evsel, cpu, thread), &count, nv * sizeof(u64)) < 0)
999                 return -errno;
1000
1001         perf_evsel__compute_deltas(evsel, cpu, thread, &count);
1002         perf_counts_values__scale(&count, scale, NULL);
1003         *perf_counts(evsel->counts, cpu, thread) = count;
1004         return 0;
1005 }
1006
1007 static int get_group_fd(struct perf_evsel *evsel, int cpu, int thread)
1008 {
1009         struct perf_evsel *leader = evsel->leader;
1010         int fd;
1011
1012         if (perf_evsel__is_group_leader(evsel))
1013                 return -1;
1014
1015         /*
1016          * Leader must be already processed/open,
1017          * if not it's a bug.
1018          */
1019         BUG_ON(!leader->fd);
1020
1021         fd = FD(leader, cpu, thread);
1022         BUG_ON(fd == -1);
1023
1024         return fd;
1025 }
1026
1027 struct bit_names {
1028         int bit;
1029         const char *name;
1030 };
1031
1032 static void __p_bits(char *buf, size_t size, u64 value, struct bit_names *bits)
1033 {
1034         bool first_bit = true;
1035         int i = 0;
1036
1037         do {
1038                 if (value & bits[i].bit) {
1039                         buf += scnprintf(buf, size, "%s%s", first_bit ? "" : "|", bits[i].name);
1040                         first_bit = false;
1041                 }
1042         } while (bits[++i].name != NULL);
1043 }
1044
1045 static void __p_sample_type(char *buf, size_t size, u64 value)
1046 {
1047 #define bit_name(n) { PERF_SAMPLE_##n, #n }
1048         struct bit_names bits[] = {
1049                 bit_name(IP), bit_name(TID), bit_name(TIME), bit_name(ADDR),
1050                 bit_name(READ), bit_name(CALLCHAIN), bit_name(ID), bit_name(CPU),
1051                 bit_name(PERIOD), bit_name(STREAM_ID), bit_name(RAW),
1052                 bit_name(BRANCH_STACK), bit_name(REGS_USER), bit_name(STACK_USER),
1053                 bit_name(IDENTIFIER), bit_name(REGS_INTR),
1054                 { .name = NULL, }
1055         };
1056 #undef bit_name
1057         __p_bits(buf, size, value, bits);
1058 }
1059
1060 static void __p_read_format(char *buf, size_t size, u64 value)
1061 {
1062 #define bit_name(n) { PERF_FORMAT_##n, #n }
1063         struct bit_names bits[] = {
1064                 bit_name(TOTAL_TIME_ENABLED), bit_name(TOTAL_TIME_RUNNING),
1065                 bit_name(ID), bit_name(GROUP),
1066                 { .name = NULL, }
1067         };
1068 #undef bit_name
1069         __p_bits(buf, size, value, bits);
1070 }
1071
1072 #define BUF_SIZE                1024
1073
1074 #define p_hex(val)              snprintf(buf, BUF_SIZE, "%#"PRIx64, (uint64_t)(val))
1075 #define p_unsigned(val)         snprintf(buf, BUF_SIZE, "%"PRIu64, (uint64_t)(val))
1076 #define p_signed(val)           snprintf(buf, BUF_SIZE, "%"PRId64, (int64_t)(val))
1077 #define p_sample_type(val)      __p_sample_type(buf, BUF_SIZE, val)
1078 #define p_read_format(val)      __p_read_format(buf, BUF_SIZE, val)
1079
1080 #define PRINT_ATTRn(_n, _f, _p)                         \
1081 do {                                                    \
1082         if (attr->_f) {                                 \
1083                 _p(attr->_f);                           \
1084                 ret += attr__fprintf(fp, _n, buf, priv);\
1085         }                                               \
1086 } while (0)
1087
1088 #define PRINT_ATTRf(_f, _p)     PRINT_ATTRn(#_f, _f, _p)
1089
1090 int perf_event_attr__fprintf(FILE *fp, struct perf_event_attr *attr,
1091                              attr__fprintf_f attr__fprintf, void *priv)
1092 {
1093         char buf[BUF_SIZE];
1094         int ret = 0;
1095
1096         PRINT_ATTRf(type, p_unsigned);
1097         PRINT_ATTRf(size, p_unsigned);
1098         PRINT_ATTRf(config, p_hex);
1099         PRINT_ATTRn("{ sample_period, sample_freq }", sample_period, p_unsigned);
1100         PRINT_ATTRf(sample_type, p_sample_type);
1101         PRINT_ATTRf(read_format, p_read_format);
1102
1103         PRINT_ATTRf(disabled, p_unsigned);
1104         PRINT_ATTRf(inherit, p_unsigned);
1105         PRINT_ATTRf(pinned, p_unsigned);
1106         PRINT_ATTRf(exclusive, p_unsigned);
1107         PRINT_ATTRf(exclude_user, p_unsigned);
1108         PRINT_ATTRf(exclude_kernel, p_unsigned);
1109         PRINT_ATTRf(exclude_hv, p_unsigned);
1110         PRINT_ATTRf(exclude_idle, p_unsigned);
1111         PRINT_ATTRf(mmap, p_unsigned);
1112         PRINT_ATTRf(comm, p_unsigned);
1113         PRINT_ATTRf(freq, p_unsigned);
1114         PRINT_ATTRf(inherit_stat, p_unsigned);
1115         PRINT_ATTRf(enable_on_exec, p_unsigned);
1116         PRINT_ATTRf(task, p_unsigned);
1117         PRINT_ATTRf(watermark, p_unsigned);
1118         PRINT_ATTRf(precise_ip, p_unsigned);
1119         PRINT_ATTRf(mmap_data, p_unsigned);
1120         PRINT_ATTRf(sample_id_all, p_unsigned);
1121         PRINT_ATTRf(exclude_host, p_unsigned);
1122         PRINT_ATTRf(exclude_guest, p_unsigned);
1123         PRINT_ATTRf(exclude_callchain_kernel, p_unsigned);
1124         PRINT_ATTRf(exclude_callchain_user, p_unsigned);
1125         PRINT_ATTRf(mmap2, p_unsigned);
1126         PRINT_ATTRf(comm_exec, p_unsigned);
1127         PRINT_ATTRf(use_clockid, p_unsigned);
1128
1129         PRINT_ATTRn("{ wakeup_events, wakeup_watermark }", wakeup_events, p_unsigned);
1130         PRINT_ATTRf(bp_type, p_unsigned);
1131         PRINT_ATTRn("{ bp_addr, config1 }", bp_addr, p_hex);
1132         PRINT_ATTRn("{ bp_len, config2 }", bp_len, p_hex);
1133         PRINT_ATTRf(sample_regs_user, p_hex);
1134         PRINT_ATTRf(sample_stack_user, p_unsigned);
1135         PRINT_ATTRf(clockid, p_signed);
1136         PRINT_ATTRf(sample_regs_intr, p_hex);
1137         PRINT_ATTRf(aux_watermark, p_unsigned);
1138
1139         return ret;
1140 }
1141
1142 static int __open_attr__fprintf(FILE *fp, const char *name, const char *val,
1143                                 void *priv __attribute__((unused)))
1144 {
1145         return fprintf(fp, "  %-32s %s\n", name, val);
1146 }
1147
1148 static int __perf_evsel__open(struct perf_evsel *evsel, struct cpu_map *cpus,
1149                               struct thread_map *threads)
1150 {
1151         int cpu, thread, nthreads;
1152         unsigned long flags = PERF_FLAG_FD_CLOEXEC;
1153         int pid = -1, err;
1154         enum { NO_CHANGE, SET_TO_MAX, INCREASED_MAX } set_rlimit = NO_CHANGE;
1155
1156         if (evsel->system_wide)
1157                 nthreads = 1;
1158         else
1159                 nthreads = threads->nr;
1160
1161         if (evsel->fd == NULL &&
1162             perf_evsel__alloc_fd(evsel, cpus->nr, nthreads) < 0)
1163                 return -ENOMEM;
1164
1165         if (evsel->cgrp) {
1166                 flags |= PERF_FLAG_PID_CGROUP;
1167                 pid = evsel->cgrp->fd;
1168         }
1169
1170 fallback_missing_features:
1171         if (perf_missing_features.clockid_wrong)
1172                 evsel->attr.clockid = CLOCK_MONOTONIC; /* should always work */
1173         if (perf_missing_features.clockid) {
1174                 evsel->attr.use_clockid = 0;
1175                 evsel->attr.clockid = 0;
1176         }
1177         if (perf_missing_features.cloexec)
1178                 flags &= ~(unsigned long)PERF_FLAG_FD_CLOEXEC;
1179         if (perf_missing_features.mmap2)
1180                 evsel->attr.mmap2 = 0;
1181         if (perf_missing_features.exclude_guest)
1182                 evsel->attr.exclude_guest = evsel->attr.exclude_host = 0;
1183 retry_sample_id:
1184         if (perf_missing_features.sample_id_all)
1185                 evsel->attr.sample_id_all = 0;
1186
1187         if (verbose >= 2) {
1188                 fprintf(stderr, "%.60s\n", graph_dotted_line);
1189                 fprintf(stderr, "perf_event_attr:\n");
1190                 perf_event_attr__fprintf(stderr, &evsel->attr, __open_attr__fprintf, NULL);
1191                 fprintf(stderr, "%.60s\n", graph_dotted_line);
1192         }
1193
1194         for (cpu = 0; cpu < cpus->nr; cpu++) {
1195
1196                 for (thread = 0; thread < nthreads; thread++) {
1197                         int group_fd;
1198
1199                         if (!evsel->cgrp && !evsel->system_wide)
1200                                 pid = thread_map__pid(threads, thread);
1201
1202                         group_fd = get_group_fd(evsel, cpu, thread);
1203 retry_open:
1204                         pr_debug2("sys_perf_event_open: pid %d  cpu %d  group_fd %d  flags %#lx\n",
1205                                   pid, cpus->map[cpu], group_fd, flags);
1206
1207                         FD(evsel, cpu, thread) = sys_perf_event_open(&evsel->attr,
1208                                                                      pid,
1209                                                                      cpus->map[cpu],
1210                                                                      group_fd, flags);
1211                         if (FD(evsel, cpu, thread) < 0) {
1212                                 err = -errno;
1213                                 pr_debug2("sys_perf_event_open failed, error %d\n",
1214                                           err);
1215                                 goto try_fallback;
1216                         }
1217                         set_rlimit = NO_CHANGE;
1218
1219                         /*
1220                          * If we succeeded but had to kill clockid, fail and
1221                          * have perf_evsel__open_strerror() print us a nice
1222                          * error.
1223                          */
1224                         if (perf_missing_features.clockid ||
1225                             perf_missing_features.clockid_wrong) {
1226                                 err = -EINVAL;
1227                                 goto out_close;
1228                         }
1229                 }
1230         }
1231
1232         return 0;
1233
1234 try_fallback:
1235         /*
1236          * perf stat needs between 5 and 22 fds per CPU. When we run out
1237          * of them try to increase the limits.
1238          */
1239         if (err == -EMFILE && set_rlimit < INCREASED_MAX) {
1240                 struct rlimit l;
1241                 int old_errno = errno;
1242
1243                 if (getrlimit(RLIMIT_NOFILE, &l) == 0) {
1244                         if (set_rlimit == NO_CHANGE)
1245                                 l.rlim_cur = l.rlim_max;
1246                         else {
1247                                 l.rlim_cur = l.rlim_max + 1000;
1248                                 l.rlim_max = l.rlim_cur;
1249                         }
1250                         if (setrlimit(RLIMIT_NOFILE, &l) == 0) {
1251                                 set_rlimit++;
1252                                 errno = old_errno;
1253                                 goto retry_open;
1254                         }
1255                 }
1256                 errno = old_errno;
1257         }
1258
1259         if (err != -EINVAL || cpu > 0 || thread > 0)
1260                 goto out_close;
1261
1262         /*
1263          * Must probe features in the order they were added to the
1264          * perf_event_attr interface.
1265          */
1266         if (!perf_missing_features.clockid_wrong && evsel->attr.use_clockid) {
1267                 perf_missing_features.clockid_wrong = true;
1268                 goto fallback_missing_features;
1269         } else if (!perf_missing_features.clockid && evsel->attr.use_clockid) {
1270                 perf_missing_features.clockid = true;
1271                 goto fallback_missing_features;
1272         } else if (!perf_missing_features.cloexec && (flags & PERF_FLAG_FD_CLOEXEC)) {
1273                 perf_missing_features.cloexec = true;
1274                 goto fallback_missing_features;
1275         } else if (!perf_missing_features.mmap2 && evsel->attr.mmap2) {
1276                 perf_missing_features.mmap2 = true;
1277                 goto fallback_missing_features;
1278         } else if (!perf_missing_features.exclude_guest &&
1279                    (evsel->attr.exclude_guest || evsel->attr.exclude_host)) {
1280                 perf_missing_features.exclude_guest = true;
1281                 goto fallback_missing_features;
1282         } else if (!perf_missing_features.sample_id_all) {
1283                 perf_missing_features.sample_id_all = true;
1284                 goto retry_sample_id;
1285         }
1286
1287 out_close:
1288         do {
1289                 while (--thread >= 0) {
1290                         close(FD(evsel, cpu, thread));
1291                         FD(evsel, cpu, thread) = -1;
1292                 }
1293                 thread = nthreads;
1294         } while (--cpu >= 0);
1295         return err;
1296 }
1297
1298 void perf_evsel__close(struct perf_evsel *evsel, int ncpus, int nthreads)
1299 {
1300         if (evsel->fd == NULL)
1301                 return;
1302
1303         perf_evsel__close_fd(evsel, ncpus, nthreads);
1304         perf_evsel__free_fd(evsel);
1305 }
1306
1307 static struct {
1308         struct cpu_map map;
1309         int cpus[1];
1310 } empty_cpu_map = {
1311         .map.nr = 1,
1312         .cpus   = { -1, },
1313 };
1314
1315 static struct {
1316         struct thread_map map;
1317         int threads[1];
1318 } empty_thread_map = {
1319         .map.nr  = 1,
1320         .threads = { -1, },
1321 };
1322
1323 int perf_evsel__open(struct perf_evsel *evsel, struct cpu_map *cpus,
1324                      struct thread_map *threads)
1325 {
1326         if (cpus == NULL) {
1327                 /* Work around old compiler warnings about strict aliasing */
1328                 cpus = &empty_cpu_map.map;
1329         }
1330
1331         if (threads == NULL)
1332                 threads = &empty_thread_map.map;
1333
1334         return __perf_evsel__open(evsel, cpus, threads);
1335 }
1336
1337 int perf_evsel__open_per_cpu(struct perf_evsel *evsel,
1338                              struct cpu_map *cpus)
1339 {
1340         return __perf_evsel__open(evsel, cpus, &empty_thread_map.map);
1341 }
1342
1343 int perf_evsel__open_per_thread(struct perf_evsel *evsel,
1344                                 struct thread_map *threads)
1345 {
1346         return __perf_evsel__open(evsel, &empty_cpu_map.map, threads);
1347 }
1348
1349 static int perf_evsel__parse_id_sample(const struct perf_evsel *evsel,
1350                                        const union perf_event *event,
1351                                        struct perf_sample *sample)
1352 {
1353         u64 type = evsel->attr.sample_type;
1354         const u64 *array = event->sample.array;
1355         bool swapped = evsel->needs_swap;
1356         union u64_swap u;
1357
1358         array += ((event->header.size -
1359                    sizeof(event->header)) / sizeof(u64)) - 1;
1360
1361         if (type & PERF_SAMPLE_IDENTIFIER) {
1362                 sample->id = *array;
1363                 array--;
1364         }
1365
1366         if (type & PERF_SAMPLE_CPU) {
1367                 u.val64 = *array;
1368                 if (swapped) {
1369                         /* undo swap of u64, then swap on individual u32s */
1370                         u.val64 = bswap_64(u.val64);
1371                         u.val32[0] = bswap_32(u.val32[0]);
1372                 }
1373
1374                 sample->cpu = u.val32[0];
1375                 array--;
1376         }
1377
1378         if (type & PERF_SAMPLE_STREAM_ID) {
1379                 sample->stream_id = *array;
1380                 array--;
1381         }
1382
1383         if (type & PERF_SAMPLE_ID) {
1384                 sample->id = *array;
1385                 array--;
1386         }
1387
1388         if (type & PERF_SAMPLE_TIME) {
1389                 sample->time = *array;
1390                 array--;
1391         }
1392
1393         if (type & PERF_SAMPLE_TID) {
1394                 u.val64 = *array;
1395                 if (swapped) {
1396                         /* undo swap of u64, then swap on individual u32s */
1397                         u.val64 = bswap_64(u.val64);
1398                         u.val32[0] = bswap_32(u.val32[0]);
1399                         u.val32[1] = bswap_32(u.val32[1]);
1400                 }
1401
1402                 sample->pid = u.val32[0];
1403                 sample->tid = u.val32[1];
1404                 array--;
1405         }
1406
1407         return 0;
1408 }
1409
1410 static inline bool overflow(const void *endp, u16 max_size, const void *offset,
1411                             u64 size)
1412 {
1413         return size > max_size || offset + size > endp;
1414 }
1415
1416 #define OVERFLOW_CHECK(offset, size, max_size)                          \
1417         do {                                                            \
1418                 if (overflow(endp, (max_size), (offset), (size)))       \
1419                         return -EFAULT;                                 \
1420         } while (0)
1421
1422 #define OVERFLOW_CHECK_u64(offset) \
1423         OVERFLOW_CHECK(offset, sizeof(u64), sizeof(u64))
1424
1425 int perf_evsel__parse_sample(struct perf_evsel *evsel, union perf_event *event,
1426                              struct perf_sample *data)
1427 {
1428         u64 type = evsel->attr.sample_type;
1429         bool swapped = evsel->needs_swap;
1430         const u64 *array;
1431         u16 max_size = event->header.size;
1432         const void *endp = (void *)event + max_size;
1433         u64 sz;
1434
1435         /*
1436          * used for cross-endian analysis. See git commit 65014ab3
1437          * for why this goofiness is needed.
1438          */
1439         union u64_swap u;
1440
1441         memset(data, 0, sizeof(*data));
1442         data->cpu = data->pid = data->tid = -1;
1443         data->stream_id = data->id = data->time = -1ULL;
1444         data->period = evsel->attr.sample_period;
1445         data->weight = 0;
1446
1447         if (event->header.type != PERF_RECORD_SAMPLE) {
1448                 if (!evsel->attr.sample_id_all)
1449                         return 0;
1450                 return perf_evsel__parse_id_sample(evsel, event, data);
1451         }
1452
1453         array = event->sample.array;
1454
1455         /*
1456          * The evsel's sample_size is based on PERF_SAMPLE_MASK which includes
1457          * up to PERF_SAMPLE_PERIOD.  After that overflow() must be used to
1458          * check the format does not go past the end of the event.
1459          */
1460         if (evsel->sample_size + sizeof(event->header) > event->header.size)
1461                 return -EFAULT;
1462
1463         data->id = -1ULL;
1464         if (type & PERF_SAMPLE_IDENTIFIER) {
1465                 data->id = *array;
1466                 array++;
1467         }
1468
1469         if (type & PERF_SAMPLE_IP) {
1470                 data->ip = *array;
1471                 array++;
1472         }
1473
1474         if (type & PERF_SAMPLE_TID) {
1475                 u.val64 = *array;
1476                 if (swapped) {
1477                         /* undo swap of u64, then swap on individual u32s */
1478                         u.val64 = bswap_64(u.val64);
1479                         u.val32[0] = bswap_32(u.val32[0]);
1480                         u.val32[1] = bswap_32(u.val32[1]);
1481                 }
1482
1483                 data->pid = u.val32[0];
1484                 data->tid = u.val32[1];
1485                 array++;
1486         }
1487
1488         if (type & PERF_SAMPLE_TIME) {
1489                 data->time = *array;
1490                 array++;
1491         }
1492
1493         data->addr = 0;
1494         if (type & PERF_SAMPLE_ADDR) {
1495                 data->addr = *array;
1496                 array++;
1497         }
1498
1499         if (type & PERF_SAMPLE_ID) {
1500                 data->id = *array;
1501                 array++;
1502         }
1503
1504         if (type & PERF_SAMPLE_STREAM_ID) {
1505                 data->stream_id = *array;
1506                 array++;
1507         }
1508
1509         if (type & PERF_SAMPLE_CPU) {
1510
1511                 u.val64 = *array;
1512                 if (swapped) {
1513                         /* undo swap of u64, then swap on individual u32s */
1514                         u.val64 = bswap_64(u.val64);
1515                         u.val32[0] = bswap_32(u.val32[0]);
1516                 }
1517
1518                 data->cpu = u.val32[0];
1519                 array++;
1520         }
1521
1522         if (type & PERF_SAMPLE_PERIOD) {
1523                 data->period = *array;
1524                 array++;
1525         }
1526
1527         if (type & PERF_SAMPLE_READ) {
1528                 u64 read_format = evsel->attr.read_format;
1529
1530                 OVERFLOW_CHECK_u64(array);
1531                 if (read_format & PERF_FORMAT_GROUP)
1532                         data->read.group.nr = *array;
1533                 else
1534                         data->read.one.value = *array;
1535
1536                 array++;
1537
1538                 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
1539                         OVERFLOW_CHECK_u64(array);
1540                         data->read.time_enabled = *array;
1541                         array++;
1542                 }
1543
1544                 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
1545                         OVERFLOW_CHECK_u64(array);
1546                         data->read.time_running = *array;
1547                         array++;
1548                 }
1549
1550                 /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
1551                 if (read_format & PERF_FORMAT_GROUP) {
1552                         const u64 max_group_nr = UINT64_MAX /
1553                                         sizeof(struct sample_read_value);
1554
1555                         if (data->read.group.nr > max_group_nr)
1556                                 return -EFAULT;
1557                         sz = data->read.group.nr *
1558                              sizeof(struct sample_read_value);
1559                         OVERFLOW_CHECK(array, sz, max_size);
1560                         data->read.group.values =
1561                                         (struct sample_read_value *)array;
1562                         array = (void *)array + sz;
1563                 } else {
1564                         OVERFLOW_CHECK_u64(array);
1565                         data->read.one.id = *array;
1566                         array++;
1567                 }
1568         }
1569
1570         if (type & PERF_SAMPLE_CALLCHAIN) {
1571                 const u64 max_callchain_nr = UINT64_MAX / sizeof(u64);
1572
1573                 OVERFLOW_CHECK_u64(array);
1574                 data->callchain = (struct ip_callchain *)array++;
1575                 if (data->callchain->nr > max_callchain_nr)
1576                         return -EFAULT;
1577                 sz = data->callchain->nr * sizeof(u64);
1578                 OVERFLOW_CHECK(array, sz, max_size);
1579                 array = (void *)array + sz;
1580         }
1581
1582         if (type & PERF_SAMPLE_RAW) {
1583                 OVERFLOW_CHECK_u64(array);
1584                 u.val64 = *array;
1585                 if (WARN_ONCE(swapped,
1586                               "Endianness of raw data not corrected!\n")) {
1587                         /* undo swap of u64, then swap on individual u32s */
1588                         u.val64 = bswap_64(u.val64);
1589                         u.val32[0] = bswap_32(u.val32[0]);
1590                         u.val32[1] = bswap_32(u.val32[1]);
1591                 }
1592                 data->raw_size = u.val32[0];
1593                 array = (void *)array + sizeof(u32);
1594
1595                 OVERFLOW_CHECK(array, data->raw_size, max_size);
1596                 data->raw_data = (void *)array;
1597                 array = (void *)array + data->raw_size;
1598         }
1599
1600         if (type & PERF_SAMPLE_BRANCH_STACK) {
1601                 const u64 max_branch_nr = UINT64_MAX /
1602                                           sizeof(struct branch_entry);
1603
1604                 OVERFLOW_CHECK_u64(array);
1605                 data->branch_stack = (struct branch_stack *)array++;
1606
1607                 if (data->branch_stack->nr > max_branch_nr)
1608                         return -EFAULT;
1609                 sz = data->branch_stack->nr * sizeof(struct branch_entry);
1610                 OVERFLOW_CHECK(array, sz, max_size);
1611                 array = (void *)array + sz;
1612         }
1613
1614         if (type & PERF_SAMPLE_REGS_USER) {
1615                 OVERFLOW_CHECK_u64(array);
1616                 data->user_regs.abi = *array;
1617                 array++;
1618
1619                 if (data->user_regs.abi) {
1620                         u64 mask = evsel->attr.sample_regs_user;
1621
1622                         sz = hweight_long(mask) * sizeof(u64);
1623                         OVERFLOW_CHECK(array, sz, max_size);
1624                         data->user_regs.mask = mask;
1625                         data->user_regs.regs = (u64 *)array;
1626                         array = (void *)array + sz;
1627                 }
1628         }
1629
1630         if (type & PERF_SAMPLE_STACK_USER) {
1631                 OVERFLOW_CHECK_u64(array);
1632                 sz = *array++;
1633
1634                 data->user_stack.offset = ((char *)(array - 1)
1635                                           - (char *) event);
1636
1637                 if (!sz) {
1638                         data->user_stack.size = 0;
1639                 } else {
1640                         OVERFLOW_CHECK(array, sz, max_size);
1641                         data->user_stack.data = (char *)array;
1642                         array = (void *)array + sz;
1643                         OVERFLOW_CHECK_u64(array);
1644                         data->user_stack.size = *array++;
1645                         if (WARN_ONCE(data->user_stack.size > sz,
1646                                       "user stack dump failure\n"))
1647                                 return -EFAULT;
1648                 }
1649         }
1650
1651         data->weight = 0;
1652         if (type & PERF_SAMPLE_WEIGHT) {
1653                 OVERFLOW_CHECK_u64(array);
1654                 data->weight = *array;
1655                 array++;
1656         }
1657
1658         data->data_src = PERF_MEM_DATA_SRC_NONE;
1659         if (type & PERF_SAMPLE_DATA_SRC) {
1660                 OVERFLOW_CHECK_u64(array);
1661                 data->data_src = *array;
1662                 array++;
1663         }
1664
1665         data->transaction = 0;
1666         if (type & PERF_SAMPLE_TRANSACTION) {
1667                 OVERFLOW_CHECK_u64(array);
1668                 data->transaction = *array;
1669                 array++;
1670         }
1671
1672         data->intr_regs.abi = PERF_SAMPLE_REGS_ABI_NONE;
1673         if (type & PERF_SAMPLE_REGS_INTR) {
1674                 OVERFLOW_CHECK_u64(array);
1675                 data->intr_regs.abi = *array;
1676                 array++;
1677
1678                 if (data->intr_regs.abi != PERF_SAMPLE_REGS_ABI_NONE) {
1679                         u64 mask = evsel->attr.sample_regs_intr;
1680
1681                         sz = hweight_long(mask) * sizeof(u64);
1682                         OVERFLOW_CHECK(array, sz, max_size);
1683                         data->intr_regs.mask = mask;
1684                         data->intr_regs.regs = (u64 *)array;
1685                         array = (void *)array + sz;
1686                 }
1687         }
1688
1689         return 0;
1690 }
1691
1692 size_t perf_event__sample_event_size(const struct perf_sample *sample, u64 type,
1693                                      u64 read_format)
1694 {
1695         size_t sz, result = sizeof(struct sample_event);
1696
1697         if (type & PERF_SAMPLE_IDENTIFIER)
1698                 result += sizeof(u64);
1699
1700         if (type & PERF_SAMPLE_IP)
1701                 result += sizeof(u64);
1702
1703         if (type & PERF_SAMPLE_TID)
1704                 result += sizeof(u64);
1705
1706         if (type & PERF_SAMPLE_TIME)
1707                 result += sizeof(u64);
1708
1709         if (type & PERF_SAMPLE_ADDR)
1710                 result += sizeof(u64);
1711
1712         if (type & PERF_SAMPLE_ID)
1713                 result += sizeof(u64);
1714
1715         if (type & PERF_SAMPLE_STREAM_ID)
1716                 result += sizeof(u64);
1717
1718         if (type & PERF_SAMPLE_CPU)
1719                 result += sizeof(u64);
1720
1721         if (type & PERF_SAMPLE_PERIOD)
1722                 result += sizeof(u64);
1723
1724         if (type & PERF_SAMPLE_READ) {
1725                 result += sizeof(u64);
1726                 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1727                         result += sizeof(u64);
1728                 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1729                         result += sizeof(u64);
1730                 /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
1731                 if (read_format & PERF_FORMAT_GROUP) {
1732                         sz = sample->read.group.nr *
1733                              sizeof(struct sample_read_value);
1734                         result += sz;
1735                 } else {
1736                         result += sizeof(u64);
1737                 }
1738         }
1739
1740         if (type & PERF_SAMPLE_CALLCHAIN) {
1741                 sz = (sample->callchain->nr + 1) * sizeof(u64);
1742                 result += sz;
1743         }
1744
1745         if (type & PERF_SAMPLE_RAW) {
1746                 result += sizeof(u32);
1747                 result += sample->raw_size;
1748         }
1749
1750         if (type & PERF_SAMPLE_BRANCH_STACK) {
1751                 sz = sample->branch_stack->nr * sizeof(struct branch_entry);
1752                 sz += sizeof(u64);
1753                 result += sz;
1754         }
1755
1756         if (type & PERF_SAMPLE_REGS_USER) {
1757                 if (sample->user_regs.abi) {
1758                         result += sizeof(u64);
1759                         sz = hweight_long(sample->user_regs.mask) * sizeof(u64);
1760                         result += sz;
1761                 } else {
1762                         result += sizeof(u64);
1763                 }
1764         }
1765
1766         if (type & PERF_SAMPLE_STACK_USER) {
1767                 sz = sample->user_stack.size;
1768                 result += sizeof(u64);
1769                 if (sz) {
1770                         result += sz;
1771                         result += sizeof(u64);
1772                 }
1773         }
1774
1775         if (type & PERF_SAMPLE_WEIGHT)
1776                 result += sizeof(u64);
1777
1778         if (type & PERF_SAMPLE_DATA_SRC)
1779                 result += sizeof(u64);
1780
1781         if (type & PERF_SAMPLE_TRANSACTION)
1782                 result += sizeof(u64);
1783
1784         if (type & PERF_SAMPLE_REGS_INTR) {
1785                 if (sample->intr_regs.abi) {
1786                         result += sizeof(u64);
1787                         sz = hweight_long(sample->intr_regs.mask) * sizeof(u64);
1788                         result += sz;
1789                 } else {
1790                         result += sizeof(u64);
1791                 }
1792         }
1793
1794         return result;
1795 }
1796
1797 int perf_event__synthesize_sample(union perf_event *event, u64 type,
1798                                   u64 read_format,
1799                                   const struct perf_sample *sample,
1800                                   bool swapped)
1801 {
1802         u64 *array;
1803         size_t sz;
1804         /*
1805          * used for cross-endian analysis. See git commit 65014ab3
1806          * for why this goofiness is needed.
1807          */
1808         union u64_swap u;
1809
1810         array = event->sample.array;
1811
1812         if (type & PERF_SAMPLE_IDENTIFIER) {
1813                 *array = sample->id;
1814                 array++;
1815         }
1816
1817         if (type & PERF_SAMPLE_IP) {
1818                 *array = sample->ip;
1819                 array++;
1820         }
1821
1822         if (type & PERF_SAMPLE_TID) {
1823                 u.val32[0] = sample->pid;
1824                 u.val32[1] = sample->tid;
1825                 if (swapped) {
1826                         /*
1827                          * Inverse of what is done in perf_evsel__parse_sample
1828                          */
1829                         u.val32[0] = bswap_32(u.val32[0]);
1830                         u.val32[1] = bswap_32(u.val32[1]);
1831                         u.val64 = bswap_64(u.val64);
1832                 }
1833
1834                 *array = u.val64;
1835                 array++;
1836         }
1837
1838         if (type & PERF_SAMPLE_TIME) {
1839                 *array = sample->time;
1840                 array++;
1841         }
1842
1843         if (type & PERF_SAMPLE_ADDR) {
1844                 *array = sample->addr;
1845                 array++;
1846         }
1847
1848         if (type & PERF_SAMPLE_ID) {
1849                 *array = sample->id;
1850                 array++;
1851         }
1852
1853         if (type & PERF_SAMPLE_STREAM_ID) {
1854                 *array = sample->stream_id;
1855                 array++;
1856         }
1857
1858         if (type & PERF_SAMPLE_CPU) {
1859                 u.val32[0] = sample->cpu;
1860                 if (swapped) {
1861                         /*
1862                          * Inverse of what is done in perf_evsel__parse_sample
1863                          */
1864                         u.val32[0] = bswap_32(u.val32[0]);
1865                         u.val64 = bswap_64(u.val64);
1866                 }
1867                 *array = u.val64;
1868                 array++;
1869         }
1870
1871         if (type & PERF_SAMPLE_PERIOD) {
1872                 *array = sample->period;
1873                 array++;
1874         }
1875
1876         if (type & PERF_SAMPLE_READ) {
1877                 if (read_format & PERF_FORMAT_GROUP)
1878                         *array = sample->read.group.nr;
1879                 else
1880                         *array = sample->read.one.value;
1881                 array++;
1882
1883                 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
1884                         *array = sample->read.time_enabled;
1885                         array++;
1886                 }
1887
1888                 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
1889                         *array = sample->read.time_running;
1890                         array++;
1891                 }
1892
1893                 /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
1894                 if (read_format & PERF_FORMAT_GROUP) {
1895                         sz = sample->read.group.nr *
1896                              sizeof(struct sample_read_value);
1897                         memcpy(array, sample->read.group.values, sz);
1898                         array = (void *)array + sz;
1899                 } else {
1900                         *array = sample->read.one.id;
1901                         array++;
1902                 }
1903         }
1904
1905         if (type & PERF_SAMPLE_CALLCHAIN) {
1906                 sz = (sample->callchain->nr + 1) * sizeof(u64);
1907                 memcpy(array, sample->callchain, sz);
1908                 array = (void *)array + sz;
1909         }
1910
1911         if (type & PERF_SAMPLE_RAW) {
1912                 u.val32[0] = sample->raw_size;
1913                 if (WARN_ONCE(swapped,
1914                               "Endianness of raw data not corrected!\n")) {
1915                         /*
1916                          * Inverse of what is done in perf_evsel__parse_sample
1917                          */
1918                         u.val32[0] = bswap_32(u.val32[0]);
1919                         u.val32[1] = bswap_32(u.val32[1]);
1920                         u.val64 = bswap_64(u.val64);
1921                 }
1922                 *array = u.val64;
1923                 array = (void *)array + sizeof(u32);
1924
1925                 memcpy(array, sample->raw_data, sample->raw_size);
1926                 array = (void *)array + sample->raw_size;
1927         }
1928
1929         if (type & PERF_SAMPLE_BRANCH_STACK) {
1930                 sz = sample->branch_stack->nr * sizeof(struct branch_entry);
1931                 sz += sizeof(u64);
1932                 memcpy(array, sample->branch_stack, sz);
1933                 array = (void *)array + sz;
1934         }
1935
1936         if (type & PERF_SAMPLE_REGS_USER) {
1937                 if (sample->user_regs.abi) {
1938                         *array++ = sample->user_regs.abi;
1939                         sz = hweight_long(sample->user_regs.mask) * sizeof(u64);
1940                         memcpy(array, sample->user_regs.regs, sz);
1941                         array = (void *)array + sz;
1942                 } else {
1943                         *array++ = 0;
1944                 }
1945         }
1946
1947         if (type & PERF_SAMPLE_STACK_USER) {
1948                 sz = sample->user_stack.size;
1949                 *array++ = sz;
1950                 if (sz) {
1951                         memcpy(array, sample->user_stack.data, sz);
1952                         array = (void *)array + sz;
1953                         *array++ = sz;
1954                 }
1955         }
1956
1957         if (type & PERF_SAMPLE_WEIGHT) {
1958                 *array = sample->weight;
1959                 array++;
1960         }
1961
1962         if (type & PERF_SAMPLE_DATA_SRC) {
1963                 *array = sample->data_src;
1964                 array++;
1965         }
1966
1967         if (type & PERF_SAMPLE_TRANSACTION) {
1968                 *array = sample->transaction;
1969                 array++;
1970         }
1971
1972         if (type & PERF_SAMPLE_REGS_INTR) {
1973                 if (sample->intr_regs.abi) {
1974                         *array++ = sample->intr_regs.abi;
1975                         sz = hweight_long(sample->intr_regs.mask) * sizeof(u64);
1976                         memcpy(array, sample->intr_regs.regs, sz);
1977                         array = (void *)array + sz;
1978                 } else {
1979                         *array++ = 0;
1980                 }
1981         }
1982
1983         return 0;
1984 }
1985
1986 struct format_field *perf_evsel__field(struct perf_evsel *evsel, const char *name)
1987 {
1988         return pevent_find_field(evsel->tp_format, name);
1989 }
1990
1991 void *perf_evsel__rawptr(struct perf_evsel *evsel, struct perf_sample *sample,
1992                          const char *name)
1993 {
1994         struct format_field *field = perf_evsel__field(evsel, name);
1995         int offset;
1996
1997         if (!field)
1998                 return NULL;
1999
2000         offset = field->offset;
2001
2002         if (field->flags & FIELD_IS_DYNAMIC) {
2003                 offset = *(int *)(sample->raw_data + field->offset);
2004                 offset &= 0xffff;
2005         }
2006
2007         return sample->raw_data + offset;
2008 }
2009
2010 u64 perf_evsel__intval(struct perf_evsel *evsel, struct perf_sample *sample,
2011                        const char *name)
2012 {
2013         struct format_field *field = perf_evsel__field(evsel, name);
2014         void *ptr;
2015         u64 value;
2016
2017         if (!field)
2018                 return 0;
2019
2020         ptr = sample->raw_data + field->offset;
2021
2022         switch (field->size) {
2023         case 1:
2024                 return *(u8 *)ptr;
2025         case 2:
2026                 value = *(u16 *)ptr;
2027                 break;
2028         case 4:
2029                 value = *(u32 *)ptr;
2030                 break;
2031         case 8:
2032                 memcpy(&value, ptr, sizeof(u64));
2033                 break;
2034         default:
2035                 return 0;
2036         }
2037
2038         if (!evsel->needs_swap)
2039                 return value;
2040
2041         switch (field->size) {
2042         case 2:
2043                 return bswap_16(value);
2044         case 4:
2045                 return bswap_32(value);
2046         case 8:
2047                 return bswap_64(value);
2048         default:
2049                 return 0;
2050         }
2051
2052         return 0;
2053 }
2054
2055 static int comma_fprintf(FILE *fp, bool *first, const char *fmt, ...)
2056 {
2057         va_list args;
2058         int ret = 0;
2059
2060         if (!*first) {
2061                 ret += fprintf(fp, ",");
2062         } else {
2063                 ret += fprintf(fp, ":");
2064                 *first = false;
2065         }
2066
2067         va_start(args, fmt);
2068         ret += vfprintf(fp, fmt, args);
2069         va_end(args);
2070         return ret;
2071 }
2072
2073 static int __print_attr__fprintf(FILE *fp, const char *name, const char *val, void *priv)
2074 {
2075         return comma_fprintf(fp, (bool *)priv, " %s: %s", name, val);
2076 }
2077
2078 int perf_evsel__fprintf(struct perf_evsel *evsel,
2079                         struct perf_attr_details *details, FILE *fp)
2080 {
2081         bool first = true;
2082         int printed = 0;
2083
2084         if (details->event_group) {
2085                 struct perf_evsel *pos;
2086
2087                 if (!perf_evsel__is_group_leader(evsel))
2088                         return 0;
2089
2090                 if (evsel->nr_members > 1)
2091                         printed += fprintf(fp, "%s{", evsel->group_name ?: "");
2092
2093                 printed += fprintf(fp, "%s", perf_evsel__name(evsel));
2094                 for_each_group_member(pos, evsel)
2095                         printed += fprintf(fp, ",%s", perf_evsel__name(pos));
2096
2097                 if (evsel->nr_members > 1)
2098                         printed += fprintf(fp, "}");
2099                 goto out;
2100         }
2101
2102         printed += fprintf(fp, "%s", perf_evsel__name(evsel));
2103
2104         if (details->verbose) {
2105                 printed += perf_event_attr__fprintf(fp, &evsel->attr,
2106                                                     __print_attr__fprintf, &first);
2107         } else if (details->freq) {
2108                 printed += comma_fprintf(fp, &first, " sample_freq=%" PRIu64,
2109                                          (u64)evsel->attr.sample_freq);
2110         }
2111 out:
2112         fputc('\n', fp);
2113         return ++printed;
2114 }
2115
2116 bool perf_evsel__fallback(struct perf_evsel *evsel, int err,
2117                           char *msg, size_t msgsize)
2118 {
2119         if ((err == ENOENT || err == ENXIO || err == ENODEV) &&
2120             evsel->attr.type   == PERF_TYPE_HARDWARE &&
2121             evsel->attr.config == PERF_COUNT_HW_CPU_CYCLES) {
2122                 /*
2123                  * If it's cycles then fall back to hrtimer based
2124                  * cpu-clock-tick sw counter, which is always available even if
2125                  * no PMU support.
2126                  *
2127                  * PPC returns ENXIO until 2.6.37 (behavior changed with commit
2128                  * b0a873e).
2129                  */
2130                 scnprintf(msg, msgsize, "%s",
2131 "The cycles event is not supported, trying to fall back to cpu-clock-ticks");
2132
2133                 evsel->attr.type   = PERF_TYPE_SOFTWARE;
2134                 evsel->attr.config = PERF_COUNT_SW_CPU_CLOCK;
2135
2136                 zfree(&evsel->name);
2137                 return true;
2138         }
2139
2140         return false;
2141 }
2142
2143 int perf_evsel__open_strerror(struct perf_evsel *evsel, struct target *target,
2144                               int err, char *msg, size_t size)
2145 {
2146         char sbuf[STRERR_BUFSIZE];
2147
2148         switch (err) {
2149         case EPERM:
2150         case EACCES:
2151                 return scnprintf(msg, size,
2152                  "You may not have permission to collect %sstats.\n"
2153                  "Consider tweaking /proc/sys/kernel/perf_event_paranoid:\n"
2154                  " -1 - Not paranoid at all\n"
2155                  "  0 - Disallow raw tracepoint access for unpriv\n"
2156                  "  1 - Disallow cpu events for unpriv\n"
2157                  "  2 - Disallow kernel profiling for unpriv",
2158                                  target->system_wide ? "system-wide " : "");
2159         case ENOENT:
2160                 return scnprintf(msg, size, "The %s event is not supported.",
2161                                  perf_evsel__name(evsel));
2162         case EMFILE:
2163                 return scnprintf(msg, size, "%s",
2164                          "Too many events are opened.\n"
2165                          "Probably the maximum number of open file descriptors has been reached.\n"
2166                          "Hint: Try again after reducing the number of events.\n"
2167                          "Hint: Try increasing the limit with 'ulimit -n <limit>'");
2168         case ENODEV:
2169                 if (target->cpu_list)
2170                         return scnprintf(msg, size, "%s",
2171          "No such device - did you specify an out-of-range profile CPU?\n");
2172                 break;
2173         case EOPNOTSUPP:
2174                 if (evsel->attr.precise_ip)
2175                         return scnprintf(msg, size, "%s",
2176         "\'precise\' request may not be supported. Try removing 'p' modifier.");
2177 #if defined(__i386__) || defined(__x86_64__)
2178                 if (evsel->attr.type == PERF_TYPE_HARDWARE)
2179                         return scnprintf(msg, size, "%s",
2180         "No hardware sampling interrupt available.\n"
2181         "No APIC? If so then you can boot the kernel with the \"lapic\" boot parameter to force-enable it.");
2182 #endif
2183                 break;
2184         case EBUSY:
2185                 if (find_process("oprofiled"))
2186                         return scnprintf(msg, size,
2187         "The PMU counters are busy/taken by another profiler.\n"
2188         "We found oprofile daemon running, please stop it and try again.");
2189                 break;
2190         case EINVAL:
2191                 if (perf_missing_features.clockid)
2192                         return scnprintf(msg, size, "clockid feature not supported.");
2193                 if (perf_missing_features.clockid_wrong)
2194                         return scnprintf(msg, size, "wrong clockid (%d).", clockid);
2195                 break;
2196         default:
2197                 break;
2198         }
2199
2200         return scnprintf(msg, size,
2201         "The sys_perf_event_open() syscall returned with %d (%s) for event (%s).\n"
2202         "/bin/dmesg may provide additional information.\n"
2203         "No CONFIG_PERF_EVENTS=y kernel support configured?\n",
2204                          err, strerror_r(err, sbuf, sizeof(sbuf)),
2205                          perf_evsel__name(evsel));
2206 }