1 // SPDX-License-Identifier: GPL-2.0-only
3 * Copyright (C) 2011, Red Hat Inc, Arnaldo Carvalho de Melo <acme@redhat.com>
5 * Parts came from builtin-{top,stat,record}.c, see those files for further
12 #include <linux/bitops.h>
13 #include <api/fs/fs.h>
14 #include <api/fs/tracing_path.h>
15 #include <linux/hw_breakpoint.h>
16 #include <linux/perf_event.h>
17 #include <linux/compiler.h>
18 #include <linux/err.h>
19 #include <linux/zalloc.h>
20 #include <sys/ioctl.h>
21 #include <sys/resource.h>
22 #include <sys/types.h>
25 #include <perf/evsel.h>
27 #include "bpf_counter.h"
28 #include "callchain.h"
34 #include "util/evsel_config.h"
35 #include "util/evsel_fprintf.h"
37 #include <perf/cpumap.h>
38 #include "thread_map.h"
40 #include "perf_regs.h"
43 #include "trace-event.h"
48 #include "util/hashmap.h"
49 #include "pmu-hybrid.h"
51 #include "../perf-sys.h"
52 #include "util/parse-branch-options.h"
53 #include "util/bpf-filter.h"
54 #include <internal/xyarray.h>
55 #include <internal/lib.h>
56 #include <internal/threadmap.h>
58 #include <linux/ctype.h>
60 #ifdef HAVE_LIBTRACEEVENT
61 #include <traceevent/event-parse.h>
64 struct perf_missing_features perf_missing_features;
66 static clockid_t clockid;
68 static const char *const perf_tool_event__tool_names[PERF_TOOL_MAX] = {
75 const char *perf_tool_event__to_str(enum perf_tool_event ev)
77 if (ev > PERF_TOOL_NONE && ev < PERF_TOOL_MAX)
78 return perf_tool_event__tool_names[ev];
83 enum perf_tool_event perf_tool_event__from_str(const char *str)
87 perf_tool_event__for_each_event(i) {
88 if (!strcmp(str, perf_tool_event__tool_names[i]))
91 return PERF_TOOL_NONE;
95 static int evsel__no_extra_init(struct evsel *evsel __maybe_unused)
100 void __weak test_attr__ready(void) { }
102 static void evsel__no_extra_fini(struct evsel *evsel __maybe_unused)
108 int (*init)(struct evsel *evsel);
109 void (*fini)(struct evsel *evsel);
110 } perf_evsel__object = {
111 .size = sizeof(struct evsel),
112 .init = evsel__no_extra_init,
113 .fini = evsel__no_extra_fini,
116 int evsel__object_config(size_t object_size, int (*init)(struct evsel *evsel),
117 void (*fini)(struct evsel *evsel))
120 if (object_size == 0)
123 if (perf_evsel__object.size > object_size)
126 perf_evsel__object.size = object_size;
130 perf_evsel__object.init = init;
133 perf_evsel__object.fini = fini;
138 #define FD(e, x, y) (*(int *)xyarray__entry(e->core.fd, x, y))
140 int __evsel__sample_size(u64 sample_type)
142 u64 mask = sample_type & PERF_SAMPLE_MASK;
146 for (i = 0; i < 64; i++) {
147 if (mask & (1ULL << i))
157 * __perf_evsel__calc_id_pos - calculate id_pos.
158 * @sample_type: sample type
160 * This function returns the position of the event id (PERF_SAMPLE_ID or
161 * PERF_SAMPLE_IDENTIFIER) in a sample event i.e. in the array of struct
162 * perf_record_sample.
164 static int __perf_evsel__calc_id_pos(u64 sample_type)
168 if (sample_type & PERF_SAMPLE_IDENTIFIER)
171 if (!(sample_type & PERF_SAMPLE_ID))
174 if (sample_type & PERF_SAMPLE_IP)
177 if (sample_type & PERF_SAMPLE_TID)
180 if (sample_type & PERF_SAMPLE_TIME)
183 if (sample_type & PERF_SAMPLE_ADDR)
190 * __perf_evsel__calc_is_pos - calculate is_pos.
191 * @sample_type: sample type
193 * This function returns the position (counting backwards) of the event id
194 * (PERF_SAMPLE_ID or PERF_SAMPLE_IDENTIFIER) in a non-sample event i.e. if
195 * sample_id_all is used there is an id sample appended to non-sample events.
197 static int __perf_evsel__calc_is_pos(u64 sample_type)
201 if (sample_type & PERF_SAMPLE_IDENTIFIER)
204 if (!(sample_type & PERF_SAMPLE_ID))
207 if (sample_type & PERF_SAMPLE_CPU)
210 if (sample_type & PERF_SAMPLE_STREAM_ID)
216 void evsel__calc_id_pos(struct evsel *evsel)
218 evsel->id_pos = __perf_evsel__calc_id_pos(evsel->core.attr.sample_type);
219 evsel->is_pos = __perf_evsel__calc_is_pos(evsel->core.attr.sample_type);
222 void __evsel__set_sample_bit(struct evsel *evsel,
223 enum perf_event_sample_format bit)
225 if (!(evsel->core.attr.sample_type & bit)) {
226 evsel->core.attr.sample_type |= bit;
227 evsel->sample_size += sizeof(u64);
228 evsel__calc_id_pos(evsel);
232 void __evsel__reset_sample_bit(struct evsel *evsel,
233 enum perf_event_sample_format bit)
235 if (evsel->core.attr.sample_type & bit) {
236 evsel->core.attr.sample_type &= ~bit;
237 evsel->sample_size -= sizeof(u64);
238 evsel__calc_id_pos(evsel);
242 void evsel__set_sample_id(struct evsel *evsel,
243 bool can_sample_identifier)
245 if (can_sample_identifier) {
246 evsel__reset_sample_bit(evsel, ID);
247 evsel__set_sample_bit(evsel, IDENTIFIER);
249 evsel__set_sample_bit(evsel, ID);
251 evsel->core.attr.read_format |= PERF_FORMAT_ID;
255 * evsel__is_function_event - Return whether given evsel is a function
258 * @evsel - evsel selector to be tested
260 * Return %true if event is function trace event
262 bool evsel__is_function_event(struct evsel *evsel)
264 #define FUNCTION_EVENT "ftrace:function"
266 return evsel->name &&
267 !strncmp(FUNCTION_EVENT, evsel->name, sizeof(FUNCTION_EVENT));
269 #undef FUNCTION_EVENT
272 void evsel__init(struct evsel *evsel,
273 struct perf_event_attr *attr, int idx)
275 perf_evsel__init(&evsel->core, attr, idx);
276 evsel->tracking = !idx;
277 evsel->unit = strdup("");
279 evsel->max_events = ULONG_MAX;
280 evsel->evlist = NULL;
281 evsel->bpf_obj = NULL;
283 INIT_LIST_HEAD(&evsel->config_terms);
284 INIT_LIST_HEAD(&evsel->bpf_counter_list);
285 perf_evsel__object.init(evsel);
286 evsel->sample_size = __evsel__sample_size(attr->sample_type);
287 evsel__calc_id_pos(evsel);
288 evsel->cmdline_group_boundary = false;
289 evsel->metric_events = NULL;
290 evsel->per_pkg_mask = NULL;
291 evsel->collect_stat = false;
292 evsel->pmu_name = NULL;
293 evsel->skippable = false;
296 struct evsel *evsel__new_idx(struct perf_event_attr *attr, int idx)
298 struct evsel *evsel = zalloc(perf_evsel__object.size);
302 evsel__init(evsel, attr, idx);
304 if (evsel__is_bpf_output(evsel) && !attr->sample_type) {
305 evsel->core.attr.sample_type = (PERF_SAMPLE_RAW | PERF_SAMPLE_TIME |
306 PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD),
307 evsel->core.attr.sample_period = 1;
310 if (evsel__is_clock(evsel)) {
311 free((char *)evsel->unit);
312 evsel->unit = strdup("msec");
319 static bool perf_event_can_profile_kernel(void)
321 return perf_event_paranoid_check(1);
324 struct evsel *evsel__new_cycles(bool precise __maybe_unused, __u32 type, __u64 config)
326 struct perf_event_attr attr = {
329 .exclude_kernel = !perf_event_can_profile_kernel(),
333 event_attr_init(&attr);
336 * Now let the usual logic to set up the perf_event_attr defaults
337 * to kick in when we return and before perf_evsel__open() is called.
339 evsel = evsel__new(&attr);
343 arch_evsel__fixup_new_cycles(&evsel->core.attr);
345 evsel->precise_max = true;
347 /* use asprintf() because free(evsel) assumes name is allocated */
348 if (asprintf(&evsel->name, "cycles%s%s%.*s",
349 (attr.precise_ip || attr.exclude_kernel) ? ":" : "",
350 attr.exclude_kernel ? "u" : "",
351 attr.precise_ip ? attr.precise_ip + 1 : 0, "ppp") < 0)
356 evsel__delete(evsel);
361 int copy_config_terms(struct list_head *dst, struct list_head *src)
363 struct evsel_config_term *pos, *tmp;
365 list_for_each_entry(pos, src, list) {
366 tmp = malloc(sizeof(*tmp));
372 tmp->val.str = strdup(pos->val.str);
373 if (tmp->val.str == NULL) {
378 list_add_tail(&tmp->list, dst);
383 static int evsel__copy_config_terms(struct evsel *dst, struct evsel *src)
385 return copy_config_terms(&dst->config_terms, &src->config_terms);
389 * evsel__clone - create a new evsel copied from @orig
390 * @orig: original evsel
392 * The assumption is that @orig is not configured nor opened yet.
393 * So we only care about the attributes that can be set while it's parsed.
395 struct evsel *evsel__clone(struct evsel *orig)
399 BUG_ON(orig->core.fd);
400 BUG_ON(orig->counts);
402 BUG_ON(orig->per_pkg_mask);
404 /* cannot handle BPF objects for now */
408 evsel = evsel__new(&orig->core.attr);
412 evsel->core.cpus = perf_cpu_map__get(orig->core.cpus);
413 evsel->core.own_cpus = perf_cpu_map__get(orig->core.own_cpus);
414 evsel->core.threads = perf_thread_map__get(orig->core.threads);
415 evsel->core.nr_members = orig->core.nr_members;
416 evsel->core.system_wide = orig->core.system_wide;
417 evsel->core.requires_cpu = orig->core.requires_cpu;
420 evsel->name = strdup(orig->name);
421 if (evsel->name == NULL)
424 if (orig->group_name) {
425 evsel->group_name = strdup(orig->group_name);
426 if (evsel->group_name == NULL)
429 if (orig->pmu_name) {
430 evsel->pmu_name = strdup(orig->pmu_name);
431 if (evsel->pmu_name == NULL)
435 evsel->filter = strdup(orig->filter);
436 if (evsel->filter == NULL)
439 if (orig->metric_id) {
440 evsel->metric_id = strdup(orig->metric_id);
441 if (evsel->metric_id == NULL)
444 evsel->cgrp = cgroup__get(orig->cgrp);
445 #ifdef HAVE_LIBTRACEEVENT
446 evsel->tp_format = orig->tp_format;
448 evsel->handler = orig->handler;
449 evsel->core.leader = orig->core.leader;
451 evsel->max_events = orig->max_events;
452 evsel->tool_event = orig->tool_event;
453 free((char *)evsel->unit);
454 evsel->unit = strdup(orig->unit);
455 if (evsel->unit == NULL)
458 evsel->scale = orig->scale;
459 evsel->snapshot = orig->snapshot;
460 evsel->per_pkg = orig->per_pkg;
461 evsel->percore = orig->percore;
462 evsel->precise_max = orig->precise_max;
463 evsel->is_libpfm_event = orig->is_libpfm_event;
465 evsel->exclude_GH = orig->exclude_GH;
466 evsel->sample_read = orig->sample_read;
467 evsel->auto_merge_stats = orig->auto_merge_stats;
468 evsel->collect_stat = orig->collect_stat;
469 evsel->weak_group = orig->weak_group;
470 evsel->use_config_name = orig->use_config_name;
471 evsel->pmu = orig->pmu;
473 if (evsel__copy_config_terms(evsel, orig) < 0)
479 evsel__delete(evsel);
484 * Returns pointer with encoded error via <linux/err.h> interface.
486 #ifdef HAVE_LIBTRACEEVENT
487 struct evsel *evsel__newtp_idx(const char *sys, const char *name, int idx)
489 struct evsel *evsel = zalloc(perf_evsel__object.size);
495 struct perf_event_attr attr = {
496 .type = PERF_TYPE_TRACEPOINT,
497 .sample_type = (PERF_SAMPLE_RAW | PERF_SAMPLE_TIME |
498 PERF_SAMPLE_CPU | PERF_SAMPLE_PERIOD),
501 if (asprintf(&evsel->name, "%s:%s", sys, name) < 0)
504 evsel->tp_format = trace_event__tp_format(sys, name);
505 if (IS_ERR(evsel->tp_format)) {
506 err = PTR_ERR(evsel->tp_format);
510 event_attr_init(&attr);
511 attr.config = evsel->tp_format->id;
512 attr.sample_period = 1;
513 evsel__init(evsel, &attr, idx);
526 const char *const evsel__hw_names[PERF_COUNT_HW_MAX] = {
534 "stalled-cycles-frontend",
535 "stalled-cycles-backend",
539 char *evsel__bpf_counter_events;
541 bool evsel__match_bpf_counter_events(const char *name)
547 if (!evsel__bpf_counter_events)
550 ptr = strstr(evsel__bpf_counter_events, name);
551 name_len = strlen(name);
553 /* check name matches a full token in evsel__bpf_counter_events */
554 match = (ptr != NULL) &&
555 ((ptr == evsel__bpf_counter_events) || (*(ptr - 1) == ',')) &&
556 ((*(ptr + name_len) == ',') || (*(ptr + name_len) == '\0'));
561 static const char *__evsel__hw_name(u64 config)
563 if (config < PERF_COUNT_HW_MAX && evsel__hw_names[config])
564 return evsel__hw_names[config];
566 return "unknown-hardware";
569 static int evsel__add_modifiers(struct evsel *evsel, char *bf, size_t size)
571 int colon = 0, r = 0;
572 struct perf_event_attr *attr = &evsel->core.attr;
573 bool exclude_guest_default = false;
575 #define MOD_PRINT(context, mod) do { \
576 if (!attr->exclude_##context) { \
577 if (!colon) colon = ++r; \
578 r += scnprintf(bf + r, size - r, "%c", mod); \
581 if (attr->exclude_kernel || attr->exclude_user || attr->exclude_hv) {
582 MOD_PRINT(kernel, 'k');
583 MOD_PRINT(user, 'u');
585 exclude_guest_default = true;
588 if (attr->precise_ip) {
591 r += scnprintf(bf + r, size - r, "%.*s", attr->precise_ip, "ppp");
592 exclude_guest_default = true;
595 if (attr->exclude_host || attr->exclude_guest == exclude_guest_default) {
596 MOD_PRINT(host, 'H');
597 MOD_PRINT(guest, 'G');
605 int __weak arch_evsel__hw_name(struct evsel *evsel, char *bf, size_t size)
607 return scnprintf(bf, size, "%s", __evsel__hw_name(evsel->core.attr.config));
610 static int evsel__hw_name(struct evsel *evsel, char *bf, size_t size)
612 int r = arch_evsel__hw_name(evsel, bf, size);
613 return r + evsel__add_modifiers(evsel, bf + r, size - r);
616 const char *const evsel__sw_names[PERF_COUNT_SW_MAX] = {
629 static const char *__evsel__sw_name(u64 config)
631 if (config < PERF_COUNT_SW_MAX && evsel__sw_names[config])
632 return evsel__sw_names[config];
633 return "unknown-software";
636 static int evsel__sw_name(struct evsel *evsel, char *bf, size_t size)
638 int r = scnprintf(bf, size, "%s", __evsel__sw_name(evsel->core.attr.config));
639 return r + evsel__add_modifiers(evsel, bf + r, size - r);
642 static int evsel__tool_name(enum perf_tool_event ev, char *bf, size_t size)
644 return scnprintf(bf, size, "%s", perf_tool_event__to_str(ev));
647 static int __evsel__bp_name(char *bf, size_t size, u64 addr, u64 type)
651 r = scnprintf(bf, size, "mem:0x%" PRIx64 ":", addr);
653 if (type & HW_BREAKPOINT_R)
654 r += scnprintf(bf + r, size - r, "r");
656 if (type & HW_BREAKPOINT_W)
657 r += scnprintf(bf + r, size - r, "w");
659 if (type & HW_BREAKPOINT_X)
660 r += scnprintf(bf + r, size - r, "x");
665 static int evsel__bp_name(struct evsel *evsel, char *bf, size_t size)
667 struct perf_event_attr *attr = &evsel->core.attr;
668 int r = __evsel__bp_name(bf, size, attr->bp_addr, attr->bp_type);
669 return r + evsel__add_modifiers(evsel, bf + r, size - r);
672 const char *const evsel__hw_cache[PERF_COUNT_HW_CACHE_MAX][EVSEL__MAX_ALIASES] = {
673 { "L1-dcache", "l1-d", "l1d", "L1-data", },
674 { "L1-icache", "l1-i", "l1i", "L1-instruction", },
676 { "dTLB", "d-tlb", "Data-TLB", },
677 { "iTLB", "i-tlb", "Instruction-TLB", },
678 { "branch", "branches", "bpu", "btb", "bpc", },
682 const char *const evsel__hw_cache_op[PERF_COUNT_HW_CACHE_OP_MAX][EVSEL__MAX_ALIASES] = {
683 { "load", "loads", "read", },
684 { "store", "stores", "write", },
685 { "prefetch", "prefetches", "speculative-read", "speculative-load", },
688 const char *const evsel__hw_cache_result[PERF_COUNT_HW_CACHE_RESULT_MAX][EVSEL__MAX_ALIASES] = {
689 { "refs", "Reference", "ops", "access", },
690 { "misses", "miss", },
693 #define C(x) PERF_COUNT_HW_CACHE_##x
694 #define CACHE_READ (1 << C(OP_READ))
695 #define CACHE_WRITE (1 << C(OP_WRITE))
696 #define CACHE_PREFETCH (1 << C(OP_PREFETCH))
697 #define COP(x) (1 << x)
700 * cache operation stat
701 * L1I : Read and prefetch only
702 * ITLB and BPU : Read-only
704 static const unsigned long evsel__hw_cache_stat[C(MAX)] = {
705 [C(L1D)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
706 [C(L1I)] = (CACHE_READ | CACHE_PREFETCH),
707 [C(LL)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
708 [C(DTLB)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
709 [C(ITLB)] = (CACHE_READ),
710 [C(BPU)] = (CACHE_READ),
711 [C(NODE)] = (CACHE_READ | CACHE_WRITE | CACHE_PREFETCH),
714 bool evsel__is_cache_op_valid(u8 type, u8 op)
716 if (evsel__hw_cache_stat[type] & COP(op))
717 return true; /* valid */
719 return false; /* invalid */
722 int __evsel__hw_cache_type_op_res_name(u8 type, u8 op, u8 result, char *bf, size_t size)
725 return scnprintf(bf, size, "%s-%s-%s", evsel__hw_cache[type][0],
726 evsel__hw_cache_op[op][0],
727 evsel__hw_cache_result[result][0]);
730 return scnprintf(bf, size, "%s-%s", evsel__hw_cache[type][0],
731 evsel__hw_cache_op[op][1]);
734 static int __evsel__hw_cache_name(u64 config, char *bf, size_t size)
736 u8 op, result, type = (config >> 0) & 0xff;
737 const char *err = "unknown-ext-hardware-cache-type";
739 if (type >= PERF_COUNT_HW_CACHE_MAX)
742 op = (config >> 8) & 0xff;
743 err = "unknown-ext-hardware-cache-op";
744 if (op >= PERF_COUNT_HW_CACHE_OP_MAX)
747 result = (config >> 16) & 0xff;
748 err = "unknown-ext-hardware-cache-result";
749 if (result >= PERF_COUNT_HW_CACHE_RESULT_MAX)
752 err = "invalid-cache";
753 if (!evsel__is_cache_op_valid(type, op))
756 return __evsel__hw_cache_type_op_res_name(type, op, result, bf, size);
758 return scnprintf(bf, size, "%s", err);
761 static int evsel__hw_cache_name(struct evsel *evsel, char *bf, size_t size)
763 int ret = __evsel__hw_cache_name(evsel->core.attr.config, bf, size);
764 return ret + evsel__add_modifiers(evsel, bf + ret, size - ret);
767 static int evsel__raw_name(struct evsel *evsel, char *bf, size_t size)
769 int ret = scnprintf(bf, size, "raw 0x%" PRIx64, evsel->core.attr.config);
770 return ret + evsel__add_modifiers(evsel, bf + ret, size - ret);
773 const char *evsel__name(struct evsel *evsel)
783 switch (evsel->core.attr.type) {
785 evsel__raw_name(evsel, bf, sizeof(bf));
788 case PERF_TYPE_HARDWARE:
789 evsel__hw_name(evsel, bf, sizeof(bf));
792 case PERF_TYPE_HW_CACHE:
793 evsel__hw_cache_name(evsel, bf, sizeof(bf));
796 case PERF_TYPE_SOFTWARE:
797 if (evsel__is_tool(evsel))
798 evsel__tool_name(evsel->tool_event, bf, sizeof(bf));
800 evsel__sw_name(evsel, bf, sizeof(bf));
803 case PERF_TYPE_TRACEPOINT:
804 scnprintf(bf, sizeof(bf), "%s", "unknown tracepoint");
807 case PERF_TYPE_BREAKPOINT:
808 evsel__bp_name(evsel, bf, sizeof(bf));
812 scnprintf(bf, sizeof(bf), "unknown attr type: %d",
813 evsel->core.attr.type);
817 evsel->name = strdup(bf);
825 bool evsel__name_is(struct evsel *evsel, const char *name)
827 return !strcmp(evsel__name(evsel), name);
830 const char *evsel__group_pmu_name(const struct evsel *evsel)
832 struct evsel *leader = evsel__leader(evsel);
836 * Software events may be in a group with other uncore PMU events. Use
837 * the pmu_name of the first non-software event to avoid breaking the
838 * software event out of the group.
840 * Aux event leaders, like intel_pt, expect a group with events from
841 * other PMUs, so substitute the AUX event's PMU in this case.
843 if (evsel->core.attr.type == PERF_TYPE_SOFTWARE || evsel__is_aux_event(leader)) {
844 /* Starting with the leader, find the first event with a named PMU. */
845 for_each_group_evsel(pos, leader) {
847 return pos->pmu_name;
851 return evsel->pmu_name ?: "cpu";
854 const char *evsel__metric_id(const struct evsel *evsel)
856 if (evsel->metric_id)
857 return evsel->metric_id;
859 if (evsel__is_tool(evsel))
860 return perf_tool_event__to_str(evsel->tool_event);
865 const char *evsel__group_name(struct evsel *evsel)
867 return evsel->group_name ?: "anon group";
871 * Returns the group details for the specified leader,
872 * with following rules.
874 * For record -e '{cycles,instructions}'
875 * 'anon group { cycles:u, instructions:u }'
877 * For record -e 'cycles,instructions' and report --group
878 * 'cycles:u, instructions:u'
880 int evsel__group_desc(struct evsel *evsel, char *buf, size_t size)
884 const char *group_name = evsel__group_name(evsel);
886 if (!evsel->forced_leader)
887 ret = scnprintf(buf, size, "%s { ", group_name);
889 ret += scnprintf(buf + ret, size - ret, "%s", evsel__name(evsel));
891 for_each_group_member(pos, evsel)
892 ret += scnprintf(buf + ret, size - ret, ", %s", evsel__name(pos));
894 if (!evsel->forced_leader)
895 ret += scnprintf(buf + ret, size - ret, " }");
900 static void __evsel__config_callchain(struct evsel *evsel, struct record_opts *opts,
901 struct callchain_param *param)
903 bool function = evsel__is_function_event(evsel);
904 struct perf_event_attr *attr = &evsel->core.attr;
906 evsel__set_sample_bit(evsel, CALLCHAIN);
908 attr->sample_max_stack = param->max_stack;
910 if (opts->kernel_callchains)
911 attr->exclude_callchain_user = 1;
912 if (opts->user_callchains)
913 attr->exclude_callchain_kernel = 1;
914 if (param->record_mode == CALLCHAIN_LBR) {
915 if (!opts->branch_stack) {
916 if (attr->exclude_user) {
917 pr_warning("LBR callstack option is only available "
918 "to get user callchain information. "
919 "Falling back to framepointers.\n");
921 evsel__set_sample_bit(evsel, BRANCH_STACK);
922 attr->branch_sample_type = PERF_SAMPLE_BRANCH_USER |
923 PERF_SAMPLE_BRANCH_CALL_STACK |
924 PERF_SAMPLE_BRANCH_NO_CYCLES |
925 PERF_SAMPLE_BRANCH_NO_FLAGS |
926 PERF_SAMPLE_BRANCH_HW_INDEX;
929 pr_warning("Cannot use LBR callstack with branch stack. "
930 "Falling back to framepointers.\n");
933 if (param->record_mode == CALLCHAIN_DWARF) {
935 evsel__set_sample_bit(evsel, REGS_USER);
936 evsel__set_sample_bit(evsel, STACK_USER);
937 if (opts->sample_user_regs && DWARF_MINIMAL_REGS != PERF_REGS_MASK) {
938 attr->sample_regs_user |= DWARF_MINIMAL_REGS;
939 pr_warning("WARNING: The use of --call-graph=dwarf may require all the user registers, "
940 "specifying a subset with --user-regs may render DWARF unwinding unreliable, "
941 "so the minimal registers set (IP, SP) is explicitly forced.\n");
943 attr->sample_regs_user |= arch__user_reg_mask();
945 attr->sample_stack_user = param->dump_size;
946 attr->exclude_callchain_user = 1;
948 pr_info("Cannot use DWARF unwind for function trace event,"
949 " falling back to framepointers.\n");
954 pr_info("Disabling user space callchains for function trace event.\n");
955 attr->exclude_callchain_user = 1;
959 void evsel__config_callchain(struct evsel *evsel, struct record_opts *opts,
960 struct callchain_param *param)
963 return __evsel__config_callchain(evsel, opts, param);
966 static void evsel__reset_callgraph(struct evsel *evsel, struct callchain_param *param)
968 struct perf_event_attr *attr = &evsel->core.attr;
970 evsel__reset_sample_bit(evsel, CALLCHAIN);
971 if (param->record_mode == CALLCHAIN_LBR) {
972 evsel__reset_sample_bit(evsel, BRANCH_STACK);
973 attr->branch_sample_type &= ~(PERF_SAMPLE_BRANCH_USER |
974 PERF_SAMPLE_BRANCH_CALL_STACK |
975 PERF_SAMPLE_BRANCH_HW_INDEX);
977 if (param->record_mode == CALLCHAIN_DWARF) {
978 evsel__reset_sample_bit(evsel, REGS_USER);
979 evsel__reset_sample_bit(evsel, STACK_USER);
983 static void evsel__apply_config_terms(struct evsel *evsel,
984 struct record_opts *opts, bool track)
986 struct evsel_config_term *term;
987 struct list_head *config_terms = &evsel->config_terms;
988 struct perf_event_attr *attr = &evsel->core.attr;
989 /* callgraph default */
990 struct callchain_param param = {
991 .record_mode = callchain_param.record_mode,
995 const char *callgraph_buf = NULL;
997 list_for_each_entry(term, config_terms, list) {
998 switch (term->type) {
999 case EVSEL__CONFIG_TERM_PERIOD:
1000 if (!(term->weak && opts->user_interval != ULLONG_MAX)) {
1001 attr->sample_period = term->val.period;
1003 evsel__reset_sample_bit(evsel, PERIOD);
1006 case EVSEL__CONFIG_TERM_FREQ:
1007 if (!(term->weak && opts->user_freq != UINT_MAX)) {
1008 attr->sample_freq = term->val.freq;
1010 evsel__set_sample_bit(evsel, PERIOD);
1013 case EVSEL__CONFIG_TERM_TIME:
1015 evsel__set_sample_bit(evsel, TIME);
1017 evsel__reset_sample_bit(evsel, TIME);
1019 case EVSEL__CONFIG_TERM_CALLGRAPH:
1020 callgraph_buf = term->val.str;
1022 case EVSEL__CONFIG_TERM_BRANCH:
1023 if (term->val.str && strcmp(term->val.str, "no")) {
1024 evsel__set_sample_bit(evsel, BRANCH_STACK);
1025 parse_branch_str(term->val.str,
1026 &attr->branch_sample_type);
1028 evsel__reset_sample_bit(evsel, BRANCH_STACK);
1030 case EVSEL__CONFIG_TERM_STACK_USER:
1031 dump_size = term->val.stack_user;
1033 case EVSEL__CONFIG_TERM_MAX_STACK:
1034 max_stack = term->val.max_stack;
1036 case EVSEL__CONFIG_TERM_MAX_EVENTS:
1037 evsel->max_events = term->val.max_events;
1039 case EVSEL__CONFIG_TERM_INHERIT:
1041 * attr->inherit should has already been set by
1042 * evsel__config. If user explicitly set
1043 * inherit using config terms, override global
1044 * opt->no_inherit setting.
1046 attr->inherit = term->val.inherit ? 1 : 0;
1048 case EVSEL__CONFIG_TERM_OVERWRITE:
1049 attr->write_backward = term->val.overwrite ? 1 : 0;
1051 case EVSEL__CONFIG_TERM_DRV_CFG:
1053 case EVSEL__CONFIG_TERM_PERCORE:
1055 case EVSEL__CONFIG_TERM_AUX_OUTPUT:
1056 attr->aux_output = term->val.aux_output ? 1 : 0;
1058 case EVSEL__CONFIG_TERM_AUX_SAMPLE_SIZE:
1059 /* Already applied by auxtrace */
1061 case EVSEL__CONFIG_TERM_CFG_CHG:
1068 /* User explicitly set per-event callgraph, clear the old setting and reset. */
1069 if ((callgraph_buf != NULL) || (dump_size > 0) || max_stack) {
1070 bool sample_address = false;
1073 param.max_stack = max_stack;
1074 if (callgraph_buf == NULL)
1075 callgraph_buf = "fp";
1078 /* parse callgraph parameters */
1079 if (callgraph_buf != NULL) {
1080 if (!strcmp(callgraph_buf, "no")) {
1081 param.enabled = false;
1082 param.record_mode = CALLCHAIN_NONE;
1084 param.enabled = true;
1085 if (parse_callchain_record(callgraph_buf, ¶m)) {
1086 pr_err("per-event callgraph setting for %s failed. "
1087 "Apply callgraph global setting for it\n",
1091 if (param.record_mode == CALLCHAIN_DWARF)
1092 sample_address = true;
1095 if (dump_size > 0) {
1096 dump_size = round_up(dump_size, sizeof(u64));
1097 param.dump_size = dump_size;
1100 /* If global callgraph set, clear it */
1101 if (callchain_param.enabled)
1102 evsel__reset_callgraph(evsel, &callchain_param);
1104 /* set perf-event callgraph */
1105 if (param.enabled) {
1106 if (sample_address) {
1107 evsel__set_sample_bit(evsel, ADDR);
1108 evsel__set_sample_bit(evsel, DATA_SRC);
1109 evsel->core.attr.mmap_data = track;
1111 evsel__config_callchain(evsel, opts, ¶m);
1116 struct evsel_config_term *__evsel__get_config_term(struct evsel *evsel, enum evsel_term_type type)
1118 struct evsel_config_term *term, *found_term = NULL;
1120 list_for_each_entry(term, &evsel->config_terms, list) {
1121 if (term->type == type)
1128 void __weak arch_evsel__set_sample_weight(struct evsel *evsel)
1130 evsel__set_sample_bit(evsel, WEIGHT);
1133 void __weak arch_evsel__fixup_new_cycles(struct perf_event_attr *attr __maybe_unused)
1137 void __weak arch__post_evsel_config(struct evsel *evsel __maybe_unused,
1138 struct perf_event_attr *attr __maybe_unused)
1142 static void evsel__set_default_freq_period(struct record_opts *opts,
1143 struct perf_event_attr *attr)
1147 attr->sample_freq = opts->freq;
1149 attr->sample_period = opts->default_interval;
1153 static bool evsel__is_offcpu_event(struct evsel *evsel)
1155 return evsel__is_bpf_output(evsel) && evsel__name_is(evsel, OFFCPU_EVENT);
1159 * The enable_on_exec/disabled value strategy:
1161 * 1) For any type of traced program:
1162 * - all independent events and group leaders are disabled
1163 * - all group members are enabled
1165 * Group members are ruled by group leaders. They need to
1166 * be enabled, because the group scheduling relies on that.
1168 * 2) For traced programs executed by perf:
1169 * - all independent events and group leaders have
1170 * enable_on_exec set
1171 * - we don't specifically enable or disable any event during
1172 * the record command
1174 * Independent events and group leaders are initially disabled
1175 * and get enabled by exec. Group members are ruled by group
1176 * leaders as stated in 1).
1178 * 3) For traced programs attached by perf (pid/tid):
1179 * - we specifically enable or disable all events during
1180 * the record command
1182 * When attaching events to already running traced we
1183 * enable/disable events specifically, as there's no
1184 * initial traced exec call.
1186 void evsel__config(struct evsel *evsel, struct record_opts *opts,
1187 struct callchain_param *callchain)
1189 struct evsel *leader = evsel__leader(evsel);
1190 struct perf_event_attr *attr = &evsel->core.attr;
1191 int track = evsel->tracking;
1192 bool per_cpu = opts->target.default_per_cpu && !opts->target.per_thread;
1194 attr->sample_id_all = perf_missing_features.sample_id_all ? 0 : 1;
1195 attr->inherit = !opts->no_inherit;
1196 attr->write_backward = opts->overwrite ? 1 : 0;
1197 attr->read_format = PERF_FORMAT_LOST;
1199 evsel__set_sample_bit(evsel, IP);
1200 evsel__set_sample_bit(evsel, TID);
1202 if (evsel->sample_read) {
1203 evsel__set_sample_bit(evsel, READ);
1206 * We need ID even in case of single event, because
1207 * PERF_SAMPLE_READ process ID specific data.
1209 evsel__set_sample_id(evsel, false);
1212 * Apply group format only if we belong to group
1213 * with more than one members.
1215 if (leader->core.nr_members > 1) {
1216 attr->read_format |= PERF_FORMAT_GROUP;
1222 * We default some events to have a default interval. But keep
1223 * it a weak assumption overridable by the user.
1225 if ((evsel->is_libpfm_event && !attr->sample_period) ||
1226 (!evsel->is_libpfm_event && (!attr->sample_period ||
1227 opts->user_freq != UINT_MAX ||
1228 opts->user_interval != ULLONG_MAX)))
1229 evsel__set_default_freq_period(opts, attr);
1232 * If attr->freq was set (here or earlier), ask for period
1236 evsel__set_sample_bit(evsel, PERIOD);
1238 if (opts->no_samples)
1239 attr->sample_freq = 0;
1241 if (opts->inherit_stat) {
1242 evsel->core.attr.read_format |=
1243 PERF_FORMAT_TOTAL_TIME_ENABLED |
1244 PERF_FORMAT_TOTAL_TIME_RUNNING |
1246 attr->inherit_stat = 1;
1249 if (opts->sample_address) {
1250 evsel__set_sample_bit(evsel, ADDR);
1251 attr->mmap_data = track;
1255 * We don't allow user space callchains for function trace
1256 * event, due to issues with page faults while tracing page
1257 * fault handler and its overall trickiness nature.
1259 if (evsel__is_function_event(evsel))
1260 evsel->core.attr.exclude_callchain_user = 1;
1262 if (callchain && callchain->enabled && !evsel->no_aux_samples)
1263 evsel__config_callchain(evsel, opts, callchain);
1265 if (opts->sample_intr_regs && !evsel->no_aux_samples &&
1266 !evsel__is_dummy_event(evsel)) {
1267 attr->sample_regs_intr = opts->sample_intr_regs;
1268 evsel__set_sample_bit(evsel, REGS_INTR);
1271 if (opts->sample_user_regs && !evsel->no_aux_samples &&
1272 !evsel__is_dummy_event(evsel)) {
1273 attr->sample_regs_user |= opts->sample_user_regs;
1274 evsel__set_sample_bit(evsel, REGS_USER);
1277 if (target__has_cpu(&opts->target) || opts->sample_cpu)
1278 evsel__set_sample_bit(evsel, CPU);
1281 * When the user explicitly disabled time don't force it here.
1283 if (opts->sample_time &&
1284 (!perf_missing_features.sample_id_all &&
1285 (!opts->no_inherit || target__has_cpu(&opts->target) || per_cpu ||
1286 opts->sample_time_set)))
1287 evsel__set_sample_bit(evsel, TIME);
1289 if (opts->raw_samples && !evsel->no_aux_samples) {
1290 evsel__set_sample_bit(evsel, TIME);
1291 evsel__set_sample_bit(evsel, RAW);
1292 evsel__set_sample_bit(evsel, CPU);
1295 if (opts->sample_address)
1296 evsel__set_sample_bit(evsel, DATA_SRC);
1298 if (opts->sample_phys_addr)
1299 evsel__set_sample_bit(evsel, PHYS_ADDR);
1301 if (opts->no_buffering) {
1302 attr->watermark = 0;
1303 attr->wakeup_events = 1;
1305 if (opts->branch_stack && !evsel->no_aux_samples) {
1306 evsel__set_sample_bit(evsel, BRANCH_STACK);
1307 attr->branch_sample_type = opts->branch_stack;
1310 if (opts->sample_weight)
1311 arch_evsel__set_sample_weight(evsel);
1315 attr->mmap2 = track && !perf_missing_features.mmap2;
1317 attr->build_id = track && opts->build_id;
1320 * ksymbol is tracked separately with text poke because it needs to be
1321 * system wide and enabled immediately.
1323 if (!opts->text_poke)
1324 attr->ksymbol = track && !perf_missing_features.ksymbol;
1325 attr->bpf_event = track && !opts->no_bpf_event && !perf_missing_features.bpf;
1327 if (opts->record_namespaces)
1328 attr->namespaces = track;
1330 if (opts->record_cgroup) {
1331 attr->cgroup = track && !perf_missing_features.cgroup;
1332 evsel__set_sample_bit(evsel, CGROUP);
1335 if (opts->sample_data_page_size)
1336 evsel__set_sample_bit(evsel, DATA_PAGE_SIZE);
1338 if (opts->sample_code_page_size)
1339 evsel__set_sample_bit(evsel, CODE_PAGE_SIZE);
1341 if (opts->record_switch_events)
1342 attr->context_switch = track;
1344 if (opts->sample_transaction)
1345 evsel__set_sample_bit(evsel, TRANSACTION);
1347 if (opts->running_time) {
1348 evsel->core.attr.read_format |=
1349 PERF_FORMAT_TOTAL_TIME_ENABLED |
1350 PERF_FORMAT_TOTAL_TIME_RUNNING;
1354 * XXX see the function comment above
1356 * Disabling only independent events or group leaders,
1357 * keeping group members enabled.
1359 if (evsel__is_group_leader(evsel))
1363 * Setting enable_on_exec for independent events and
1364 * group leaders for traced executed by perf.
1366 if (target__none(&opts->target) && evsel__is_group_leader(evsel) &&
1367 !opts->target.initial_delay)
1368 attr->enable_on_exec = 1;
1370 if (evsel->immediate) {
1372 attr->enable_on_exec = 0;
1375 clockid = opts->clockid;
1376 if (opts->use_clockid) {
1377 attr->use_clockid = 1;
1378 attr->clockid = opts->clockid;
1381 if (evsel->precise_max)
1382 attr->precise_ip = 3;
1384 if (opts->all_user) {
1385 attr->exclude_kernel = 1;
1386 attr->exclude_user = 0;
1389 if (opts->all_kernel) {
1390 attr->exclude_kernel = 0;
1391 attr->exclude_user = 1;
1394 if (evsel->core.own_cpus || evsel->unit)
1395 evsel->core.attr.read_format |= PERF_FORMAT_ID;
1398 * Apply event specific term settings,
1399 * it overloads any global configuration.
1401 evsel__apply_config_terms(evsel, opts, track);
1403 evsel->ignore_missing_thread = opts->ignore_missing_thread;
1405 /* The --period option takes the precedence. */
1406 if (opts->period_set) {
1408 evsel__set_sample_bit(evsel, PERIOD);
1410 evsel__reset_sample_bit(evsel, PERIOD);
1414 * A dummy event never triggers any actual counter and therefore
1415 * cannot be used with branch_stack.
1417 * For initial_delay, a dummy event is added implicitly.
1418 * The software event will trigger -EOPNOTSUPP error out,
1419 * if BRANCH_STACK bit is set.
1421 if (evsel__is_dummy_event(evsel))
1422 evsel__reset_sample_bit(evsel, BRANCH_STACK);
1424 if (evsel__is_offcpu_event(evsel))
1425 evsel->core.attr.sample_type &= OFFCPU_SAMPLE_TYPES;
1427 arch__post_evsel_config(evsel, attr);
1430 int evsel__set_filter(struct evsel *evsel, const char *filter)
1432 char *new_filter = strdup(filter);
1434 if (new_filter != NULL) {
1435 free(evsel->filter);
1436 evsel->filter = new_filter;
1443 static int evsel__append_filter(struct evsel *evsel, const char *fmt, const char *filter)
1447 if (evsel->filter == NULL)
1448 return evsel__set_filter(evsel, filter);
1450 if (asprintf(&new_filter, fmt, evsel->filter, filter) > 0) {
1451 free(evsel->filter);
1452 evsel->filter = new_filter;
1459 int evsel__append_tp_filter(struct evsel *evsel, const char *filter)
1461 return evsel__append_filter(evsel, "(%s) && (%s)", filter);
1464 int evsel__append_addr_filter(struct evsel *evsel, const char *filter)
1466 return evsel__append_filter(evsel, "%s,%s", filter);
1469 /* Caller has to clear disabled after going through all CPUs. */
1470 int evsel__enable_cpu(struct evsel *evsel, int cpu_map_idx)
1472 return perf_evsel__enable_cpu(&evsel->core, cpu_map_idx);
1475 int evsel__enable(struct evsel *evsel)
1477 int err = perf_evsel__enable(&evsel->core);
1480 evsel->disabled = false;
1484 /* Caller has to set disabled after going through all CPUs. */
1485 int evsel__disable_cpu(struct evsel *evsel, int cpu_map_idx)
1487 return perf_evsel__disable_cpu(&evsel->core, cpu_map_idx);
1490 int evsel__disable(struct evsel *evsel)
1492 int err = perf_evsel__disable(&evsel->core);
1494 * We mark it disabled here so that tools that disable a event can
1495 * ignore events after they disable it. I.e. the ring buffer may have
1496 * already a few more events queued up before the kernel got the stop
1500 evsel->disabled = true;
1505 void free_config_terms(struct list_head *config_terms)
1507 struct evsel_config_term *term, *h;
1509 list_for_each_entry_safe(term, h, config_terms, list) {
1510 list_del_init(&term->list);
1512 zfree(&term->val.str);
1517 static void evsel__free_config_terms(struct evsel *evsel)
1519 free_config_terms(&evsel->config_terms);
1522 void evsel__exit(struct evsel *evsel)
1524 assert(list_empty(&evsel->core.node));
1525 assert(evsel->evlist == NULL);
1526 bpf_counter__destroy(evsel);
1527 perf_bpf_filter__destroy(evsel);
1528 evsel__free_counts(evsel);
1529 perf_evsel__free_fd(&evsel->core);
1530 perf_evsel__free_id(&evsel->core);
1531 evsel__free_config_terms(evsel);
1532 cgroup__put(evsel->cgrp);
1533 perf_cpu_map__put(evsel->core.cpus);
1534 perf_cpu_map__put(evsel->core.own_cpus);
1535 perf_thread_map__put(evsel->core.threads);
1536 zfree(&evsel->group_name);
1537 zfree(&evsel->name);
1538 zfree(&evsel->pmu_name);
1539 zfree(&evsel->unit);
1540 zfree(&evsel->metric_id);
1541 evsel__zero_per_pkg(evsel);
1542 hashmap__free(evsel->per_pkg_mask);
1543 evsel->per_pkg_mask = NULL;
1544 zfree(&evsel->metric_events);
1545 perf_evsel__object.fini(evsel);
1548 void evsel__delete(struct evsel *evsel)
1557 void evsel__compute_deltas(struct evsel *evsel, int cpu_map_idx, int thread,
1558 struct perf_counts_values *count)
1560 struct perf_counts_values tmp;
1562 if (!evsel->prev_raw_counts)
1565 tmp = *perf_counts(evsel->prev_raw_counts, cpu_map_idx, thread);
1566 *perf_counts(evsel->prev_raw_counts, cpu_map_idx, thread) = *count;
1568 count->val = count->val - tmp.val;
1569 count->ena = count->ena - tmp.ena;
1570 count->run = count->run - tmp.run;
1573 static int evsel__read_one(struct evsel *evsel, int cpu_map_idx, int thread)
1575 struct perf_counts_values *count = perf_counts(evsel->counts, cpu_map_idx, thread);
1577 return perf_evsel__read(&evsel->core, cpu_map_idx, thread, count);
1580 static void evsel__set_count(struct evsel *counter, int cpu_map_idx, int thread,
1581 u64 val, u64 ena, u64 run, u64 lost)
1583 struct perf_counts_values *count;
1585 count = perf_counts(counter->counts, cpu_map_idx, thread);
1592 perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, true);
1595 static int evsel__process_group_data(struct evsel *leader, int cpu_map_idx, int thread, u64 *data)
1597 u64 read_format = leader->core.attr.read_format;
1598 struct sample_read_value *v;
1599 u64 nr, ena = 0, run = 0, lost = 0;
1603 if (nr != (u64) leader->core.nr_members)
1606 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1609 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1613 sample_read_group__for_each(v, nr, read_format) {
1614 struct evsel *counter;
1616 counter = evlist__id2evsel(leader->evlist, v->id);
1620 if (read_format & PERF_FORMAT_LOST)
1623 evsel__set_count(counter, cpu_map_idx, thread, v->value, ena, run, lost);
1629 static int evsel__read_group(struct evsel *leader, int cpu_map_idx, int thread)
1631 struct perf_stat_evsel *ps = leader->stats;
1632 u64 read_format = leader->core.attr.read_format;
1633 int size = perf_evsel__read_size(&leader->core);
1634 u64 *data = ps->group_data;
1636 if (!(read_format & PERF_FORMAT_ID))
1639 if (!evsel__is_group_leader(leader))
1643 data = zalloc(size);
1647 ps->group_data = data;
1650 if (FD(leader, cpu_map_idx, thread) < 0)
1653 if (readn(FD(leader, cpu_map_idx, thread), data, size) <= 0)
1656 return evsel__process_group_data(leader, cpu_map_idx, thread, data);
1659 int evsel__read_counter(struct evsel *evsel, int cpu_map_idx, int thread)
1661 u64 read_format = evsel->core.attr.read_format;
1663 if (read_format & PERF_FORMAT_GROUP)
1664 return evsel__read_group(evsel, cpu_map_idx, thread);
1666 return evsel__read_one(evsel, cpu_map_idx, thread);
1669 int __evsel__read_on_cpu(struct evsel *evsel, int cpu_map_idx, int thread, bool scale)
1671 struct perf_counts_values count;
1672 size_t nv = scale ? 3 : 1;
1674 if (FD(evsel, cpu_map_idx, thread) < 0)
1677 if (evsel->counts == NULL && evsel__alloc_counts(evsel) < 0)
1680 if (readn(FD(evsel, cpu_map_idx, thread), &count, nv * sizeof(u64)) <= 0)
1683 evsel__compute_deltas(evsel, cpu_map_idx, thread, &count);
1684 perf_counts_values__scale(&count, scale, NULL);
1685 *perf_counts(evsel->counts, cpu_map_idx, thread) = count;
1689 static int evsel__match_other_cpu(struct evsel *evsel, struct evsel *other,
1692 struct perf_cpu cpu;
1694 cpu = perf_cpu_map__cpu(evsel->core.cpus, cpu_map_idx);
1695 return perf_cpu_map__idx(other->core.cpus, cpu);
1698 static int evsel__hybrid_group_cpu_map_idx(struct evsel *evsel, int cpu_map_idx)
1700 struct evsel *leader = evsel__leader(evsel);
1702 if ((evsel__is_hybrid(evsel) && !evsel__is_hybrid(leader)) ||
1703 (!evsel__is_hybrid(evsel) && evsel__is_hybrid(leader))) {
1704 return evsel__match_other_cpu(evsel, leader, cpu_map_idx);
1710 static int get_group_fd(struct evsel *evsel, int cpu_map_idx, int thread)
1712 struct evsel *leader = evsel__leader(evsel);
1715 if (evsel__is_group_leader(evsel))
1719 * Leader must be already processed/open,
1720 * if not it's a bug.
1722 BUG_ON(!leader->core.fd);
1724 cpu_map_idx = evsel__hybrid_group_cpu_map_idx(evsel, cpu_map_idx);
1725 if (cpu_map_idx == -1)
1728 fd = FD(leader, cpu_map_idx, thread);
1729 BUG_ON(fd == -1 && !leader->skippable);
1732 * When the leader has been skipped, return -2 to distinguish from no
1733 * group leader case.
1735 return fd == -1 ? -2 : fd;
1738 static void evsel__remove_fd(struct evsel *pos, int nr_cpus, int nr_threads, int thread_idx)
1740 for (int cpu = 0; cpu < nr_cpus; cpu++)
1741 for (int thread = thread_idx; thread < nr_threads - 1; thread++)
1742 FD(pos, cpu, thread) = FD(pos, cpu, thread + 1);
1745 static int update_fds(struct evsel *evsel,
1746 int nr_cpus, int cpu_map_idx,
1747 int nr_threads, int thread_idx)
1751 if (cpu_map_idx >= nr_cpus || thread_idx >= nr_threads)
1754 evlist__for_each_entry(evsel->evlist, pos) {
1755 nr_cpus = pos != evsel ? nr_cpus : cpu_map_idx;
1757 evsel__remove_fd(pos, nr_cpus, nr_threads, thread_idx);
1760 * Since fds for next evsel has not been created,
1761 * there is no need to iterate whole event list.
1769 static bool evsel__ignore_missing_thread(struct evsel *evsel,
1770 int nr_cpus, int cpu_map_idx,
1771 struct perf_thread_map *threads,
1772 int thread, int err)
1774 pid_t ignore_pid = perf_thread_map__pid(threads, thread);
1776 if (!evsel->ignore_missing_thread)
1779 /* The system wide setup does not work with threads. */
1780 if (evsel->core.system_wide)
1783 /* The -ESRCH is perf event syscall errno for pid's not found. */
1787 /* If there's only one thread, let it fail. */
1788 if (threads->nr == 1)
1792 * We should remove fd for missing_thread first
1793 * because thread_map__remove() will decrease threads->nr.
1795 if (update_fds(evsel, nr_cpus, cpu_map_idx, threads->nr, thread))
1798 if (thread_map__remove(threads, thread))
1801 pr_warning("WARNING: Ignored open failure for pid %d\n",
1806 static int __open_attr__fprintf(FILE *fp, const char *name, const char *val,
1807 void *priv __maybe_unused)
1809 return fprintf(fp, " %-32s %s\n", name, val);
1812 static void display_attr(struct perf_event_attr *attr)
1814 if (verbose >= 2 || debug_peo_args) {
1815 fprintf(stderr, "%.60s\n", graph_dotted_line);
1816 fprintf(stderr, "perf_event_attr:\n");
1817 perf_event_attr__fprintf(stderr, attr, __open_attr__fprintf, NULL);
1818 fprintf(stderr, "%.60s\n", graph_dotted_line);
1822 bool evsel__precise_ip_fallback(struct evsel *evsel)
1824 /* Do not try less precise if not requested. */
1825 if (!evsel->precise_max)
1829 * We tried all the precise_ip values, and it's
1830 * still failing, so leave it to standard fallback.
1832 if (!evsel->core.attr.precise_ip) {
1833 evsel->core.attr.precise_ip = evsel->precise_ip_original;
1837 if (!evsel->precise_ip_original)
1838 evsel->precise_ip_original = evsel->core.attr.precise_ip;
1840 evsel->core.attr.precise_ip--;
1841 pr_debug2_peo("decreasing precise_ip by one (%d)\n", evsel->core.attr.precise_ip);
1842 display_attr(&evsel->core.attr);
1846 static struct perf_cpu_map *empty_cpu_map;
1847 static struct perf_thread_map *empty_thread_map;
1849 static int __evsel__prepare_open(struct evsel *evsel, struct perf_cpu_map *cpus,
1850 struct perf_thread_map *threads)
1852 int nthreads = perf_thread_map__nr(threads);
1854 if ((perf_missing_features.write_backward && evsel->core.attr.write_backward) ||
1855 (perf_missing_features.aux_output && evsel->core.attr.aux_output))
1859 if (empty_cpu_map == NULL) {
1860 empty_cpu_map = perf_cpu_map__dummy_new();
1861 if (empty_cpu_map == NULL)
1865 cpus = empty_cpu_map;
1868 if (threads == NULL) {
1869 if (empty_thread_map == NULL) {
1870 empty_thread_map = thread_map__new_by_tid(-1);
1871 if (empty_thread_map == NULL)
1875 threads = empty_thread_map;
1878 if (evsel->core.fd == NULL &&
1879 perf_evsel__alloc_fd(&evsel->core, perf_cpu_map__nr(cpus), nthreads) < 0)
1882 evsel->open_flags = PERF_FLAG_FD_CLOEXEC;
1884 evsel->open_flags |= PERF_FLAG_PID_CGROUP;
1889 static void evsel__disable_missing_features(struct evsel *evsel)
1891 if (perf_missing_features.read_lost)
1892 evsel->core.attr.read_format &= ~PERF_FORMAT_LOST;
1893 if (perf_missing_features.weight_struct) {
1894 evsel__set_sample_bit(evsel, WEIGHT);
1895 evsel__reset_sample_bit(evsel, WEIGHT_STRUCT);
1897 if (perf_missing_features.clockid_wrong)
1898 evsel->core.attr.clockid = CLOCK_MONOTONIC; /* should always work */
1899 if (perf_missing_features.clockid) {
1900 evsel->core.attr.use_clockid = 0;
1901 evsel->core.attr.clockid = 0;
1903 if (perf_missing_features.cloexec)
1904 evsel->open_flags &= ~(unsigned long)PERF_FLAG_FD_CLOEXEC;
1905 if (perf_missing_features.mmap2)
1906 evsel->core.attr.mmap2 = 0;
1907 if (evsel->pmu && evsel->pmu->missing_features.exclude_guest)
1908 evsel->core.attr.exclude_guest = evsel->core.attr.exclude_host = 0;
1909 if (perf_missing_features.lbr_flags)
1910 evsel->core.attr.branch_sample_type &= ~(PERF_SAMPLE_BRANCH_NO_FLAGS |
1911 PERF_SAMPLE_BRANCH_NO_CYCLES);
1912 if (perf_missing_features.group_read && evsel->core.attr.inherit)
1913 evsel->core.attr.read_format &= ~(PERF_FORMAT_GROUP|PERF_FORMAT_ID);
1914 if (perf_missing_features.ksymbol)
1915 evsel->core.attr.ksymbol = 0;
1916 if (perf_missing_features.bpf)
1917 evsel->core.attr.bpf_event = 0;
1918 if (perf_missing_features.branch_hw_idx)
1919 evsel->core.attr.branch_sample_type &= ~PERF_SAMPLE_BRANCH_HW_INDEX;
1920 if (perf_missing_features.sample_id_all)
1921 evsel->core.attr.sample_id_all = 0;
1924 int evsel__prepare_open(struct evsel *evsel, struct perf_cpu_map *cpus,
1925 struct perf_thread_map *threads)
1929 err = __evsel__prepare_open(evsel, cpus, threads);
1933 evsel__disable_missing_features(evsel);
1938 bool evsel__detect_missing_features(struct evsel *evsel)
1941 * Must probe features in the order they were added to the
1942 * perf_event_attr interface.
1944 if (!perf_missing_features.read_lost &&
1945 (evsel->core.attr.read_format & PERF_FORMAT_LOST)) {
1946 perf_missing_features.read_lost = true;
1947 pr_debug2("switching off PERF_FORMAT_LOST support\n");
1949 } else if (!perf_missing_features.weight_struct &&
1950 (evsel->core.attr.sample_type & PERF_SAMPLE_WEIGHT_STRUCT)) {
1951 perf_missing_features.weight_struct = true;
1952 pr_debug2("switching off weight struct support\n");
1954 } else if (!perf_missing_features.code_page_size &&
1955 (evsel->core.attr.sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)) {
1956 perf_missing_features.code_page_size = true;
1957 pr_debug2_peo("Kernel has no PERF_SAMPLE_CODE_PAGE_SIZE support, bailing out\n");
1959 } else if (!perf_missing_features.data_page_size &&
1960 (evsel->core.attr.sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)) {
1961 perf_missing_features.data_page_size = true;
1962 pr_debug2_peo("Kernel has no PERF_SAMPLE_DATA_PAGE_SIZE support, bailing out\n");
1964 } else if (!perf_missing_features.cgroup && evsel->core.attr.cgroup) {
1965 perf_missing_features.cgroup = true;
1966 pr_debug2_peo("Kernel has no cgroup sampling support, bailing out\n");
1968 } else if (!perf_missing_features.branch_hw_idx &&
1969 (evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX)) {
1970 perf_missing_features.branch_hw_idx = true;
1971 pr_debug2("switching off branch HW index support\n");
1973 } else if (!perf_missing_features.aux_output && evsel->core.attr.aux_output) {
1974 perf_missing_features.aux_output = true;
1975 pr_debug2_peo("Kernel has no attr.aux_output support, bailing out\n");
1977 } else if (!perf_missing_features.bpf && evsel->core.attr.bpf_event) {
1978 perf_missing_features.bpf = true;
1979 pr_debug2_peo("switching off bpf_event\n");
1981 } else if (!perf_missing_features.ksymbol && evsel->core.attr.ksymbol) {
1982 perf_missing_features.ksymbol = true;
1983 pr_debug2_peo("switching off ksymbol\n");
1985 } else if (!perf_missing_features.write_backward && evsel->core.attr.write_backward) {
1986 perf_missing_features.write_backward = true;
1987 pr_debug2_peo("switching off write_backward\n");
1989 } else if (!perf_missing_features.clockid_wrong && evsel->core.attr.use_clockid) {
1990 perf_missing_features.clockid_wrong = true;
1991 pr_debug2_peo("switching off clockid\n");
1993 } else if (!perf_missing_features.clockid && evsel->core.attr.use_clockid) {
1994 perf_missing_features.clockid = true;
1995 pr_debug2_peo("switching off use_clockid\n");
1997 } else if (!perf_missing_features.cloexec && (evsel->open_flags & PERF_FLAG_FD_CLOEXEC)) {
1998 perf_missing_features.cloexec = true;
1999 pr_debug2_peo("switching off cloexec flag\n");
2001 } else if (!perf_missing_features.mmap2 && evsel->core.attr.mmap2) {
2002 perf_missing_features.mmap2 = true;
2003 pr_debug2_peo("switching off mmap2\n");
2005 } else if (evsel->core.attr.exclude_guest || evsel->core.attr.exclude_host) {
2006 if (evsel->pmu == NULL)
2007 evsel->pmu = evsel__find_pmu(evsel);
2010 evsel->pmu->missing_features.exclude_guest = true;
2012 /* we cannot find PMU, disable attrs now */
2013 evsel->core.attr.exclude_host = false;
2014 evsel->core.attr.exclude_guest = false;
2017 if (evsel->exclude_GH) {
2018 pr_debug2_peo("PMU has no exclude_host/guest support, bailing out\n");
2021 if (!perf_missing_features.exclude_guest) {
2022 perf_missing_features.exclude_guest = true;
2023 pr_debug2_peo("switching off exclude_guest, exclude_host\n");
2026 } else if (!perf_missing_features.sample_id_all) {
2027 perf_missing_features.sample_id_all = true;
2028 pr_debug2_peo("switching off sample_id_all\n");
2030 } else if (!perf_missing_features.lbr_flags &&
2031 (evsel->core.attr.branch_sample_type &
2032 (PERF_SAMPLE_BRANCH_NO_CYCLES |
2033 PERF_SAMPLE_BRANCH_NO_FLAGS))) {
2034 perf_missing_features.lbr_flags = true;
2035 pr_debug2_peo("switching off branch sample type no (cycles/flags)\n");
2037 } else if (!perf_missing_features.group_read &&
2038 evsel->core.attr.inherit &&
2039 (evsel->core.attr.read_format & PERF_FORMAT_GROUP) &&
2040 evsel__is_group_leader(evsel)) {
2041 perf_missing_features.group_read = true;
2042 pr_debug2_peo("switching off group read\n");
2049 bool evsel__increase_rlimit(enum rlimit_action *set_rlimit)
2054 if (*set_rlimit < INCREASED_MAX) {
2057 if (getrlimit(RLIMIT_NOFILE, &l) == 0) {
2058 if (*set_rlimit == NO_CHANGE) {
2059 l.rlim_cur = l.rlim_max;
2061 l.rlim_cur = l.rlim_max + 1000;
2062 l.rlim_max = l.rlim_cur;
2064 if (setrlimit(RLIMIT_NOFILE, &l) == 0) {
2076 static int evsel__open_cpu(struct evsel *evsel, struct perf_cpu_map *cpus,
2077 struct perf_thread_map *threads,
2078 int start_cpu_map_idx, int end_cpu_map_idx)
2080 int idx, thread, nthreads;
2081 int pid = -1, err, old_errno;
2082 enum rlimit_action set_rlimit = NO_CHANGE;
2084 err = __evsel__prepare_open(evsel, cpus, threads);
2089 cpus = empty_cpu_map;
2091 if (threads == NULL)
2092 threads = empty_thread_map;
2094 nthreads = perf_thread_map__nr(threads);
2097 pid = evsel->cgrp->fd;
2099 fallback_missing_features:
2100 evsel__disable_missing_features(evsel);
2102 display_attr(&evsel->core.attr);
2104 for (idx = start_cpu_map_idx; idx < end_cpu_map_idx; idx++) {
2106 for (thread = 0; thread < nthreads; thread++) {
2109 if (thread >= nthreads)
2112 if (!evsel->cgrp && !evsel->core.system_wide)
2113 pid = perf_thread_map__pid(threads, thread);
2115 group_fd = get_group_fd(evsel, idx, thread);
2117 if (group_fd == -2) {
2118 pr_debug("broken group leader for %s\n", evsel->name);
2125 /* Debug message used by test scripts */
2126 pr_debug2_peo("sys_perf_event_open: pid %d cpu %d group_fd %d flags %#lx",
2127 pid, perf_cpu_map__cpu(cpus, idx).cpu, group_fd, evsel->open_flags);
2129 fd = sys_perf_event_open(&evsel->core.attr, pid,
2130 perf_cpu_map__cpu(cpus, idx).cpu,
2131 group_fd, evsel->open_flags);
2133 FD(evsel, idx, thread) = fd;
2138 pr_debug2_peo("\nsys_perf_event_open failed, error %d\n",
2143 bpf_counter__install_pe(evsel, idx, fd);
2145 if (unlikely(test_attr__enabled)) {
2146 test_attr__open(&evsel->core.attr, pid,
2147 perf_cpu_map__cpu(cpus, idx),
2148 fd, group_fd, evsel->open_flags);
2151 /* Debug message used by test scripts */
2152 pr_debug2_peo(" = %d\n", fd);
2154 if (evsel->bpf_fd >= 0) {
2156 int bpf_fd = evsel->bpf_fd;
2159 PERF_EVENT_IOC_SET_BPF,
2161 if (err && errno != EEXIST) {
2162 pr_err("failed to attach bpf fd %d: %s\n",
2163 bpf_fd, strerror(errno));
2169 set_rlimit = NO_CHANGE;
2172 * If we succeeded but had to kill clockid, fail and
2173 * have evsel__open_strerror() print us a nice error.
2175 if (perf_missing_features.clockid ||
2176 perf_missing_features.clockid_wrong) {
2186 if (evsel__precise_ip_fallback(evsel))
2189 if (evsel__ignore_missing_thread(evsel, perf_cpu_map__nr(cpus),
2190 idx, threads, thread, err)) {
2191 /* We just removed 1 thread, so lower the upper nthreads limit. */
2194 /* ... and pretend like nothing have happened. */
2199 * perf stat needs between 5 and 22 fds per CPU. When we run out
2200 * of them try to increase the limits.
2202 if (err == -EMFILE && evsel__increase_rlimit(&set_rlimit))
2205 if (err != -EINVAL || idx > 0 || thread > 0)
2208 if (evsel__detect_missing_features(evsel))
2209 goto fallback_missing_features;
2212 threads->err_thread = thread;
2216 while (--thread >= 0) {
2217 if (FD(evsel, idx, thread) >= 0)
2218 close(FD(evsel, idx, thread));
2219 FD(evsel, idx, thread) = -1;
2222 } while (--idx >= 0);
2227 int evsel__open(struct evsel *evsel, struct perf_cpu_map *cpus,
2228 struct perf_thread_map *threads)
2230 return evsel__open_cpu(evsel, cpus, threads, 0, perf_cpu_map__nr(cpus));
2233 void evsel__close(struct evsel *evsel)
2235 perf_evsel__close(&evsel->core);
2236 perf_evsel__free_id(&evsel->core);
2239 int evsel__open_per_cpu(struct evsel *evsel, struct perf_cpu_map *cpus, int cpu_map_idx)
2241 if (cpu_map_idx == -1)
2242 return evsel__open_cpu(evsel, cpus, NULL, 0, perf_cpu_map__nr(cpus));
2244 return evsel__open_cpu(evsel, cpus, NULL, cpu_map_idx, cpu_map_idx + 1);
2247 int evsel__open_per_thread(struct evsel *evsel, struct perf_thread_map *threads)
2249 return evsel__open(evsel, NULL, threads);
2252 static int perf_evsel__parse_id_sample(const struct evsel *evsel,
2253 const union perf_event *event,
2254 struct perf_sample *sample)
2256 u64 type = evsel->core.attr.sample_type;
2257 const __u64 *array = event->sample.array;
2258 bool swapped = evsel->needs_swap;
2261 array += ((event->header.size -
2262 sizeof(event->header)) / sizeof(u64)) - 1;
2264 if (type & PERF_SAMPLE_IDENTIFIER) {
2265 sample->id = *array;
2269 if (type & PERF_SAMPLE_CPU) {
2272 /* undo swap of u64, then swap on individual u32s */
2273 u.val64 = bswap_64(u.val64);
2274 u.val32[0] = bswap_32(u.val32[0]);
2277 sample->cpu = u.val32[0];
2281 if (type & PERF_SAMPLE_STREAM_ID) {
2282 sample->stream_id = *array;
2286 if (type & PERF_SAMPLE_ID) {
2287 sample->id = *array;
2291 if (type & PERF_SAMPLE_TIME) {
2292 sample->time = *array;
2296 if (type & PERF_SAMPLE_TID) {
2299 /* undo swap of u64, then swap on individual u32s */
2300 u.val64 = bswap_64(u.val64);
2301 u.val32[0] = bswap_32(u.val32[0]);
2302 u.val32[1] = bswap_32(u.val32[1]);
2305 sample->pid = u.val32[0];
2306 sample->tid = u.val32[1];
2313 static inline bool overflow(const void *endp, u16 max_size, const void *offset,
2316 return size > max_size || offset + size > endp;
2319 #define OVERFLOW_CHECK(offset, size, max_size) \
2321 if (overflow(endp, (max_size), (offset), (size))) \
2325 #define OVERFLOW_CHECK_u64(offset) \
2326 OVERFLOW_CHECK(offset, sizeof(u64), sizeof(u64))
2329 perf_event__check_size(union perf_event *event, unsigned int sample_size)
2332 * The evsel's sample_size is based on PERF_SAMPLE_MASK which includes
2333 * up to PERF_SAMPLE_PERIOD. After that overflow() must be used to
2334 * check the format does not go past the end of the event.
2336 if (sample_size + sizeof(event->header) > event->header.size)
2342 void __weak arch_perf_parse_sample_weight(struct perf_sample *data,
2344 u64 type __maybe_unused)
2346 data->weight = *array;
2349 u64 evsel__bitfield_swap_branch_flags(u64 value)
2358 * mispred:1 //target mispredicted
2359 * predicted:1 //target predicted
2360 * in_tx:1 //in transaction
2361 * abort:1 //transaction abort
2362 * cycles:16 //cycle count to last branch
2363 * type:4 //branch type
2364 * spec:2 //branch speculation info
2365 * new_type:4 //additional branch type
2366 * priv:3 //privilege level
2371 * Avoid bswap64() the entire branch_flag.value,
2372 * as it has variable bit-field sizes. Instead the
2373 * macro takes the bit-field position/size,
2374 * swaps it based on the host endianness.
2376 if (host_is_bigendian()) {
2377 new_val = bitfield_swap(value, 0, 1);
2378 new_val |= bitfield_swap(value, 1, 1);
2379 new_val |= bitfield_swap(value, 2, 1);
2380 new_val |= bitfield_swap(value, 3, 1);
2381 new_val |= bitfield_swap(value, 4, 16);
2382 new_val |= bitfield_swap(value, 20, 4);
2383 new_val |= bitfield_swap(value, 24, 2);
2384 new_val |= bitfield_swap(value, 26, 4);
2385 new_val |= bitfield_swap(value, 30, 3);
2386 new_val |= bitfield_swap(value, 33, 31);
2388 new_val = bitfield_swap(value, 63, 1);
2389 new_val |= bitfield_swap(value, 62, 1);
2390 new_val |= bitfield_swap(value, 61, 1);
2391 new_val |= bitfield_swap(value, 60, 1);
2392 new_val |= bitfield_swap(value, 44, 16);
2393 new_val |= bitfield_swap(value, 40, 4);
2394 new_val |= bitfield_swap(value, 38, 2);
2395 new_val |= bitfield_swap(value, 34, 4);
2396 new_val |= bitfield_swap(value, 31, 3);
2397 new_val |= bitfield_swap(value, 0, 31);
2403 int evsel__parse_sample(struct evsel *evsel, union perf_event *event,
2404 struct perf_sample *data)
2406 u64 type = evsel->core.attr.sample_type;
2407 bool swapped = evsel->needs_swap;
2409 u16 max_size = event->header.size;
2410 const void *endp = (void *)event + max_size;
2414 * used for cross-endian analysis. See git commit 65014ab3
2415 * for why this goofiness is needed.
2419 memset(data, 0, sizeof(*data));
2420 data->cpu = data->pid = data->tid = -1;
2421 data->stream_id = data->id = data->time = -1ULL;
2422 data->period = evsel->core.attr.sample_period;
2423 data->cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
2424 data->misc = event->header.misc;
2426 data->data_src = PERF_MEM_DATA_SRC_NONE;
2429 if (event->header.type != PERF_RECORD_SAMPLE) {
2430 if (!evsel->core.attr.sample_id_all)
2432 return perf_evsel__parse_id_sample(evsel, event, data);
2435 array = event->sample.array;
2437 if (perf_event__check_size(event, evsel->sample_size))
2440 if (type & PERF_SAMPLE_IDENTIFIER) {
2445 if (type & PERF_SAMPLE_IP) {
2450 if (type & PERF_SAMPLE_TID) {
2453 /* undo swap of u64, then swap on individual u32s */
2454 u.val64 = bswap_64(u.val64);
2455 u.val32[0] = bswap_32(u.val32[0]);
2456 u.val32[1] = bswap_32(u.val32[1]);
2459 data->pid = u.val32[0];
2460 data->tid = u.val32[1];
2464 if (type & PERF_SAMPLE_TIME) {
2465 data->time = *array;
2469 if (type & PERF_SAMPLE_ADDR) {
2470 data->addr = *array;
2474 if (type & PERF_SAMPLE_ID) {
2479 if (type & PERF_SAMPLE_STREAM_ID) {
2480 data->stream_id = *array;
2484 if (type & PERF_SAMPLE_CPU) {
2488 /* undo swap of u64, then swap on individual u32s */
2489 u.val64 = bswap_64(u.val64);
2490 u.val32[0] = bswap_32(u.val32[0]);
2493 data->cpu = u.val32[0];
2497 if (type & PERF_SAMPLE_PERIOD) {
2498 data->period = *array;
2502 if (type & PERF_SAMPLE_READ) {
2503 u64 read_format = evsel->core.attr.read_format;
2505 OVERFLOW_CHECK_u64(array);
2506 if (read_format & PERF_FORMAT_GROUP)
2507 data->read.group.nr = *array;
2509 data->read.one.value = *array;
2513 if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2514 OVERFLOW_CHECK_u64(array);
2515 data->read.time_enabled = *array;
2519 if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2520 OVERFLOW_CHECK_u64(array);
2521 data->read.time_running = *array;
2525 /* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
2526 if (read_format & PERF_FORMAT_GROUP) {
2527 const u64 max_group_nr = UINT64_MAX /
2528 sizeof(struct sample_read_value);
2530 if (data->read.group.nr > max_group_nr)
2533 sz = data->read.group.nr * sample_read_value_size(read_format);
2534 OVERFLOW_CHECK(array, sz, max_size);
2535 data->read.group.values =
2536 (struct sample_read_value *)array;
2537 array = (void *)array + sz;
2539 OVERFLOW_CHECK_u64(array);
2540 data->read.one.id = *array;
2543 if (read_format & PERF_FORMAT_LOST) {
2544 OVERFLOW_CHECK_u64(array);
2545 data->read.one.lost = *array;
2551 if (type & PERF_SAMPLE_CALLCHAIN) {
2552 const u64 max_callchain_nr = UINT64_MAX / sizeof(u64);
2554 OVERFLOW_CHECK_u64(array);
2555 data->callchain = (struct ip_callchain *)array++;
2556 if (data->callchain->nr > max_callchain_nr)
2558 sz = data->callchain->nr * sizeof(u64);
2559 OVERFLOW_CHECK(array, sz, max_size);
2560 array = (void *)array + sz;
2563 if (type & PERF_SAMPLE_RAW) {
2564 OVERFLOW_CHECK_u64(array);
2568 * Undo swap of u64, then swap on individual u32s,
2569 * get the size of the raw area and undo all of the
2570 * swap. The pevent interface handles endianness by
2574 u.val64 = bswap_64(u.val64);
2575 u.val32[0] = bswap_32(u.val32[0]);
2576 u.val32[1] = bswap_32(u.val32[1]);
2578 data->raw_size = u.val32[0];
2581 * The raw data is aligned on 64bits including the
2582 * u32 size, so it's safe to use mem_bswap_64.
2585 mem_bswap_64((void *) array, data->raw_size);
2587 array = (void *)array + sizeof(u32);
2589 OVERFLOW_CHECK(array, data->raw_size, max_size);
2590 data->raw_data = (void *)array;
2591 array = (void *)array + data->raw_size;
2594 if (type & PERF_SAMPLE_BRANCH_STACK) {
2595 const u64 max_branch_nr = UINT64_MAX /
2596 sizeof(struct branch_entry);
2597 struct branch_entry *e;
2600 OVERFLOW_CHECK_u64(array);
2601 data->branch_stack = (struct branch_stack *)array++;
2603 if (data->branch_stack->nr > max_branch_nr)
2606 sz = data->branch_stack->nr * sizeof(struct branch_entry);
2607 if (evsel__has_branch_hw_idx(evsel)) {
2609 e = &data->branch_stack->entries[0];
2611 data->no_hw_idx = true;
2613 * if the PERF_SAMPLE_BRANCH_HW_INDEX is not applied,
2614 * only nr and entries[] will be output by kernel.
2616 e = (struct branch_entry *)&data->branch_stack->hw_idx;
2621 * struct branch_flag does not have endian
2622 * specific bit field definition. And bswap
2623 * will not resolve the issue, since these
2626 * evsel__bitfield_swap_branch_flags() uses a
2627 * bitfield_swap macro to swap the bit position
2628 * based on the host endians.
2630 for (i = 0; i < data->branch_stack->nr; i++, e++)
2631 e->flags.value = evsel__bitfield_swap_branch_flags(e->flags.value);
2634 OVERFLOW_CHECK(array, sz, max_size);
2635 array = (void *)array + sz;
2638 if (type & PERF_SAMPLE_REGS_USER) {
2639 OVERFLOW_CHECK_u64(array);
2640 data->user_regs.abi = *array;
2643 if (data->user_regs.abi) {
2644 u64 mask = evsel->core.attr.sample_regs_user;
2646 sz = hweight64(mask) * sizeof(u64);
2647 OVERFLOW_CHECK(array, sz, max_size);
2648 data->user_regs.mask = mask;
2649 data->user_regs.regs = (u64 *)array;
2650 array = (void *)array + sz;
2654 if (type & PERF_SAMPLE_STACK_USER) {
2655 OVERFLOW_CHECK_u64(array);
2658 data->user_stack.offset = ((char *)(array - 1)
2662 data->user_stack.size = 0;
2664 OVERFLOW_CHECK(array, sz, max_size);
2665 data->user_stack.data = (char *)array;
2666 array = (void *)array + sz;
2667 OVERFLOW_CHECK_u64(array);
2668 data->user_stack.size = *array++;
2669 if (WARN_ONCE(data->user_stack.size > sz,
2670 "user stack dump failure\n"))
2675 if (type & PERF_SAMPLE_WEIGHT_TYPE) {
2676 OVERFLOW_CHECK_u64(array);
2677 arch_perf_parse_sample_weight(data, array, type);
2681 if (type & PERF_SAMPLE_DATA_SRC) {
2682 OVERFLOW_CHECK_u64(array);
2683 data->data_src = *array;
2687 if (type & PERF_SAMPLE_TRANSACTION) {
2688 OVERFLOW_CHECK_u64(array);
2689 data->transaction = *array;
2693 data->intr_regs.abi = PERF_SAMPLE_REGS_ABI_NONE;
2694 if (type & PERF_SAMPLE_REGS_INTR) {
2695 OVERFLOW_CHECK_u64(array);
2696 data->intr_regs.abi = *array;
2699 if (data->intr_regs.abi != PERF_SAMPLE_REGS_ABI_NONE) {
2700 u64 mask = evsel->core.attr.sample_regs_intr;
2702 sz = hweight64(mask) * sizeof(u64);
2703 OVERFLOW_CHECK(array, sz, max_size);
2704 data->intr_regs.mask = mask;
2705 data->intr_regs.regs = (u64 *)array;
2706 array = (void *)array + sz;
2710 data->phys_addr = 0;
2711 if (type & PERF_SAMPLE_PHYS_ADDR) {
2712 data->phys_addr = *array;
2717 if (type & PERF_SAMPLE_CGROUP) {
2718 data->cgroup = *array;
2722 data->data_page_size = 0;
2723 if (type & PERF_SAMPLE_DATA_PAGE_SIZE) {
2724 data->data_page_size = *array;
2728 data->code_page_size = 0;
2729 if (type & PERF_SAMPLE_CODE_PAGE_SIZE) {
2730 data->code_page_size = *array;
2734 if (type & PERF_SAMPLE_AUX) {
2735 OVERFLOW_CHECK_u64(array);
2738 OVERFLOW_CHECK(array, sz, max_size);
2739 /* Undo swap of data */
2741 mem_bswap_64((char *)array, sz);
2742 data->aux_sample.size = sz;
2743 data->aux_sample.data = (char *)array;
2744 array = (void *)array + sz;
2750 int evsel__parse_sample_timestamp(struct evsel *evsel, union perf_event *event,
2753 u64 type = evsel->core.attr.sample_type;
2756 if (!(type & PERF_SAMPLE_TIME))
2759 if (event->header.type != PERF_RECORD_SAMPLE) {
2760 struct perf_sample data = {
2764 if (!evsel->core.attr.sample_id_all)
2766 if (perf_evsel__parse_id_sample(evsel, event, &data))
2769 *timestamp = data.time;
2773 array = event->sample.array;
2775 if (perf_event__check_size(event, evsel->sample_size))
2778 if (type & PERF_SAMPLE_IDENTIFIER)
2781 if (type & PERF_SAMPLE_IP)
2784 if (type & PERF_SAMPLE_TID)
2787 if (type & PERF_SAMPLE_TIME)
2788 *timestamp = *array;
2793 u16 evsel__id_hdr_size(struct evsel *evsel)
2795 u64 sample_type = evsel->core.attr.sample_type;
2798 if (sample_type & PERF_SAMPLE_TID)
2799 size += sizeof(u64);
2801 if (sample_type & PERF_SAMPLE_TIME)
2802 size += sizeof(u64);
2804 if (sample_type & PERF_SAMPLE_ID)
2805 size += sizeof(u64);
2807 if (sample_type & PERF_SAMPLE_STREAM_ID)
2808 size += sizeof(u64);
2810 if (sample_type & PERF_SAMPLE_CPU)
2811 size += sizeof(u64);
2813 if (sample_type & PERF_SAMPLE_IDENTIFIER)
2814 size += sizeof(u64);
2819 #ifdef HAVE_LIBTRACEEVENT
2820 struct tep_format_field *evsel__field(struct evsel *evsel, const char *name)
2822 return tep_find_field(evsel->tp_format, name);
2825 void *evsel__rawptr(struct evsel *evsel, struct perf_sample *sample, const char *name)
2827 struct tep_format_field *field = evsel__field(evsel, name);
2833 offset = field->offset;
2835 if (field->flags & TEP_FIELD_IS_DYNAMIC) {
2836 offset = *(int *)(sample->raw_data + field->offset);
2838 if (tep_field_is_relative(field->flags))
2839 offset += field->offset + field->size;
2842 return sample->raw_data + offset;
2845 u64 format_field__intval(struct tep_format_field *field, struct perf_sample *sample,
2849 void *ptr = sample->raw_data + field->offset;
2851 switch (field->size) {
2855 value = *(u16 *)ptr;
2858 value = *(u32 *)ptr;
2861 memcpy(&value, ptr, sizeof(u64));
2870 switch (field->size) {
2872 return bswap_16(value);
2874 return bswap_32(value);
2876 return bswap_64(value);
2884 u64 evsel__intval(struct evsel *evsel, struct perf_sample *sample, const char *name)
2886 struct tep_format_field *field = evsel__field(evsel, name);
2891 return field ? format_field__intval(field, sample, evsel->needs_swap) : 0;
2895 bool evsel__fallback(struct evsel *evsel, int err, char *msg, size_t msgsize)
2899 if ((err == ENOENT || err == ENXIO || err == ENODEV) &&
2900 evsel->core.attr.type == PERF_TYPE_HARDWARE &&
2901 evsel->core.attr.config == PERF_COUNT_HW_CPU_CYCLES) {
2903 * If it's cycles then fall back to hrtimer based
2904 * cpu-clock-tick sw counter, which is always available even if
2907 * PPC returns ENXIO until 2.6.37 (behavior changed with commit
2910 scnprintf(msg, msgsize, "%s",
2911 "The cycles event is not supported, trying to fall back to cpu-clock-ticks");
2913 evsel->core.attr.type = PERF_TYPE_SOFTWARE;
2914 evsel->core.attr.config = PERF_COUNT_SW_CPU_CLOCK;
2916 zfree(&evsel->name);
2918 } else if (err == EACCES && !evsel->core.attr.exclude_kernel &&
2919 (paranoid = perf_event_paranoid()) > 1) {
2920 const char *name = evsel__name(evsel);
2922 const char *sep = ":";
2924 /* If event has exclude user then don't exclude kernel. */
2925 if (evsel->core.attr.exclude_user)
2928 /* Is there already the separator in the name. */
2929 if (strchr(name, '/') ||
2930 (strchr(name, ':') && !evsel->is_libpfm_event))
2933 if (asprintf(&new_name, "%s%su", name, sep) < 0)
2937 evsel->name = new_name;
2938 scnprintf(msg, msgsize, "kernel.perf_event_paranoid=%d, trying "
2939 "to fall back to excluding kernel and hypervisor "
2940 " samples", paranoid);
2941 evsel->core.attr.exclude_kernel = 1;
2942 evsel->core.attr.exclude_hv = 1;
2950 static bool find_process(const char *name)
2952 size_t len = strlen(name);
2957 dir = opendir(procfs__mountpoint());
2961 /* Walk through the directory. */
2962 while (ret && (d = readdir(dir)) != NULL) {
2963 char path[PATH_MAX];
2967 if ((d->d_type != DT_DIR) ||
2968 !strcmp(".", d->d_name) ||
2969 !strcmp("..", d->d_name))
2972 scnprintf(path, sizeof(path), "%s/%s/comm",
2973 procfs__mountpoint(), d->d_name);
2975 if (filename__read_str(path, &data, &size))
2978 ret = strncmp(name, data, len);
2983 return ret ? false : true;
2986 static bool is_amd(const char *arch, const char *cpuid)
2988 return arch && !strcmp("x86", arch) && cpuid && strstarts(cpuid, "AuthenticAMD");
2991 static bool is_amd_ibs(struct evsel *evsel)
2993 return evsel->core.attr.precise_ip
2994 || (evsel->pmu_name && !strncmp(evsel->pmu_name, "ibs", 3));
2997 int evsel__open_strerror(struct evsel *evsel, struct target *target,
2998 int err, char *msg, size_t size)
3000 struct perf_env *env = evsel__env(evsel);
3001 const char *arch = perf_env__arch(env);
3002 const char *cpuid = perf_env__cpuid(env);
3003 char sbuf[STRERR_BUFSIZE];
3004 int printed = 0, enforced = 0;
3009 printed += scnprintf(msg + printed, size - printed,
3010 "Access to performance monitoring and observability operations is limited.\n");
3012 if (!sysfs__read_int("fs/selinux/enforce", &enforced)) {
3014 printed += scnprintf(msg + printed, size - printed,
3015 "Enforced MAC policy settings (SELinux) can limit access to performance\n"
3016 "monitoring and observability operations. Inspect system audit records for\n"
3017 "more perf_event access control information and adjusting the policy.\n");
3022 printed += scnprintf(msg, size,
3023 "No permission to enable %s event.\n\n", evsel__name(evsel));
3025 return scnprintf(msg + printed, size - printed,
3026 "Consider adjusting /proc/sys/kernel/perf_event_paranoid setting to open\n"
3027 "access to performance monitoring and observability operations for processes\n"
3028 "without CAP_PERFMON, CAP_SYS_PTRACE or CAP_SYS_ADMIN Linux capability.\n"
3029 "More information can be found at 'Perf events and tool security' document:\n"
3030 "https://www.kernel.org/doc/html/latest/admin-guide/perf-security.html\n"
3031 "perf_event_paranoid setting is %d:\n"
3032 " -1: Allow use of (almost) all events by all users\n"
3033 " Ignore mlock limit after perf_event_mlock_kb without CAP_IPC_LOCK\n"
3034 ">= 0: Disallow raw and ftrace function tracepoint access\n"
3035 ">= 1: Disallow CPU event access\n"
3036 ">= 2: Disallow kernel profiling\n"
3037 "To make the adjusted perf_event_paranoid setting permanent preserve it\n"
3038 "in /etc/sysctl.conf (e.g. kernel.perf_event_paranoid = <setting>)",
3039 perf_event_paranoid());
3041 return scnprintf(msg, size, "The %s event is not supported.", evsel__name(evsel));
3043 return scnprintf(msg, size, "%s",
3044 "Too many events are opened.\n"
3045 "Probably the maximum number of open file descriptors has been reached.\n"
3046 "Hint: Try again after reducing the number of events.\n"
3047 "Hint: Try increasing the limit with 'ulimit -n <limit>'");
3049 if (evsel__has_callchain(evsel) &&
3050 access("/proc/sys/kernel/perf_event_max_stack", F_OK) == 0)
3051 return scnprintf(msg, size,
3052 "Not enough memory to setup event with callchain.\n"
3053 "Hint: Try tweaking /proc/sys/kernel/perf_event_max_stack\n"
3054 "Hint: Current value: %d", sysctl__max_stack());
3057 if (target->cpu_list)
3058 return scnprintf(msg, size, "%s",
3059 "No such device - did you specify an out-of-range profile CPU?");
3062 if (evsel->core.attr.sample_type & PERF_SAMPLE_BRANCH_STACK)
3063 return scnprintf(msg, size,
3064 "%s: PMU Hardware or event type doesn't support branch stack sampling.",
3065 evsel__name(evsel));
3066 if (evsel->core.attr.aux_output)
3067 return scnprintf(msg, size,
3068 "%s: PMU Hardware doesn't support 'aux_output' feature",
3069 evsel__name(evsel));
3070 if (evsel->core.attr.sample_period != 0)
3071 return scnprintf(msg, size,
3072 "%s: PMU Hardware doesn't support sampling/overflow-interrupts. Try 'perf stat'",
3073 evsel__name(evsel));
3074 if (evsel->core.attr.precise_ip)
3075 return scnprintf(msg, size, "%s",
3076 "\'precise\' request may not be supported. Try removing 'p' modifier.");
3077 #if defined(__i386__) || defined(__x86_64__)
3078 if (evsel->core.attr.type == PERF_TYPE_HARDWARE)
3079 return scnprintf(msg, size, "%s",
3080 "No hardware sampling interrupt available.\n");
3084 if (find_process("oprofiled"))
3085 return scnprintf(msg, size,
3086 "The PMU counters are busy/taken by another profiler.\n"
3087 "We found oprofile daemon running, please stop it and try again.");
3090 if (evsel->core.attr.sample_type & PERF_SAMPLE_CODE_PAGE_SIZE && perf_missing_features.code_page_size)
3091 return scnprintf(msg, size, "Asking for the code page size isn't supported by this kernel.");
3092 if (evsel->core.attr.sample_type & PERF_SAMPLE_DATA_PAGE_SIZE && perf_missing_features.data_page_size)
3093 return scnprintf(msg, size, "Asking for the data page size isn't supported by this kernel.");
3094 if (evsel->core.attr.write_backward && perf_missing_features.write_backward)
3095 return scnprintf(msg, size, "Reading from overwrite event is not supported by this kernel.");
3096 if (perf_missing_features.clockid)
3097 return scnprintf(msg, size, "clockid feature not supported.");
3098 if (perf_missing_features.clockid_wrong)
3099 return scnprintf(msg, size, "wrong clockid (%d).", clockid);
3100 if (perf_missing_features.aux_output)
3101 return scnprintf(msg, size, "The 'aux_output' feature is not supported, update the kernel.");
3102 if (!target__has_cpu(target))
3103 return scnprintf(msg, size,
3104 "Invalid event (%s) in per-thread mode, enable system wide with '-a'.",
3105 evsel__name(evsel));
3106 if (is_amd(arch, cpuid)) {
3107 if (is_amd_ibs(evsel)) {
3108 if (evsel->core.attr.exclude_kernel)
3109 return scnprintf(msg, size,
3110 "AMD IBS can't exclude kernel events. Try running at a higher privilege level.");
3111 if (!evsel->core.system_wide)
3112 return scnprintf(msg, size,
3113 "AMD IBS may only be available in system-wide/per-cpu mode. Try using -a, or -C and workload affinity");
3119 return scnprintf(msg, size, "Cannot collect data source with the load latency event alone. "
3120 "Please add an auxiliary event in front of the load latency event.");
3125 return scnprintf(msg, size,
3126 "The sys_perf_event_open() syscall returned with %d (%s) for event (%s).\n"
3127 "/bin/dmesg | grep -i perf may provide additional information.\n",
3128 err, str_error_r(err, sbuf, sizeof(sbuf)), evsel__name(evsel));
3131 struct perf_env *evsel__env(struct evsel *evsel)
3133 if (evsel && evsel->evlist && evsel->evlist->env)
3134 return evsel->evlist->env;
3138 static int store_evsel_ids(struct evsel *evsel, struct evlist *evlist)
3140 int cpu_map_idx, thread;
3142 for (cpu_map_idx = 0; cpu_map_idx < xyarray__max_x(evsel->core.fd); cpu_map_idx++) {
3143 for (thread = 0; thread < xyarray__max_y(evsel->core.fd);
3145 int fd = FD(evsel, cpu_map_idx, thread);
3147 if (perf_evlist__id_add_fd(&evlist->core, &evsel->core,
3148 cpu_map_idx, thread, fd) < 0)
3156 int evsel__store_ids(struct evsel *evsel, struct evlist *evlist)
3158 struct perf_cpu_map *cpus = evsel->core.cpus;
3159 struct perf_thread_map *threads = evsel->core.threads;
3161 if (perf_evsel__alloc_id(&evsel->core, perf_cpu_map__nr(cpus), threads->nr))
3164 return store_evsel_ids(evsel, evlist);
3167 void evsel__zero_per_pkg(struct evsel *evsel)
3169 struct hashmap_entry *cur;
3172 if (evsel->per_pkg_mask) {
3173 hashmap__for_each_entry(evsel->per_pkg_mask, cur, bkt)
3176 hashmap__clear(evsel->per_pkg_mask);
3180 bool evsel__is_hybrid(const struct evsel *evsel)
3182 return evsel->pmu_name && perf_pmu__is_hybrid(evsel->pmu_name);
3185 struct evsel *evsel__leader(const struct evsel *evsel)
3187 return container_of(evsel->core.leader, struct evsel, core);
3190 bool evsel__has_leader(struct evsel *evsel, struct evsel *leader)
3192 return evsel->core.leader == &leader->core;
3195 bool evsel__is_leader(struct evsel *evsel)
3197 return evsel__has_leader(evsel, evsel);
3200 void evsel__set_leader(struct evsel *evsel, struct evsel *leader)
3202 evsel->core.leader = &leader->core;
3205 int evsel__source_count(const struct evsel *evsel)
3210 evlist__for_each_entry(evsel->evlist, pos) {
3211 if (pos->metric_leader == evsel)
3217 bool __weak arch_evsel__must_be_in_group(const struct evsel *evsel __maybe_unused)
3223 * Remove an event from a given group (leader).
3224 * Some events, e.g., perf metrics Topdown events,
3225 * must always be grouped. Ignore the events.
3227 void evsel__remove_from_group(struct evsel *evsel, struct evsel *leader)
3229 if (!arch_evsel__must_be_in_group(evsel) && evsel != leader) {
3230 evsel__set_leader(evsel, evsel);
3231 evsel->core.nr_members = 0;
3232 leader->core.nr_members--;