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