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