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