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