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