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