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