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