projects/linux·blob master · refs

4758 lines · 120.9 KiB

1// SPDX-License-Identifier: GPL-2.0-only
2/*
3 * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <[email protected]>
4 *
5 * Parts came from builtin-{top,stat,record}.c, see those files for further
6 * copyright notes.
7 */
8/*
9 * Powerpc needs __SANE_USERSPACE_TYPES__ before <linux/types.h> to select
10 * 'int-ll64.h' and avoid compile warnings when printing __u64 with %llu.
11 */
12#define __SANE_USERSPACE_TYPES__
13
14#include "evsel.h"
15
16#include <errno.h>
17#include <inttypes.h>
18#include <stdlib.h>
19#include <string.h>
20
21#include <dirent.h>
22#include <linux/bitops.h>
23#include <linux/bitmap.h>
24#include <linux/compiler.h>
25#include <linux/ctype.h>
26#include <linux/err.h>
27#include <linux/hw_breakpoint.h>
28#include <linux/perf_event.h>
29#include <linux/zalloc.h>
30#include <sys/ioctl.h>
31#include <sys/resource.h>
32#include <sys/syscall.h>
33#include <sys/types.h>
34
35#include <api/fs/fs.h>
36#include <api/fs/tracing_path.h>
37#include <byteswap.h>
38#include <internal/lib.h>
39#include <internal/threadmap.h>
40#include <internal/xyarray.h>
41#include <perf/cpumap.h>
42#include <perf/evsel.h>
43
44#include "../perf-sys.h"
45#include "asm/bug.h"
46#include "bpf-filter.h"
47#include "bpf_counter.h"
48#include "callchain.h"
49#include "cgroup.h"
50#include "counts.h"
51#include "debug.h"
52#include "drm_pmu.h"
53#include "dwarf-regs.h"
54#include "env.h"
55#include "event.h"
56#include "evlist.h"
57#include "evsel_config.h"
58#include "evsel_fprintf.h"
59#include "hashmap.h"
60#include "hist.h"
61#include "hwmon_pmu.h"
62#include "intel-tpebs.h"
63#include "memswap.h"
64#include "off_cpu.h"
65#include "parse-branch-options.h"
66#include "perf_regs.h"
67#include "pmu.h"
68#include "pmus.h"
69#include "record.h"
70#include "rlimit.h"
71#include "session.h"
72#include "stat.h"
73#include "string2.h"
74#include "target.h"
75#include "thread_map.h"
76#include "time-utils.h"
77#include "tool_pmu.h"
78#include "tp_pmu.h"
79#include "trace-event.h"
80#include "util.h"
81
82#ifdef HAVE_LIBTRACEEVENT
83#include <event-parse.h>
84#endif
85
86struct perf_missing_features perf_missing_features;
87
88static clockid_t clockid;
89
90static int evsel__no_extra_init(struct evsel *evsel __maybe_unused)
91{
92 return 0;
93}
94
95static bool test_attr__enabled(void)
96{
97 static bool test_attr__enabled;
98 static bool test_attr__enabled_tested;
99
100 if (!test_attr__enabled_tested) {
101 char *dir = getenv("PERF_TEST_ATTR");
102
103 test_attr__enabled = (dir != NULL);
104 test_attr__enabled_tested = true;
105 }
106 return test_attr__enabled;
107}
108
109#define __WRITE_ASS(str, fmt, data) \
110do { \
111 if (fprintf(file, #str "=%"fmt "\n", data) < 0) { \
112 perror("test attr - failed to write event file"); \
113 fclose(file); \
114 return -1; \
115 } \
116} while (0)
117
118#define WRITE_ASS(field, fmt) __WRITE_ASS(field, fmt, attr->field)
119
120static int store_event(struct perf_event_attr *attr, pid_t pid, struct perf_cpu cpu,
121 int fd, int group_fd, unsigned long flags)
122{
123 FILE *file;
124 char path[PATH_MAX];
125 char *dir = getenv("PERF_TEST_ATTR");
126
127 snprintf(path, PATH_MAX, "%s/event-%d-%llu-%d", dir,
128 attr->type, attr->config, fd);
129
130 file = fopen(path, "w+");
131 if (!file) {
132 perror("test attr - failed to open event file");
133 return -1;
134 }
135
136 if (fprintf(file, "[event-%d-%llu-%d]\n",
137 attr->type, attr->config, fd) < 0) {
138 perror("test attr - failed to write event file");
139 fclose(file);
140 return -1;
141 }
142
143 /* syscall arguments */
144 __WRITE_ASS(fd, "d", fd);
145 __WRITE_ASS(group_fd, "d", group_fd);
146 __WRITE_ASS(cpu, "d", cpu.cpu);
147 __WRITE_ASS(pid, "d", pid);
148 __WRITE_ASS(flags, "lu", flags);
149
150 /* struct perf_event_attr */
151 WRITE_ASS(type, PRIu32);
152 WRITE_ASS(size, PRIu32);
153 WRITE_ASS(config, "llu");
154 WRITE_ASS(sample_period, "llu");
155 WRITE_ASS(sample_type, "llu");
156 WRITE_ASS(read_format, "llu");
157 WRITE_ASS(disabled, "d");
158 WRITE_ASS(inherit, "d");
159 WRITE_ASS(pinned, "d");
160 WRITE_ASS(exclusive, "d");
161 WRITE_ASS(exclude_user, "d");
162 WRITE_ASS(exclude_kernel, "d");
163 WRITE_ASS(exclude_hv, "d");
164 WRITE_ASS(exclude_idle, "d");
165 WRITE_ASS(mmap, "d");
166 WRITE_ASS(comm, "d");
167 WRITE_ASS(freq, "d");
168 WRITE_ASS(inherit_stat, "d");
169 WRITE_ASS(enable_on_exec, "d");
170 WRITE_ASS(task, "d");
171 WRITE_ASS(watermark, "d");
172 WRITE_ASS(precise_ip, "d");
173 WRITE_ASS(mmap_data, "d");
174 WRITE_ASS(sample_id_all, "d");
175 WRITE_ASS(exclude_host, "d");
176 WRITE_ASS(exclude_guest, "d");
177 WRITE_ASS(exclude_callchain_kernel, "d");
178 WRITE_ASS(exclude_callchain_user, "d");
179 WRITE_ASS(mmap2, "d");
180 WRITE_ASS(comm_exec, "d");
181 WRITE_ASS(context_switch, "d");
182 WRITE_ASS(write_backward, "d");
183 WRITE_ASS(namespaces, "d");
184 WRITE_ASS(use_clockid, "d");
185 WRITE_ASS(wakeup_events, PRIu32);
186 WRITE_ASS(bp_type, PRIu32);
187 WRITE_ASS(config1, "llu");
188 WRITE_ASS(config2, "llu");
189 WRITE_ASS(branch_sample_type, "llu");
190 WRITE_ASS(sample_regs_user, "llu");
191 WRITE_ASS(sample_stack_user, PRIu32);
192
193 fclose(file);
194 return 0;
195}
196
197#undef __WRITE_ASS
198#undef WRITE_ASS
199
200static void test_attr__open(struct perf_event_attr *attr, pid_t pid, struct perf_cpu cpu,
201 int fd, int group_fd, unsigned long flags)
202{
203 int errno_saved = errno;
204
205 if ((fd != -1) && store_event(attr, pid, cpu, fd, group_fd, flags)) {
206 pr_err("test attr FAILED");
207 exit(128);
208 }
209
210 errno = errno_saved;
211}
212
213static void evsel__no_extra_fini(struct evsel *evsel __maybe_unused)
214{
215}
216
217static struct {
218 size_t size;
219 int (*init)(struct evsel *evsel);
220 void (*fini)(struct evsel *evsel);
221} perf_evsel__object = {
222 .size = sizeof(struct evsel),
223 .init = evsel__no_extra_init,
224 .fini = evsel__no_extra_fini,
225};
226
227int evsel__object_config(size_t object_size, int (*init)(struct evsel *evsel),
228 void (*fini)(struct evsel *evsel))
229{
230
231 if (object_size == 0)
232 goto set_methods;
233
234 if (perf_evsel__object.size > object_size)
235 return -EINVAL;
236
237 perf_evsel__object.size = object_size;
238
239set_methods:
240 if (init != NULL)
241 perf_evsel__object.init = init;
242
243 if (fini != NULL)
244 perf_evsel__object.fini = fini;
245
246 return 0;
247}
248
249const char *evsel__pmu_name(const struct evsel *evsel)
250{
251 struct perf_pmu *pmu = evsel__find_pmu(evsel);
252
253 if (pmu)
254 return pmu->name;
255
256 return event_type(evsel->core.attr.type);
257}
258
259enum evsel_probe_type {
260 PROBE__UNKNOWN = 0,
261 PROBE__NOPE = 1,
262 PROBE__KPROBE = 2,
263 PROBE__UPROBE = 3,
264 /*
265 * Ftrace-based dynamic probes (kprobes/uprobes/fprobes created via
266 * tracefs) report PMU "tracepoint", not "kprobe"/"uprobe". Detect
267 * them by the __probe_ip field that the kernel adds to all dynamic
268 * probe formats.
269 */
270 PROBE__FTRACE = 4,
271};
272
273static void evsel__resolve_probe_type(struct evsel *evsel)
274{
275 const char *name = evsel__pmu_name(evsel);
276
277 if (!strcmp(name, "kprobe"))
278 evsel->probe_type = PROBE__KPROBE;
279 else if (!strcmp(name, "uprobe"))
280 evsel->probe_type = PROBE__UPROBE;
281 else if (!strcmp(name, "tracepoint") && evsel__field(evsel, "__probe_ip"))
282 evsel->probe_type = PROBE__FTRACE;
283 else
284 evsel->probe_type = PROBE__NOPE;
285}
286
287bool evsel__is_probe(struct evsel *evsel)
288{
289 if (evsel->probe_type == PROBE__UNKNOWN)
290 evsel__resolve_probe_type(evsel);
291
292 return evsel->probe_type > PROBE__NOPE;
293}
294
295bool evsel__is_kprobe(struct evsel *evsel)
296{
297 if (evsel->probe_type == PROBE__UNKNOWN)
298 evsel__resolve_probe_type(evsel);
299
300 return evsel->probe_type == PROBE__KPROBE;
301}
302
303bool evsel__is_uprobe(struct evsel *evsel)
304{
305 if (evsel->probe_type == PROBE__UNKNOWN)
306 evsel__resolve_probe_type(evsel);
307
308 return evsel->probe_type == PROBE__UPROBE;
309}
310
311#define FD(e, x, y) (*(int *)xyarray__entry(e->core.fd, x, y))
312
313int __evsel__sample_size(u64 sample_type)
314{
315 u64 mask = sample_type & PERF_SAMPLE_MASK;
316 int size = 0;
317 int i;
318
319 for (i = 0; i < 64; i++) {
320 if (mask & (1ULL << i))
321 size++;
322 }
323
324 size *= sizeof(u64);
325
326 return size;
327}
328
329/**
330 * __perf_evsel__calc_id_pos - calculate id_pos.
331 * @sample_type: sample type
332 *
333 * This function returns the position of the event id (PERF_SAMPLE_ID or
334 * PERF_SAMPLE_IDENTIFIER) in a sample event i.e. in the array of struct
335 * perf_record_sample.
336 */
337static int __perf_evsel__calc_id_pos(u64 sample_type)
338{
339 int idx = 0;
340
341 if (sample_type & PERF_SAMPLE_IDENTIFIER)
342 return 0;
343
344 if (!(sample_type & PERF_SAMPLE_ID))
345 return -1;
346
347 if (sample_type & PERF_SAMPLE_IP)
348 idx += 1;
349
350 if (sample_type & PERF_SAMPLE_TID)
351 idx += 1;
352
353 if (sample_type & PERF_SAMPLE_TIME)
354 idx += 1;
355
356 if (sample_type & PERF_SAMPLE_ADDR)
357 idx += 1;
358
359 return idx;
360}
361
362/**
363 * __perf_evsel__calc_is_pos - calculate is_pos.
364 * @sample_type: sample type
365 *
366 * This function returns the position (counting backwards) of the event id
367 * (PERF_SAMPLE_ID or PERF_SAMPLE_IDENTIFIER) in a non-sample event i.e. if
368 * sample_id_all is used there is an id sample appended to non-sample events.
369 */
370static int __perf_evsel__calc_is_pos(u64 sample_type)
371{
372 int idx = 1;
373
374 if (sample_type & PERF_SAMPLE_IDENTIFIER)
375 return 1;
376
377 if (!(sample_type & PERF_SAMPLE_ID))
378 return -1;
379
380 if (sample_type & PERF_SAMPLE_CPU)
381 idx += 1;
382
383 if (sample_type & PERF_SAMPLE_STREAM_ID)
384 idx += 1;
385
386 return idx;
387}
388
389void evsel__calc_id_pos(struct evsel *evsel)
390{
391 evsel->id_pos = __perf_evsel__calc_id_pos(evsel->core.attr.sample_type);
392 evsel->is_pos = __perf_evsel__calc_is_pos(evsel->core.attr.sample_type);
393}
394
395void __evsel__set_sample_bit(struct evsel *evsel,
396 enum perf_event_sample_format bit)
397{
398 if (!(evsel->core.attr.sample_type & bit)) {
399 evsel->core.attr.sample_type |= bit;
400 evsel->sample_size += sizeof(u64);
401 evsel__calc_id_pos(evsel);
402 }
403}
404
405void __evsel__reset_sample_bit(struct evsel *evsel,
406 enum perf_event_sample_format bit)
407{
408 if (evsel->core.attr.sample_type & bit) {
409 evsel->core.attr.sample_type &= ~bit;
410 evsel->sample_size -= sizeof(u64);
411 evsel__calc_id_pos(evsel);
412 }
413}
414
415void evsel__set_sample_id(struct evsel *evsel,
416 bool can_sample_identifier)
417{
418 if (can_sample_identifier) {
419 evsel__reset_sample_bit(evsel, ID);
420 evsel__set_sample_bit(evsel, IDENTIFIER);
421 } else {
422 evsel__set_sample_bit(evsel, ID);
423 }
424 evsel->core.attr.read_format |= PERF_FORMAT_ID;
425}
426
427bool evsel__is_non_perf_event_open_pmu(const struct evsel *evsel)
428{
429 return evsel->pmu && evsel->pmu->type > PERF_PMU_TYPE_PE_END;
430}
431
432/**
433 * evsel__is_function_event - Return whether given evsel is a function
434 * trace event
435 *
436 * @evsel - evsel selector to be tested
437 *
438 * Return %true if event is function trace event
439 */
440bool evsel__is_function_event(struct evsel *evsel)
441{
442#define FUNCTION_EVENT "ftrace:function"
443
444 return evsel->name &&
445 !strncmp(FUNCTION_EVENT, evsel->name, sizeof(FUNCTION_EVENT));
446
447#undef FUNCTION_EVENT
448}
449
450static void evsel__init(struct evsel *evsel,
451 struct perf_event_attr *attr, int idx)
452{
453 perf_evsel__init(&evsel->core, attr, idx);
454 refcount_set(&evsel->refcnt, 1);
455 evsel->tracking = !idx;
456 evsel->unit = strdup("");
457 evsel->scale = 1.0;
458 evsel->max_events = ULONG_MAX;
459 evsel->evlist = NULL;
460 INIT_LIST_HEAD(&evsel->config_terms);
461 INIT_LIST_HEAD(&evsel->bpf_counter_list);
462 INIT_LIST_HEAD(&evsel->bpf_filters);
463 perf_evsel__object.init(evsel);
464 evsel->sample_size = __evsel__sample_size(attr->sample_type);
465 evsel__calc_id_pos(evsel);
466 evsel->cmdline_group_boundary = false;
467 evsel->per_pkg_mask = NULL;
468 evsel->collect_stat = false;
469 evsel->group_pmu_name = NULL;
470 evsel->skippable = false;
471 evsel->supported = true;
472 evsel->alternate_hw_config = PERF_COUNT_HW_MAX;
473 evsel->script_output_type = -1; // FIXME: OUTPUT_TYPE_UNSET, see builtin-script.c
474 evsel->probe_type = PROBE__UNKNOWN;
475}
476
477struct evsel *evsel__new_idx(struct perf_event_attr *attr, int idx)
478{
479 struct evsel *evsel = zalloc(perf_evsel__object.size);
480
481 if (!evsel)
482 return NULL;
483 evsel__init(evsel, attr, idx);
484
485 if (evsel__is_bpf_output(evsel) && !attr->sample_type) {
486 evsel->core.attr.sample_type = (PERF_SAMPLE_RAW | PERF_SAMPLE_TIME |
487 PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD),
488 evsel->core.attr.sample_period = 1;
489 }
490
491 if (evsel__is_clock(evsel)) {
492 free((char *)evsel->unit);
493 evsel->unit = strdup("msec");
494 evsel->scale = 1e-6;
495 }
496
497 return evsel;
498}
499
500int copy_config_terms(struct list_head *dst, struct list_head *src)
501{
502 struct evsel_config_term *pos, *tmp;
503
504 list_for_each_entry(pos, src, list) {
505 tmp = malloc(sizeof(*tmp));
506 if (tmp == NULL)
507 return -ENOMEM;
508
509 *tmp = *pos;
510 if (tmp->free_str) {
511 tmp->val.str = strdup(pos->val.str);
512 if (tmp->val.str == NULL) {
513 free(tmp);
514 return -ENOMEM;
515 }
516 }
517 list_add_tail(&tmp->list, dst);
518 }
519 return 0;
520}
521
522static int evsel__copy_config_terms(struct evsel *dst, struct evsel *src)
523{
524 return copy_config_terms(&dst->config_terms, &src->config_terms);
525}
526
527/**
528 * evsel__clone - create a new evsel copied from @orig
529 * @orig: original evsel
530 *
531 * The assumption is that @orig is not configured nor opened yet.
532 * So we only care about the attributes that can be set while it's parsed.
533 */
534struct evsel *evsel__clone(struct evsel *orig)
535{
536 struct evsel *evsel;
537
538 BUG_ON(orig->core.fd);
539 BUG_ON(orig->counts);
540 BUG_ON(orig->priv);
541 BUG_ON(orig->per_pkg_mask);
542
543 evsel = evsel__new(&orig->core.attr);
544 if (evsel == NULL)
545 return NULL;
546
547 evsel->core.cpus = perf_cpu_map__get(orig->core.cpus);
548 evsel->core.pmu_cpus = perf_cpu_map__get(orig->core.pmu_cpus);
549 evsel->core.threads = perf_thread_map__get(orig->core.threads);
550 evsel->core.nr_members = orig->core.nr_members;
551 evsel->core.system_wide = orig->core.system_wide;
552 evsel->core.requires_cpu = orig->core.requires_cpu;
553 evsel->core.is_pmu_core = orig->core.is_pmu_core;
554
555 if (orig->name) {
556 evsel->name = strdup(orig->name);
557 if (evsel->name == NULL)
558 goto out_err;
559 }
560 if (orig->group_name) {
561 evsel->group_name = strdup(orig->group_name);
562 if (evsel->group_name == NULL)
563 goto out_err;
564 }
565 if (orig->group_pmu_name) {
566 evsel->group_pmu_name = strdup(orig->group_pmu_name);
567 if (evsel->group_pmu_name == NULL)
568 goto out_err;
569 }
570 if (orig->filter) {
571 evsel->filter = strdup(orig->filter);
572 if (evsel->filter == NULL)
573 goto out_err;
574 }
575 if (orig->metric_id) {
576 evsel->metric_id = strdup(orig->metric_id);
577 if (evsel->metric_id == NULL)
578 goto out_err;
579 }
580 evsel->cgrp = cgroup__get(orig->cgrp);
581#ifdef HAVE_LIBTRACEEVENT
582 if (orig->tp_sys) {
583 evsel->tp_sys = strdup(orig->tp_sys);
584 if (evsel->tp_sys == NULL)
585 goto out_err;
586 }
587 if (orig->tp_name) {
588 evsel->tp_name = strdup(orig->tp_name);
589 if (evsel->tp_name == NULL)
590 goto out_err;
591 }
592 evsel->tp_format = orig->tp_format;
593#endif
594 evsel->handler = orig->handler;
595 evsel->core.leader = orig->core.leader;
596 evsel->metric_leader = orig->metric_leader;
597
598 evsel->max_events = orig->max_events;
599 zfree(&evsel->unit);
600 if (orig->unit) {
601 evsel->unit = strdup(orig->unit);
602 if (evsel->unit == NULL)
603 goto out_err;
604 }
605 evsel->scale = orig->scale;
606 evsel->snapshot = orig->snapshot;
607 evsel->per_pkg = orig->per_pkg;
608 evsel->percore = orig->percore;
609 evsel->precise_max = orig->precise_max;
610 evsel->is_libpfm_event = orig->is_libpfm_event;
611
612 evsel->exclude_GH = orig->exclude_GH;
613 evsel->sample_read = orig->sample_read;
614 evsel->collect_stat = orig->collect_stat;
615 evsel->weak_group = orig->weak_group;
616 evsel->bpf_counter = orig->bpf_counter;
617 evsel->use_config_name = orig->use_config_name;
618 evsel->skippable = orig->skippable;
619 evsel->dont_regroup = orig->dont_regroup;
620 evsel->default_metricgroup = orig->default_metricgroup;
621 evsel->default_show_events = orig->default_show_events;
622
623 evsel->pmu = orig->pmu;
624 evsel->first_wildcard_match = orig->first_wildcard_match;
625
626 if (evsel__copy_config_terms(evsel, orig) < 0)
627 goto out_err;
628
629 evsel->alternate_hw_config = orig->alternate_hw_config;
630
631 evsel->retire_lat = orig->retire_lat;
632 if (evsel->retire_lat)
633 evsel->retirement_latency = orig->retirement_latency;
634
635 return evsel;
636
637out_err:
638 evsel__put(evsel);
639 return NULL;
640}
641
642/*
643 * Returns pointer with encoded error via <linux/err.h> interface.
644 */
645struct evsel *evsel__newtp_idx(const char *sys, const char *name, int idx, bool format)
646{
647 struct perf_event_attr attr = {
648 .type = PERF_TYPE_TRACEPOINT,
649 .sample_type = (PERF_SAMPLE_RAW | PERF_SAMPLE_TIME |
650 PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD),
651 };
652 struct evsel *evsel = zalloc(perf_evsel__object.size);
653 int err = -ENOMEM, id = -1;
654
655 if (evsel == NULL)
656 goto out_err;
657
658
659 if (asprintf(&evsel->name, "%s:%s", sys, name) < 0)
660 goto out_free;
661
662#ifdef HAVE_LIBTRACEEVENT
663 evsel->tp_sys = strdup(sys);
664 if (!evsel->tp_sys)
665 goto out_free;
666
667 evsel->tp_name = strdup(name);
668 if (!evsel->tp_name)
669 goto out_free;
670#endif
671
672 event_attr_init(&attr);
673
674 if (format) {
675 id = tp_pmu__id(sys, name);
676 if (id < 0) {
677 err = id;
678 goto out_free;
679 }
680 }
681 attr.config = (__u64)id;
682 attr.sample_period = 1;
683 evsel__init(evsel, &attr, idx);
684 return evsel;
685
686out_free:
687 zfree(&evsel->name);
688#ifdef HAVE_LIBTRACEEVENT
689 zfree(&evsel->tp_sys);
690 zfree(&evsel->tp_name);
691#endif
692 free(evsel);
693out_err:
694 return ERR_PTR(err);
695}
696
697struct evsel *evsel__get(struct evsel *evsel)
698{
699 refcount_inc(&evsel->refcnt);
700 return evsel;
701}
702
703#ifdef HAVE_LIBTRACEEVENT
704struct tep_event *evsel__tp_format(struct evsel *evsel)
705{
706 struct tep_event *tp_format = evsel->tp_format;
707
708 if (tp_format)
709 return tp_format;
710
711 if (evsel->core.attr.type != PERF_TYPE_TRACEPOINT)
712 return NULL;
713
714 if (!evsel->tp_sys)
715 tp_format = trace_event__tp_format_id(evsel->core.attr.config);
716 else
717 tp_format = trace_event__tp_format(evsel->tp_sys, evsel->tp_name);
718
719 if (IS_ERR(tp_format)) {
720 int err = -PTR_ERR(tp_format);
721
722 errno = err;
723 pr_err("Error getting tracepoint format '%s': %m\n",
724 evsel__name(evsel));
725 return NULL;
726 }
727 evsel->tp_format = tp_format;
728 return evsel->tp_format;
729}
730#endif
731
732const char *const evsel__hw_names[PERF_COUNT_HW_MAX] = {
733 "cycles",
734 "instructions",
735 "cache-references",
736 "cache-misses",
737 "branches",
738 "branch-misses",
739 "bus-cycles",
740 "stalled-cycles-frontend",
741 "stalled-cycles-backend",
742 "ref-cycles",
743};
744
745char *evsel__bpf_counter_events;
746
747bool evsel__match_bpf_counter_events(const char *name)
748{
749 int name_len;
750 bool match;
751 char *ptr;
752
753 if (!evsel__bpf_counter_events)
754 return false;
755
756 ptr = strstr(evsel__bpf_counter_events, name);
757 name_len = strlen(name);
758
759 /* check name matches a full token in evsel__bpf_counter_events */
760 match = (ptr != NULL) &&
761 ((ptr == evsel__bpf_counter_events) || (*(ptr - 1) == ',')) &&
762 ((*(ptr + name_len) == ',') || (*(ptr + name_len) == '\0'));
763
764 return match;
765}
766
767static const char *__evsel__hw_name(u64 config)
768{
769 if (config < PERF_COUNT_HW_MAX && evsel__hw_names[config])
770 return evsel__hw_names[config];
771
772 return "unknown-hardware";
773}
774
775static int evsel__add_modifiers(struct evsel *evsel, char *bf, size_t size)
776{
777 int colon = 0, r = 0;
778 struct perf_event_attr *attr = &evsel->core.attr;
779
780#define MOD_PRINT(context, mod) do { \
781 if (!attr->exclude_##context) { \
782 if (!colon) colon = ++r; \
783 r += scnprintf(bf + r, size - r, "%c", mod); \
784 } } while(0)
785
786 if (attr->exclude_kernel || attr->exclude_user || attr->exclude_hv) {
787 MOD_PRINT(kernel, 'k');
788 MOD_PRINT(user, 'u');
789 MOD_PRINT(hv, 'h');
790 }
791
792 if (attr->precise_ip) {
793 if (!colon)
794 colon = ++r;
795 r += scnprintf(bf + r, size - r, "%.*s", attr->precise_ip, "ppp");
796 }
797
798 if (attr->exclude_host || attr->exclude_guest) {
799 MOD_PRINT(host, 'H');
800 MOD_PRINT(guest, 'G');
801 }
802#undef MOD_PRINT
803 if (colon)
804 bf[colon - 1] = ':';
805 return r;
806}
807
808int __weak arch_evsel__hw_name(struct evsel *evsel, char *bf, size_t size)
809{
810 return scnprintf(bf, size, "%s", __evsel__hw_name(evsel->core.attr.config));
811}
812
813static int evsel__hw_name(struct evsel *evsel, char *bf, size_t size)
814{
815 int r = arch_evsel__hw_name(evsel, bf, size);
816 return r + evsel__add_modifiers(evsel, bf + r, size - r);
817}
818
819const char *const evsel__sw_names[PERF_COUNT_SW_MAX] = {
820 "cpu-clock",
821 "task-clock",
822 "page-faults",
823 "context-switches",
824 "cpu-migrations",
825 "minor-faults",
826 "major-faults",
827 "alignment-faults",
828 "emulation-faults",
829 "dummy",
830};
831
832static const char *__evsel__sw_name(u64 config)
833{
834 if (config < PERF_COUNT_SW_MAX && evsel__sw_names[config])
835 return evsel__sw_names[config];
836 return "unknown-software";
837}
838
839static int evsel__sw_name(struct evsel *evsel, char *bf, size_t size)
840{
841 int r = scnprintf(bf, size, "%s", __evsel__sw_name(evsel->core.attr.config));
842 return r + evsel__add_modifiers(evsel, bf + r, size - r);
843}
844
845static int __evsel__bp_name(char *bf, size_t size, u64 addr, u64 type)
846{
847 int r;
848
849 r = scnprintf(bf, size, "mem:0x%" PRIx64 ":", addr);
850
851 if (type & HW_BREAKPOINT_R)
852 r += scnprintf(bf + r, size - r, "r");
853
854 if (type & HW_BREAKPOINT_W)
855 r += scnprintf(bf + r, size - r, "w");
856
857 if (type & HW_BREAKPOINT_X)
858 r += scnprintf(bf + r, size - r, "x");
859
860 return r;
861}
862
863static int evsel__bp_name(struct evsel *evsel, char *bf, size_t size)
864{
865 struct perf_event_attr *attr = &evsel->core.attr;
866 int r = __evsel__bp_name(bf, size, attr->bp_addr, attr->bp_type);
867 return r + evsel__add_modifiers(evsel, bf + r, size - r);
868}
869
870const char *const evsel__hw_cache[PERF_COUNT_HW_CACHE_MAX][EVSEL__MAX_ALIASES] = {
871 { "L1-dcache", "l1-d", "l1d", "L1-data", },
872 { "L1-icache", "l1-i", "l1i", "L1-instruction", },
873 { "LLC", "L2", },
874 { "dTLB", "d-tlb", "Data-TLB", },
875 { "iTLB", "i-tlb", "Instruction-TLB", },
876 { "branch", "branches", "bpu", "btb", "bpc", },
877 { "node", },
878};
879
880const char *const evsel__hw_cache_op[PERF_COUNT_HW_CACHE_OP_MAX][EVSEL__MAX_ALIASES] = {
881 { "load", "loads", "read", },
882 { "store", "stores", "write", },
883 { "prefetch", "prefetches", "speculative-read", "speculative-load", },
884};
885
886const char *const evsel__hw_cache_result[PERF_COUNT_HW_CACHE_RESULT_MAX][EVSEL__MAX_ALIASES] = {
887 { "refs", "Reference", "ops", "access", },
888 { "misses", "miss", },
889};
890
891#define C(x) PERF_COUNT_HW_CACHE_##x
892#define CACHE_READ (1 << C(OP_READ))
893#define CACHE_WRITE (1 << C(OP_WRITE))
894#define CACHE_PREFETCH (1 << C(OP_PREFETCH))
895#define COP(x) (1 << x)
896
897/*
898 * cache operation stat
899 * L1I : Read and prefetch only
900 * ITLB and BPU : Read-only
901 */
902static const unsigned long evsel__hw_cache_stat[C(MAX)] = {
903 [C(L1D)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
904 [C(L1I)] = (CACHE_READ | CACHE_PREFETCH),
905 [C(LL)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
906 [C(DTLB)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
907 [C(ITLB)] = (CACHE_READ),
908 [C(BPU)] = (CACHE_READ),
909 [C(NODE)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
910};
911
912bool evsel__is_cache_op_valid(u8 type, u8 op)
913{
914 if (evsel__hw_cache_stat[type] & COP(op))
915 return true; /* valid */
916 else
917 return false; /* invalid */
918}
919
920int __evsel__hw_cache_type_op_res_name(u8 type, u8 op, u8 result, char *bf, size_t size)
921{
922 if (result) {
923 return scnprintf(bf, size, "%s-%s-%s", evsel__hw_cache[type][0],
924 evsel__hw_cache_op[op][0],
925 evsel__hw_cache_result[result][0]);
926 }
927
928 return scnprintf(bf, size, "%s-%s", evsel__hw_cache[type][0],
929 evsel__hw_cache_op[op][1]);
930}
931
932static int __evsel__hw_cache_name(u64 config, char *bf, size_t size)
933{
934 u8 op, result, type = (config >> 0) & 0xff;
935 const char *err = "unknown-ext-hardware-cache-type";
936
937 if (type >= PERF_COUNT_HW_CACHE_MAX)
938 goto out_err;
939
940 op = (config >> 8) & 0xff;
941 err = "unknown-ext-hardware-cache-op";
942 if (op >= PERF_COUNT_HW_CACHE_OP_MAX)
943 goto out_err;
944
945 result = (config >> 16) & 0xff;
946 err = "unknown-ext-hardware-cache-result";
947 if (result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
948 goto out_err;
949
950 err = "invalid-cache";
951 if (!evsel__is_cache_op_valid(type, op))
952 goto out_err;
953
954 return __evsel__hw_cache_type_op_res_name(type, op, result, bf, size);
955out_err:
956 return scnprintf(bf, size, "%s", err);
957}
958
959static int evsel__hw_cache_name(struct evsel *evsel, char *bf, size_t size)
960{
961 int ret = __evsel__hw_cache_name(evsel->core.attr.config, bf, size);
962 return ret + evsel__add_modifiers(evsel, bf + ret, size - ret);
963}
964
965static int evsel__raw_name(struct evsel *evsel, char *bf, size_t size)
966{
967 int ret = scnprintf(bf, size, "raw 0x%" PRIx64, evsel->core.attr.config);
968 return ret + evsel__add_modifiers(evsel, bf + ret, size - ret);
969}
970
971const char *evsel__name(struct evsel *evsel)
972{
973 char bf[128];
974
975 if (!evsel)
976 goto out_unknown;
977
978 if (evsel->name)
979 return evsel->name;
980
981 switch (evsel->core.attr.type) {
982 case PERF_TYPE_RAW:
983 evsel__raw_name(evsel, bf, sizeof(bf));
984 break;
985
986 case PERF_TYPE_HARDWARE:
987 evsel__hw_name(evsel, bf, sizeof(bf));
988 break;
989
990 case PERF_TYPE_HW_CACHE:
991 evsel__hw_cache_name(evsel, bf, sizeof(bf));
992 break;
993
994 case PERF_TYPE_SOFTWARE:
995 evsel__sw_name(evsel, bf, sizeof(bf));
996 break;
997
998 case PERF_TYPE_TRACEPOINT:
999 scnprintf(bf, sizeof(bf), "unknown tracepoint id=%#"PRIx64,
1000 evsel->core.attr.config);
1001 break;
1002
1003 case PERF_TYPE_BREAKPOINT:
1004 evsel__bp_name(evsel, bf, sizeof(bf));
1005 break;
1006
1007 case PERF_PMU_TYPE_TOOL:
1008 scnprintf(bf, sizeof(bf), "%s", evsel__tool_pmu_event_name(evsel));
1009 break;
1010
1011 default:
1012 scnprintf(bf, sizeof(bf), "unknown event PMU=%d config=%#"PRIx64,
1013 evsel->core.attr.type, evsel->core.attr.config);
1014 break;
1015 }
1016
1017 evsel->name = strdup(bf);
1018
1019 if (evsel->name)
1020 return evsel->name;
1021out_unknown:
1022 return "unknown";
1023}
1024
1025bool evsel__name_is(struct evsel *evsel, const char *name)
1026{
1027 return !strcmp(evsel__name(evsel), name);
1028}
1029
1030const char *evsel__metric_id(const struct evsel *evsel)
1031{
1032 if (evsel->metric_id)
1033 return evsel->metric_id;
1034
1035 if (evsel__is_tool(evsel))
1036 return evsel__tool_pmu_event_name(evsel);
1037
1038 return "unknown";
1039}
1040
1041const char *evsel__group_name(struct evsel *evsel)
1042{
1043 return evsel->group_name ?: "anon group";
1044}
1045
1046/*
1047 * Returns the group details for the specified leader,
1048 * with following rules.
1049 *
1050 * For record -e '{cycles,instructions}'
1051 * 'anon group { cycles:u, instructions:u }'
1052 *
1053 * For record -e 'cycles,instructions' and report --group
1054 * 'cycles:u, instructions:u'
1055 */
1056int evsel__group_desc(struct evsel *evsel, char *buf, size_t size)
1057{
1058 int ret = 0;
1059 bool first = true;
1060 struct evsel *pos;
1061 const char *group_name = evsel__group_name(evsel);
1062
1063 if (!evsel->forced_leader)
1064 ret = scnprintf(buf, size, "%s { ", group_name);
1065
1066 for_each_group_evsel(pos, evsel) {
1067 if (symbol_conf.skip_empty &&
1068 evsel__hists(pos)->stats.nr_samples == 0)
1069 continue;
1070
1071 ret += scnprintf(buf + ret, size - ret, "%s%s",
1072 first ? "" : ", ", evsel__name(pos));
1073 first = false;
1074 }
1075
1076 if (!evsel->forced_leader)
1077 ret += scnprintf(buf + ret, size - ret, " }");
1078
1079 return ret;
1080}
1081
1082uint16_t evsel__e_machine(struct evsel *evsel, uint32_t *e_flags)
1083{
1084 struct perf_session *session = evsel__session(evsel);
1085
1086 return perf_session__e_machine(session, e_flags);
1087}
1088
1089static void __evsel__config_callchain(struct evsel *evsel, const struct record_opts *opts,
1090 const struct callchain_param *param)
1091{
1092 bool function = evsel__is_function_event(evsel);
1093 struct perf_event_attr *attr = &evsel->core.attr;
1094
1095 if (EM_HOST == EM_S390 && param->record_mode == CALLCHAIN_FP) {
1096 pr_warning_once(
1097 "Framepointer unwinding lacks kernel support. Use '--call-graph dwarf'\n");
1098 }
1099
1100 evsel__set_sample_bit(evsel, CALLCHAIN);
1101
1102 attr->sample_max_stack = param->max_stack;
1103
1104 if (opts->kernel_callchains)
1105 attr->exclude_callchain_user = 1;
1106 if (opts->user_callchains)
1107 attr->exclude_callchain_kernel = 1;
1108 if (param->record_mode == CALLCHAIN_LBR) {
1109 if (!opts->branch_stack) {
1110 if (attr->exclude_user) {
1111 pr_warning("LBR callstack option is only available "
1112 "to get user callchain information. "
1113 "Falling back to framepointers.\n");
1114 } else {
1115 evsel__set_sample_bit(evsel, BRANCH_STACK);
1116 attr->branch_sample_type = PERF_SAMPLE_BRANCH_USER |
1117 PERF_SAMPLE_BRANCH_CALL_STACK |
1118 PERF_SAMPLE_BRANCH_NO_CYCLES |
1119 PERF_SAMPLE_BRANCH_NO_FLAGS |
1120 PERF_SAMPLE_BRANCH_HW_INDEX;
1121 }
1122 } else
1123 pr_warning("Cannot use LBR callstack with branch stack. "
1124 "Falling back to framepointers.\n");
1125 }
1126
1127 if (param->record_mode == CALLCHAIN_DWARF) {
1128 if (!function) {
1129 uint16_t e_machine = evsel__e_machine(evsel, /*e_flags=*/NULL);
1130
1131 evsel__set_sample_bit(evsel, REGS_USER);
1132 evsel__set_sample_bit(evsel, STACK_USER);
1133 if (opts->sample_user_regs &&
1134 DWARF_MINIMAL_REGS(e_machine) != perf_user_reg_mask(EM_HOST)) {
1135 attr->sample_regs_user |= DWARF_MINIMAL_REGS(e_machine);
1136 pr_warning("WARNING: The use of --call-graph=dwarf may require all the user registers, "
1137 "specifying a subset with --user-regs may render DWARF unwinding unreliable, "
1138 "so the minimal registers set (IP, SP) is explicitly forced.\n");
1139 } else {
1140 attr->sample_regs_user |= perf_user_reg_mask(EM_HOST);
1141 }
1142 attr->sample_stack_user = param->dump_size;
1143 attr->exclude_callchain_user = 1;
1144 } else {
1145 pr_info("Cannot use DWARF unwind for function trace event,"
1146 " falling back to framepointers.\n");
1147 }
1148 }
1149
1150 if (function) {
1151 pr_info("Disabling user space callchains for function trace event.\n");
1152 attr->exclude_callchain_user = 1;
1153 }
1154
1155 if (param->defer && !attr->exclude_callchain_user)
1156 attr->defer_callchain = 1;
1157}
1158
1159void evsel__config_callchain(struct evsel *evsel, const struct record_opts *opts,
1160 const struct callchain_param *param)
1161{
1162 if (param->enabled)
1163 return __evsel__config_callchain(evsel, opts, param);
1164}
1165
1166static void evsel__reset_callgraph(struct evsel *evsel, const struct callchain_param *param)
1167{
1168 struct perf_event_attr *attr = &evsel->core.attr;
1169
1170 evsel__reset_sample_bit(evsel, CALLCHAIN);
1171 if (param->record_mode == CALLCHAIN_LBR) {
1172 evsel__reset_sample_bit(evsel, BRANCH_STACK);
1173 attr->branch_sample_type &= ~(PERF_SAMPLE_BRANCH_USER |
1174 PERF_SAMPLE_BRANCH_CALL_STACK |
1175 PERF_SAMPLE_BRANCH_HW_INDEX);
1176 }
1177 if (param->record_mode == CALLCHAIN_DWARF) {
1178 evsel__reset_sample_bit(evsel, REGS_USER);
1179 evsel__reset_sample_bit(evsel, STACK_USER);
1180 }
1181}
1182
1183static void evsel__apply_ratio_to_prev(struct evsel *evsel,
1184 struct perf_event_attr *attr,
1185 const struct record_opts *opts,
1186 const char *buf)
1187{
1188 struct perf_event_attr *prev_attr = NULL;
1189 struct evsel *evsel_prev = NULL;
1190 u64 type = evsel->core.attr.sample_type;
1191 u64 prev_type = 0;
1192 double rtp;
1193
1194 rtp = strtod(buf, NULL);
1195 if (rtp <= 0) {
1196 pr_err("Invalid ratio-to-prev value %lf\n", rtp);
1197 return;
1198 }
1199 if (evsel == evsel__leader(evsel)) {
1200 pr_err("Invalid use of ratio-to-prev term without preceding element in group\n");
1201 return;
1202 }
1203 if (!evsel->pmu->is_core) {
1204 pr_err("Event using ratio-to-prev term must have a core PMU\n");
1205 return;
1206 }
1207
1208 evsel_prev = evsel__prev(evsel);
1209 if (!evsel_prev) {
1210 pr_err("Previous event does not exist.\n");
1211 return;
1212 }
1213
1214 if (evsel_prev->pmu->type != evsel->pmu->type) {
1215 pr_err("Compared events (\"%s\", \"%s\") must have same PMU\n",
1216 evsel->name, evsel_prev->name);
1217 return;
1218 }
1219
1220 prev_attr = &evsel_prev->core.attr;
1221 prev_type = evsel_prev->core.attr.sample_type;
1222
1223 if (!(prev_type & PERF_SAMPLE_PERIOD)) {
1224 attr->sample_period = prev_attr->sample_period * rtp;
1225 attr->freq = 0;
1226 evsel__reset_sample_bit(evsel, PERIOD);
1227 } else if (!(type & PERF_SAMPLE_PERIOD)) {
1228 prev_attr->sample_period = attr->sample_period / rtp;
1229 prev_attr->freq = 0;
1230 evsel__reset_sample_bit(evsel_prev, PERIOD);
1231 } else {
1232 if (opts->user_interval != ULLONG_MAX) {
1233 prev_attr->sample_period = opts->user_interval;
1234 attr->sample_period = prev_attr->sample_period * rtp;
1235 prev_attr->freq = 0;
1236 attr->freq = 0;
1237 evsel__reset_sample_bit(evsel_prev, PERIOD);
1238 evsel__reset_sample_bit(evsel, PERIOD);
1239 } else {
1240 pr_err("Event period term or count (-c) must be set when using ratio-to-prev term.\n");
1241 return;
1242 }
1243 }
1244
1245 arch_evsel__apply_ratio_to_prev(evsel, attr);
1246}
1247
1248static void evsel__apply_config_terms(struct evsel *evsel,
1249 const struct record_opts *opts, bool track)
1250{
1251 struct evsel_config_term *term;
1252 struct list_head *config_terms = &evsel->config_terms;
1253 struct perf_event_attr *attr = &evsel->core.attr;
1254 /* callgraph default */
1255 struct callchain_param param = {
1256 .record_mode = callchain_param.record_mode,
1257 };
1258 u32 dump_size = 0;
1259 int max_stack = 0;
1260 const char *callgraph_buf = NULL;
1261 const char *rtp_buf = NULL;
1262
1263 list_for_each_entry(term, config_terms, list) {
1264 switch (term->type) {
1265 case EVSEL__CONFIG_TERM_PERIOD:
1266 if (!(term->weak && opts->user_interval != ULLONG_MAX)) {
1267 attr->sample_period = term->val.period;
1268 attr->freq = 0;
1269 evsel__reset_sample_bit(evsel, PERIOD);
1270 }
1271 break;
1272 case EVSEL__CONFIG_TERM_FREQ:
1273 if (!(term->weak && opts->user_freq != UINT_MAX)) {
1274 attr->sample_freq = term->val.freq;
1275 attr->freq = 1;
1276 evsel__set_sample_bit(evsel, PERIOD);
1277 }
1278 break;
1279 case EVSEL__CONFIG_TERM_TIME:
1280 if (term->val.time)
1281 evsel__set_sample_bit(evsel, TIME);
1282 else
1283 evsel__reset_sample_bit(evsel, TIME);
1284 break;
1285 case EVSEL__CONFIG_TERM_CALLGRAPH:
1286 callgraph_buf = term->val.str;
1287 break;
1288 case EVSEL__CONFIG_TERM_BRANCH:
1289 if (term->val.str && strcmp(term->val.str, "no")) {
1290 evsel__set_sample_bit(evsel, BRANCH_STACK);
1291 parse_branch_str(term->val.str,
1292 &attr->branch_sample_type);
1293 } else
1294 evsel__reset_sample_bit(evsel, BRANCH_STACK);
1295 break;
1296 case EVSEL__CONFIG_TERM_STACK_USER:
1297 dump_size = term->val.stack_user;
1298 break;
1299 case EVSEL__CONFIG_TERM_MAX_STACK:
1300 max_stack = term->val.max_stack;
1301 break;
1302 case EVSEL__CONFIG_TERM_MAX_EVENTS:
1303 evsel->max_events = term->val.max_events;
1304 break;
1305 case EVSEL__CONFIG_TERM_INHERIT:
1306 /*
1307 * attr->inherit should has already been set by
1308 * evsel__config. If user explicitly set
1309 * inherit using config terms, override global
1310 * opt->no_inherit setting.
1311 */
1312 attr->inherit = term->val.inherit ? 1 : 0;
1313 break;
1314 case EVSEL__CONFIG_TERM_OVERWRITE:
1315 attr->write_backward = term->val.overwrite ? 1 : 0;
1316 break;
1317 case EVSEL__CONFIG_TERM_DRV_CFG:
1318 break;
1319 case EVSEL__CONFIG_TERM_PERCORE:
1320 break;
1321 case EVSEL__CONFIG_TERM_AUX_OUTPUT:
1322 attr->aux_output = term->val.aux_output ? 1 : 0;
1323 break;
1324 case EVSEL__CONFIG_TERM_AUX_ACTION:
1325 /* Already applied by auxtrace */
1326 break;
1327 case EVSEL__CONFIG_TERM_AUX_SAMPLE_SIZE:
1328 /* Already applied by auxtrace */
1329 break;
1330 case EVSEL__CONFIG_TERM_USR_CHG_CONFIG:
1331 case EVSEL__CONFIG_TERM_USR_CHG_CONFIG1:
1332 case EVSEL__CONFIG_TERM_USR_CHG_CONFIG2:
1333 case EVSEL__CONFIG_TERM_USR_CHG_CONFIG3:
1334 case EVSEL__CONFIG_TERM_USR_CHG_CONFIG4:
1335 break;
1336 case EVSEL__CONFIG_TERM_RATIO_TO_PREV:
1337 rtp_buf = term->val.str;
1338 break;
1339 default:
1340 break;
1341 }
1342 }
1343
1344 /* User explicitly set per-event callgraph, clear the old setting and reset. */
1345 if ((callgraph_buf != NULL) || (dump_size > 0) || max_stack) {
1346 bool sample_address = false;
1347
1348 if (max_stack) {
1349 param.max_stack = max_stack;
1350 if (callgraph_buf == NULL)
1351 callgraph_buf = "fp";
1352 }
1353
1354 /* parse callgraph parameters */
1355 if (callgraph_buf != NULL) {
1356 if (!strcmp(callgraph_buf, "no")) {
1357 param.enabled = false;
1358 param.record_mode = CALLCHAIN_NONE;
1359 } else {
1360 param.enabled = true;
1361 if (parse_callchain_record(callgraph_buf, &param)) {
1362 pr_err("per-event callgraph setting for %s failed. "
1363 "Apply callgraph global setting for it\n",
1364 evsel->name);
1365 return;
1366 }
1367 if (param.record_mode == CALLCHAIN_DWARF)
1368 sample_address = true;
1369 }
1370 }
1371 if (dump_size > 0) {
1372 dump_size = round_up(dump_size, sizeof(u64));
1373 param.dump_size = dump_size;
1374 }
1375
1376 /* If global callgraph set, clear it */
1377 if (callchain_param.enabled)
1378 evsel__reset_callgraph(evsel, &callchain_param);
1379
1380 /* set perf-event callgraph */
1381 if (param.enabled) {
1382 if (sample_address) {
1383 evsel__set_sample_bit(evsel, ADDR);
1384 evsel__set_sample_bit(evsel, DATA_SRC);
1385 evsel->core.attr.mmap_data = track;
1386 }
1387 evsel__config_callchain(evsel, opts, &param);
1388 }
1389 }
1390 if (rtp_buf)
1391 evsel__apply_ratio_to_prev(evsel, attr, opts, rtp_buf);
1392}
1393
1394struct evsel_config_term *__evsel__get_config_term(struct evsel *evsel, enum evsel_term_type type)
1395{
1396 struct evsel_config_term *term, *found_term = NULL;
1397
1398 list_for_each_entry(term, &evsel->config_terms, list) {
1399 if (term->type == type)
1400 found_term = term;
1401 }
1402
1403 return found_term;
1404}
1405
1406/*
1407 * Set @config_name to @val as long as the user hasn't already set or cleared it
1408 * by passing a config term on the command line.
1409 *
1410 * @val is the value to put into the bits specified by @config_name rather than
1411 * the bit pattern. It is shifted into position by this function, so to set
1412 * something to true, pass 1 for val rather than a pre shifted value.
1413 */
1414void evsel__set_config_if_unset(struct evsel *evsel, const char *config_name,
1415 u64 val)
1416{
1417 u64 user_bits = 0;
1418 struct evsel_config_term *term = evsel__get_config_term(evsel,
1419 USR_CHG_CONFIG);
1420 struct perf_pmu_format *format = pmu_find_format(&evsel->pmu->format,
1421 config_name);
1422 int fbit;
1423 __u64 *vp;
1424
1425 if (!format)
1426 return;
1427
1428 switch (format->value) {
1429 case PERF_PMU_FORMAT_VALUE_CONFIG:
1430 term = evsel__get_config_term(evsel, USR_CHG_CONFIG);
1431 vp = &evsel->core.attr.config;
1432 break;
1433 case PERF_PMU_FORMAT_VALUE_CONFIG1:
1434 term = evsel__get_config_term(evsel, USR_CHG_CONFIG1);
1435 vp = &evsel->core.attr.config1;
1436 break;
1437 case PERF_PMU_FORMAT_VALUE_CONFIG2:
1438 term = evsel__get_config_term(evsel, USR_CHG_CONFIG2);
1439 vp = &evsel->core.attr.config2;
1440 break;
1441 case PERF_PMU_FORMAT_VALUE_CONFIG3:
1442 term = evsel__get_config_term(evsel, USR_CHG_CONFIG3);
1443 vp = &evsel->core.attr.config3;
1444 break;
1445 case PERF_PMU_FORMAT_VALUE_CONFIG4:
1446 term = evsel__get_config_term(evsel, USR_CHG_CONFIG4);
1447 vp = &evsel->core.attr.config4;
1448 break;
1449 default:
1450 pr_err("Unknown format value: %d\n", format->value);
1451 return;
1452 }
1453
1454 if (!format)
1455 return;
1456
1457 if (term)
1458 user_bits = term->val.cfg_chg;
1459
1460 /* Do nothing if the user changed the value */
1461 for_each_set_bit(fbit, format->bits, PERF_PMU_FORMAT_BITS)
1462 if ((1ULL << fbit) & user_bits)
1463 return;
1464
1465 /* Otherwise replace it */
1466 perf_pmu__format_pack(format->bits, val, vp, /*zero=*/true);
1467}
1468
1469bool evsel__config_exists(const struct evsel *evsel, const char *config_name)
1470{
1471 struct perf_pmu_format *format = pmu_find_format(&evsel->pmu->format, config_name);
1472
1473 return format && !bitmap_empty(format->bits, PERF_PMU_FORMAT_BITS);
1474}
1475
1476int evsel__get_config_val(const struct evsel *evsel, const char *config_name,
1477 u64 *val)
1478{
1479 struct perf_pmu_format *format = pmu_find_format(&evsel->pmu->format, config_name);
1480
1481 if (!format || bitmap_empty(format->bits, PERF_PMU_FORMAT_BITS)) {
1482 pr_err("Unknown/empty format name: %s\n", config_name);
1483 *val = 0;
1484 return -EINVAL;
1485 }
1486
1487 switch (format->value) {
1488 case PERF_PMU_FORMAT_VALUE_CONFIG:
1489 *val = perf_pmu__format_unpack(format->bits,
1490 evsel->core.attr.config);
1491 return 0;
1492 case PERF_PMU_FORMAT_VALUE_CONFIG1:
1493 *val = perf_pmu__format_unpack(format->bits,
1494 evsel->core.attr.config1);
1495 return 0;
1496 case PERF_PMU_FORMAT_VALUE_CONFIG2:
1497 *val = perf_pmu__format_unpack(format->bits,
1498 evsel->core.attr.config2);
1499 return 0;
1500 case PERF_PMU_FORMAT_VALUE_CONFIG3:
1501 *val = perf_pmu__format_unpack(format->bits,
1502 evsel->core.attr.config3);
1503 return 0;
1504 case PERF_PMU_FORMAT_VALUE_CONFIG4:
1505 *val = perf_pmu__format_unpack(format->bits,
1506 evsel->core.attr.config4);
1507 return 0;
1508 default:
1509 pr_err("Unknown format value: %d\n", format->value);
1510 *val = 0;
1511 return -EINVAL;
1512 }
1513}
1514
1515void __weak arch_evsel__set_sample_weight(struct evsel *evsel)
1516{
1517 evsel__set_sample_bit(evsel, WEIGHT);
1518}
1519
1520void __weak arch__post_evsel_config(struct evsel *evsel __maybe_unused,
1521 struct perf_event_attr *attr __maybe_unused)
1522{
1523}
1524
1525void __weak arch_evsel__apply_ratio_to_prev(struct evsel *evsel __maybe_unused,
1526 struct perf_event_attr *attr __maybe_unused)
1527{
1528}
1529
1530static void evsel__set_default_freq_period(const struct record_opts *opts,
1531 struct perf_event_attr *attr)
1532{
1533 if (opts->freq) {
1534 attr->freq = 1;
1535 attr->sample_freq = opts->freq;
1536 } else {
1537 attr->sample_period = opts->default_interval;
1538 }
1539}
1540
1541bool evsel__is_offcpu_event(struct evsel *evsel)
1542{
1543 return evsel__is_bpf_output(evsel) && evsel__name_is(evsel, OFFCPU_EVENT) &&
1544 evsel->core.attr.sample_type & PERF_SAMPLE_RAW;
1545}
1546
1547/*
1548 * The enable_on_exec/disabled value strategy:
1549 *
1550 * 1) For any type of traced program:
1551 * - all independent events and group leaders are disabled
1552 * - all group members are enabled
1553 *
1554 * Group members are ruled by group leaders. They need to
1555 * be enabled, because the group scheduling relies on that.
1556 *
1557 * 2) For traced programs executed by perf:
1558 * - all independent events and group leaders have
1559 * enable_on_exec set
1560 * - we don't specifically enable or disable any event during
1561 * the record command
1562 *
1563 * Independent events and group leaders are initially disabled
1564 * and get enabled by exec. Group members are ruled by group
1565 * leaders as stated in 1).
1566 *
1567 * 3) For traced programs attached by perf (pid/tid):
1568 * - we specifically enable or disable all events during
1569 * the record command
1570 *
1571 * When attaching events to already running traced we
1572 * enable/disable events specifically, as there's no
1573 * initial traced exec call.
1574 */
1575void evsel__config(struct evsel *evsel, const struct record_opts *opts,
1576 const struct callchain_param *callchain)
1577{
1578 struct evsel *leader = evsel__leader(evsel);
1579 struct perf_event_attr *attr = &evsel->core.attr;
1580 int track = evsel->tracking;
1581 bool per_cpu = opts->target.default_per_cpu && !opts->target.per_thread;
1582
1583 attr->sample_id_all = perf_missing_features.sample_id_all ? 0 : 1;
1584 attr->inherit = target__has_cpu(&opts->target) ? 0 : !opts->no_inherit;
1585 attr->write_backward = opts->overwrite ? 1 : 0;
1586 attr->read_format = PERF_FORMAT_LOST;
1587
1588 evsel__set_sample_bit(evsel, IP);
1589 evsel__set_sample_bit(evsel, TID);
1590
1591 if (evsel->sample_read) {
1592 evsel__set_sample_bit(evsel, READ);
1593
1594 /*
1595 * We need ID even in case of single event, because
1596 * PERF_SAMPLE_READ process ID specific data.
1597 */
1598 evsel__set_sample_id(evsel, false);
1599
1600 /*
1601 * Apply group format only if we belong to group
1602 * with more than one members.
1603 */
1604 if (leader->core.nr_members > 1) {
1605 attr->read_format |= PERF_FORMAT_GROUP;
1606 }
1607
1608 /*
1609 * Inherit + SAMPLE_READ requires SAMPLE_TID in the read_format
1610 */
1611 if (attr->inherit) {
1612 evsel__set_sample_bit(evsel, TID);
1613 evsel->core.attr.read_format |=
1614 PERF_FORMAT_ID;
1615 }
1616 }
1617
1618 /*
1619 * We default some events to have a default interval. But keep
1620 * it a weak assumption overridable by the user.
1621 */
1622 if ((evsel->is_libpfm_event && !attr->sample_period) ||
1623 (!evsel->is_libpfm_event && (!attr->sample_period ||
1624 opts->user_freq != UINT_MAX ||
1625 opts->user_interval != ULLONG_MAX)))
1626 evsel__set_default_freq_period(opts, attr);
1627
1628 /*
1629 * If attr->freq was set (here or earlier), ask for period
1630 * to be sampled.
1631 */
1632 if (attr->freq)
1633 evsel__set_sample_bit(evsel, PERIOD);
1634
1635 if (opts->no_samples)
1636 attr->sample_freq = 0;
1637
1638 if (opts->inherit_stat) {
1639 evsel->core.attr.read_format |=
1640 PERF_FORMAT_TOTAL_TIME_ENABLED |
1641 PERF_FORMAT_TOTAL_TIME_RUNNING |
1642 PERF_FORMAT_ID;
1643 attr->inherit_stat = 1;
1644 }
1645
1646 if (opts->sample_address)
1647 evsel__set_sample_bit(evsel, ADDR);
1648
1649 if (opts->record_data_mmap)
1650 attr->mmap_data = track;
1651
1652 /*
1653 * We don't allow user space callchains for function trace
1654 * event, due to issues with page faults while tracing page
1655 * fault handler and its overall trickiness nature.
1656 */
1657 if (evsel__is_function_event(evsel))
1658 evsel->core.attr.exclude_callchain_user = 1;
1659
1660 if (callchain && callchain->enabled && !evsel->no_aux_samples)
1661 evsel__config_callchain(evsel, opts, callchain);
1662
1663 if (opts->sample_intr_regs && !evsel->no_aux_samples &&
1664 !evsel__is_dummy_event(evsel)) {
1665 attr->sample_regs_intr = opts->sample_intr_regs;
1666 evsel__set_sample_bit(evsel, REGS_INTR);
1667 }
1668
1669 if (opts->sample_user_regs && !evsel->no_aux_samples &&
1670 !evsel__is_dummy_event(evsel)) {
1671 attr->sample_regs_user |= opts->sample_user_regs;
1672 evsel__set_sample_bit(evsel, REGS_USER);
1673 }
1674
1675 if (target__has_cpu(&opts->target) || opts->sample_cpu)
1676 evsel__set_sample_bit(evsel, CPU);
1677
1678 /*
1679 * When the user explicitly disabled time don't force it here.
1680 */
1681 if (opts->sample_time &&
1682 (!perf_missing_features.sample_id_all &&
1683 (!opts->no_inherit || target__has_cpu(&opts->target) || per_cpu ||
1684 opts->sample_time_set)))
1685 evsel__set_sample_bit(evsel, TIME);
1686
1687 if (opts->raw_samples && !evsel->no_aux_samples) {
1688 evsel__set_sample_bit(evsel, TIME);
1689 evsel__set_sample_bit(evsel, RAW);
1690 evsel__set_sample_bit(evsel, CPU);
1691 }
1692
1693 if (opts->sample_data_src)
1694 evsel__set_sample_bit(evsel, DATA_SRC);
1695
1696 if (opts->sample_phys_addr)
1697 evsel__set_sample_bit(evsel, PHYS_ADDR);
1698
1699 if (opts->no_buffering) {
1700 attr->watermark = 0;
1701 attr->wakeup_events = 1;
1702 }
1703 if (opts->branch_stack && !evsel->no_aux_samples) {
1704 evsel__set_sample_bit(evsel, BRANCH_STACK);
1705 attr->branch_sample_type = opts->branch_stack;
1706 }
1707
1708 if (opts->sample_weight || evsel->retire_lat) {
1709 arch_evsel__set_sample_weight(evsel);
1710 evsel->retire_lat = false;
1711 }
1712 attr->task = track;
1713 attr->mmap = track;
1714 attr->mmap2 = track && !perf_missing_features.mmap2;
1715 attr->comm = track;
1716 attr->build_id = track && opts->build_id;
1717 attr->defer_output = track && callchain && callchain->defer;
1718
1719 /*
1720 * ksymbol is tracked separately with text poke because it needs to be
1721 * system wide and enabled immediately.
1722 */
1723 if (!opts->text_poke)
1724 attr->ksymbol = track && !perf_missing_features.ksymbol;
1725 attr->bpf_event = track && !opts->no_bpf_event && !perf_missing_features.bpf;
1726
1727 if (opts->record_namespaces)
1728 attr->namespaces = track;
1729
1730 if (opts->record_cgroup) {
1731 attr->cgroup = track && !perf_missing_features.cgroup;
1732 evsel__set_sample_bit(evsel, CGROUP);
1733 }
1734
1735 if (opts->sample_data_page_size)
1736 evsel__set_sample_bit(evsel, DATA_PAGE_SIZE);
1737
1738 if (opts->sample_code_page_size)
1739 evsel__set_sample_bit(evsel, CODE_PAGE_SIZE);
1740
1741 if (opts->record_switch_events)
1742 attr->context_switch = track;
1743
1744 if (opts->sample_transaction)
1745 evsel__set_sample_bit(evsel, TRANSACTION);
1746
1747 if (opts->running_time) {
1748 evsel->core.attr.read_format |=
1749 PERF_FORMAT_TOTAL_TIME_ENABLED |
1750 PERF_FORMAT_TOTAL_TIME_RUNNING;
1751 }
1752
1753 /*
1754 * XXX see the function comment above
1755 *
1756 * Disabling only independent events or group leaders,
1757 * keeping group members enabled.
1758 */
1759 if (evsel__is_group_leader(evsel))
1760 attr->disabled = 1;
1761
1762 /*
1763 * Setting enable_on_exec for independent events and
1764 * group leaders for traced executed by perf.
1765 */
1766 if (target__none(&opts->target) && evsel__is_group_leader(evsel) &&
1767 !opts->target.initial_delay)
1768 attr->enable_on_exec = 1;
1769
1770 if (evsel->immediate) {
1771 attr->disabled = 0;
1772 attr->enable_on_exec = 0;
1773 }
1774
1775 clockid = opts->clockid;
1776 if (opts->use_clockid) {
1777 attr->use_clockid = 1;
1778 attr->clockid = opts->clockid;
1779 }
1780
1781 if (evsel->precise_max)
1782 attr->precise_ip = 3;
1783
1784 if (opts->all_user) {
1785 attr->exclude_kernel = 1;
1786 attr->exclude_user = 0;
1787 }
1788
1789 if (opts->all_kernel) {
1790 attr->exclude_kernel = 0;
1791 attr->exclude_user = 1;
1792 }
1793
1794 if (evsel->core.pmu_cpus || evsel->unit)
1795 evsel->core.attr.read_format |= PERF_FORMAT_ID;
1796
1797 /*
1798 * Apply event specific term settings,
1799 * it overloads any global configuration.
1800 */
1801 evsel__apply_config_terms(evsel, opts, track);
1802
1803 evsel->ignore_missing_thread = opts->ignore_missing_thread;
1804
1805 /* The --period option takes the precedence. */
1806 if (opts->period_set) {
1807 if (opts->period)
1808 evsel__set_sample_bit(evsel, PERIOD);
1809 else
1810 evsel__reset_sample_bit(evsel, PERIOD);
1811 }
1812
1813 /*
1814 * A dummy event never triggers any actual counter and therefore
1815 * cannot be used with branch_stack.
1816 *
1817 * For initial_delay, a dummy event is added implicitly.
1818 * The software event will trigger -EOPNOTSUPP error out,
1819 * if BRANCH_STACK bit is set.
1820 */
1821 if (evsel__is_dummy_event(evsel))
1822 evsel__reset_sample_bit(evsel, BRANCH_STACK);
1823
1824 if (evsel__is_offcpu_event(evsel)) {
1825 evsel->core.attr.sample_type &= OFFCPU_SAMPLE_TYPES;
1826 attr->inherit = 0;
1827 }
1828
1829 arch__post_evsel_config(evsel, attr);
1830}
1831
1832int evsel__set_filter(struct evsel *evsel, const char *filter)
1833{
1834 char *new_filter = strdup(filter);
1835
1836 if (new_filter != NULL) {
1837 free(evsel->filter);
1838 evsel->filter = new_filter;
1839 return 0;
1840 }
1841
1842 return -1;
1843}
1844
1845static int evsel__append_filter(struct evsel *evsel, const char *fmt, const char *filter)
1846{
1847 char *new_filter;
1848
1849 if (evsel->filter == NULL)
1850 return evsel__set_filter(evsel, filter);
1851
1852 if (asprintf(&new_filter, fmt, evsel->filter, filter) > 0) {
1853 free(evsel->filter);
1854 evsel->filter = new_filter;
1855 return 0;
1856 }
1857
1858 return -1;
1859}
1860
1861int evsel__append_tp_filter(struct evsel *evsel, const char *filter)
1862{
1863 return evsel__append_filter(evsel, "(%s) && (%s)", filter);
1864}
1865
1866int evsel__append_addr_filter(struct evsel *evsel, const char *filter)
1867{
1868 return evsel__append_filter(evsel, "%s,%s", filter);
1869}
1870
1871/* Caller has to clear disabled after going through all CPUs. */
1872int evsel__enable_cpu(struct evsel *evsel, int cpu_map_idx)
1873{
1874 int err;
1875
1876 if (evsel__is_tool(evsel))
1877 err = evsel__tool_pmu_enable_cpu(evsel, cpu_map_idx);
1878 else
1879 err = perf_evsel__enable_cpu(&evsel->core, cpu_map_idx);
1880
1881 if (!err && evsel__is_group_leader(evsel)) {
1882 struct evsel *member;
1883
1884 for_each_group_member(member, evsel) {
1885 if (evsel__is_non_perf_event_open_pmu(evsel) ||
1886 evsel__is_non_perf_event_open_pmu(member)) {
1887 /*
1888 * In a mixed PMU group, userspace PMUs are not
1889 * grouped in the kernel (opened with group_fd = -1)
1890 * and are skipped by the kernel when enabling the
1891 * group leader. We must manually enable them in
1892 * userspace.
1893 */
1894 int mem_err = evsel__enable_cpu(member, cpu_map_idx);
1895
1896 if (mem_err)
1897 return mem_err;
1898 }
1899 }
1900 }
1901 return err;
1902}
1903
1904int evsel__enable(struct evsel *evsel)
1905{
1906 int err;
1907
1908 if (evsel__is_tool(evsel))
1909 err = evsel__tool_pmu_enable(evsel);
1910 else
1911 err = perf_evsel__enable(&evsel->core);
1912
1913 if (!err)
1914 evsel->disabled = false;
1915
1916 if (!err && evsel__is_group_leader(evsel)) {
1917 struct evsel *member;
1918
1919 for_each_group_member(member, evsel) {
1920 if (evsel__is_non_perf_event_open_pmu(evsel) ||
1921 evsel__is_non_perf_event_open_pmu(member)) {
1922 /*
1923 * In a mixed PMU group, userspace PMUs are not
1924 * grouped in the kernel (opened with group_fd = -1)
1925 * and are skipped by the kernel when enabling the
1926 * group leader. We must manually enable them in
1927 * userspace.
1928 */
1929 int mem_err = evsel__enable(member);
1930
1931 if (mem_err)
1932 return mem_err;
1933 }
1934 member->disabled = false;
1935 }
1936 }
1937
1938 return err;
1939}
1940
1941/* Caller has to set disabled after going through all CPUs. */
1942int evsel__disable_cpu(struct evsel *evsel, int cpu_map_idx)
1943{
1944 int err;
1945
1946 if (evsel__is_tool(evsel))
1947 err = evsel__tool_pmu_disable_cpu(evsel, cpu_map_idx);
1948 else
1949 err = perf_evsel__disable_cpu(&evsel->core, cpu_map_idx);
1950
1951 if (!err && evsel__is_group_leader(evsel)) {
1952 struct evsel *member;
1953
1954 for_each_group_member(member, evsel) {
1955 if (evsel__is_non_perf_event_open_pmu(evsel) ||
1956 evsel__is_non_perf_event_open_pmu(member)) {
1957 /*
1958 * In a mixed PMU group, userspace PMUs are not
1959 * grouped in the kernel and are skipped by the
1960 * kernel when disabling the group leader. We must
1961 * manually disable them in userspace.
1962 */
1963 int mem_err = evsel__disable_cpu(member, cpu_map_idx);
1964
1965 if (mem_err)
1966 return mem_err;
1967 }
1968 }
1969 }
1970 return err;
1971}
1972
1973int evsel__disable(struct evsel *evsel)
1974{
1975 int err;
1976
1977 if (evsel__is_tool(evsel))
1978 err = evsel__tool_pmu_disable(evsel);
1979 else
1980 err = perf_evsel__disable(&evsel->core);
1981
1982 /*
1983 * We mark it disabled here so that tools that disable a event can
1984 * ignore events after they disable it. I.e. the ring buffer may have
1985 * already a few more events queued up before the kernel got the stop
1986 * request.
1987 */
1988 if (!err)
1989 evsel->disabled = true;
1990
1991 if (!err && evsel__is_group_leader(evsel)) {
1992 struct evsel *member;
1993
1994 for_each_group_member(member, evsel) {
1995 if (evsel__is_non_perf_event_open_pmu(evsel) ||
1996 evsel__is_non_perf_event_open_pmu(member)) {
1997 /*
1998 * In a mixed PMU group, userspace PMUs are not
1999 * grouped in the kernel and are skipped by the
2000 * kernel when disabling the group leader. We must
2001 * manually disable them in userspace.
2002 */
2003 int mem_err = evsel__disable(member);
2004
2005 if (mem_err)
2006 return mem_err;
2007 }
2008 member->disabled = true;
2009 }
2010 }
2011
2012 return err;
2013}
2014
2015void free_config_terms(struct list_head *config_terms)
2016{
2017 struct evsel_config_term *term, *h;
2018
2019 list_for_each_entry_safe(term, h, config_terms, list) {
2020 list_del_init(&term->list);
2021 if (term->free_str)
2022 zfree(&term->val.str);
2023 free(term);
2024 }
2025}
2026
2027static void evsel__free_config_terms(struct evsel *evsel)
2028{
2029 free_config_terms(&evsel->config_terms);
2030}
2031
2032static void (*evsel__priv_destructor)(void *priv);
2033
2034void evsel__set_priv_destructor(void (*destructor)(void *priv))
2035{
2036 assert(evsel__priv_destructor == NULL);
2037
2038 evsel__priv_destructor = destructor;
2039}
2040
2041static void evsel__exit(struct evsel *evsel)
2042{
2043 assert(list_empty(&evsel->core.node));
2044 assert(evsel->evlist == NULL);
2045 if (evsel__is_retire_lat(evsel))
2046 evsel__tpebs_close(evsel);
2047 bpf_counter__destroy(evsel);
2048 perf_bpf_filter__destroy(evsel);
2049 evsel__free_counts(evsel);
2050 perf_evsel__free_fd(&evsel->core);
2051 perf_evsel__free_id(&evsel->core);
2052 evsel__free_config_terms(evsel);
2053 cgroup__put(evsel->cgrp);
2054 perf_evsel__exit(&evsel->core);
2055 zfree(&evsel->group_name);
2056 zfree(&evsel->name);
2057#ifdef HAVE_LIBTRACEEVENT
2058 zfree(&evsel->tp_sys);
2059 zfree(&evsel->tp_name);
2060#endif
2061 zfree(&evsel->filter);
2062 zfree(&evsel->group_pmu_name);
2063 zfree(&evsel->unit);
2064 zfree(&evsel->metric_id);
2065 evsel__zero_per_pkg(evsel);
2066 hashmap__free(evsel->per_pkg_mask);
2067 evsel->per_pkg_mask = NULL;
2068 if (evsel__priv_destructor)
2069 evsel__priv_destructor(evsel->priv);
2070 perf_evsel__object.fini(evsel);
2071 if (evsel__tool_event(evsel) == TOOL_PMU__EVENT_SYSTEM_TIME ||
2072 evsel__tool_event(evsel) == TOOL_PMU__EVENT_USER_TIME) {
2073 xyarray__delete(evsel->process_time.start_times);
2074 xyarray__delete(evsel->process_time.accumulated_times);
2075 }
2076}
2077
2078void evsel__put(struct evsel *evsel)
2079{
2080 if (!evsel)
2081 return;
2082
2083 if (!refcount_dec_and_test(&evsel->refcnt))
2084 return;
2085
2086 evsel__exit(evsel);
2087 free(evsel);
2088}
2089
2090void evsel__compute_deltas(struct evsel *evsel, int cpu_map_idx, int thread,
2091 struct perf_counts_values *count)
2092{
2093 struct perf_counts_values tmp;
2094
2095 if (!evsel->prev_raw_counts)
2096 return;
2097
2098 tmp = *perf_counts(evsel->prev_raw_counts, cpu_map_idx, thread);
2099 *perf_counts(evsel->prev_raw_counts, cpu_map_idx, thread) = *count;
2100
2101 count->val = count->val - tmp.val;
2102 count->ena = count->ena - tmp.ena;
2103 count->run = count->run - tmp.run;
2104}
2105
2106static int evsel__read_one(struct evsel *evsel, int cpu_map_idx, int thread)
2107{
2108 struct perf_counts_values *count = perf_counts(evsel->counts, cpu_map_idx, thread);
2109
2110 return perf_evsel__read(&evsel->core, cpu_map_idx, thread, count);
2111}
2112
2113static void evsel__set_count(struct evsel *counter, int cpu_map_idx, int thread,
2114 u64 val, u64 ena, u64 run, u64 lost)
2115{
2116 struct perf_counts_values *count;
2117
2118 count = perf_counts(counter->counts, cpu_map_idx, thread);
2119
2120 if (evsel__is_retire_lat(counter)) {
2121 evsel__tpebs_read(counter, cpu_map_idx, thread);
2122 perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, true);
2123 return;
2124 }
2125
2126 count->val = val;
2127 count->ena = ena;
2128 count->run = run;
2129 count->lost = lost;
2130
2131 perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, true);
2132}
2133
2134static bool evsel__group_has_tpebs(struct evsel *leader)
2135{
2136 struct evsel *evsel;
2137
2138 for_each_group_evsel(evsel, leader) {
2139 if (evsel__is_retire_lat(evsel))
2140 return true;
2141 }
2142 return false;
2143}
2144
2145static u64 evsel__group_read_nr_members(struct evsel *leader)
2146{
2147 u64 nr = leader->core.nr_members;
2148 struct evsel *evsel;
2149
2150 for_each_group_evsel(evsel, leader) {
2151 if (evsel__is_retire_lat(evsel))
2152 nr--;
2153 }
2154 return nr;
2155}
2156
2157static u64 evsel__group_read_size(struct evsel *leader)
2158{
2159 u64 read_format = leader->core.attr.read_format;
2160 int entry = sizeof(u64); /* value */
2161 int size = 0;
2162 int nr = 1;
2163
2164 if (!evsel__group_has_tpebs(leader))
2165 return perf_evsel__read_size(&leader->core);
2166
2167 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2168 size += sizeof(u64);
2169
2170 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2171 size += sizeof(u64);
2172
2173 if (read_format & PERF_FORMAT_ID)
2174 entry += sizeof(u64);
2175
2176 if (read_format & PERF_FORMAT_LOST)
2177 entry += sizeof(u64);
2178
2179 if (read_format & PERF_FORMAT_GROUP) {
2180 nr = evsel__group_read_nr_members(leader);
2181 size += sizeof(u64);
2182 }
2183
2184 size += entry * nr;
2185 return size;
2186}
2187
2188static int evsel__process_group_data(struct evsel *leader, int cpu_map_idx, int thread, u64 *data)
2189{
2190 u64 read_format = leader->core.attr.read_format;
2191 struct sample_read_value *v;
2192 u64 nr, ena = 0, run = 0, lost = 0;
2193
2194 nr = *data++;
2195
2196 if (nr != evsel__group_read_nr_members(leader))
2197 return -EINVAL;
2198
2199 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
2200 ena = *data++;
2201
2202 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
2203 run = *data++;
2204
2205 v = (void *)data;
2206 sample_read_group__for_each(v, nr, read_format) {
2207 struct evsel *counter;
2208
2209 counter = evlist__id2evsel(leader->evlist, v->id);
2210 if (!counter)
2211 return -EINVAL;
2212
2213 if (read_format & PERF_FORMAT_LOST)
2214 lost = v->lost;
2215
2216 evsel__set_count(counter, cpu_map_idx, thread, v->value, ena, run, lost);
2217 }
2218
2219 return 0;
2220}
2221
2222static int evsel__read_group(struct evsel *leader, int cpu_map_idx, int thread)
2223{
2224 struct perf_stat_evsel *ps = leader->stats;
2225 u64 read_format = leader->core.attr.read_format;
2226 int size = evsel__group_read_size(leader);
2227 u64 *data = ps->group_data;
2228
2229 if (!(read_format & PERF_FORMAT_ID))
2230 return -EINVAL;
2231
2232 if (!evsel__is_group_leader(leader))
2233 return -EINVAL;
2234
2235 if (!data) {
2236 data = zalloc(size);
2237 if (!data)
2238 return -ENOMEM;
2239
2240 ps->group_data = data;
2241 }
2242
2243 if (FD(leader, cpu_map_idx, thread) < 0)
2244 return -EINVAL;
2245
2246 if (readn(FD(leader, cpu_map_idx, thread), data, size) <= 0)
2247 return -errno;
2248
2249 return evsel__process_group_data(leader, cpu_map_idx, thread, data);
2250}
2251
2252bool __evsel__match(const struct evsel *evsel, u32 type, u64 config)
2253{
2254
2255 u32 e_type = evsel->core.attr.type;
2256 u64 e_config = evsel->core.attr.config;
2257
2258 if (e_type == type && e_config == config)
2259 return true;
2260 if (type != PERF_TYPE_HARDWARE && type != PERF_TYPE_HW_CACHE)
2261 return false;
2262 if ((e_type == PERF_TYPE_HARDWARE || e_type == PERF_TYPE_HW_CACHE) &&
2263 perf_pmus__supports_extended_type())
2264 e_config &= PERF_HW_EVENT_MASK;
2265 if (e_type == type && e_config == config)
2266 return true;
2267 if (type == PERF_TYPE_HARDWARE && evsel->pmu && evsel->pmu->is_core &&
2268 evsel->alternate_hw_config == config)
2269 return true;
2270 return false;
2271}
2272
2273int evsel__read_counter(struct evsel *evsel, int cpu_map_idx, int thread)
2274{
2275 if (evsel__is_tool(evsel))
2276 return evsel__tool_pmu_read(evsel, cpu_map_idx, thread);
2277
2278 if (evsel__is_hwmon(evsel))
2279 return evsel__hwmon_pmu_read(evsel, cpu_map_idx, thread);
2280
2281 if (evsel__is_drm(evsel))
2282 return evsel__drm_pmu_read(evsel, cpu_map_idx, thread);
2283
2284 if (evsel__is_retire_lat(evsel))
2285 return evsel__tpebs_read(evsel, cpu_map_idx, thread);
2286
2287 if (evsel->core.attr.read_format & PERF_FORMAT_GROUP)
2288 return evsel__read_group(evsel, cpu_map_idx, thread);
2289
2290 return evsel__read_one(evsel, cpu_map_idx, thread);
2291}
2292
2293int __evsel__read_on_cpu(struct evsel *evsel, int cpu_map_idx, int thread, bool scale)
2294{
2295 struct perf_counts_values count;
2296 size_t nv = scale ? 3 : 1;
2297
2298 if (FD(evsel, cpu_map_idx, thread) < 0)
2299 return -EINVAL;
2300
2301 if (evsel->counts == NULL && evsel__alloc_counts(evsel) < 0)
2302 return -ENOMEM;
2303
2304 if (readn(FD(evsel, cpu_map_idx, thread), &count, nv * sizeof(u64)) <= 0)
2305 return -errno;
2306
2307 evsel__compute_deltas(evsel, cpu_map_idx, thread, &count);
2308 perf_counts_values__scale(&count, scale, NULL);
2309 *perf_counts(evsel->counts, cpu_map_idx, thread) = count;
2310 return 0;
2311}
2312
2313static int evsel__match_other_cpu(struct evsel *evsel, struct evsel *other,
2314 int cpu_map_idx)
2315{
2316 struct perf_cpu cpu;
2317
2318 cpu = perf_cpu_map__cpu(evsel->core.cpus, cpu_map_idx);
2319 return perf_cpu_map__idx(other->core.cpus, cpu);
2320}
2321
2322static int evsel__hybrid_group_cpu_map_idx(struct evsel *evsel, int cpu_map_idx)
2323{
2324 struct evsel *leader = evsel__leader(evsel);
2325
2326 if ((evsel__is_hybrid(evsel) && !evsel__is_hybrid(leader)) ||
2327 (!evsel__is_hybrid(evsel) && evsel__is_hybrid(leader))) {
2328 return evsel__match_other_cpu(evsel, leader, cpu_map_idx);
2329 }
2330
2331 return cpu_map_idx;
2332}
2333
2334static int get_group_fd(struct evsel *evsel, int cpu_map_idx, int thread)
2335{
2336 struct evsel *leader = evsel__leader(evsel);
2337 int fd;
2338
2339 if (!evsel->supported || evsel__is_group_leader(evsel))
2340 return -1;
2341
2342 /*
2343 * Leader must be already processed/open,
2344 * if not it's a bug.
2345 */
2346 BUG_ON(!leader->core.fd);
2347
2348 cpu_map_idx = evsel__hybrid_group_cpu_map_idx(evsel, cpu_map_idx);
2349 if (cpu_map_idx == -1)
2350 return -1;
2351
2352 fd = FD(leader, cpu_map_idx, thread);
2353 BUG_ON(fd == -1 && leader->supported);
2354
2355 /*
2356 * When the leader has been skipped, return -2 to distinguish from no
2357 * group leader case.
2358 */
2359 return fd == -1 ? -2 : fd;
2360}
2361
2362static void evsel__remove_fd(struct evsel *pos, int nr_cpus, int nr_threads, int thread_idx)
2363{
2364 for (int cpu = 0; cpu < nr_cpus; cpu++)
2365 for (int thread = thread_idx; thread < nr_threads - 1; thread++)
2366 FD(pos, cpu, thread) = FD(pos, cpu, thread + 1);
2367}
2368
2369static int update_fds(struct evsel *evsel,
2370 int nr_cpus, int cpu_map_idx,
2371 int nr_threads, int thread_idx)
2372{
2373 struct evsel *pos;
2374
2375 if (cpu_map_idx >= nr_cpus || thread_idx >= nr_threads)
2376 return -EINVAL;
2377
2378 evlist__for_each_entry(evsel->evlist, pos) {
2379 nr_cpus = pos != evsel ? nr_cpus : cpu_map_idx;
2380
2381 evsel__remove_fd(pos, nr_cpus, nr_threads, thread_idx);
2382
2383 /*
2384 * Since fds for next evsel has not been created,
2385 * there is no need to iterate whole event list.
2386 */
2387 if (pos == evsel)
2388 break;
2389 }
2390 return 0;
2391}
2392
2393static bool evsel__ignore_missing_thread(struct evsel *evsel,
2394 int nr_cpus, int cpu_map_idx,
2395 struct perf_thread_map *threads,
2396 int thread, int err)
2397{
2398 pid_t ignore_pid = perf_thread_map__pid(threads, thread);
2399
2400 if (!evsel->ignore_missing_thread)
2401 return false;
2402
2403 /* The system wide setup does not work with threads. */
2404 if (evsel->core.system_wide)
2405 return false;
2406
2407 /* The -ESRCH is perf event syscall errno for pid's not found. */
2408 if (err != -ESRCH)
2409 return false;
2410
2411 /* If there's only one thread, let it fail. */
2412 if (threads->nr == 1)
2413 return false;
2414
2415 /*
2416 * We should remove fd for missing_thread first
2417 * because thread_map__remove() will decrease threads->nr.
2418 */
2419 if (update_fds(evsel, nr_cpus, cpu_map_idx, threads->nr, thread))
2420 return false;
2421
2422 if (thread_map__remove(threads, thread))
2423 return false;
2424
2425 pr_warning("WARNING: Ignored open failure for pid %d\n",
2426 ignore_pid);
2427 return true;
2428}
2429
2430static int __open_attr__fprintf(FILE *fp, const char *name, const char *val,
2431 void *priv __maybe_unused)
2432{
2433 return fprintf(fp, " %-32s %s\n", name, val);
2434}
2435
2436static void display_attr(struct perf_event_attr *attr)
2437{
2438 if (verbose >= 2 || debug_peo_args) {
2439 fprintf(stderr, "%.60s\n", graph_dotted_line);
2440 fprintf(stderr, "perf_event_attr:\n");
2441 perf_event_attr__fprintf(stderr, attr, __open_attr__fprintf, NULL);
2442 fprintf(stderr, "%.60s\n", graph_dotted_line);
2443 }
2444}
2445
2446bool evsel__precise_ip_fallback(struct evsel *evsel)
2447{
2448 /* Do not try less precise if not requested. */
2449 if (!evsel->precise_max)
2450 return false;
2451
2452 /*
2453 * We tried all the precise_ip values, and it's
2454 * still failing, so leave it to standard fallback.
2455 */
2456 if (!evsel->core.attr.precise_ip) {
2457 evsel->core.attr.precise_ip = evsel->precise_ip_original;
2458 return false;
2459 }
2460
2461 if (!evsel->precise_ip_original)
2462 evsel->precise_ip_original = evsel->core.attr.precise_ip;
2463
2464 evsel->core.attr.precise_ip--;
2465 pr_debug2_peo("decreasing precise_ip by one (%d)\n", evsel->core.attr.precise_ip);
2466 display_attr(&evsel->core.attr);
2467 return true;
2468}
2469
2470static struct perf_cpu_map *empty_cpu_map;
2471static struct perf_thread_map *empty_thread_map;
2472
2473static int __evsel__prepare_open(struct evsel *evsel, struct perf_cpu_map *cpus,
2474 struct perf_thread_map *threads)
2475{
2476 int ret = 0;
2477 int nthreads = perf_thread_map__nr(threads);
2478
2479 if ((perf_missing_features.write_backward && evsel->core.attr.write_backward) ||
2480 (perf_missing_features.aux_output && evsel->core.attr.aux_output))
2481 return -EINVAL;
2482
2483 if (cpus == NULL) {
2484 if (empty_cpu_map == NULL) {
2485 empty_cpu_map = perf_cpu_map__new_any_cpu();
2486 if (empty_cpu_map == NULL)
2487 return -ENOMEM;
2488 }
2489
2490 cpus = empty_cpu_map;
2491 }
2492
2493 if (threads == NULL) {
2494 if (empty_thread_map == NULL) {
2495 empty_thread_map = thread_map__new_by_tid(-1);
2496 if (empty_thread_map == NULL)
2497 return -ENOMEM;
2498 }
2499
2500 threads = empty_thread_map;
2501 }
2502
2503 if (evsel->core.fd == NULL &&
2504 perf_evsel__alloc_fd(&evsel->core, perf_cpu_map__nr(cpus), nthreads) < 0)
2505 return -ENOMEM;
2506
2507 if (evsel__is_tool(evsel))
2508 ret = evsel__tool_pmu_prepare_open(evsel, cpus, nthreads);
2509
2510 evsel->open_flags = PERF_FLAG_FD_CLOEXEC;
2511 if (evsel->cgrp)
2512 evsel->open_flags |= PERF_FLAG_PID_CGROUP;
2513
2514 return ret;
2515}
2516
2517static void evsel__disable_missing_features(struct evsel *evsel)
2518{
2519 if (perf_missing_features.defer_callchain && evsel->core.attr.defer_callchain)
2520 evsel->core.attr.defer_callchain = 0;
2521 if (perf_missing_features.defer_callchain && evsel->core.attr.defer_output)
2522 evsel->core.attr.defer_output = 0;
2523 if (perf_missing_features.inherit_sample_read && evsel->core.attr.inherit &&
2524 (evsel->core.attr.sample_type & PERF_SAMPLE_READ))
2525 evsel->core.attr.inherit = 0;
2526 if (perf_missing_features.branch_counters)
2527 evsel->core.attr.branch_sample_type &= ~PERF_SAMPLE_BRANCH_COUNTERS;
2528 if (perf_missing_features.read_lost)
2529 evsel->core.attr.read_format &= ~PERF_FORMAT_LOST;
2530 if (perf_missing_features.weight_struct) {
2531 evsel__set_sample_bit(evsel, WEIGHT);
2532 evsel__reset_sample_bit(evsel, WEIGHT_STRUCT);
2533 }
2534 if (perf_missing_features.clockid_wrong)
2535 evsel->core.attr.clockid = CLOCK_MONOTONIC; /* should always work */
2536 if (perf_missing_features.clockid) {
2537 evsel->core.attr.use_clockid = 0;
2538 evsel->core.attr.clockid = 0;
2539 }
2540 if (perf_missing_features.cloexec)
2541 evsel->open_flags &= ~(unsigned long)PERF_FLAG_FD_CLOEXEC;
2542 if (perf_missing_features.mmap2)
2543 evsel->core.attr.mmap2 = 0;
2544 if (evsel->pmu && evsel->pmu->missing_features.exclude_guest)
2545 evsel->core.attr.exclude_guest = evsel->core.attr.exclude_host = 0;
2546 if (perf_missing_features.lbr_flags)
2547 evsel->core.attr.branch_sample_type &= ~(PERF_SAMPLE_BRANCH_NO_FLAGS |
2548 PERF_SAMPLE_BRANCH_NO_CYCLES);
2549 if (perf_missing_features.group_read && evsel->core.attr.inherit)
2550 evsel->core.attr.read_format &= ~(PERF_FORMAT_GROUP|PERF_FORMAT_ID);
2551 if (perf_missing_features.ksymbol)
2552 evsel->core.attr.ksymbol = 0;
2553 if (perf_missing_features.bpf)
2554 evsel->core.attr.bpf_event = 0;
2555 if (perf_missing_features.branch_hw_idx)
2556 evsel->core.attr.branch_sample_type &= ~PERF_SAMPLE_BRANCH_HW_INDEX;
2557 if (perf_missing_features.sample_id_all)
2558 evsel->core.attr.sample_id_all = 0;
2559}
2560
2561int evsel__prepare_open(struct evsel *evsel, struct perf_cpu_map *cpus,
2562 struct perf_thread_map *threads)
2563{
2564 int err;
2565
2566 err = __evsel__prepare_open(evsel, cpus, threads);
2567 if (err)
2568 return err;
2569
2570 evsel__disable_missing_features(evsel);
2571
2572 return err;
2573}
2574
2575static bool __has_attr_feature(struct perf_event_attr *attr,
2576 struct perf_cpu cpu, unsigned long flags)
2577{
2578 int fd = syscall(SYS_perf_event_open, attr, /*pid=*/0, cpu.cpu,
2579 /*group_fd=*/-1, flags);
2580 close(fd);
2581
2582 if (fd < 0) {
2583 attr->exclude_kernel = 1;
2584
2585 fd = syscall(SYS_perf_event_open, attr, /*pid=*/0, cpu.cpu,
2586 /*group_fd=*/-1, flags);
2587 close(fd);
2588 }
2589
2590 if (fd < 0) {
2591 attr->exclude_hv = 1;
2592
2593 fd = syscall(SYS_perf_event_open, attr, /*pid=*/0, cpu.cpu,
2594 /*group_fd=*/-1, flags);
2595 close(fd);
2596 }
2597
2598 if (fd < 0) {
2599 attr->exclude_guest = 1;
2600
2601 fd = syscall(SYS_perf_event_open, attr, /*pid=*/0, cpu.cpu,
2602 /*group_fd=*/-1, flags);
2603 close(fd);
2604 }
2605
2606 attr->exclude_kernel = 0;
2607 attr->exclude_guest = 0;
2608 attr->exclude_hv = 0;
2609
2610 return fd >= 0;
2611}
2612
2613static bool has_attr_feature(struct perf_event_attr *attr, unsigned long flags)
2614{
2615 struct perf_cpu cpu = {.cpu = -1};
2616
2617 return __has_attr_feature(attr, cpu, flags);
2618}
2619
2620static void evsel__detect_missing_pmu_features(struct evsel *evsel)
2621{
2622 struct perf_event_attr attr = {
2623 .type = evsel->core.attr.type,
2624 .config = evsel->core.attr.config,
2625 .disabled = 1,
2626 };
2627 struct perf_pmu *pmu = evsel->pmu;
2628 int old_errno;
2629
2630 old_errno = errno;
2631
2632 if (pmu == NULL)
2633 pmu = evsel->pmu = evsel__find_pmu(evsel);
2634
2635 if (pmu == NULL || pmu->missing_features.checked)
2636 goto out;
2637
2638 /*
2639 * Must probe features in the order they were added to the
2640 * perf_event_attr interface. These are kernel core limitation but
2641 * specific to PMUs with branch stack. So we can detect with the given
2642 * hardware event and stop on the first one succeeded.
2643 */
2644
2645 /* Please add new feature detection here. */
2646
2647 attr.exclude_guest = 1;
2648 if (has_attr_feature(&attr, /*flags=*/0))
2649 goto found;
2650 pmu->missing_features.exclude_guest = true;
2651 pr_debug2("switching off exclude_guest for PMU %s\n", pmu->name);
2652
2653found:
2654 pmu->missing_features.checked = true;
2655out:
2656 errno = old_errno;
2657}
2658
2659static void evsel__detect_missing_brstack_features(struct evsel *evsel)
2660{
2661 static bool detection_done = false;
2662 struct perf_event_attr attr = {
2663 .type = evsel->core.attr.type,
2664 .config = evsel->core.attr.config,
2665 .disabled = 1,
2666 .sample_type = PERF_SAMPLE_BRANCH_STACK,
2667 .sample_period = 1000,
2668 };
2669 int old_errno;
2670
2671 if (detection_done)
2672 return;
2673
2674 old_errno = errno;
2675
2676 /*
2677 * Must probe features in the order they were added to the
2678 * perf_event_attr interface. These are PMU specific limitation
2679 * so we can detect with the given hardware event and stop on the
2680 * first one succeeded.
2681 */
2682
2683 /* Please add new feature detection here. */
2684
2685 attr.branch_sample_type = PERF_SAMPLE_BRANCH_COUNTERS;
2686 if (has_attr_feature(&attr, /*flags=*/0))
2687 goto found;
2688 perf_missing_features.branch_counters = true;
2689 pr_debug2("switching off branch counters support\n");
2690
2691 attr.branch_sample_type = PERF_SAMPLE_BRANCH_HW_INDEX;
2692 if (has_attr_feature(&attr, /*flags=*/0))
2693 goto found;
2694 perf_missing_features.branch_hw_idx = true;
2695 pr_debug2("switching off branch HW index support\n");
2696
2697 attr.branch_sample_type = PERF_SAMPLE_BRANCH_NO_CYCLES | PERF_SAMPLE_BRANCH_NO_FLAGS;
2698 if (has_attr_feature(&attr, /*flags=*/0))
2699 goto found;
2700 perf_missing_features.lbr_flags = true;
2701 pr_debug2_peo("switching off branch sample type no (cycles/flags)\n");
2702
2703found:
2704 detection_done = true;
2705 errno = old_errno;
2706}
2707
2708static bool evsel__probe_aux_action(struct evsel *evsel, struct perf_cpu cpu)
2709{
2710 struct perf_event_attr attr = evsel->core.attr;
2711 int old_errno = errno;
2712
2713 attr.disabled = 1;
2714 attr.aux_start_paused = 1;
2715
2716 if (__has_attr_feature(&attr, cpu, /*flags=*/0)) {
2717 errno = old_errno;
2718 return true;
2719 }
2720
2721 /*
2722 * EOPNOTSUPP means the kernel supports the feature but the PMU does
2723 * not, so keep that distinction if possible.
2724 */
2725 if (errno != EOPNOTSUPP)
2726 errno = old_errno;
2727
2728 return false;
2729}
2730
2731static void evsel__detect_missing_aux_action_feature(struct evsel *evsel, struct perf_cpu cpu)
2732{
2733 static bool detection_done;
2734 struct evsel *leader;
2735
2736 /*
2737 * Don't bother probing aux_action if it is not being used or has been
2738 * probed before.
2739 */
2740 if (!evsel->core.attr.aux_action || detection_done)
2741 return;
2742
2743 detection_done = true;
2744
2745 /*
2746 * The leader is an AUX area event. If it has failed, assume the feature
2747 * is not supported.
2748 */
2749 leader = evsel__leader(evsel);
2750 if (evsel == leader) {
2751 perf_missing_features.aux_action = true;
2752 return;
2753 }
2754
2755 /*
2756 * AUX area event with aux_action must have been opened successfully
2757 * already, so feature is supported.
2758 */
2759 if (leader->core.attr.aux_action)
2760 return;
2761
2762 if (!evsel__probe_aux_action(leader, cpu))
2763 perf_missing_features.aux_action = true;
2764}
2765
2766static bool evsel__detect_missing_features(struct evsel *evsel, struct perf_cpu cpu)
2767{
2768 static bool detection_done = false;
2769 struct perf_event_attr attr = {
2770 .type = PERF_TYPE_SOFTWARE,
2771 .config = PERF_COUNT_SW_TASK_CLOCK,
2772 .disabled = 1,
2773 };
2774 int old_errno;
2775
2776 evsel__detect_missing_aux_action_feature(evsel, cpu);
2777
2778 evsel__detect_missing_pmu_features(evsel);
2779
2780 if (evsel__has_br_stack(evsel))
2781 evsel__detect_missing_brstack_features(evsel);
2782
2783 if (detection_done)
2784 goto check;
2785
2786 old_errno = errno;
2787
2788 /*
2789 * Must probe features in the order they were added to the
2790 * perf_event_attr interface. These are kernel core limitation
2791 * not PMU-specific so we can detect with a software event and
2792 * stop on the first one succeeded.
2793 */
2794
2795 /* Please add new feature detection here. */
2796
2797 attr.defer_callchain = true;
2798 if (has_attr_feature(&attr, /*flags=*/0))
2799 goto found;
2800 perf_missing_features.defer_callchain = true;
2801 pr_debug2("switching off deferred callchain support\n");
2802 attr.defer_callchain = false;
2803
2804 attr.inherit = true;
2805 attr.sample_type = PERF_SAMPLE_READ | PERF_SAMPLE_TID;
2806 if (has_attr_feature(&attr, /*flags=*/0))
2807 goto found;
2808 perf_missing_features.inherit_sample_read = true;
2809 pr_debug2("Using PERF_SAMPLE_READ / :S modifier is not compatible with inherit, falling back to no-inherit.\n");
2810 attr.inherit = false;
2811 attr.sample_type = 0;
2812
2813 attr.read_format = PERF_FORMAT_LOST;
2814 if (has_attr_feature(&attr, /*flags=*/0))
2815 goto found;
2816 perf_missing_features.read_lost = true;
2817 pr_debug2("switching off PERF_FORMAT_LOST support\n");
2818 attr.read_format = 0;
2819
2820 attr.sample_type = PERF_SAMPLE_WEIGHT_STRUCT;
2821 if (has_attr_feature(&attr, /*flags=*/0))
2822 goto found;
2823 perf_missing_features.weight_struct = true;
2824 pr_debug2("switching off weight struct support\n");
2825 attr.sample_type = 0;
2826
2827 attr.sample_type = PERF_SAMPLE_CODE_PAGE_SIZE;
2828 if (has_attr_feature(&attr, /*flags=*/0))
2829 goto found;
2830 perf_missing_features.code_page_size = true;
2831 pr_debug2_peo("Kernel has no PERF_SAMPLE_CODE_PAGE_SIZE support\n");
2832 attr.sample_type = 0;
2833
2834 attr.sample_type = PERF_SAMPLE_DATA_PAGE_SIZE;
2835 if (has_attr_feature(&attr, /*flags=*/0))
2836 goto found;
2837 perf_missing_features.data_page_size = true;
2838 pr_debug2_peo("Kernel has no PERF_SAMPLE_DATA_PAGE_SIZE support\n");
2839 attr.sample_type = 0;
2840
2841 attr.cgroup = 1;
2842 if (has_attr_feature(&attr, /*flags=*/0))
2843 goto found;
2844 perf_missing_features.cgroup = true;
2845 pr_debug2_peo("Kernel has no cgroup sampling support\n");
2846 attr.cgroup = 0;
2847
2848 attr.aux_output = 1;
2849 if (has_attr_feature(&attr, /*flags=*/0))
2850 goto found;
2851 perf_missing_features.aux_output = true;
2852 pr_debug2_peo("Kernel has no attr.aux_output support\n");
2853 attr.aux_output = 0;
2854
2855 attr.bpf_event = 1;
2856 if (has_attr_feature(&attr, /*flags=*/0))
2857 goto found;
2858 perf_missing_features.bpf = true;
2859 pr_debug2_peo("switching off bpf_event\n");
2860 attr.bpf_event = 0;
2861
2862 attr.ksymbol = 1;
2863 if (has_attr_feature(&attr, /*flags=*/0))
2864 goto found;
2865 perf_missing_features.ksymbol = true;
2866 pr_debug2_peo("switching off ksymbol\n");
2867 attr.ksymbol = 0;
2868
2869 attr.write_backward = 1;
2870 if (has_attr_feature(&attr, /*flags=*/0))
2871 goto found;
2872 perf_missing_features.write_backward = true;
2873 pr_debug2_peo("switching off write_backward\n");
2874 attr.write_backward = 0;
2875
2876 attr.use_clockid = 1;
2877 attr.clockid = CLOCK_MONOTONIC;
2878 if (has_attr_feature(&attr, /*flags=*/0))
2879 goto found;
2880 perf_missing_features.clockid = true;
2881 pr_debug2_peo("switching off clockid\n");
2882 attr.use_clockid = 0;
2883 attr.clockid = 0;
2884
2885 if (has_attr_feature(&attr, /*flags=*/PERF_FLAG_FD_CLOEXEC))
2886 goto found;
2887 perf_missing_features.cloexec = true;
2888 pr_debug2_peo("switching off cloexec flag\n");
2889
2890 attr.mmap2 = 1;
2891 if (has_attr_feature(&attr, /*flags=*/0))
2892 goto found;
2893 perf_missing_features.mmap2 = true;
2894 pr_debug2_peo("switching off mmap2\n");
2895 attr.mmap2 = 0;
2896
2897 /* set this unconditionally? */
2898 perf_missing_features.sample_id_all = true;
2899 pr_debug2_peo("switching off sample_id_all\n");
2900
2901 attr.inherit = 1;
2902 attr.read_format = PERF_FORMAT_GROUP;
2903 if (has_attr_feature(&attr, /*flags=*/0))
2904 goto found;
2905 perf_missing_features.group_read = true;
2906 pr_debug2_peo("switching off group read\n");
2907 attr.inherit = 0;
2908 attr.read_format = 0;
2909
2910found:
2911 detection_done = true;
2912 errno = old_errno;
2913
2914check:
2915 if ((evsel->core.attr.defer_callchain || evsel->core.attr.defer_output) &&
2916 perf_missing_features.defer_callchain)
2917 return true;
2918
2919 if (evsel->core.attr.inherit &&
2920 (evsel->core.attr.sample_type & PERF_SAMPLE_READ) &&
2921 perf_missing_features.inherit_sample_read)
2922 return true;
2923
2924 if ((evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS) &&
2925 perf_missing_features.branch_counters)
2926 return true;
2927
2928 if ((evsel->core.attr.read_format & PERF_FORMAT_LOST) &&
2929 perf_missing_features.read_lost)
2930 return true;
2931
2932 if ((evsel->core.attr.sample_type & PERF_SAMPLE_WEIGHT_STRUCT) &&
2933 perf_missing_features.weight_struct)
2934 return true;
2935
2936 if (evsel->core.attr.use_clockid && evsel->core.attr.clockid != CLOCK_MONOTONIC &&
2937 !perf_missing_features.clockid) {
2938 perf_missing_features.clockid_wrong = true;
2939 return true;
2940 }
2941
2942 if (evsel->core.attr.use_clockid && perf_missing_features.clockid)
2943 return true;
2944
2945 if ((evsel->open_flags & PERF_FLAG_FD_CLOEXEC) &&
2946 perf_missing_features.cloexec)
2947 return true;
2948
2949 if (evsel->core.attr.mmap2 && perf_missing_features.mmap2)
2950 return true;
2951
2952 if ((evsel->core.attr.branch_sample_type & (PERF_SAMPLE_BRANCH_NO_FLAGS |
2953 PERF_SAMPLE_BRANCH_NO_CYCLES)) &&
2954 perf_missing_features.lbr_flags)
2955 return true;
2956
2957 if (evsel->core.attr.inherit && (evsel->core.attr.read_format & PERF_FORMAT_GROUP) &&
2958 perf_missing_features.group_read)
2959 return true;
2960
2961 if (evsel->core.attr.ksymbol && perf_missing_features.ksymbol)
2962 return true;
2963
2964 if (evsel->core.attr.bpf_event && perf_missing_features.bpf)
2965 return true;
2966
2967 if ((evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX) &&
2968 perf_missing_features.branch_hw_idx)
2969 return true;
2970
2971 if (evsel->core.attr.sample_id_all && perf_missing_features.sample_id_all)
2972 return true;
2973
2974 return false;
2975}
2976
2977static int evsel__open_cpu(struct evsel *evsel, struct perf_cpu_map *cpus,
2978 struct perf_thread_map *threads,
2979 int start_cpu_map_idx, int end_cpu_map_idx)
2980{
2981 int idx, thread, nthreads;
2982 int pid = -1, err, old_errno;
2983 enum rlimit_action set_rlimit = NO_CHANGE;
2984 struct perf_cpu cpu;
2985
2986 if (evsel__is_retire_lat(evsel)) {
2987 err = evsel__tpebs_open(evsel);
2988 goto out;
2989 }
2990
2991 err = __evsel__prepare_open(evsel, cpus, threads);
2992 if (err)
2993 goto out;
2994
2995 if (cpus == NULL)
2996 cpus = empty_cpu_map;
2997
2998 if (threads == NULL)
2999 threads = empty_thread_map;
3000
3001 nthreads = perf_thread_map__nr(threads);
3002
3003 if (evsel->cgrp)
3004 pid = evsel->cgrp->fd;
3005
3006fallback_missing_features:
3007 evsel__disable_missing_features(evsel);
3008
3009 pr_debug3("Opening: %s\n", evsel__name(evsel));
3010 display_attr(&evsel->core.attr);
3011
3012 if (evsel__is_tool(evsel)) {
3013 err = evsel__tool_pmu_open(evsel, threads,
3014 start_cpu_map_idx,
3015 end_cpu_map_idx);
3016 goto out;
3017 }
3018 if (evsel__is_hwmon(evsel)) {
3019 err = evsel__hwmon_pmu_open(evsel, threads,
3020 start_cpu_map_idx,
3021 end_cpu_map_idx);
3022 goto out;
3023 }
3024 if (evsel__is_drm(evsel)) {
3025 err = evsel__drm_pmu_open(evsel, threads,
3026 start_cpu_map_idx,
3027 end_cpu_map_idx);
3028 goto out;
3029 }
3030
3031 for (idx = start_cpu_map_idx; idx < end_cpu_map_idx; idx++) {
3032 cpu = perf_cpu_map__cpu(cpus, idx);
3033
3034 for (thread = 0; thread < nthreads; thread++) {
3035 int fd, group_fd;
3036retry_open:
3037 if (thread >= nthreads)
3038 break;
3039
3040 if (!evsel->cgrp && !evsel->core.system_wide)
3041 pid = perf_thread_map__pid(threads, thread);
3042
3043 group_fd = get_group_fd(evsel, idx, thread);
3044
3045 if (group_fd == -2) {
3046 pr_debug("broken group leader for %s\n", evsel->name);
3047 err = -EINVAL;
3048 goto out_close;
3049 }
3050
3051 /* Debug message used by test scripts */
3052 pr_debug2_peo("sys_perf_event_open: pid %d cpu %d group_fd %d flags %#lx",
3053 pid, cpu.cpu, group_fd, evsel->open_flags);
3054
3055 fd = sys_perf_event_open(&evsel->core.attr, pid, cpu.cpu,
3056 group_fd, evsel->open_flags);
3057
3058 FD(evsel, idx, thread) = fd;
3059
3060 if (fd < 0) {
3061 err = -errno;
3062
3063 pr_debug2_peo("\nsys_perf_event_open failed, error %d\n",
3064 err);
3065 goto try_fallback;
3066 }
3067
3068 bpf_counter__install_pe(evsel, idx, fd);
3069
3070 if (unlikely(test_attr__enabled())) {
3071 test_attr__open(&evsel->core.attr, pid, cpu,
3072 fd, group_fd, evsel->open_flags);
3073 }
3074
3075 /* Debug message used by test scripts */
3076 pr_debug2_peo(" = %d\n", fd);
3077
3078 set_rlimit = NO_CHANGE;
3079
3080 /*
3081 * If we succeeded but had to kill clockid, fail and
3082 * have evsel__open_strerror() print us a nice error.
3083 */
3084 if (perf_missing_features.clockid ||
3085 perf_missing_features.clockid_wrong) {
3086 err = -EINVAL;
3087 goto out_close;
3088 }
3089 }
3090 }
3091
3092 err = 0;
3093 goto out;
3094
3095try_fallback:
3096 if (evsel__ignore_missing_thread(evsel, perf_cpu_map__nr(cpus),
3097 idx, threads, thread, err)) {
3098 /* We just removed 1 thread, so lower the upper nthreads limit. */
3099 nthreads--;
3100
3101 /* ... and pretend like nothing have happened. */
3102 err = 0;
3103 goto retry_open;
3104 }
3105 /*
3106 * perf stat needs between 5 and 22 fds per CPU. When we run out
3107 * of them try to increase the limits.
3108 */
3109 if (err == -EMFILE && rlimit__increase_nofile(&set_rlimit))
3110 goto retry_open;
3111
3112 if (err == -EINVAL && evsel__detect_missing_features(evsel, cpu))
3113 goto fallback_missing_features;
3114
3115 if (evsel__precise_ip_fallback(evsel))
3116 goto retry_open;
3117
3118out_close:
3119 if (err)
3120 threads->err_thread = thread;
3121
3122 old_errno = errno;
3123 do {
3124 while (--thread >= 0) {
3125 if (FD(evsel, idx, thread) >= 0)
3126 close(FD(evsel, idx, thread));
3127 FD(evsel, idx, thread) = -1;
3128 }
3129 thread = nthreads;
3130 } while (--idx >= 0);
3131 errno = old_errno;
3132out:
3133 if (err)
3134 evsel->supported = false;
3135 return err;
3136}
3137
3138int evsel__open(struct evsel *evsel, struct perf_cpu_map *cpus,
3139 struct perf_thread_map *threads)
3140{
3141 return evsel__open_cpu(evsel, cpus, threads, 0, perf_cpu_map__nr(cpus));
3142}
3143
3144void evsel__close(struct evsel *evsel)
3145{
3146 if (evsel__is_retire_lat(evsel))
3147 evsel__tpebs_close(evsel);
3148 perf_evsel__close(&evsel->core);
3149 perf_evsel__free_id(&evsel->core);
3150}
3151
3152int evsel__open_per_cpu_and_thread(struct evsel *evsel,
3153 struct perf_cpu_map *cpus, int cpu_map_idx,
3154 struct perf_thread_map *threads)
3155{
3156 if (cpu_map_idx == -1)
3157 return evsel__open_cpu(evsel, cpus, threads, 0, perf_cpu_map__nr(cpus));
3158
3159 return evsel__open_cpu(evsel, cpus, threads, cpu_map_idx, cpu_map_idx + 1);
3160}
3161
3162int evsel__open_per_cpu(struct evsel *evsel, struct perf_cpu_map *cpus, int cpu_map_idx)
3163{
3164 struct perf_thread_map *threads = thread_map__new_by_tid(-1);
3165 int ret = evsel__open_per_cpu_and_thread(evsel, cpus, cpu_map_idx, threads);
3166
3167 perf_thread_map__put(threads);
3168 return ret;
3169}
3170
3171int evsel__open_per_thread(struct evsel *evsel, struct perf_thread_map *threads)
3172{
3173 struct perf_cpu_map *cpus = perf_cpu_map__new_any_cpu();
3174 int ret = evsel__open_per_cpu_and_thread(evsel, cpus, -1, threads);
3175
3176 perf_cpu_map__put(cpus);
3177 return ret;
3178}
3179
3180static int perf_evsel__parse_id_sample(const union perf_event *event,
3181 struct perf_sample *sample)
3182{
3183 const struct evsel *evsel = sample->evsel;
3184 u64 type = evsel->core.attr.sample_type;
3185 const __u64 *array = event->sample.array;
3186 bool swapped = evsel->needs_swap;
3187 union u64_swap u;
3188 int i = ((event->header.size - sizeof(event->header)) / sizeof(u64)) - 1;
3189
3190 if (type & PERF_SAMPLE_IDENTIFIER) {
3191 if (i < 0)
3192 return -EFAULT;
3193
3194 sample->id = array[i--];
3195 }
3196
3197 if (type & PERF_SAMPLE_CPU) {
3198 if (i < 0)
3199 return -EFAULT;
3200
3201 u.val64 = array[i--];
3202 if (swapped) {
3203 /* undo swap of u64, then swap on individual u32s */
3204 u.val64 = bswap_64(u.val64);
3205 u.val32[0] = bswap_32(u.val32[0]);
3206 }
3207 sample->cpu = u.val32[0];
3208 }
3209
3210 if (type & PERF_SAMPLE_STREAM_ID) {
3211 if (i < 0)
3212 return -EFAULT;
3213
3214 sample->stream_id = array[i--];
3215 }
3216
3217 if (type & PERF_SAMPLE_ID) {
3218 if (i < 0)
3219 return -EFAULT;
3220
3221 sample->id = array[i--];
3222 }
3223
3224 if (type & PERF_SAMPLE_TIME) {
3225 if (i < 0)
3226 return -EFAULT;
3227
3228 sample->time = array[i--];
3229 }
3230
3231 if (type & PERF_SAMPLE_TID) {
3232 if (i < 0)
3233 return -EFAULT;
3234
3235 u.val64 = array[i--];
3236 if (swapped) {
3237 /* undo swap of u64, then swap on individual u32s */
3238 u.val64 = bswap_64(u.val64);
3239 u.val32[0] = bswap_32(u.val32[0]);
3240 u.val32[1] = bswap_32(u.val32[1]);
3241 }
3242
3243 sample->pid = u.val32[0];
3244 sample->tid = u.val32[1];
3245 }
3246
3247 return 0;
3248}
3249
3250static inline bool overflow(const void *endp, u16 max_size, const void *offset,
3251 u64 size)
3252{
3253 return size > max_size || offset + size > endp;
3254}
3255
3256#define OVERFLOW_CHECK(offset, size, max_size) \
3257 do { \
3258 if (overflow(endp, (max_size), (offset), (size))) \
3259 goto out_efault; \
3260 } while (0)
3261
3262#define OVERFLOW_CHECK_u64(offset) \
3263 OVERFLOW_CHECK(offset, sizeof(u64), sizeof(u64))
3264
3265static int
3266perf_event__check_size(union perf_event *event, unsigned int sample_size)
3267{
3268 /*
3269 * The evsel's sample_size is based on PERF_SAMPLE_MASK which includes
3270 * up to PERF_SAMPLE_PERIOD. After that overflow() must be used to
3271 * check the format does not go past the end of the event.
3272 */
3273 if (sample_size + sizeof(event->header) > event->header.size)
3274 return -EFAULT;
3275
3276 return 0;
3277}
3278
3279static void perf_parse_sample_weight(struct perf_sample *data, const __u64 *array, u64 type)
3280{
3281 union perf_sample_weight weight;
3282
3283 weight.full = *array;
3284 if (type & PERF_SAMPLE_WEIGHT_STRUCT) {
3285 data->weight = weight.var1_dw;
3286 data->ins_lat = weight.var2_w;
3287 data->weight3 = weight.var3_w;
3288 } else {
3289 data->weight = weight.full;
3290 }
3291}
3292
3293u64 evsel__bitfield_swap_branch_flags(u64 value)
3294{
3295 u64 new_val = 0;
3296
3297 /*
3298 * branch_flags
3299 * union {
3300 * u64 values;
3301 * struct {
3302 * mispred:1 //target mispredicted
3303 * predicted:1 //target predicted
3304 * in_tx:1 //in transaction
3305 * abort:1 //transaction abort
3306 * cycles:16 //cycle count to last branch
3307 * type:4 //branch type
3308 * spec:2 //branch speculation info
3309 * new_type:4 //additional branch type
3310 * priv:3 //privilege level
3311 * reserved:31
3312 * }
3313 * }
3314 *
3315 * Avoid bswap64() the entire branch_flag.value,
3316 * as it has variable bit-field sizes. Instead the
3317 * macro takes the bit-field position/size,
3318 * swaps it based on the host endianness.
3319 */
3320 if (host_is_bigendian()) {
3321 new_val = bitfield_swap(value, 0, 1);
3322 new_val |= bitfield_swap(value, 1, 1);
3323 new_val |= bitfield_swap(value, 2, 1);
3324 new_val |= bitfield_swap(value, 3, 1);
3325 new_val |= bitfield_swap(value, 4, 16);
3326 new_val |= bitfield_swap(value, 20, 4);
3327 new_val |= bitfield_swap(value, 24, 2);
3328 new_val |= bitfield_swap(value, 26, 4);
3329 new_val |= bitfield_swap(value, 30, 3);
3330 new_val |= bitfield_swap(value, 33, 31);
3331 } else {
3332 new_val = bitfield_swap(value, 63, 1);
3333 new_val |= bitfield_swap(value, 62, 1);
3334 new_val |= bitfield_swap(value, 61, 1);
3335 new_val |= bitfield_swap(value, 60, 1);
3336 new_val |= bitfield_swap(value, 44, 16);
3337 new_val |= bitfield_swap(value, 40, 4);
3338 new_val |= bitfield_swap(value, 38, 2);
3339 new_val |= bitfield_swap(value, 34, 4);
3340 new_val |= bitfield_swap(value, 31, 3);
3341 new_val |= bitfield_swap(value, 0, 31);
3342 }
3343
3344 return new_val;
3345}
3346
3347static inline bool evsel__has_branch_counters(const struct evsel *evsel)
3348{
3349 struct evsel *leader = evsel__leader(evsel);
3350
3351 /* The branch counters feature only supports group */
3352 if (!leader || !evsel->evlist)
3353 return false;
3354
3355 if (evlist__nr_br_cntr(evsel->evlist) < 0)
3356 evlist__update_br_cntr(evsel->evlist);
3357
3358 if (leader->br_cntr_nr > 0)
3359 return true;
3360
3361 return false;
3362}
3363
3364static int __set_offcpu_sample(struct perf_sample *data)
3365{
3366 u64 *array = data->raw_data;
3367 u32 max_size = data->raw_size, *p32;
3368 const void *endp = (void *)array + max_size;
3369
3370 if (array == NULL)
3371 return -EFAULT;
3372
3373 OVERFLOW_CHECK_u64(array);
3374 p32 = (void *)array++;
3375 data->pid = p32[0];
3376 data->tid = p32[1];
3377
3378 OVERFLOW_CHECK_u64(array);
3379 data->period = *array++;
3380
3381 OVERFLOW_CHECK_u64(array);
3382 data->callchain = (struct ip_callchain *)array++;
3383 OVERFLOW_CHECK(array, data->callchain->nr * sizeof(u64), max_size);
3384 data->ip = data->callchain->ips[1];
3385 array += data->callchain->nr;
3386
3387 OVERFLOW_CHECK_u64(array);
3388 data->cgroup = *array;
3389
3390 return 0;
3391out_efault:
3392 return -EFAULT;
3393}
3394
3395int __evsel__parse_sample(struct evsel *evsel, union perf_event *event,
3396 struct perf_sample *data, bool needs_swap)
3397{
3398 u64 type = evsel->core.attr.sample_type;
3399 bool swapped = needs_swap;
3400 const __u64 *array;
3401 u16 max_size = event->header.size;
3402 const void *endp = (void *)event + max_size;
3403 u64 sz;
3404
3405 /*
3406 * used for cross-endian analysis. See git commit 65014ab3
3407 * for why this goofiness is needed.
3408 */
3409 union u64_swap u;
3410
3411 perf_sample__init(data, /*all=*/true);
3412 data->evsel = evsel__get(evsel);
3413 data->cpu = data->pid = data->tid = -1;
3414 data->stream_id = data->id = data->time = -1ULL;
3415 data->period = evsel->core.attr.sample_period;
3416 data->cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
3417 data->misc = event->header.misc;
3418 data->data_src = PERF_MEM_DATA_SRC_NONE;
3419 data->vcpu = -1;
3420
3421 if (event->header.type == PERF_RECORD_CALLCHAIN_DEFERRED) {
3422 const u64 max_callchain_nr = UINT64_MAX / sizeof(u64);
3423
3424 data->callchain = (struct ip_callchain *)&event->callchain_deferred.nr;
3425 if (data->callchain->nr > max_callchain_nr)
3426 goto out_efault;
3427
3428 data->deferred_cookie = event->callchain_deferred.cookie;
3429
3430 if (evsel->core.attr.sample_id_all) {
3431 if (perf_evsel__parse_id_sample(event, data))
3432 goto out_efault;
3433 }
3434 return 0;
3435 }
3436
3437 if (event->header.type != PERF_RECORD_SAMPLE) {
3438 if (evsel->core.attr.sample_id_all) {
3439 if (perf_evsel__parse_id_sample(event, data))
3440 goto out_efault;
3441 }
3442 return 0;
3443 }
3444
3445 array = event->sample.array;
3446
3447 if (perf_event__check_size(event, evsel->sample_size))
3448 goto out_efault;
3449
3450 if (type & PERF_SAMPLE_IDENTIFIER) {
3451 data->id = *array;
3452 array++;
3453 }
3454
3455 if (type & PERF_SAMPLE_IP) {
3456 data->ip = *array;
3457 array++;
3458 }
3459
3460 if (type & PERF_SAMPLE_TID) {
3461 u.val64 = *array;
3462 if (swapped) {
3463 /* undo swap of u64, then swap on individual u32s */
3464 u.val64 = bswap_64(u.val64);
3465 u.val32[0] = bswap_32(u.val32[0]);
3466 u.val32[1] = bswap_32(u.val32[1]);
3467 }
3468
3469 data->pid = u.val32[0];
3470 data->tid = u.val32[1];
3471 array++;
3472 }
3473
3474 if (type & PERF_SAMPLE_TIME) {
3475 data->time = *array;
3476 array++;
3477 }
3478
3479 if (type & PERF_SAMPLE_ADDR) {
3480 data->addr = *array;
3481 array++;
3482 }
3483
3484 if (type & PERF_SAMPLE_ID) {
3485 data->id = *array;
3486 array++;
3487 }
3488
3489 if (type & PERF_SAMPLE_STREAM_ID) {
3490 data->stream_id = *array;
3491 array++;
3492 }
3493
3494 if (type & PERF_SAMPLE_CPU) {
3495
3496 u.val64 = *array;
3497 if (swapped) {
3498 /* undo swap of u64, then swap on individual u32s */
3499 u.val64 = bswap_64(u.val64);
3500 u.val32[0] = bswap_32(u.val32[0]);
3501 }
3502
3503 data->cpu = u.val32[0];
3504 array++;
3505 }
3506
3507 if (type & PERF_SAMPLE_PERIOD) {
3508 data->period = *array;
3509 array++;
3510 }
3511
3512 if (type & PERF_SAMPLE_READ) {
3513 u64 read_format = evsel->core.attr.read_format;
3514
3515 OVERFLOW_CHECK_u64(array);
3516 if (read_format & PERF_FORMAT_GROUP)
3517 data->read.group.nr = *array;
3518 else
3519 data->read.one.value = *array;
3520
3521 array++;
3522
3523 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3524 OVERFLOW_CHECK_u64(array);
3525 data->read.time_enabled = *array;
3526 array++;
3527 }
3528
3529 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3530 OVERFLOW_CHECK_u64(array);
3531 data->read.time_running = *array;
3532 array++;
3533 }
3534
3535 /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
3536 if (read_format & PERF_FORMAT_GROUP) {
3537 const u64 max_group_nr = UINT64_MAX /
3538 sizeof(struct sample_read_value);
3539
3540 if (data->read.group.nr > max_group_nr)
3541 goto out_efault;
3542
3543 sz = data->read.group.nr * sample_read_value_size(read_format);
3544 OVERFLOW_CHECK(array, sz, max_size);
3545 data->read.group.values =
3546 (struct sample_read_value *)array;
3547 array = (void *)array + sz;
3548 } else {
3549 OVERFLOW_CHECK_u64(array);
3550 data->read.one.id = *array;
3551 array++;
3552
3553 if (read_format & PERF_FORMAT_LOST) {
3554 OVERFLOW_CHECK_u64(array);
3555 data->read.one.lost = *array;
3556 array++;
3557 }
3558 }
3559 }
3560
3561 if (type & PERF_SAMPLE_CALLCHAIN) {
3562 const u64 max_callchain_nr = UINT64_MAX / sizeof(u64);
3563 u64 callchain_nr;
3564
3565 OVERFLOW_CHECK_u64(array);
3566 data->callchain = (struct ip_callchain *)array++;
3567 callchain_nr = data->callchain->nr;
3568 if (callchain_nr > max_callchain_nr)
3569 goto out_efault;
3570 sz = callchain_nr * sizeof(u64);
3571 /*
3572 * Save the cookie for the deferred user callchain. The last 2
3573 * entries in the callchain should be the context marker and the
3574 * cookie. The cookie will be used to match PERF_RECORD_
3575 * CALLCHAIN_DEFERRED later.
3576 */
3577 if (evsel->core.attr.defer_callchain && callchain_nr >= 2 &&
3578 data->callchain->ips[callchain_nr - 2] == PERF_CONTEXT_USER_DEFERRED) {
3579 data->deferred_cookie = data->callchain->ips[callchain_nr - 1];
3580 data->deferred_callchain = true;
3581 }
3582 OVERFLOW_CHECK(array, sz, max_size);
3583 array = (void *)array + sz;
3584 }
3585
3586 if (type & PERF_SAMPLE_RAW) {
3587 OVERFLOW_CHECK_u64(array);
3588 u.val64 = *array;
3589
3590 /*
3591 * Undo swap of u64, then swap on individual u32s,
3592 * get the size of the raw area and undo all of the
3593 * swap. The pevent interface handles endianness by
3594 * itself.
3595 */
3596 if (swapped) {
3597 u.val64 = bswap_64(u.val64);
3598 u.val32[0] = bswap_32(u.val32[0]);
3599 u.val32[1] = bswap_32(u.val32[1]);
3600 }
3601 data->raw_size = u.val32[0];
3602
3603 /*
3604 * The raw data is aligned on 64bits including the
3605 * u32 size, so it's safe to use mem_bswap_64.
3606 */
3607 if (swapped)
3608 mem_bswap_64((void *) array, data->raw_size);
3609
3610 array = (void *)array + sizeof(u32);
3611
3612 OVERFLOW_CHECK(array, data->raw_size, max_size);
3613 data->raw_data = (void *)array;
3614 array = (void *)array + data->raw_size;
3615 }
3616
3617 if (type & PERF_SAMPLE_BRANCH_STACK) {
3618 const u64 max_branch_nr = UINT64_MAX /
3619 sizeof(struct branch_entry);
3620 struct branch_entry *e;
3621 unsigned int i;
3622
3623 OVERFLOW_CHECK_u64(array);
3624 data->branch_stack = (struct branch_stack *)array++;
3625
3626 if (data->branch_stack->nr > max_branch_nr)
3627 goto out_efault;
3628
3629 sz = data->branch_stack->nr * sizeof(struct branch_entry);
3630 if (evsel__has_branch_hw_idx(evsel)) {
3631 sz += sizeof(u64);
3632 e = &data->branch_stack->entries[0];
3633 } else {
3634 data->no_hw_idx = true;
3635 /*
3636 * if the PERF_SAMPLE_BRANCH_HW_INDEX is not applied,
3637 * only nr and entries[] will be output by kernel.
3638 */
3639 e = (struct branch_entry *)&data->branch_stack->hw_idx;
3640 }
3641
3642 if (swapped) {
3643 /*
3644 * struct branch_flag does not have endian
3645 * specific bit field definition. And bswap
3646 * will not resolve the issue, since these
3647 * are bit fields.
3648 *
3649 * evsel__bitfield_swap_branch_flags() uses a
3650 * bitfield_swap macro to swap the bit position
3651 * based on the host endians.
3652 */
3653 for (i = 0; i < data->branch_stack->nr; i++, e++)
3654 e->flags.value = evsel__bitfield_swap_branch_flags(e->flags.value);
3655 }
3656
3657 OVERFLOW_CHECK(array, sz, max_size);
3658 array = (void *)array + sz;
3659
3660 if (evsel__has_branch_counters(evsel)) {
3661 data->branch_stack_cntr = (u64 *)array;
3662 sz = data->branch_stack->nr * sizeof(u64);
3663
3664 OVERFLOW_CHECK(array, sz, max_size);
3665 array = (void *)array + sz;
3666 }
3667 }
3668
3669 if (type & PERF_SAMPLE_REGS_USER) {
3670 struct regs_dump *regs = perf_sample__user_regs(data);
3671
3672 OVERFLOW_CHECK_u64(array);
3673 regs->abi = *array;
3674 array++;
3675
3676 if (regs->abi) {
3677 u64 mask = evsel->core.attr.sample_regs_user;
3678
3679 sz = hweight64(mask) * sizeof(u64);
3680 OVERFLOW_CHECK(array, sz, max_size);
3681 regs->mask = mask;
3682 regs->regs = (u64 *)array;
3683 array = (void *)array + sz;
3684 }
3685 }
3686
3687 if (type & PERF_SAMPLE_STACK_USER) {
3688 OVERFLOW_CHECK_u64(array);
3689 sz = *array++;
3690
3691 data->user_stack.offset = ((char *)(array - 1)
3692 - (char *) event);
3693
3694 if (!sz) {
3695 data->user_stack.size = 0;
3696 } else {
3697 OVERFLOW_CHECK(array, sz, max_size);
3698 data->user_stack.data = (char *)array;
3699 array = (void *)array + sz;
3700 OVERFLOW_CHECK_u64(array);
3701 data->user_stack.size = *array++;
3702 if (WARN_ONCE(data->user_stack.size > sz,
3703 "user stack dump failure\n"))
3704 goto out_efault;
3705 }
3706 }
3707
3708 if (type & PERF_SAMPLE_WEIGHT_TYPE) {
3709 OVERFLOW_CHECK_u64(array);
3710 perf_parse_sample_weight(data, array, type);
3711 array++;
3712 }
3713
3714 if (type & PERF_SAMPLE_DATA_SRC) {
3715 OVERFLOW_CHECK_u64(array);
3716 data->data_src = *array;
3717 array++;
3718 }
3719
3720 if (type & PERF_SAMPLE_TRANSACTION) {
3721 OVERFLOW_CHECK_u64(array);
3722 data->transaction = *array;
3723 array++;
3724 }
3725
3726 if (type & PERF_SAMPLE_REGS_INTR) {
3727 struct regs_dump *regs = perf_sample__intr_regs(data);
3728
3729 OVERFLOW_CHECK_u64(array);
3730 regs->abi = *array;
3731 array++;
3732
3733 if (regs->abi != PERF_SAMPLE_REGS_ABI_NONE) {
3734 u64 mask = evsel->core.attr.sample_regs_intr;
3735
3736 sz = hweight64(mask) * sizeof(u64);
3737 OVERFLOW_CHECK(array, sz, max_size);
3738 regs->mask = mask;
3739 regs->regs = (u64 *)array;
3740 array = (void *)array + sz;
3741 }
3742 }
3743
3744 data->phys_addr = 0;
3745 if (type & PERF_SAMPLE_PHYS_ADDR) {
3746 data->phys_addr = *array;
3747 array++;
3748 }
3749
3750 data->cgroup = 0;
3751 if (type & PERF_SAMPLE_CGROUP) {
3752 data->cgroup = *array;
3753 array++;
3754 }
3755
3756 data->data_page_size = 0;
3757 if (type & PERF_SAMPLE_DATA_PAGE_SIZE) {
3758 data->data_page_size = *array;
3759 array++;
3760 }
3761
3762 data->code_page_size = 0;
3763 if (type & PERF_SAMPLE_CODE_PAGE_SIZE) {
3764 data->code_page_size = *array;
3765 array++;
3766 }
3767
3768 if (type & PERF_SAMPLE_AUX) {
3769 OVERFLOW_CHECK_u64(array);
3770 sz = *array++;
3771
3772 OVERFLOW_CHECK(array, sz, max_size);
3773 /* Undo swap of data */
3774 if (swapped)
3775 mem_bswap_64((char *)array, sz);
3776 data->aux_sample.size = sz;
3777 data->aux_sample.data = (char *)array;
3778 array = (void *)array + sz;
3779 }
3780
3781 if (evsel__is_offcpu_event(evsel)) {
3782 if (__set_offcpu_sample(data))
3783 goto out_efault;
3784 }
3785
3786 return 0;
3787out_efault:
3788 perf_sample__exit(data);
3789 return -EFAULT;
3790}
3791
3792int evsel__parse_sample_timestamp(struct evsel *evsel, union perf_event *event,
3793 u64 *timestamp)
3794{
3795 u64 type = evsel->core.attr.sample_type;
3796 const __u64 *array;
3797
3798 if (!(type & PERF_SAMPLE_TIME))
3799 return -1;
3800
3801 if (event->header.type != PERF_RECORD_SAMPLE) {
3802 struct perf_sample data = {
3803 .evsel = evsel,
3804 .time = -1ULL,
3805 };
3806
3807 if (!evsel->core.attr.sample_id_all)
3808 return -1;
3809 if (perf_evsel__parse_id_sample(event, &data))
3810 return -1;
3811
3812 *timestamp = data.time;
3813 return 0;
3814 }
3815
3816 array = event->sample.array;
3817
3818 if (perf_event__check_size(event, evsel->sample_size))
3819 return -EFAULT;
3820
3821 if (type & PERF_SAMPLE_IDENTIFIER)
3822 array++;
3823
3824 if (type & PERF_SAMPLE_IP)
3825 array++;
3826
3827 if (type & PERF_SAMPLE_TID)
3828 array++;
3829
3830 if (type & PERF_SAMPLE_TIME)
3831 *timestamp = *array;
3832
3833 return 0;
3834}
3835
3836u16 evsel__id_hdr_size(const struct evsel *evsel)
3837{
3838 u64 sample_type = evsel->core.attr.sample_type;
3839 u16 size = 0;
3840
3841 if (sample_type & PERF_SAMPLE_TID)
3842 size += sizeof(u64);
3843
3844 if (sample_type & PERF_SAMPLE_TIME)
3845 size += sizeof(u64);
3846
3847 if (sample_type & PERF_SAMPLE_ID)
3848 size += sizeof(u64);
3849
3850 if (sample_type & PERF_SAMPLE_STREAM_ID)
3851 size += sizeof(u64);
3852
3853 if (sample_type & PERF_SAMPLE_CPU)
3854 size += sizeof(u64);
3855
3856 if (sample_type & PERF_SAMPLE_IDENTIFIER)
3857 size += sizeof(u64);
3858
3859 return size;
3860}
3861
3862#ifdef HAVE_LIBTRACEEVENT
3863struct tep_format_field *evsel__field(struct evsel *evsel, const char *name)
3864{
3865 struct tep_event *tp_format = evsel__tp_format(evsel);
3866
3867 return tp_format ? tep_find_field(tp_format, name) : NULL;
3868}
3869
3870struct tep_format_field *evsel__common_field(struct evsel *evsel, const char *name)
3871{
3872 struct tep_event *tp_format = evsel__tp_format(evsel);
3873
3874 return tp_format ? tep_find_common_field(tp_format, name) : NULL;
3875}
3876
3877static bool out_of_bounds(const struct tep_format_field *field, int offset, int size, u32 raw_size)
3878{
3879 if (offset < 0) {
3880 pr_warning("Negative trace point field offset %d in %s\n",
3881 offset, field->name);
3882 return true;
3883 }
3884 if (size < 0) {
3885 pr_warning("Negative trace point field size %d in %s\n",
3886 size, field->name);
3887 return true;
3888 }
3889 if ((u32)offset + (u32)size > raw_size) {
3890 pr_warning("Out of bound tracepoint field (%s) offset %d size %d in %u\n",
3891 field->name, offset, size, raw_size);
3892 return true;
3893 }
3894 return false;
3895}
3896
3897void *perf_sample__rawptr(struct perf_sample *sample, const char *name)
3898{
3899 struct tep_format_field *field = evsel__field(sample->evsel, name);
3900 int offset, size;
3901
3902 if (!field)
3903 return NULL;
3904
3905 offset = field->offset;
3906 size = field->size;
3907 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
3908 int dynamic_data;
3909
3910 if (out_of_bounds(field, offset, 4, sample->raw_size))
3911 return NULL;
3912
3913 dynamic_data = *(int *)(sample->raw_data + field->offset);
3914
3915 if (sample->evsel->needs_swap)
3916 dynamic_data = bswap_32(dynamic_data);
3917
3918 offset = dynamic_data & 0xffff;
3919 size = (dynamic_data >> 16) & 0xffff;
3920
3921 if (tep_field_is_relative(field->flags)) {
3922 /*
3923 * Newer kernel feature: Relative offsets (__rel_loc).
3924 * If the relative flag is set, the parsed offset is not
3925 * absolute from the start of the record. Instead, it is
3926 * relative to the *end* of the dynamic field descriptor
3927 * itself.
3928 */
3929 offset += field->offset + field->size;
3930 }
3931 }
3932 if (out_of_bounds(field, offset, size, sample->raw_size))
3933 return NULL;
3934
3935 return sample->raw_data + offset;
3936}
3937
3938void *format_field__get_raw_data(struct tep_format_field *field, struct
3939 perf_sample *sample, bool needs_swap,
3940 u16 *len_out)
3941{
3942 int offset = field->offset;
3943 int size = field->size;
3944
3945 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
3946 unsigned int dynamic_data;
3947
3948 if (out_of_bounds(field, field->offset, field->size, sample->raw_size))
3949 return NULL;
3950
3951 dynamic_data = format_field__intval(field, sample, needs_swap);
3952
3953 offset = dynamic_data & 0xffff;
3954 size = (dynamic_data >> 16) & 0xffff;
3955
3956 if (tep_field_is_relative(field->flags))
3957 offset += field->offset + field->size;
3958 }
3959
3960 if (out_of_bounds(field, offset, size, sample->raw_size))
3961 return NULL;
3962
3963 *len_out = size;
3964 return sample->raw_data + offset;
3965}
3966
3967unsigned long *format_field__get_cpumask(struct tep_format_field *field,
3968 struct perf_sample *sample,
3969 bool needs_swap, u16 *len_out)
3970{
3971 u16 len;
3972 void *ptr = format_field__get_raw_data(field, sample, needs_swap, &len);
3973 unsigned long *mask;
3974 struct perf_env *env;
3975 bool target_is_64;
3976 int target_word_size;
3977 int nr_words;
3978 int bit_idx;
3979 int nbits;
3980
3981 if (!ptr)
3982 return NULL;
3983
3984 nbits = len * 8;
3985 mask = bitmap_zalloc(nbits ?: 1);
3986 if (!mask)
3987 return NULL;
3988
3989 env = evsel__env(sample->evsel);
3990 target_is_64 = env ? perf_env__kernel_is_64_bit(env) : (sizeof(void *) == 8);
3991 target_word_size = target_is_64 ? 8 : 4;
3992 nr_words = len / target_word_size;
3993
3994 for (bit_idx = 0; bit_idx < nbits; bit_idx++) {
3995 int w_idx = bit_idx / (target_word_size * 8);
3996 int bit_in_word = bit_idx % (target_word_size * 8);
3997 bool set = false;
3998
3999 if (w_idx >= nr_words)
4000 break;
4001
4002 if (target_is_64) {
4003 u64 word;
4004 memcpy(&word, (unsigned char *)ptr + w_idx * 8, 8);
4005 if (needs_swap)
4006 word = bswap_64(word);
4007 set = (word & (1ULL << bit_in_word)) != 0;
4008 } else {
4009 u32 word32;
4010 memcpy(&word32, (unsigned char *)ptr + w_idx * 4, 4);
4011 if (needs_swap)
4012 word32 = bswap_32(word32);
4013 set = (word32 & (1U << bit_in_word)) != 0;
4014 }
4015
4016 if (set) {
4017 int host_w_idx = bit_idx / BITS_PER_LONG;
4018 int host_bit_in_word = bit_idx % BITS_PER_LONG;
4019 mask[host_w_idx] |= (1UL << host_bit_in_word);
4020 }
4021 }
4022
4023 *len_out = len;
4024 return mask;
4025}
4026
4027u64 format_field__intval(struct tep_format_field *field, struct perf_sample *sample,
4028 bool needs_swap)
4029{
4030 u64 value;
4031 void *ptr = sample->raw_data + field->offset;
4032
4033 if (out_of_bounds(field, field->offset, field->size, sample->raw_size))
4034 return 0;
4035
4036 switch (field->size) {
4037 case 1:
4038 return *(u8 *)ptr;
4039 case 2:
4040 value = *(u16 *)ptr;
4041 break;
4042 case 4:
4043 value = *(u32 *)ptr;
4044 break;
4045 case 8:
4046 memcpy(&value, ptr, sizeof(u64));
4047 break;
4048 default:
4049 return 0;
4050 }
4051
4052 if (!needs_swap)
4053 return value;
4054
4055 switch (field->size) {
4056 case 2:
4057 return bswap_16(value);
4058 case 4:
4059 return bswap_32(value);
4060 case 8:
4061 return bswap_64(value);
4062 default:
4063 return 0;
4064 }
4065
4066 return 0;
4067}
4068
4069u64 perf_sample__intval(struct perf_sample *sample, const char *name)
4070{
4071 struct tep_format_field *field = evsel__field(sample->evsel, name);
4072
4073 return field ? format_field__intval(field, sample, sample->evsel->needs_swap) : 0;
4074}
4075
4076u64 perf_sample__intval_common(struct perf_sample *sample, const char *name)
4077{
4078 struct tep_format_field *field = evsel__common_field(sample->evsel, name);
4079
4080 return field ? format_field__intval(field, sample, sample->evsel->needs_swap) : 0;
4081}
4082
4083char perf_sample__taskstate(struct perf_sample *sample, const char *name)
4084{
4085 static struct tep_format_field *prev_state_field;
4086 static const char *states;
4087 struct tep_format_field *field;
4088 unsigned long long val;
4089 unsigned int bit;
4090 char state = '?'; /* '?' denotes unknown task state */
4091
4092 field = evsel__field(sample->evsel, name);
4093
4094 if (!field)
4095 return state;
4096
4097 if (!states || field != prev_state_field) {
4098 states = parse_task_states(field);
4099 if (!states)
4100 return state;
4101 prev_state_field = field;
4102 }
4103
4104 /*
4105 * Note since the kernel exposes TASK_REPORT_MAX to userspace
4106 * to denote the 'preempted' state, we might as welll report
4107 * 'R' for this case, which make senses to users as well.
4108 *
4109 * We can change this if we have a good reason in the future.
4110 */
4111 val = perf_sample__intval(sample, name);
4112 bit = val ? ffs(val) : 0;
4113 state = (!bit || bit > strlen(states)) ? 'R' : states[bit-1];
4114 return state;
4115}
4116#endif
4117
4118bool evsel__fallback(struct evsel *evsel, struct target *target, int err,
4119 char *msg, size_t msgsize)
4120{
4121 int paranoid;
4122
4123 if ((err == ENODEV || err == ENOENT || err == ENXIO) &&
4124 evsel__match(evsel, HARDWARE, HW_CPU_CYCLES)) {
4125 /*
4126 * If it's the legacy hardware cycles event fails then fall back
4127 * to hrtimer based cpu-clock sw counter, which is always
4128 * available even if no PMU support. PPC returned ENXIO rather
4129 * than ENODEV or ENOENT until 2.6.37.
4130 */
4131 evsel->pmu = perf_pmus__find_by_type(PERF_TYPE_SOFTWARE);
4132 assert(evsel->pmu); /* software is a "well-known" and can't fail PMU type. */
4133
4134 /* Configure the event. */
4135 evsel->core.attr.type = PERF_TYPE_SOFTWARE;
4136 evsel->core.attr.config = target__has_cpu(target)
4137 ? PERF_COUNT_SW_CPU_CLOCK
4138 : PERF_COUNT_SW_TASK_CLOCK;
4139 evsel->core.is_pmu_core = false;
4140
4141 /* Remove excludes for new event. */
4142 if (evsel->fallenback_eacces) {
4143 evsel->core.attr.exclude_kernel = 0;
4144 evsel->core.attr.exclude_hv = 0;
4145 evsel->fallenback_eacces = false;
4146 }
4147 if (evsel->fallenback_eopnotsupp) {
4148 evsel->core.attr.exclude_guest = 0;
4149 evsel->fallenback_eopnotsupp = false;
4150 }
4151
4152 /* Name is recomputed by evsel__name. */
4153 zfree(&evsel->name);
4154
4155 /* Log message. */
4156 scnprintf(msg, msgsize,
4157 "The cycles event is not supported, trying to fall back to %s",
4158 evsel__name(evsel));
4159 return true;
4160 } else if (err == EACCES && !evsel->core.attr.exclude_kernel &&
4161 (paranoid = perf_event_paranoid()) > 1) {
4162 const char *name = evsel__name(evsel);
4163 char *new_name;
4164 const char *sep = ":";
4165
4166 /* If event has exclude user then don't exclude kernel. */
4167 if (evsel->core.attr.exclude_user)
4168 goto no_fallback;
4169
4170 /* Is there already the separator in the name. */
4171 if (strchr(name, '/') ||
4172 (strchr(name, ':') && !evsel->is_libpfm_event))
4173 sep = "";
4174
4175 if (asprintf(&new_name, "%s%su", name, sep) < 0)
4176 goto no_fallback;
4177
4178 free(evsel->name);
4179 evsel->name = new_name;
4180 scnprintf(msg, msgsize, "kernel.perf_event_paranoid=%d, trying "
4181 "to fall back to excluding kernel and hypervisor "
4182 " samples", paranoid);
4183 evsel->core.attr.exclude_kernel = 1;
4184 evsel->core.attr.exclude_hv = 1;
4185 evsel->fallenback_eacces = true;
4186 return true;
4187 } else if (err == EOPNOTSUPP && !evsel->core.attr.exclude_guest &&
4188 !evsel->exclude_GH) {
4189 const char *name = evsel__name(evsel);
4190 char *new_name;
4191 const char *sep = ":";
4192
4193 /* Is there already the separator in the name. */
4194 if (strchr(name, '/') ||
4195 (strchr(name, ':') && !evsel->is_libpfm_event))
4196 sep = "";
4197
4198 if (asprintf(&new_name, "%s%sH", name, sep) < 0)
4199 goto no_fallback;
4200
4201 free(evsel->name);
4202 evsel->name = new_name;
4203 /* Apple M1 requires exclude_guest */
4204 scnprintf(msg, msgsize, "Trying to fall back to excluding guest samples");
4205 evsel->core.attr.exclude_guest = 1;
4206 evsel->fallenback_eopnotsupp = true;
4207 return true;
4208 }
4209no_fallback:
4210 scnprintf(msg, msgsize, "No fallback found for '%s' for error %d",
4211 evsel__name(evsel), err);
4212 return false;
4213}
4214
4215static bool find_process(const char *name)
4216{
4217 size_t len = strlen(name);
4218 DIR *dir;
4219 struct dirent *d;
4220 int ret = -1;
4221
4222 dir = opendir(procfs__mountpoint());
4223 if (!dir)
4224 return false;
4225
4226 /* Walk through the directory. */
4227 while (ret && (d = readdir(dir)) != NULL) {
4228 char path[PATH_MAX];
4229 char *data;
4230 size_t size;
4231
4232 if ((d->d_type != DT_DIR) ||
4233 !strcmp(".", d->d_name) ||
4234 !strcmp("..", d->d_name))
4235 continue;
4236
4237 scnprintf(path, sizeof(path), "%s/%s/comm",
4238 procfs__mountpoint(), d->d_name);
4239
4240 if (filename__read_str(path, &data, &size))
4241 continue;
4242
4243 ret = strncmp(name, data, len);
4244 free(data);
4245 }
4246
4247 closedir(dir);
4248 return ret ? false : true;
4249}
4250
4251static int dump_perf_event_processes(char *msg, size_t size)
4252{
4253 DIR *proc_dir;
4254 struct dirent *proc_entry;
4255 int printed = 0;
4256
4257 proc_dir = opendir(procfs__mountpoint());
4258 if (!proc_dir)
4259 return 0;
4260
4261 /* Walk through the /proc directory. */
4262 while ((proc_entry = readdir(proc_dir)) != NULL) {
4263 char buf[256];
4264 DIR *fd_dir;
4265 struct dirent *fd_entry;
4266 int fd_dir_fd;
4267
4268 if (proc_entry->d_type != DT_DIR ||
4269 !isdigit(proc_entry->d_name[0]) ||
4270 strlen(proc_entry->d_name) > sizeof(buf) - 4)
4271 continue;
4272
4273 scnprintf(buf, sizeof(buf), "%s/fd", proc_entry->d_name);
4274 fd_dir_fd = openat(dirfd(proc_dir), buf, O_DIRECTORY);
4275 if (fd_dir_fd == -1)
4276 continue;
4277 fd_dir = fdopendir(fd_dir_fd);
4278 if (!fd_dir) {
4279 close(fd_dir_fd);
4280 continue;
4281 }
4282 while ((fd_entry = readdir(fd_dir)) != NULL) {
4283 ssize_t link_size;
4284
4285 if (fd_entry->d_type != DT_LNK)
4286 continue;
4287 link_size = readlinkat(fd_dir_fd, fd_entry->d_name, buf, sizeof(buf));
4288 if (link_size < 0)
4289 continue;
4290 /* Take care as readlink doesn't null terminate the string. */
4291 if (!strncmp(buf, "anon_inode:[perf_event]", link_size)) {
4292 int cmdline_fd;
4293 ssize_t cmdline_size;
4294
4295 scnprintf(buf, sizeof(buf), "%s/cmdline", proc_entry->d_name);
4296 cmdline_fd = openat(dirfd(proc_dir), buf, O_RDONLY);
4297 if (cmdline_fd == -1)
4298 continue;
4299 cmdline_size = read(cmdline_fd, buf, sizeof(buf) - 1);
4300 close(cmdline_fd);
4301 if (cmdline_size < 0)
4302 continue;
4303 buf[cmdline_size] = '\0';
4304 for (ssize_t i = 0; i < cmdline_size; i++) {
4305 if (buf[i] == '\0')
4306 buf[i] = ' ';
4307 }
4308
4309 if (printed == 0)
4310 printed += scnprintf(msg, size, "Possible processes:\n");
4311
4312 printed += scnprintf(msg + printed, size - printed,
4313 "%s %s\n", proc_entry->d_name, buf);
4314 break;
4315 }
4316 }
4317 closedir(fd_dir);
4318 }
4319 closedir(proc_dir);
4320 return printed;
4321}
4322
4323int __weak arch_evsel__open_strerror(struct evsel *evsel __maybe_unused,
4324 int err __maybe_unused,
4325 char *msg __maybe_unused,
4326 size_t size __maybe_unused)
4327{
4328 return 0;
4329}
4330
4331int evsel__open_strerror(struct evsel *evsel, struct target *target,
4332 int err, char *msg, size_t size)
4333{
4334 struct perf_pmu *pmu;
4335 int printed = 0, enforced = 0;
4336 int ret;
4337
4338 switch (err) {
4339 case EPERM:
4340 case EACCES:
4341 printed += scnprintf(msg + printed, size - printed,
4342 "Access to performance monitoring and observability operations is limited.\n");
4343
4344 if (!sysfs__read_int("fs/selinux/enforce", &enforced)) {
4345 if (enforced) {
4346 printed += scnprintf(msg + printed, size - printed,
4347 "Enforced MAC policy settings (SELinux) can limit access to performance\n"
4348 "monitoring and observability operations. Inspect system audit records for\n"
4349 "more perf_event access control information and adjusting the policy.\n");
4350 }
4351 }
4352
4353 if (err == EPERM)
4354 printed += scnprintf(msg, size,
4355 "No permission to enable %s event.\n\n", evsel__name(evsel));
4356
4357 return printed + scnprintf(msg + printed, size - printed,
4358 "Consider adjusting /proc/sys/kernel/perf_event_paranoid setting to open\n"
4359 "access to performance monitoring and observability operations for processes\n"
4360 "without CAP_PERFMON, CAP_SYS_PTRACE or CAP_SYS_ADMIN Linux capability.\n"
4361 "More information can be found at 'Perf events and tool security' document:\n"
4362 "https://www.kernel.org/doc/html/latest/admin-guide/perf-security.html\n"
4363 "perf_event_paranoid setting is %d:\n"
4364 " -1: Allow use of (almost) all events by all users\n"
4365 " Ignore mlock limit after perf_event_mlock_kb without CAP_IPC_LOCK\n"
4366 ">= 0: Disallow raw and ftrace function tracepoint access\n"
4367 ">= 1: Disallow CPU event access\n"
4368 ">= 2: Disallow kernel profiling\n"
4369 "To make the adjusted perf_event_paranoid setting permanent preserve it\n"
4370 "in /etc/sysctl.conf (e.g. kernel.perf_event_paranoid = <setting>)",
4371 perf_event_paranoid());
4372 case ENOENT:
4373 return scnprintf(msg, size, "The %s event is not supported.", evsel__name(evsel));
4374 case EMFILE:
4375 return scnprintf(msg, size, "%s",
4376 "Too many events are opened.\n"
4377 "Probably the maximum number of open file descriptors has been reached.\n"
4378 "Hint: Try again after reducing the number of events.\n"
4379 "Hint: Try increasing the limit with 'ulimit -n <limit>'");
4380 case ENOMEM:
4381 if (evsel__has_callchain(evsel) &&
4382 access("/proc/sys/kernel/perf_event_max_stack", F_OK) == 0)
4383 return scnprintf(msg, size,
4384 "Not enough memory to setup event with callchain.\n"
4385 "Hint: Try tweaking /proc/sys/kernel/perf_event_max_stack\n"
4386 "Hint: Current value: %d", sysctl__max_stack());
4387 break;
4388 case ENODEV:
4389 if (target->cpu_list)
4390 return scnprintf(msg, size, "%s",
4391 "No such device - did you specify an out-of-range profile CPU?");
4392 break;
4393 case EOPNOTSUPP:
4394 if (evsel->core.attr.sample_type & PERF_SAMPLE_BRANCH_STACK)
4395 return scnprintf(msg, size,
4396 "%s: PMU Hardware or event type doesn't support branch stack sampling.",
4397 evsel__name(evsel));
4398 if (evsel->core.attr.aux_output)
4399 return scnprintf(msg, size,
4400 "%s: PMU Hardware doesn't support 'aux_output' feature",
4401 evsel__name(evsel));
4402 if (evsel->core.attr.aux_action)
4403 return scnprintf(msg, size,
4404 "%s: PMU Hardware doesn't support 'aux_action' feature",
4405 evsel__name(evsel));
4406 if (evsel->core.attr.sample_period != 0)
4407 return scnprintf(msg, size,
4408 "%s: PMU Hardware doesn't support sampling/overflow-interrupts. Try 'perf stat'",
4409 evsel__name(evsel));
4410 if (evsel->core.attr.precise_ip)
4411 return scnprintf(msg, size, "%s",
4412 "\'precise\' request may not be supported. Try removing 'p' modifier.");
4413#if defined(__i386__) || defined(__x86_64__)
4414 if (evsel->core.attr.type == PERF_TYPE_HARDWARE)
4415 return scnprintf(msg, size, "%s",
4416 "No hardware sampling interrupt available.\n");
4417#endif
4418 if (!target__has_cpu(target))
4419 return scnprintf(msg, size,
4420 "Unsupported event (%s) in per-thread mode, enable system wide with '-a'.",
4421 evsel__name(evsel));
4422 break;
4423 case EBUSY:
4424 if (find_process("oprofiled"))
4425 return scnprintf(msg, size,
4426 "The PMU counters are busy/taken by another profiler.\n"
4427 "We found oprofile daemon running, please stop it and try again.");
4428 printed += scnprintf(
4429 msg, size,
4430 "The PMU %s counters are busy and in use by another process.\n",
4431 evsel->pmu ? evsel->pmu->name : "");
4432 return printed + dump_perf_event_processes(msg + printed, size - printed);
4433 break;
4434 case EINVAL:
4435 if (evsel->core.attr.sample_type & PERF_SAMPLE_CODE_PAGE_SIZE && perf_missing_features.code_page_size)
4436 return scnprintf(msg, size, "Asking for the code page size isn't supported by this kernel.");
4437 if (evsel->core.attr.sample_type & PERF_SAMPLE_DATA_PAGE_SIZE && perf_missing_features.data_page_size)
4438 return scnprintf(msg, size, "Asking for the data page size isn't supported by this kernel.");
4439 if (evsel->core.attr.write_backward && perf_missing_features.write_backward)
4440 return scnprintf(msg, size, "Reading from overwrite event is not supported by this kernel.");
4441 if (perf_missing_features.clockid)
4442 return scnprintf(msg, size, "clockid feature not supported.");
4443 if (perf_missing_features.clockid_wrong)
4444 return scnprintf(msg, size, "wrong clockid (%d).", clockid);
4445 if (perf_missing_features.aux_action)
4446 return scnprintf(msg, size, "The 'aux_action' feature is not supported, update the kernel.");
4447 if (perf_missing_features.aux_output)
4448 return scnprintf(msg, size, "The 'aux_output' feature is not supported, update the kernel.");
4449 pmu = evsel__find_pmu(evsel);
4450 if (!pmu->is_core && !target__has_cpu(target))
4451 return scnprintf(msg, size,
4452 "Invalid event (%s) in per-thread mode, enable system wide with '-a'.",
4453 evsel__name(evsel));
4454
4455 break;
4456 case ENODATA:
4457 return scnprintf(msg, size, "Cannot collect data source with the load latency event alone. "
4458 "Please add an auxiliary event in front of the load latency event.");
4459 default:
4460 break;
4461 }
4462
4463 ret = arch_evsel__open_strerror(evsel, err, msg, size);
4464 if (ret)
4465 return ret;
4466
4467 errno = err;
4468 return scnprintf(msg, size,
4469 "The sys_perf_event_open() syscall failed for event (%s): %m\n"
4470 "\"dmesg | grep -i perf\" may provide additional information.\n",
4471 evsel__name(evsel));
4472}
4473
4474struct perf_session *evsel__session(struct evsel *evsel)
4475{
4476 return evsel && evsel->evlist ? evlist__session(evsel->evlist) : NULL;
4477}
4478
4479struct perf_env *evsel__env(struct evsel *evsel)
4480{
4481 struct perf_session *session = evsel__session(evsel);
4482
4483 return session ? perf_session__env(session) : NULL;
4484}
4485
4486static int store_evsel_ids(struct evsel *evsel, struct evlist *evlist)
4487{
4488 int cpu_map_idx, thread;
4489
4490 if (evsel__is_retire_lat(evsel))
4491 return 0;
4492
4493 if (perf_pmu__kind(evsel->pmu) != PERF_PMU_KIND_PE)
4494 return 0;
4495
4496 for (cpu_map_idx = 0; cpu_map_idx < xyarray__max_x(evsel->core.fd); cpu_map_idx++) {
4497 for (thread = 0; thread < xyarray__max_y(evsel->core.fd);
4498 thread++) {
4499 int fd = FD(evsel, cpu_map_idx, thread);
4500
4501 if (perf_evlist__id_add_fd(evlist__core(evlist), &evsel->core,
4502 cpu_map_idx, thread, fd) < 0)
4503 return -1;
4504 }
4505 }
4506
4507 return 0;
4508}
4509
4510int evsel__store_ids(struct evsel *evsel, struct evlist *evlist)
4511{
4512 struct perf_cpu_map *cpus = evsel->core.cpus;
4513 struct perf_thread_map *threads = evsel->core.threads;
4514
4515 if (perf_evsel__alloc_id(&evsel->core, perf_cpu_map__nr(cpus), threads->nr))
4516 return -ENOMEM;
4517
4518 return store_evsel_ids(evsel, evlist);
4519}
4520
4521void evsel__zero_per_pkg(struct evsel *evsel)
4522{
4523 struct hashmap_entry *cur;
4524 size_t bkt;
4525
4526 if (evsel->per_pkg_mask) {
4527 hashmap__for_each_entry(evsel->per_pkg_mask, cur, bkt)
4528 zfree(&cur->pkey);
4529
4530 hashmap__clear(evsel->per_pkg_mask);
4531 }
4532}
4533
4534/**
4535 * evsel__is_hybrid - does the evsel have a known PMU that is hybrid. Note, this
4536 * will be false on hybrid systems for hardware and legacy
4537 * cache events.
4538 */
4539bool evsel__is_hybrid(const struct evsel *evsel)
4540{
4541 if (!evsel->core.is_pmu_core)
4542 return false;
4543
4544 return perf_pmus__num_core_pmus() > 1;
4545}
4546
4547struct evsel *evsel__leader(const struct evsel *evsel)
4548{
4549 if (evsel->core.leader == NULL)
4550 return NULL;
4551 return container_of(evsel->core.leader, struct evsel, core);
4552}
4553
4554bool evsel__has_leader(struct evsel *evsel, struct evsel *leader)
4555{
4556 return evsel->core.leader == &leader->core;
4557}
4558
4559bool evsel__is_leader(struct evsel *evsel)
4560{
4561 return evsel__has_leader(evsel, evsel);
4562}
4563
4564void evsel__set_leader(struct evsel *evsel, struct evsel *leader)
4565{
4566 evsel->core.leader = &leader->core;
4567}
4568
4569bool evsel__is_aux_event(const struct evsel *evsel)
4570{
4571 struct perf_pmu *pmu;
4572
4573 if (evsel->needs_auxtrace_mmap)
4574 return true;
4575
4576 pmu = evsel__find_pmu(evsel);
4577 return pmu && pmu->auxtrace;
4578}
4579
4580int evsel__source_count(const struct evsel *evsel)
4581{
4582 struct evsel *pos;
4583 int count = 0;
4584
4585 evlist__for_each_entry(evsel->evlist, pos) {
4586 if (pos->metric_leader == evsel)
4587 count++;
4588 }
4589 return count;
4590}
4591
4592bool __weak arch_evsel__must_be_in_group(const struct evsel *evsel __maybe_unused)
4593{
4594 return false;
4595}
4596
4597/*
4598 * Remove an event from a given group (leader).
4599 * Some events, e.g., perf metrics Topdown events,
4600 * must always be grouped. Ignore the events.
4601 */
4602void evsel__remove_from_group(struct evsel *evsel, struct evsel *leader)
4603{
4604 if (!arch_evsel__must_be_in_group(evsel) && evsel != leader) {
4605 evsel__set_leader(evsel, evsel);
4606 evsel->core.nr_members = 0;
4607 leader->core.nr_members--;
4608 }
4609}
4610
4611bool evsel__set_needs_uniquify(struct evsel *counter, const struct perf_stat_config *config)
4612{
4613 struct evsel *evsel;
4614
4615 if (counter->needs_uniquify) {
4616 /* Already set. */
4617 return true;
4618 }
4619
4620 if (counter->use_config_name || counter->is_libpfm_event) {
4621 /* Original name will be used. */
4622 return false;
4623 }
4624
4625 if (!config->hybrid_merge && evsel__is_hybrid(counter)) {
4626 /* Unique hybrid counters necessary. */
4627 counter->needs_uniquify = true;
4628 return true;
4629 }
4630
4631 if (counter->core.attr.type < PERF_TYPE_MAX && counter->core.attr.type != PERF_TYPE_RAW) {
4632 /* Legacy event, don't uniquify. */
4633 return false;
4634 }
4635
4636 if (counter->pmu && counter->pmu->is_core &&
4637 counter->alternate_hw_config != PERF_COUNT_HW_MAX) {
4638 /* A sysfs or json event replacing a legacy event, don't uniquify. */
4639 return false;
4640 }
4641
4642 if (config->aggr_mode == AGGR_NONE) {
4643 /* Always unique with no aggregation. */
4644 counter->needs_uniquify = true;
4645 return true;
4646 }
4647
4648 if (counter->first_wildcard_match != NULL) {
4649 /*
4650 * If stats are merged then only the first_wildcard_match is
4651 * displayed, there is no need to uniquify this evsel as the
4652 * name won't be shown.
4653 */
4654 return false;
4655 }
4656
4657 /*
4658 * Do other non-merged events in the evlist have the same name? If so
4659 * uniquify is necessary.
4660 */
4661 evlist__for_each_entry(counter->evlist, evsel) {
4662 if (evsel == counter || evsel->first_wildcard_match || evsel->pmu == counter->pmu)
4663 continue;
4664
4665 if (evsel__name_is(counter, evsel__name(evsel))) {
4666 counter->needs_uniquify = true;
4667 return true;
4668 }
4669 }
4670 return false;
4671}
4672
4673void evsel__uniquify_counter(struct evsel *counter)
4674{
4675 const char *name, *pmu_name, *config;
4676 char *new_name;
4677 int len, ret;
4678
4679 /* No uniquification necessary. */
4680 if (!counter->needs_uniquify)
4681 return;
4682
4683 /* The evsel was already uniquified. */
4684 if (counter->uniquified_name)
4685 return;
4686
4687 /* Avoid checking to uniquify twice. */
4688 counter->uniquified_name = true;
4689
4690 name = evsel__name(counter);
4691 config = strchr(name, '/');
4692 pmu_name = counter->pmu->name;
4693
4694 /* Already prefixed by the PMU name? */
4695 len = pmu_name_len_no_suffix(pmu_name);
4696
4697 if (!strncmp(name, pmu_name, len)) {
4698 /*
4699 * If the PMU name is there, then there is no sense in not
4700 * having a slash. Do this for robustness.
4701 */
4702 if (config == NULL)
4703 config = name - 1;
4704
4705 ret = asprintf(&new_name, "%s/%s", pmu_name, config + 1);
4706 } else if (config) {
4707 len = config - name;
4708 if (config[1] == '/') {
4709 /* case: event// */
4710 ret = asprintf(&new_name, "%s/%.*s/%s", pmu_name, len, name, config + 2);
4711 } else {
4712 /* case: event/.../ */
4713 ret = asprintf(&new_name, "%s/%.*s,%s", pmu_name, len, name, config + 1);
4714 }
4715 } else {
4716 config = strchr(name, ':');
4717 if (config) {
4718 /* case: event:.. */
4719 len = config - name;
4720
4721 ret = asprintf(&new_name, "%s/%.*s/%s", pmu_name, len, name, config + 1);
4722 } else {
4723 /* case: event */
4724 ret = asprintf(&new_name, "%s/%s/", pmu_name, name);
4725 }
4726 }
4727 if (ret > 0) {
4728 free(counter->name);
4729 counter->name = new_name;
4730 } else {
4731 /* ENOMEM from asprintf. */
4732 counter->uniquified_name = false;
4733 }
4734}
4735
4736void evsel__warn_user_requested_cpus(struct evsel *evsel, struct perf_cpu_map *user_requested_cpus)
4737{
4738 struct perf_cpu_map *intersect, *online = NULL;
4739 const struct perf_pmu *pmu = evsel__find_pmu(evsel);
4740
4741 if (pmu && pmu->is_core) {
4742 intersect = perf_cpu_map__intersect(pmu->cpus, user_requested_cpus);
4743 } else {
4744 online = cpu_map__online();
4745 intersect = perf_cpu_map__intersect(online, user_requested_cpus);
4746 }
4747 if (!perf_cpu_map__equal(intersect, user_requested_cpus)) {
4748 char buf1[128];
4749 char buf2[128];
4750
4751 cpu_map__snprint(user_requested_cpus, buf1, sizeof(buf1));
4752 cpu_map__snprint(online ?: pmu->cpus, buf2, sizeof(buf2));
4753 pr_warning("WARNING: A requested CPU in '%s' is not supported by PMU '%s' (CPUs %s) for event '%s'\n",
4754 buf1, pmu ? pmu->name : "cpu", buf2, evsel__name(evsel));
4755 }
4756 perf_cpu_map__put(intersect);
4757 perf_cpu_map__put(online);
4758}