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