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