OSDN Git Service

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