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