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