xref: /openbmc/linux/tools/perf/util/evsel.c (revision c0ecca6604b80e438b032578634c6e133c7028f6)
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 get_group_fd(struct evsel *evsel, int cpu, int thread)
1586 {
1587 	struct evsel *leader = evsel->leader;
1588 	int fd;
1589 
1590 	if (evsel__is_group_leader(evsel))
1591 		return -1;
1592 
1593 	/*
1594 	 * Leader must be already processed/open,
1595 	 * if not it's a bug.
1596 	 */
1597 	BUG_ON(!leader->core.fd);
1598 
1599 	fd = FD(leader, cpu, thread);
1600 	BUG_ON(fd == -1);
1601 
1602 	return fd;
1603 }
1604 
1605 static void evsel__remove_fd(struct evsel *pos, int nr_cpus, int nr_threads, int thread_idx)
1606 {
1607 	for (int cpu = 0; cpu < nr_cpus; cpu++)
1608 		for (int thread = thread_idx; thread < nr_threads - 1; thread++)
1609 			FD(pos, cpu, thread) = FD(pos, cpu, thread + 1);
1610 }
1611 
1612 static int update_fds(struct evsel *evsel,
1613 		      int nr_cpus, int cpu_idx,
1614 		      int nr_threads, int thread_idx)
1615 {
1616 	struct evsel *pos;
1617 
1618 	if (cpu_idx >= nr_cpus || thread_idx >= nr_threads)
1619 		return -EINVAL;
1620 
1621 	evlist__for_each_entry(evsel->evlist, pos) {
1622 		nr_cpus = pos != evsel ? nr_cpus : cpu_idx;
1623 
1624 		evsel__remove_fd(pos, nr_cpus, nr_threads, thread_idx);
1625 
1626 		/*
1627 		 * Since fds for next evsel has not been created,
1628 		 * there is no need to iterate whole event list.
1629 		 */
1630 		if (pos == evsel)
1631 			break;
1632 	}
1633 	return 0;
1634 }
1635 
1636 static bool ignore_missing_thread(struct evsel *evsel,
1637 				  int nr_cpus, int cpu,
1638 				  struct perf_thread_map *threads,
1639 				  int thread, int err)
1640 {
1641 	pid_t ignore_pid = perf_thread_map__pid(threads, thread);
1642 
1643 	if (!evsel->ignore_missing_thread)
1644 		return false;
1645 
1646 	/* The system wide setup does not work with threads. */
1647 	if (evsel->core.system_wide)
1648 		return false;
1649 
1650 	/* The -ESRCH is perf event syscall errno for pid's not found. */
1651 	if (err != -ESRCH)
1652 		return false;
1653 
1654 	/* If there's only one thread, let it fail. */
1655 	if (threads->nr == 1)
1656 		return false;
1657 
1658 	/*
1659 	 * We should remove fd for missing_thread first
1660 	 * because thread_map__remove() will decrease threads->nr.
1661 	 */
1662 	if (update_fds(evsel, nr_cpus, cpu, threads->nr, thread))
1663 		return false;
1664 
1665 	if (thread_map__remove(threads, thread))
1666 		return false;
1667 
1668 	pr_warning("WARNING: Ignored open failure for pid %d\n",
1669 		   ignore_pid);
1670 	return true;
1671 }
1672 
1673 static int __open_attr__fprintf(FILE *fp, const char *name, const char *val,
1674 				void *priv __maybe_unused)
1675 {
1676 	return fprintf(fp, "  %-32s %s\n", name, val);
1677 }
1678 
1679 static void display_attr(struct perf_event_attr *attr)
1680 {
1681 	if (verbose >= 2 || debug_peo_args) {
1682 		fprintf(stderr, "%.60s\n", graph_dotted_line);
1683 		fprintf(stderr, "perf_event_attr:\n");
1684 		perf_event_attr__fprintf(stderr, attr, __open_attr__fprintf, NULL);
1685 		fprintf(stderr, "%.60s\n", graph_dotted_line);
1686 	}
1687 }
1688 
1689 static int perf_event_open(struct evsel *evsel,
1690 			   pid_t pid, int cpu, int group_fd,
1691 			   unsigned long flags)
1692 {
1693 	int precise_ip = evsel->core.attr.precise_ip;
1694 	int fd;
1695 
1696 	while (1) {
1697 		pr_debug2_peo("sys_perf_event_open: pid %d  cpu %d  group_fd %d  flags %#lx",
1698 			  pid, cpu, group_fd, flags);
1699 
1700 		fd = sys_perf_event_open(&evsel->core.attr, pid, cpu, group_fd, flags);
1701 		if (fd >= 0)
1702 			break;
1703 
1704 		/* Do not try less precise if not requested. */
1705 		if (!evsel->precise_max)
1706 			break;
1707 
1708 		/*
1709 		 * We tried all the precise_ip values, and it's
1710 		 * still failing, so leave it to standard fallback.
1711 		 */
1712 		if (!evsel->core.attr.precise_ip) {
1713 			evsel->core.attr.precise_ip = precise_ip;
1714 			break;
1715 		}
1716 
1717 		pr_debug2_peo("\nsys_perf_event_open failed, error %d\n", -ENOTSUP);
1718 		evsel->core.attr.precise_ip--;
1719 		pr_debug2_peo("decreasing precise_ip by one (%d)\n", evsel->core.attr.precise_ip);
1720 		display_attr(&evsel->core.attr);
1721 	}
1722 
1723 	return fd;
1724 }
1725 
1726 static int evsel__open_cpu(struct evsel *evsel, struct perf_cpu_map *cpus,
1727 		struct perf_thread_map *threads,
1728 		int start_cpu, int end_cpu)
1729 {
1730 	int cpu, thread, nthreads;
1731 	unsigned long flags = PERF_FLAG_FD_CLOEXEC;
1732 	int pid = -1, err, old_errno;
1733 	enum { NO_CHANGE, SET_TO_MAX, INCREASED_MAX } set_rlimit = NO_CHANGE;
1734 
1735 	if ((perf_missing_features.write_backward && evsel->core.attr.write_backward) ||
1736 	    (perf_missing_features.aux_output     && evsel->core.attr.aux_output))
1737 		return -EINVAL;
1738 
1739 	if (cpus == NULL) {
1740 		static struct perf_cpu_map *empty_cpu_map;
1741 
1742 		if (empty_cpu_map == NULL) {
1743 			empty_cpu_map = perf_cpu_map__dummy_new();
1744 			if (empty_cpu_map == NULL)
1745 				return -ENOMEM;
1746 		}
1747 
1748 		cpus = empty_cpu_map;
1749 	}
1750 
1751 	if (threads == NULL) {
1752 		static struct perf_thread_map *empty_thread_map;
1753 
1754 		if (empty_thread_map == NULL) {
1755 			empty_thread_map = thread_map__new_by_tid(-1);
1756 			if (empty_thread_map == NULL)
1757 				return -ENOMEM;
1758 		}
1759 
1760 		threads = empty_thread_map;
1761 	}
1762 
1763 	if (evsel->core.system_wide)
1764 		nthreads = 1;
1765 	else
1766 		nthreads = threads->nr;
1767 
1768 	if (evsel->core.fd == NULL &&
1769 	    perf_evsel__alloc_fd(&evsel->core, cpus->nr, nthreads) < 0)
1770 		return -ENOMEM;
1771 
1772 	if (evsel->cgrp) {
1773 		flags |= PERF_FLAG_PID_CGROUP;
1774 		pid = evsel->cgrp->fd;
1775 	}
1776 
1777 fallback_missing_features:
1778 	if (perf_missing_features.weight_struct) {
1779 		evsel__set_sample_bit(evsel, WEIGHT);
1780 		evsel__reset_sample_bit(evsel, WEIGHT_STRUCT);
1781 	}
1782 	if (perf_missing_features.clockid_wrong)
1783 		evsel->core.attr.clockid = CLOCK_MONOTONIC; /* should always work */
1784 	if (perf_missing_features.clockid) {
1785 		evsel->core.attr.use_clockid = 0;
1786 		evsel->core.attr.clockid = 0;
1787 	}
1788 	if (perf_missing_features.cloexec)
1789 		flags &= ~(unsigned long)PERF_FLAG_FD_CLOEXEC;
1790 	if (perf_missing_features.mmap2)
1791 		evsel->core.attr.mmap2 = 0;
1792 	if (perf_missing_features.exclude_guest)
1793 		evsel->core.attr.exclude_guest = evsel->core.attr.exclude_host = 0;
1794 	if (perf_missing_features.lbr_flags)
1795 		evsel->core.attr.branch_sample_type &= ~(PERF_SAMPLE_BRANCH_NO_FLAGS |
1796 				     PERF_SAMPLE_BRANCH_NO_CYCLES);
1797 	if (perf_missing_features.group_read && evsel->core.attr.inherit)
1798 		evsel->core.attr.read_format &= ~(PERF_FORMAT_GROUP|PERF_FORMAT_ID);
1799 	if (perf_missing_features.ksymbol)
1800 		evsel->core.attr.ksymbol = 0;
1801 	if (perf_missing_features.bpf)
1802 		evsel->core.attr.bpf_event = 0;
1803 	if (perf_missing_features.branch_hw_idx)
1804 		evsel->core.attr.branch_sample_type &= ~PERF_SAMPLE_BRANCH_HW_INDEX;
1805 retry_sample_id:
1806 	if (perf_missing_features.sample_id_all)
1807 		evsel->core.attr.sample_id_all = 0;
1808 
1809 	display_attr(&evsel->core.attr);
1810 
1811 	for (cpu = start_cpu; cpu < end_cpu; cpu++) {
1812 
1813 		for (thread = 0; thread < nthreads; thread++) {
1814 			int fd, group_fd;
1815 
1816 			if (!evsel->cgrp && !evsel->core.system_wide)
1817 				pid = perf_thread_map__pid(threads, thread);
1818 
1819 			group_fd = get_group_fd(evsel, cpu, thread);
1820 retry_open:
1821 			test_attr__ready();
1822 
1823 			fd = perf_event_open(evsel, pid, cpus->map[cpu],
1824 					     group_fd, flags);
1825 
1826 			FD(evsel, cpu, thread) = fd;
1827 
1828 			bpf_counter__install_pe(evsel, cpu, fd);
1829 
1830 			if (unlikely(test_attr__enabled)) {
1831 				test_attr__open(&evsel->core.attr, pid, cpus->map[cpu],
1832 						fd, group_fd, flags);
1833 			}
1834 
1835 			if (fd < 0) {
1836 				err = -errno;
1837 
1838 				if (ignore_missing_thread(evsel, cpus->nr, cpu, threads, thread, err)) {
1839 					/*
1840 					 * We just removed 1 thread, so take a step
1841 					 * back on thread index and lower the upper
1842 					 * nthreads limit.
1843 					 */
1844 					nthreads--;
1845 					thread--;
1846 
1847 					/* ... and pretend like nothing have happened. */
1848 					err = 0;
1849 					continue;
1850 				}
1851 
1852 				pr_debug2_peo("\nsys_perf_event_open failed, error %d\n",
1853 					  err);
1854 				goto try_fallback;
1855 			}
1856 
1857 			pr_debug2_peo(" = %d\n", fd);
1858 
1859 			if (evsel->bpf_fd >= 0) {
1860 				int evt_fd = fd;
1861 				int bpf_fd = evsel->bpf_fd;
1862 
1863 				err = ioctl(evt_fd,
1864 					    PERF_EVENT_IOC_SET_BPF,
1865 					    bpf_fd);
1866 				if (err && errno != EEXIST) {
1867 					pr_err("failed to attach bpf fd %d: %s\n",
1868 					       bpf_fd, strerror(errno));
1869 					err = -EINVAL;
1870 					goto out_close;
1871 				}
1872 			}
1873 
1874 			set_rlimit = NO_CHANGE;
1875 
1876 			/*
1877 			 * If we succeeded but had to kill clockid, fail and
1878 			 * have evsel__open_strerror() print us a nice error.
1879 			 */
1880 			if (perf_missing_features.clockid ||
1881 			    perf_missing_features.clockid_wrong) {
1882 				err = -EINVAL;
1883 				goto out_close;
1884 			}
1885 		}
1886 	}
1887 
1888 	return 0;
1889 
1890 try_fallback:
1891 	/*
1892 	 * perf stat needs between 5 and 22 fds per CPU. When we run out
1893 	 * of them try to increase the limits.
1894 	 */
1895 	if (err == -EMFILE && set_rlimit < INCREASED_MAX) {
1896 		struct rlimit l;
1897 
1898 		old_errno = errno;
1899 		if (getrlimit(RLIMIT_NOFILE, &l) == 0) {
1900 			if (set_rlimit == NO_CHANGE)
1901 				l.rlim_cur = l.rlim_max;
1902 			else {
1903 				l.rlim_cur = l.rlim_max + 1000;
1904 				l.rlim_max = l.rlim_cur;
1905 			}
1906 			if (setrlimit(RLIMIT_NOFILE, &l) == 0) {
1907 				set_rlimit++;
1908 				errno = old_errno;
1909 				goto retry_open;
1910 			}
1911 		}
1912 		errno = old_errno;
1913 	}
1914 
1915 	if (err != -EINVAL || cpu > 0 || thread > 0)
1916 		goto out_close;
1917 
1918 	/*
1919 	 * Must probe features in the order they were added to the
1920 	 * perf_event_attr interface.
1921 	 */
1922 	if (!perf_missing_features.weight_struct &&
1923 	    (evsel->core.attr.sample_type & PERF_SAMPLE_WEIGHT_STRUCT)) {
1924 		perf_missing_features.weight_struct = true;
1925 		pr_debug2("switching off weight struct support\n");
1926 		goto fallback_missing_features;
1927 	} else if (!perf_missing_features.code_page_size &&
1928 	    (evsel->core.attr.sample_type & PERF_SAMPLE_CODE_PAGE_SIZE)) {
1929 		perf_missing_features.code_page_size = true;
1930 		pr_debug2_peo("Kernel has no PERF_SAMPLE_CODE_PAGE_SIZE support, bailing out\n");
1931 		goto out_close;
1932 	} else if (!perf_missing_features.data_page_size &&
1933 	    (evsel->core.attr.sample_type & PERF_SAMPLE_DATA_PAGE_SIZE)) {
1934 		perf_missing_features.data_page_size = true;
1935 		pr_debug2_peo("Kernel has no PERF_SAMPLE_DATA_PAGE_SIZE support, bailing out\n");
1936 		goto out_close;
1937 	} else if (!perf_missing_features.cgroup && evsel->core.attr.cgroup) {
1938 		perf_missing_features.cgroup = true;
1939 		pr_debug2_peo("Kernel has no cgroup sampling support, bailing out\n");
1940 		goto out_close;
1941         } else if (!perf_missing_features.branch_hw_idx &&
1942 	    (evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX)) {
1943 		perf_missing_features.branch_hw_idx = true;
1944 		pr_debug2("switching off branch HW index support\n");
1945 		goto fallback_missing_features;
1946 	} else if (!perf_missing_features.aux_output && evsel->core.attr.aux_output) {
1947 		perf_missing_features.aux_output = true;
1948 		pr_debug2_peo("Kernel has no attr.aux_output support, bailing out\n");
1949 		goto out_close;
1950 	} else if (!perf_missing_features.bpf && evsel->core.attr.bpf_event) {
1951 		perf_missing_features.bpf = true;
1952 		pr_debug2_peo("switching off bpf_event\n");
1953 		goto fallback_missing_features;
1954 	} else if (!perf_missing_features.ksymbol && evsel->core.attr.ksymbol) {
1955 		perf_missing_features.ksymbol = true;
1956 		pr_debug2_peo("switching off ksymbol\n");
1957 		goto fallback_missing_features;
1958 	} else if (!perf_missing_features.write_backward && evsel->core.attr.write_backward) {
1959 		perf_missing_features.write_backward = true;
1960 		pr_debug2_peo("switching off write_backward\n");
1961 		goto out_close;
1962 	} else if (!perf_missing_features.clockid_wrong && evsel->core.attr.use_clockid) {
1963 		perf_missing_features.clockid_wrong = true;
1964 		pr_debug2_peo("switching off clockid\n");
1965 		goto fallback_missing_features;
1966 	} else if (!perf_missing_features.clockid && evsel->core.attr.use_clockid) {
1967 		perf_missing_features.clockid = true;
1968 		pr_debug2_peo("switching off use_clockid\n");
1969 		goto fallback_missing_features;
1970 	} else if (!perf_missing_features.cloexec && (flags & PERF_FLAG_FD_CLOEXEC)) {
1971 		perf_missing_features.cloexec = true;
1972 		pr_debug2_peo("switching off cloexec flag\n");
1973 		goto fallback_missing_features;
1974 	} else if (!perf_missing_features.mmap2 && evsel->core.attr.mmap2) {
1975 		perf_missing_features.mmap2 = true;
1976 		pr_debug2_peo("switching off mmap2\n");
1977 		goto fallback_missing_features;
1978 	} else if (!perf_missing_features.exclude_guest &&
1979 		   (evsel->core.attr.exclude_guest || evsel->core.attr.exclude_host)) {
1980 		perf_missing_features.exclude_guest = true;
1981 		pr_debug2_peo("switching off exclude_guest, exclude_host\n");
1982 		goto fallback_missing_features;
1983 	} else if (!perf_missing_features.sample_id_all) {
1984 		perf_missing_features.sample_id_all = true;
1985 		pr_debug2_peo("switching off sample_id_all\n");
1986 		goto retry_sample_id;
1987 	} else if (!perf_missing_features.lbr_flags &&
1988 			(evsel->core.attr.branch_sample_type &
1989 			 (PERF_SAMPLE_BRANCH_NO_CYCLES |
1990 			  PERF_SAMPLE_BRANCH_NO_FLAGS))) {
1991 		perf_missing_features.lbr_flags = true;
1992 		pr_debug2_peo("switching off branch sample type no (cycles/flags)\n");
1993 		goto fallback_missing_features;
1994 	} else if (!perf_missing_features.group_read &&
1995 		    evsel->core.attr.inherit &&
1996 		   (evsel->core.attr.read_format & PERF_FORMAT_GROUP) &&
1997 		   evsel__is_group_leader(evsel)) {
1998 		perf_missing_features.group_read = true;
1999 		pr_debug2_peo("switching off group read\n");
2000 		goto fallback_missing_features;
2001 	}
2002 out_close:
2003 	if (err)
2004 		threads->err_thread = thread;
2005 
2006 	old_errno = errno;
2007 	do {
2008 		while (--thread >= 0) {
2009 			if (FD(evsel, cpu, thread) >= 0)
2010 				close(FD(evsel, cpu, thread));
2011 			FD(evsel, cpu, thread) = -1;
2012 		}
2013 		thread = nthreads;
2014 	} while (--cpu >= 0);
2015 	errno = old_errno;
2016 	return err;
2017 }
2018 
2019 int evsel__open(struct evsel *evsel, struct perf_cpu_map *cpus,
2020 		struct perf_thread_map *threads)
2021 {
2022 	return evsel__open_cpu(evsel, cpus, threads, 0, cpus ? cpus->nr : 1);
2023 }
2024 
2025 void evsel__close(struct evsel *evsel)
2026 {
2027 	perf_evsel__close(&evsel->core);
2028 	perf_evsel__free_id(&evsel->core);
2029 }
2030 
2031 int evsel__open_per_cpu(struct evsel *evsel, struct perf_cpu_map *cpus, int cpu)
2032 {
2033 	if (cpu == -1)
2034 		return evsel__open_cpu(evsel, cpus, NULL, 0,
2035 					cpus ? cpus->nr : 1);
2036 
2037 	return evsel__open_cpu(evsel, cpus, NULL, cpu, cpu + 1);
2038 }
2039 
2040 int evsel__open_per_thread(struct evsel *evsel, struct perf_thread_map *threads)
2041 {
2042 	return evsel__open(evsel, NULL, threads);
2043 }
2044 
2045 static int perf_evsel__parse_id_sample(const struct evsel *evsel,
2046 				       const union perf_event *event,
2047 				       struct perf_sample *sample)
2048 {
2049 	u64 type = evsel->core.attr.sample_type;
2050 	const __u64 *array = event->sample.array;
2051 	bool swapped = evsel->needs_swap;
2052 	union u64_swap u;
2053 
2054 	array += ((event->header.size -
2055 		   sizeof(event->header)) / sizeof(u64)) - 1;
2056 
2057 	if (type & PERF_SAMPLE_IDENTIFIER) {
2058 		sample->id = *array;
2059 		array--;
2060 	}
2061 
2062 	if (type & PERF_SAMPLE_CPU) {
2063 		u.val64 = *array;
2064 		if (swapped) {
2065 			/* undo swap of u64, then swap on individual u32s */
2066 			u.val64 = bswap_64(u.val64);
2067 			u.val32[0] = bswap_32(u.val32[0]);
2068 		}
2069 
2070 		sample->cpu = u.val32[0];
2071 		array--;
2072 	}
2073 
2074 	if (type & PERF_SAMPLE_STREAM_ID) {
2075 		sample->stream_id = *array;
2076 		array--;
2077 	}
2078 
2079 	if (type & PERF_SAMPLE_ID) {
2080 		sample->id = *array;
2081 		array--;
2082 	}
2083 
2084 	if (type & PERF_SAMPLE_TIME) {
2085 		sample->time = *array;
2086 		array--;
2087 	}
2088 
2089 	if (type & PERF_SAMPLE_TID) {
2090 		u.val64 = *array;
2091 		if (swapped) {
2092 			/* undo swap of u64, then swap on individual u32s */
2093 			u.val64 = bswap_64(u.val64);
2094 			u.val32[0] = bswap_32(u.val32[0]);
2095 			u.val32[1] = bswap_32(u.val32[1]);
2096 		}
2097 
2098 		sample->pid = u.val32[0];
2099 		sample->tid = u.val32[1];
2100 		array--;
2101 	}
2102 
2103 	return 0;
2104 }
2105 
2106 static inline bool overflow(const void *endp, u16 max_size, const void *offset,
2107 			    u64 size)
2108 {
2109 	return size > max_size || offset + size > endp;
2110 }
2111 
2112 #define OVERFLOW_CHECK(offset, size, max_size)				\
2113 	do {								\
2114 		if (overflow(endp, (max_size), (offset), (size)))	\
2115 			return -EFAULT;					\
2116 	} while (0)
2117 
2118 #define OVERFLOW_CHECK_u64(offset) \
2119 	OVERFLOW_CHECK(offset, sizeof(u64), sizeof(u64))
2120 
2121 static int
2122 perf_event__check_size(union perf_event *event, unsigned int sample_size)
2123 {
2124 	/*
2125 	 * The evsel's sample_size is based on PERF_SAMPLE_MASK which includes
2126 	 * up to PERF_SAMPLE_PERIOD.  After that overflow() must be used to
2127 	 * check the format does not go past the end of the event.
2128 	 */
2129 	if (sample_size + sizeof(event->header) > event->header.size)
2130 		return -EFAULT;
2131 
2132 	return 0;
2133 }
2134 
2135 void __weak arch_perf_parse_sample_weight(struct perf_sample *data,
2136 					  const __u64 *array,
2137 					  u64 type __maybe_unused)
2138 {
2139 	data->weight = *array;
2140 }
2141 
2142 int evsel__parse_sample(struct evsel *evsel, union perf_event *event,
2143 			struct perf_sample *data)
2144 {
2145 	u64 type = evsel->core.attr.sample_type;
2146 	bool swapped = evsel->needs_swap;
2147 	const __u64 *array;
2148 	u16 max_size = event->header.size;
2149 	const void *endp = (void *)event + max_size;
2150 	u64 sz;
2151 
2152 	/*
2153 	 * used for cross-endian analysis. See git commit 65014ab3
2154 	 * for why this goofiness is needed.
2155 	 */
2156 	union u64_swap u;
2157 
2158 	memset(data, 0, sizeof(*data));
2159 	data->cpu = data->pid = data->tid = -1;
2160 	data->stream_id = data->id = data->time = -1ULL;
2161 	data->period = evsel->core.attr.sample_period;
2162 	data->cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
2163 	data->misc    = event->header.misc;
2164 	data->id = -1ULL;
2165 	data->data_src = PERF_MEM_DATA_SRC_NONE;
2166 
2167 	if (event->header.type != PERF_RECORD_SAMPLE) {
2168 		if (!evsel->core.attr.sample_id_all)
2169 			return 0;
2170 		return perf_evsel__parse_id_sample(evsel, event, data);
2171 	}
2172 
2173 	array = event->sample.array;
2174 
2175 	if (perf_event__check_size(event, evsel->sample_size))
2176 		return -EFAULT;
2177 
2178 	if (type & PERF_SAMPLE_IDENTIFIER) {
2179 		data->id = *array;
2180 		array++;
2181 	}
2182 
2183 	if (type & PERF_SAMPLE_IP) {
2184 		data->ip = *array;
2185 		array++;
2186 	}
2187 
2188 	if (type & PERF_SAMPLE_TID) {
2189 		u.val64 = *array;
2190 		if (swapped) {
2191 			/* undo swap of u64, then swap on individual u32s */
2192 			u.val64 = bswap_64(u.val64);
2193 			u.val32[0] = bswap_32(u.val32[0]);
2194 			u.val32[1] = bswap_32(u.val32[1]);
2195 		}
2196 
2197 		data->pid = u.val32[0];
2198 		data->tid = u.val32[1];
2199 		array++;
2200 	}
2201 
2202 	if (type & PERF_SAMPLE_TIME) {
2203 		data->time = *array;
2204 		array++;
2205 	}
2206 
2207 	if (type & PERF_SAMPLE_ADDR) {
2208 		data->addr = *array;
2209 		array++;
2210 	}
2211 
2212 	if (type & PERF_SAMPLE_ID) {
2213 		data->id = *array;
2214 		array++;
2215 	}
2216 
2217 	if (type & PERF_SAMPLE_STREAM_ID) {
2218 		data->stream_id = *array;
2219 		array++;
2220 	}
2221 
2222 	if (type & PERF_SAMPLE_CPU) {
2223 
2224 		u.val64 = *array;
2225 		if (swapped) {
2226 			/* undo swap of u64, then swap on individual u32s */
2227 			u.val64 = bswap_64(u.val64);
2228 			u.val32[0] = bswap_32(u.val32[0]);
2229 		}
2230 
2231 		data->cpu = u.val32[0];
2232 		array++;
2233 	}
2234 
2235 	if (type & PERF_SAMPLE_PERIOD) {
2236 		data->period = *array;
2237 		array++;
2238 	}
2239 
2240 	if (type & PERF_SAMPLE_READ) {
2241 		u64 read_format = evsel->core.attr.read_format;
2242 
2243 		OVERFLOW_CHECK_u64(array);
2244 		if (read_format & PERF_FORMAT_GROUP)
2245 			data->read.group.nr = *array;
2246 		else
2247 			data->read.one.value = *array;
2248 
2249 		array++;
2250 
2251 		if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
2252 			OVERFLOW_CHECK_u64(array);
2253 			data->read.time_enabled = *array;
2254 			array++;
2255 		}
2256 
2257 		if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
2258 			OVERFLOW_CHECK_u64(array);
2259 			data->read.time_running = *array;
2260 			array++;
2261 		}
2262 
2263 		/* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
2264 		if (read_format & PERF_FORMAT_GROUP) {
2265 			const u64 max_group_nr = UINT64_MAX /
2266 					sizeof(struct sample_read_value);
2267 
2268 			if (data->read.group.nr > max_group_nr)
2269 				return -EFAULT;
2270 			sz = data->read.group.nr *
2271 			     sizeof(struct sample_read_value);
2272 			OVERFLOW_CHECK(array, sz, max_size);
2273 			data->read.group.values =
2274 					(struct sample_read_value *)array;
2275 			array = (void *)array + sz;
2276 		} else {
2277 			OVERFLOW_CHECK_u64(array);
2278 			data->read.one.id = *array;
2279 			array++;
2280 		}
2281 	}
2282 
2283 	if (type & PERF_SAMPLE_CALLCHAIN) {
2284 		const u64 max_callchain_nr = UINT64_MAX / sizeof(u64);
2285 
2286 		OVERFLOW_CHECK_u64(array);
2287 		data->callchain = (struct ip_callchain *)array++;
2288 		if (data->callchain->nr > max_callchain_nr)
2289 			return -EFAULT;
2290 		sz = data->callchain->nr * sizeof(u64);
2291 		OVERFLOW_CHECK(array, sz, max_size);
2292 		array = (void *)array + sz;
2293 	}
2294 
2295 	if (type & PERF_SAMPLE_RAW) {
2296 		OVERFLOW_CHECK_u64(array);
2297 		u.val64 = *array;
2298 
2299 		/*
2300 		 * Undo swap of u64, then swap on individual u32s,
2301 		 * get the size of the raw area and undo all of the
2302 		 * swap. The pevent interface handles endianness by
2303 		 * itself.
2304 		 */
2305 		if (swapped) {
2306 			u.val64 = bswap_64(u.val64);
2307 			u.val32[0] = bswap_32(u.val32[0]);
2308 			u.val32[1] = bswap_32(u.val32[1]);
2309 		}
2310 		data->raw_size = u.val32[0];
2311 
2312 		/*
2313 		 * The raw data is aligned on 64bits including the
2314 		 * u32 size, so it's safe to use mem_bswap_64.
2315 		 */
2316 		if (swapped)
2317 			mem_bswap_64((void *) array, data->raw_size);
2318 
2319 		array = (void *)array + sizeof(u32);
2320 
2321 		OVERFLOW_CHECK(array, data->raw_size, max_size);
2322 		data->raw_data = (void *)array;
2323 		array = (void *)array + data->raw_size;
2324 	}
2325 
2326 	if (type & PERF_SAMPLE_BRANCH_STACK) {
2327 		const u64 max_branch_nr = UINT64_MAX /
2328 					  sizeof(struct branch_entry);
2329 
2330 		OVERFLOW_CHECK_u64(array);
2331 		data->branch_stack = (struct branch_stack *)array++;
2332 
2333 		if (data->branch_stack->nr > max_branch_nr)
2334 			return -EFAULT;
2335 
2336 		sz = data->branch_stack->nr * sizeof(struct branch_entry);
2337 		if (evsel__has_branch_hw_idx(evsel))
2338 			sz += sizeof(u64);
2339 		else
2340 			data->no_hw_idx = true;
2341 		OVERFLOW_CHECK(array, sz, max_size);
2342 		array = (void *)array + sz;
2343 	}
2344 
2345 	if (type & PERF_SAMPLE_REGS_USER) {
2346 		OVERFLOW_CHECK_u64(array);
2347 		data->user_regs.abi = *array;
2348 		array++;
2349 
2350 		if (data->user_regs.abi) {
2351 			u64 mask = evsel->core.attr.sample_regs_user;
2352 
2353 			sz = hweight64(mask) * sizeof(u64);
2354 			OVERFLOW_CHECK(array, sz, max_size);
2355 			data->user_regs.mask = mask;
2356 			data->user_regs.regs = (u64 *)array;
2357 			array = (void *)array + sz;
2358 		}
2359 	}
2360 
2361 	if (type & PERF_SAMPLE_STACK_USER) {
2362 		OVERFLOW_CHECK_u64(array);
2363 		sz = *array++;
2364 
2365 		data->user_stack.offset = ((char *)(array - 1)
2366 					  - (char *) event);
2367 
2368 		if (!sz) {
2369 			data->user_stack.size = 0;
2370 		} else {
2371 			OVERFLOW_CHECK(array, sz, max_size);
2372 			data->user_stack.data = (char *)array;
2373 			array = (void *)array + sz;
2374 			OVERFLOW_CHECK_u64(array);
2375 			data->user_stack.size = *array++;
2376 			if (WARN_ONCE(data->user_stack.size > sz,
2377 				      "user stack dump failure\n"))
2378 				return -EFAULT;
2379 		}
2380 	}
2381 
2382 	if (type & PERF_SAMPLE_WEIGHT_TYPE) {
2383 		OVERFLOW_CHECK_u64(array);
2384 		arch_perf_parse_sample_weight(data, array, type);
2385 		array++;
2386 	}
2387 
2388 	if (type & PERF_SAMPLE_DATA_SRC) {
2389 		OVERFLOW_CHECK_u64(array);
2390 		data->data_src = *array;
2391 		array++;
2392 	}
2393 
2394 	if (type & PERF_SAMPLE_TRANSACTION) {
2395 		OVERFLOW_CHECK_u64(array);
2396 		data->transaction = *array;
2397 		array++;
2398 	}
2399 
2400 	data->intr_regs.abi = PERF_SAMPLE_REGS_ABI_NONE;
2401 	if (type & PERF_SAMPLE_REGS_INTR) {
2402 		OVERFLOW_CHECK_u64(array);
2403 		data->intr_regs.abi = *array;
2404 		array++;
2405 
2406 		if (data->intr_regs.abi != PERF_SAMPLE_REGS_ABI_NONE) {
2407 			u64 mask = evsel->core.attr.sample_regs_intr;
2408 
2409 			sz = hweight64(mask) * sizeof(u64);
2410 			OVERFLOW_CHECK(array, sz, max_size);
2411 			data->intr_regs.mask = mask;
2412 			data->intr_regs.regs = (u64 *)array;
2413 			array = (void *)array + sz;
2414 		}
2415 	}
2416 
2417 	data->phys_addr = 0;
2418 	if (type & PERF_SAMPLE_PHYS_ADDR) {
2419 		data->phys_addr = *array;
2420 		array++;
2421 	}
2422 
2423 	data->cgroup = 0;
2424 	if (type & PERF_SAMPLE_CGROUP) {
2425 		data->cgroup = *array;
2426 		array++;
2427 	}
2428 
2429 	data->data_page_size = 0;
2430 	if (type & PERF_SAMPLE_DATA_PAGE_SIZE) {
2431 		data->data_page_size = *array;
2432 		array++;
2433 	}
2434 
2435 	data->code_page_size = 0;
2436 	if (type & PERF_SAMPLE_CODE_PAGE_SIZE) {
2437 		data->code_page_size = *array;
2438 		array++;
2439 	}
2440 
2441 	if (type & PERF_SAMPLE_AUX) {
2442 		OVERFLOW_CHECK_u64(array);
2443 		sz = *array++;
2444 
2445 		OVERFLOW_CHECK(array, sz, max_size);
2446 		/* Undo swap of data */
2447 		if (swapped)
2448 			mem_bswap_64((char *)array, sz);
2449 		data->aux_sample.size = sz;
2450 		data->aux_sample.data = (char *)array;
2451 		array = (void *)array + sz;
2452 	}
2453 
2454 	return 0;
2455 }
2456 
2457 int evsel__parse_sample_timestamp(struct evsel *evsel, union perf_event *event,
2458 				  u64 *timestamp)
2459 {
2460 	u64 type = evsel->core.attr.sample_type;
2461 	const __u64 *array;
2462 
2463 	if (!(type & PERF_SAMPLE_TIME))
2464 		return -1;
2465 
2466 	if (event->header.type != PERF_RECORD_SAMPLE) {
2467 		struct perf_sample data = {
2468 			.time = -1ULL,
2469 		};
2470 
2471 		if (!evsel->core.attr.sample_id_all)
2472 			return -1;
2473 		if (perf_evsel__parse_id_sample(evsel, event, &data))
2474 			return -1;
2475 
2476 		*timestamp = data.time;
2477 		return 0;
2478 	}
2479 
2480 	array = event->sample.array;
2481 
2482 	if (perf_event__check_size(event, evsel->sample_size))
2483 		return -EFAULT;
2484 
2485 	if (type & PERF_SAMPLE_IDENTIFIER)
2486 		array++;
2487 
2488 	if (type & PERF_SAMPLE_IP)
2489 		array++;
2490 
2491 	if (type & PERF_SAMPLE_TID)
2492 		array++;
2493 
2494 	if (type & PERF_SAMPLE_TIME)
2495 		*timestamp = *array;
2496 
2497 	return 0;
2498 }
2499 
2500 struct tep_format_field *evsel__field(struct evsel *evsel, const char *name)
2501 {
2502 	return tep_find_field(evsel->tp_format, name);
2503 }
2504 
2505 void *evsel__rawptr(struct evsel *evsel, struct perf_sample *sample, const char *name)
2506 {
2507 	struct tep_format_field *field = evsel__field(evsel, name);
2508 	int offset;
2509 
2510 	if (!field)
2511 		return NULL;
2512 
2513 	offset = field->offset;
2514 
2515 	if (field->flags & TEP_FIELD_IS_DYNAMIC) {
2516 		offset = *(int *)(sample->raw_data + field->offset);
2517 		offset &= 0xffff;
2518 	}
2519 
2520 	return sample->raw_data + offset;
2521 }
2522 
2523 u64 format_field__intval(struct tep_format_field *field, struct perf_sample *sample,
2524 			 bool needs_swap)
2525 {
2526 	u64 value;
2527 	void *ptr = sample->raw_data + field->offset;
2528 
2529 	switch (field->size) {
2530 	case 1:
2531 		return *(u8 *)ptr;
2532 	case 2:
2533 		value = *(u16 *)ptr;
2534 		break;
2535 	case 4:
2536 		value = *(u32 *)ptr;
2537 		break;
2538 	case 8:
2539 		memcpy(&value, ptr, sizeof(u64));
2540 		break;
2541 	default:
2542 		return 0;
2543 	}
2544 
2545 	if (!needs_swap)
2546 		return value;
2547 
2548 	switch (field->size) {
2549 	case 2:
2550 		return bswap_16(value);
2551 	case 4:
2552 		return bswap_32(value);
2553 	case 8:
2554 		return bswap_64(value);
2555 	default:
2556 		return 0;
2557 	}
2558 
2559 	return 0;
2560 }
2561 
2562 u64 evsel__intval(struct evsel *evsel, struct perf_sample *sample, const char *name)
2563 {
2564 	struct tep_format_field *field = evsel__field(evsel, name);
2565 
2566 	if (!field)
2567 		return 0;
2568 
2569 	return field ? format_field__intval(field, sample, evsel->needs_swap) : 0;
2570 }
2571 
2572 bool evsel__fallback(struct evsel *evsel, int err, char *msg, size_t msgsize)
2573 {
2574 	int paranoid;
2575 
2576 	if ((err == ENOENT || err == ENXIO || err == ENODEV) &&
2577 	    evsel->core.attr.type   == PERF_TYPE_HARDWARE &&
2578 	    evsel->core.attr.config == PERF_COUNT_HW_CPU_CYCLES) {
2579 		/*
2580 		 * If it's cycles then fall back to hrtimer based
2581 		 * cpu-clock-tick sw counter, which is always available even if
2582 		 * no PMU support.
2583 		 *
2584 		 * PPC returns ENXIO until 2.6.37 (behavior changed with commit
2585 		 * b0a873e).
2586 		 */
2587 		scnprintf(msg, msgsize, "%s",
2588 "The cycles event is not supported, trying to fall back to cpu-clock-ticks");
2589 
2590 		evsel->core.attr.type   = PERF_TYPE_SOFTWARE;
2591 		evsel->core.attr.config = PERF_COUNT_SW_CPU_CLOCK;
2592 
2593 		zfree(&evsel->name);
2594 		return true;
2595 	} else if (err == EACCES && !evsel->core.attr.exclude_kernel &&
2596 		   (paranoid = perf_event_paranoid()) > 1) {
2597 		const char *name = evsel__name(evsel);
2598 		char *new_name;
2599 		const char *sep = ":";
2600 
2601 		/* If event has exclude user then don't exclude kernel. */
2602 		if (evsel->core.attr.exclude_user)
2603 			return false;
2604 
2605 		/* Is there already the separator in the name. */
2606 		if (strchr(name, '/') ||
2607 		    (strchr(name, ':') && !evsel->is_libpfm_event))
2608 			sep = "";
2609 
2610 		if (asprintf(&new_name, "%s%su", name, sep) < 0)
2611 			return false;
2612 
2613 		if (evsel->name)
2614 			free(evsel->name);
2615 		evsel->name = new_name;
2616 		scnprintf(msg, msgsize, "kernel.perf_event_paranoid=%d, trying "
2617 			  "to fall back to excluding kernel and hypervisor "
2618 			  " samples", paranoid);
2619 		evsel->core.attr.exclude_kernel = 1;
2620 		evsel->core.attr.exclude_hv     = 1;
2621 
2622 		return true;
2623 	}
2624 
2625 	return false;
2626 }
2627 
2628 static bool find_process(const char *name)
2629 {
2630 	size_t len = strlen(name);
2631 	DIR *dir;
2632 	struct dirent *d;
2633 	int ret = -1;
2634 
2635 	dir = opendir(procfs__mountpoint());
2636 	if (!dir)
2637 		return false;
2638 
2639 	/* Walk through the directory. */
2640 	while (ret && (d = readdir(dir)) != NULL) {
2641 		char path[PATH_MAX];
2642 		char *data;
2643 		size_t size;
2644 
2645 		if ((d->d_type != DT_DIR) ||
2646 		     !strcmp(".", d->d_name) ||
2647 		     !strcmp("..", d->d_name))
2648 			continue;
2649 
2650 		scnprintf(path, sizeof(path), "%s/%s/comm",
2651 			  procfs__mountpoint(), d->d_name);
2652 
2653 		if (filename__read_str(path, &data, &size))
2654 			continue;
2655 
2656 		ret = strncmp(name, data, len);
2657 		free(data);
2658 	}
2659 
2660 	closedir(dir);
2661 	return ret ? false : true;
2662 }
2663 
2664 int evsel__open_strerror(struct evsel *evsel, struct target *target,
2665 			 int err, char *msg, size_t size)
2666 {
2667 	char sbuf[STRERR_BUFSIZE];
2668 	int printed = 0, enforced = 0;
2669 
2670 	switch (err) {
2671 	case EPERM:
2672 	case EACCES:
2673 		printed += scnprintf(msg + printed, size - printed,
2674 			"Access to performance monitoring and observability operations is limited.\n");
2675 
2676 		if (!sysfs__read_int("fs/selinux/enforce", &enforced)) {
2677 			if (enforced) {
2678 				printed += scnprintf(msg + printed, size - printed,
2679 					"Enforced MAC policy settings (SELinux) can limit access to performance\n"
2680 					"monitoring and observability operations. Inspect system audit records for\n"
2681 					"more perf_event access control information and adjusting the policy.\n");
2682 			}
2683 		}
2684 
2685 		if (err == EPERM)
2686 			printed += scnprintf(msg, size,
2687 				"No permission to enable %s event.\n\n", evsel__name(evsel));
2688 
2689 		return scnprintf(msg + printed, size - printed,
2690 		 "Consider adjusting /proc/sys/kernel/perf_event_paranoid setting to open\n"
2691 		 "access to performance monitoring and observability operations for processes\n"
2692 		 "without CAP_PERFMON, CAP_SYS_PTRACE or CAP_SYS_ADMIN Linux capability.\n"
2693 		 "More information can be found at 'Perf events and tool security' document:\n"
2694 		 "https://www.kernel.org/doc/html/latest/admin-guide/perf-security.html\n"
2695 		 "perf_event_paranoid setting is %d:\n"
2696 		 "  -1: Allow use of (almost) all events by all users\n"
2697 		 "      Ignore mlock limit after perf_event_mlock_kb without CAP_IPC_LOCK\n"
2698 		 ">= 0: Disallow raw and ftrace function tracepoint access\n"
2699 		 ">= 1: Disallow CPU event access\n"
2700 		 ">= 2: Disallow kernel profiling\n"
2701 		 "To make the adjusted perf_event_paranoid setting permanent preserve it\n"
2702 		 "in /etc/sysctl.conf (e.g. kernel.perf_event_paranoid = <setting>)",
2703 		 perf_event_paranoid());
2704 	case ENOENT:
2705 		return scnprintf(msg, size, "The %s event is not supported.", evsel__name(evsel));
2706 	case EMFILE:
2707 		return scnprintf(msg, size, "%s",
2708 			 "Too many events are opened.\n"
2709 			 "Probably the maximum number of open file descriptors has been reached.\n"
2710 			 "Hint: Try again after reducing the number of events.\n"
2711 			 "Hint: Try increasing the limit with 'ulimit -n <limit>'");
2712 	case ENOMEM:
2713 		if (evsel__has_callchain(evsel) &&
2714 		    access("/proc/sys/kernel/perf_event_max_stack", F_OK) == 0)
2715 			return scnprintf(msg, size,
2716 					 "Not enough memory to setup event with callchain.\n"
2717 					 "Hint: Try tweaking /proc/sys/kernel/perf_event_max_stack\n"
2718 					 "Hint: Current value: %d", sysctl__max_stack());
2719 		break;
2720 	case ENODEV:
2721 		if (target->cpu_list)
2722 			return scnprintf(msg, size, "%s",
2723 	 "No such device - did you specify an out-of-range profile CPU?");
2724 		break;
2725 	case EOPNOTSUPP:
2726 		if (evsel->core.attr.aux_output)
2727 			return scnprintf(msg, size,
2728 	"%s: PMU Hardware doesn't support 'aux_output' feature",
2729 					 evsel__name(evsel));
2730 		if (evsel->core.attr.sample_period != 0)
2731 			return scnprintf(msg, size,
2732 	"%s: PMU Hardware doesn't support sampling/overflow-interrupts. Try 'perf stat'",
2733 					 evsel__name(evsel));
2734 		if (evsel->core.attr.precise_ip)
2735 			return scnprintf(msg, size, "%s",
2736 	"\'precise\' request may not be supported. Try removing 'p' modifier.");
2737 #if defined(__i386__) || defined(__x86_64__)
2738 		if (evsel->core.attr.type == PERF_TYPE_HARDWARE)
2739 			return scnprintf(msg, size, "%s",
2740 	"No hardware sampling interrupt available.\n");
2741 #endif
2742 		break;
2743 	case EBUSY:
2744 		if (find_process("oprofiled"))
2745 			return scnprintf(msg, size,
2746 	"The PMU counters are busy/taken by another profiler.\n"
2747 	"We found oprofile daemon running, please stop it and try again.");
2748 		break;
2749 	case EINVAL:
2750 		if (evsel->core.attr.sample_type & PERF_SAMPLE_CODE_PAGE_SIZE && perf_missing_features.code_page_size)
2751 			return scnprintf(msg, size, "Asking for the code page size isn't supported by this kernel.");
2752 		if (evsel->core.attr.sample_type & PERF_SAMPLE_DATA_PAGE_SIZE && perf_missing_features.data_page_size)
2753 			return scnprintf(msg, size, "Asking for the data page size isn't supported by this kernel.");
2754 		if (evsel->core.attr.write_backward && perf_missing_features.write_backward)
2755 			return scnprintf(msg, size, "Reading from overwrite event is not supported by this kernel.");
2756 		if (perf_missing_features.clockid)
2757 			return scnprintf(msg, size, "clockid feature not supported.");
2758 		if (perf_missing_features.clockid_wrong)
2759 			return scnprintf(msg, size, "wrong clockid (%d).", clockid);
2760 		if (perf_missing_features.aux_output)
2761 			return scnprintf(msg, size, "The 'aux_output' feature is not supported, update the kernel.");
2762 		break;
2763 	case ENODATA:
2764 		return scnprintf(msg, size, "Cannot collect data source with the load latency event alone. "
2765 				 "Please add an auxiliary event in front of the load latency event.");
2766 	default:
2767 		break;
2768 	}
2769 
2770 	return scnprintf(msg, size,
2771 	"The sys_perf_event_open() syscall returned with %d (%s) for event (%s).\n"
2772 	"/bin/dmesg | grep -i perf may provide additional information.\n",
2773 			 err, str_error_r(err, sbuf, sizeof(sbuf)), evsel__name(evsel));
2774 }
2775 
2776 struct perf_env *evsel__env(struct evsel *evsel)
2777 {
2778 	if (evsel && evsel->evlist)
2779 		return evsel->evlist->env;
2780 	return &perf_env;
2781 }
2782 
2783 static int store_evsel_ids(struct evsel *evsel, struct evlist *evlist)
2784 {
2785 	int cpu, thread;
2786 
2787 	for (cpu = 0; cpu < xyarray__max_x(evsel->core.fd); cpu++) {
2788 		for (thread = 0; thread < xyarray__max_y(evsel->core.fd);
2789 		     thread++) {
2790 			int fd = FD(evsel, cpu, thread);
2791 
2792 			if (perf_evlist__id_add_fd(&evlist->core, &evsel->core,
2793 						   cpu, thread, fd) < 0)
2794 				return -1;
2795 		}
2796 	}
2797 
2798 	return 0;
2799 }
2800 
2801 int evsel__store_ids(struct evsel *evsel, struct evlist *evlist)
2802 {
2803 	struct perf_cpu_map *cpus = evsel->core.cpus;
2804 	struct perf_thread_map *threads = evsel->core.threads;
2805 
2806 	if (perf_evsel__alloc_id(&evsel->core, cpus->nr, threads->nr))
2807 		return -ENOMEM;
2808 
2809 	return store_evsel_ids(evsel, evlist);
2810 }
2811 
2812 void evsel__zero_per_pkg(struct evsel *evsel)
2813 {
2814 	struct hashmap_entry *cur;
2815 	size_t bkt;
2816 
2817 	if (evsel->per_pkg_mask) {
2818 		hashmap__for_each_entry(evsel->per_pkg_mask, cur, bkt)
2819 			free((char *)cur->key);
2820 
2821 		hashmap__clear(evsel->per_pkg_mask);
2822 	}
2823 }
2824 
2825 bool evsel__is_hybrid(struct evsel *evsel)
2826 {
2827 	return evsel->pmu_name && perf_pmu__is_hybrid(evsel->pmu_name);
2828 }
2829