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