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