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