xref: /linux/tools/perf/util/evsel.c (revision d9f2ecbc5e47fca7bda7c13cff3b3534b1467b32)
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.pmu_cpus = perf_cpu_map__get(orig->core.pmu_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.pmu_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 static void (*evsel__priv_destructor)(void *priv);
1661 
1662 void evsel__set_priv_destructor(void (*destructor)(void *priv))
1663 {
1664 	assert(evsel__priv_destructor == NULL);
1665 
1666 	evsel__priv_destructor = destructor;
1667 }
1668 
1669 void evsel__exit(struct evsel *evsel)
1670 {
1671 	assert(list_empty(&evsel->core.node));
1672 	assert(evsel->evlist == NULL);
1673 	if (evsel__is_retire_lat(evsel))
1674 		evsel__tpebs_close(evsel);
1675 	bpf_counter__destroy(evsel);
1676 	perf_bpf_filter__destroy(evsel);
1677 	evsel__free_counts(evsel);
1678 	perf_evsel__free_fd(&evsel->core);
1679 	perf_evsel__free_id(&evsel->core);
1680 	evsel__free_config_terms(evsel);
1681 	cgroup__put(evsel->cgrp);
1682 	perf_evsel__exit(&evsel->core);
1683 	zfree(&evsel->group_name);
1684 	zfree(&evsel->name);
1685 #ifdef HAVE_LIBTRACEEVENT
1686 	zfree(&evsel->tp_sys);
1687 	zfree(&evsel->tp_name);
1688 #endif
1689 	zfree(&evsel->filter);
1690 	zfree(&evsel->group_pmu_name);
1691 	zfree(&evsel->unit);
1692 	zfree(&evsel->metric_id);
1693 	evsel__zero_per_pkg(evsel);
1694 	hashmap__free(evsel->per_pkg_mask);
1695 	evsel->per_pkg_mask = NULL;
1696 	zfree(&evsel->metric_events);
1697 	if (evsel__priv_destructor)
1698 		evsel__priv_destructor(evsel->priv);
1699 	perf_evsel__object.fini(evsel);
1700 	if (evsel__tool_event(evsel) == TOOL_PMU__EVENT_SYSTEM_TIME ||
1701 	    evsel__tool_event(evsel) == TOOL_PMU__EVENT_USER_TIME)
1702 		xyarray__delete(evsel->start_times);
1703 }
1704 
1705 void evsel__delete(struct evsel *evsel)
1706 {
1707 	if (!evsel)
1708 		return;
1709 
1710 	evsel__exit(evsel);
1711 	free(evsel);
1712 }
1713 
1714 void evsel__compute_deltas(struct evsel *evsel, int cpu_map_idx, int thread,
1715 			   struct perf_counts_values *count)
1716 {
1717 	struct perf_counts_values tmp;
1718 
1719 	if (!evsel->prev_raw_counts)
1720 		return;
1721 
1722 	tmp = *perf_counts(evsel->prev_raw_counts, cpu_map_idx, thread);
1723 	*perf_counts(evsel->prev_raw_counts, cpu_map_idx, thread) = *count;
1724 
1725 	count->val = count->val - tmp.val;
1726 	count->ena = count->ena - tmp.ena;
1727 	count->run = count->run - tmp.run;
1728 }
1729 
1730 static int evsel__read_one(struct evsel *evsel, int cpu_map_idx, int thread)
1731 {
1732 	struct perf_counts_values *count = perf_counts(evsel->counts, cpu_map_idx, thread);
1733 
1734 	return perf_evsel__read(&evsel->core, cpu_map_idx, thread, count);
1735 }
1736 
1737 static void evsel__set_count(struct evsel *counter, int cpu_map_idx, int thread,
1738 			     u64 val, u64 ena, u64 run, u64 lost)
1739 {
1740 	struct perf_counts_values *count;
1741 
1742 	count = perf_counts(counter->counts, cpu_map_idx, thread);
1743 
1744 	if (evsel__is_retire_lat(counter)) {
1745 		evsel__tpebs_read(counter, cpu_map_idx, thread);
1746 		perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, true);
1747 		return;
1748 	}
1749 
1750 	count->val    = val;
1751 	count->ena    = ena;
1752 	count->run    = run;
1753 	count->lost   = lost;
1754 
1755 	perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, true);
1756 }
1757 
1758 static bool evsel__group_has_tpebs(struct evsel *leader)
1759 {
1760 	struct evsel *evsel;
1761 
1762 	for_each_group_evsel(evsel, leader) {
1763 		if (evsel__is_retire_lat(evsel))
1764 			return true;
1765 	}
1766 	return false;
1767 }
1768 
1769 static u64 evsel__group_read_nr_members(struct evsel *leader)
1770 {
1771 	u64 nr = leader->core.nr_members;
1772 	struct evsel *evsel;
1773 
1774 	for_each_group_evsel(evsel, leader) {
1775 		if (evsel__is_retire_lat(evsel))
1776 			nr--;
1777 	}
1778 	return nr;
1779 }
1780 
1781 static u64 evsel__group_read_size(struct evsel *leader)
1782 {
1783 	u64 read_format = leader->core.attr.read_format;
1784 	int entry = sizeof(u64); /* value */
1785 	int size = 0;
1786 	int nr = 1;
1787 
1788 	if (!evsel__group_has_tpebs(leader))
1789 		return perf_evsel__read_size(&leader->core);
1790 
1791 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1792 		size += sizeof(u64);
1793 
1794 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1795 		size += sizeof(u64);
1796 
1797 	if (read_format & PERF_FORMAT_ID)
1798 		entry += sizeof(u64);
1799 
1800 	if (read_format & PERF_FORMAT_LOST)
1801 		entry += sizeof(u64);
1802 
1803 	if (read_format & PERF_FORMAT_GROUP) {
1804 		nr = evsel__group_read_nr_members(leader);
1805 		size += sizeof(u64);
1806 	}
1807 
1808 	size += entry * nr;
1809 	return size;
1810 }
1811 
1812 static int evsel__process_group_data(struct evsel *leader, int cpu_map_idx, int thread, u64 *data)
1813 {
1814 	u64 read_format = leader->core.attr.read_format;
1815 	struct sample_read_value *v;
1816 	u64 nr, ena = 0, run = 0, lost = 0;
1817 
1818 	nr = *data++;
1819 
1820 	if (nr != evsel__group_read_nr_members(leader))
1821 		return -EINVAL;
1822 
1823 	if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED)
1824 		ena = *data++;
1825 
1826 	if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING)
1827 		run = *data++;
1828 
1829 	v = (void *)data;
1830 	sample_read_group__for_each(v, nr, read_format) {
1831 		struct evsel *counter;
1832 
1833 		counter = evlist__id2evsel(leader->evlist, v->id);
1834 		if (!counter)
1835 			return -EINVAL;
1836 
1837 		if (read_format & PERF_FORMAT_LOST)
1838 			lost = v->lost;
1839 
1840 		evsel__set_count(counter, cpu_map_idx, thread, v->value, ena, run, lost);
1841 	}
1842 
1843 	return 0;
1844 }
1845 
1846 static int evsel__read_group(struct evsel *leader, int cpu_map_idx, int thread)
1847 {
1848 	struct perf_stat_evsel *ps = leader->stats;
1849 	u64 read_format = leader->core.attr.read_format;
1850 	int size = evsel__group_read_size(leader);
1851 	u64 *data = ps->group_data;
1852 
1853 	if (!(read_format & PERF_FORMAT_ID))
1854 		return -EINVAL;
1855 
1856 	if (!evsel__is_group_leader(leader))
1857 		return -EINVAL;
1858 
1859 	if (!data) {
1860 		data = zalloc(size);
1861 		if (!data)
1862 			return -ENOMEM;
1863 
1864 		ps->group_data = data;
1865 	}
1866 
1867 	if (FD(leader, cpu_map_idx, thread) < 0)
1868 		return -EINVAL;
1869 
1870 	if (readn(FD(leader, cpu_map_idx, thread), data, size) <= 0)
1871 		return -errno;
1872 
1873 	return evsel__process_group_data(leader, cpu_map_idx, thread, data);
1874 }
1875 
1876 bool __evsel__match(const struct evsel *evsel, u32 type, u64 config)
1877 {
1878 
1879 	u32 e_type = evsel->core.attr.type;
1880 	u64 e_config = evsel->core.attr.config;
1881 
1882 	if (e_type != type) {
1883 		return type == PERF_TYPE_HARDWARE && evsel->pmu && evsel->pmu->is_core &&
1884 			evsel->alternate_hw_config == config;
1885 	}
1886 
1887 	if ((type == PERF_TYPE_HARDWARE || type == PERF_TYPE_HW_CACHE) &&
1888 	    perf_pmus__supports_extended_type())
1889 		e_config &= PERF_HW_EVENT_MASK;
1890 
1891 	return e_config == config;
1892 }
1893 
1894 int evsel__read_counter(struct evsel *evsel, int cpu_map_idx, int thread)
1895 {
1896 	if (evsel__is_tool(evsel))
1897 		return evsel__tool_pmu_read(evsel, cpu_map_idx, thread);
1898 
1899 	if (evsel__is_hwmon(evsel))
1900 		return evsel__hwmon_pmu_read(evsel, cpu_map_idx, thread);
1901 
1902 	if (evsel__is_drm(evsel))
1903 		return evsel__drm_pmu_read(evsel, cpu_map_idx, thread);
1904 
1905 	if (evsel__is_retire_lat(evsel))
1906 		return evsel__tpebs_read(evsel, cpu_map_idx, thread);
1907 
1908 	if (evsel->core.attr.read_format & PERF_FORMAT_GROUP)
1909 		return evsel__read_group(evsel, cpu_map_idx, thread);
1910 
1911 	return evsel__read_one(evsel, cpu_map_idx, thread);
1912 }
1913 
1914 int __evsel__read_on_cpu(struct evsel *evsel, int cpu_map_idx, int thread, bool scale)
1915 {
1916 	struct perf_counts_values count;
1917 	size_t nv = scale ? 3 : 1;
1918 
1919 	if (FD(evsel, cpu_map_idx, thread) < 0)
1920 		return -EINVAL;
1921 
1922 	if (evsel->counts == NULL && evsel__alloc_counts(evsel) < 0)
1923 		return -ENOMEM;
1924 
1925 	if (readn(FD(evsel, cpu_map_idx, thread), &count, nv * sizeof(u64)) <= 0)
1926 		return -errno;
1927 
1928 	evsel__compute_deltas(evsel, cpu_map_idx, thread, &count);
1929 	perf_counts_values__scale(&count, scale, NULL);
1930 	*perf_counts(evsel->counts, cpu_map_idx, thread) = count;
1931 	return 0;
1932 }
1933 
1934 static int evsel__match_other_cpu(struct evsel *evsel, struct evsel *other,
1935 				  int cpu_map_idx)
1936 {
1937 	struct perf_cpu cpu;
1938 
1939 	cpu = perf_cpu_map__cpu(evsel->core.cpus, cpu_map_idx);
1940 	return perf_cpu_map__idx(other->core.cpus, cpu);
1941 }
1942 
1943 static int evsel__hybrid_group_cpu_map_idx(struct evsel *evsel, int cpu_map_idx)
1944 {
1945 	struct evsel *leader = evsel__leader(evsel);
1946 
1947 	if ((evsel__is_hybrid(evsel) && !evsel__is_hybrid(leader)) ||
1948 	    (!evsel__is_hybrid(evsel) && evsel__is_hybrid(leader))) {
1949 		return evsel__match_other_cpu(evsel, leader, cpu_map_idx);
1950 	}
1951 
1952 	return cpu_map_idx;
1953 }
1954 
1955 static int get_group_fd(struct evsel *evsel, int cpu_map_idx, int thread)
1956 {
1957 	struct evsel *leader = evsel__leader(evsel);
1958 	int fd;
1959 
1960 	if (evsel__is_group_leader(evsel))
1961 		return -1;
1962 
1963 	/*
1964 	 * Leader must be already processed/open,
1965 	 * if not it's a bug.
1966 	 */
1967 	BUG_ON(!leader->core.fd);
1968 
1969 	cpu_map_idx = evsel__hybrid_group_cpu_map_idx(evsel, cpu_map_idx);
1970 	if (cpu_map_idx == -1)
1971 		return -1;
1972 
1973 	fd = FD(leader, cpu_map_idx, thread);
1974 	BUG_ON(fd == -1 && !leader->skippable);
1975 
1976 	/*
1977 	 * When the leader has been skipped, return -2 to distinguish from no
1978 	 * group leader case.
1979 	 */
1980 	return fd == -1 ? -2 : fd;
1981 }
1982 
1983 static void evsel__remove_fd(struct evsel *pos, int nr_cpus, int nr_threads, int thread_idx)
1984 {
1985 	for (int cpu = 0; cpu < nr_cpus; cpu++)
1986 		for (int thread = thread_idx; thread < nr_threads - 1; thread++)
1987 			FD(pos, cpu, thread) = FD(pos, cpu, thread + 1);
1988 }
1989 
1990 static int update_fds(struct evsel *evsel,
1991 		      int nr_cpus, int cpu_map_idx,
1992 		      int nr_threads, int thread_idx)
1993 {
1994 	struct evsel *pos;
1995 
1996 	if (cpu_map_idx >= nr_cpus || thread_idx >= nr_threads)
1997 		return -EINVAL;
1998 
1999 	evlist__for_each_entry(evsel->evlist, pos) {
2000 		nr_cpus = pos != evsel ? nr_cpus : cpu_map_idx;
2001 
2002 		evsel__remove_fd(pos, nr_cpus, nr_threads, thread_idx);
2003 
2004 		/*
2005 		 * Since fds for next evsel has not been created,
2006 		 * there is no need to iterate whole event list.
2007 		 */
2008 		if (pos == evsel)
2009 			break;
2010 	}
2011 	return 0;
2012 }
2013 
2014 static bool evsel__ignore_missing_thread(struct evsel *evsel,
2015 					 int nr_cpus, int cpu_map_idx,
2016 					 struct perf_thread_map *threads,
2017 					 int thread, int err)
2018 {
2019 	pid_t ignore_pid = perf_thread_map__pid(threads, thread);
2020 
2021 	if (!evsel->ignore_missing_thread)
2022 		return false;
2023 
2024 	/* The system wide setup does not work with threads. */
2025 	if (evsel->core.system_wide)
2026 		return false;
2027 
2028 	/* The -ESRCH is perf event syscall errno for pid's not found. */
2029 	if (err != -ESRCH)
2030 		return false;
2031 
2032 	/* If there's only one thread, let it fail. */
2033 	if (threads->nr == 1)
2034 		return false;
2035 
2036 	/*
2037 	 * We should remove fd for missing_thread first
2038 	 * because thread_map__remove() will decrease threads->nr.
2039 	 */
2040 	if (update_fds(evsel, nr_cpus, cpu_map_idx, threads->nr, thread))
2041 		return false;
2042 
2043 	if (thread_map__remove(threads, thread))
2044 		return false;
2045 
2046 	pr_warning("WARNING: Ignored open failure for pid %d\n",
2047 		   ignore_pid);
2048 	return true;
2049 }
2050 
2051 static int __open_attr__fprintf(FILE *fp, const char *name, const char *val,
2052 				void *priv __maybe_unused)
2053 {
2054 	return fprintf(fp, "  %-32s %s\n", name, val);
2055 }
2056 
2057 static void display_attr(struct perf_event_attr *attr)
2058 {
2059 	if (verbose >= 2 || debug_peo_args) {
2060 		fprintf(stderr, "%.60s\n", graph_dotted_line);
2061 		fprintf(stderr, "perf_event_attr:\n");
2062 		perf_event_attr__fprintf(stderr, attr, __open_attr__fprintf, NULL);
2063 		fprintf(stderr, "%.60s\n", graph_dotted_line);
2064 	}
2065 }
2066 
2067 bool evsel__precise_ip_fallback(struct evsel *evsel)
2068 {
2069 	/* Do not try less precise if not requested. */
2070 	if (!evsel->precise_max)
2071 		return false;
2072 
2073 	/*
2074 	 * We tried all the precise_ip values, and it's
2075 	 * still failing, so leave it to standard fallback.
2076 	 */
2077 	if (!evsel->core.attr.precise_ip) {
2078 		evsel->core.attr.precise_ip = evsel->precise_ip_original;
2079 		return false;
2080 	}
2081 
2082 	if (!evsel->precise_ip_original)
2083 		evsel->precise_ip_original = evsel->core.attr.precise_ip;
2084 
2085 	evsel->core.attr.precise_ip--;
2086 	pr_debug2_peo("decreasing precise_ip by one (%d)\n", evsel->core.attr.precise_ip);
2087 	display_attr(&evsel->core.attr);
2088 	return true;
2089 }
2090 
2091 static struct perf_cpu_map *empty_cpu_map;
2092 static struct perf_thread_map *empty_thread_map;
2093 
2094 static int __evsel__prepare_open(struct evsel *evsel, struct perf_cpu_map *cpus,
2095 		struct perf_thread_map *threads)
2096 {
2097 	int ret = 0;
2098 	int nthreads = perf_thread_map__nr(threads);
2099 
2100 	if ((perf_missing_features.write_backward && evsel->core.attr.write_backward) ||
2101 	    (perf_missing_features.aux_output     && evsel->core.attr.aux_output))
2102 		return -EINVAL;
2103 
2104 	if (cpus == NULL) {
2105 		if (empty_cpu_map == NULL) {
2106 			empty_cpu_map = perf_cpu_map__new_any_cpu();
2107 			if (empty_cpu_map == NULL)
2108 				return -ENOMEM;
2109 		}
2110 
2111 		cpus = empty_cpu_map;
2112 	}
2113 
2114 	if (threads == NULL) {
2115 		if (empty_thread_map == NULL) {
2116 			empty_thread_map = thread_map__new_by_tid(-1);
2117 			if (empty_thread_map == NULL)
2118 				return -ENOMEM;
2119 		}
2120 
2121 		threads = empty_thread_map;
2122 	}
2123 
2124 	if (evsel->core.fd == NULL &&
2125 	    perf_evsel__alloc_fd(&evsel->core, perf_cpu_map__nr(cpus), nthreads) < 0)
2126 		return -ENOMEM;
2127 
2128 	if (evsel__is_tool(evsel))
2129 		ret = evsel__tool_pmu_prepare_open(evsel, cpus, nthreads);
2130 
2131 	evsel->open_flags = PERF_FLAG_FD_CLOEXEC;
2132 	if (evsel->cgrp)
2133 		evsel->open_flags |= PERF_FLAG_PID_CGROUP;
2134 
2135 	return ret;
2136 }
2137 
2138 static void evsel__disable_missing_features(struct evsel *evsel)
2139 {
2140 	if (perf_missing_features.inherit_sample_read && evsel->core.attr.inherit &&
2141 	    (evsel->core.attr.sample_type & PERF_SAMPLE_READ))
2142 		evsel->core.attr.inherit = 0;
2143 	if (perf_missing_features.branch_counters)
2144 		evsel->core.attr.branch_sample_type &= ~PERF_SAMPLE_BRANCH_COUNTERS;
2145 	if (perf_missing_features.read_lost)
2146 		evsel->core.attr.read_format &= ~PERF_FORMAT_LOST;
2147 	if (perf_missing_features.weight_struct) {
2148 		evsel__set_sample_bit(evsel, WEIGHT);
2149 		evsel__reset_sample_bit(evsel, WEIGHT_STRUCT);
2150 	}
2151 	if (perf_missing_features.clockid_wrong)
2152 		evsel->core.attr.clockid = CLOCK_MONOTONIC; /* should always work */
2153 	if (perf_missing_features.clockid) {
2154 		evsel->core.attr.use_clockid = 0;
2155 		evsel->core.attr.clockid = 0;
2156 	}
2157 	if (perf_missing_features.cloexec)
2158 		evsel->open_flags &= ~(unsigned long)PERF_FLAG_FD_CLOEXEC;
2159 	if (perf_missing_features.mmap2)
2160 		evsel->core.attr.mmap2 = 0;
2161 	if (evsel->pmu && evsel->pmu->missing_features.exclude_guest)
2162 		evsel->core.attr.exclude_guest = evsel->core.attr.exclude_host = 0;
2163 	if (perf_missing_features.lbr_flags)
2164 		evsel->core.attr.branch_sample_type &= ~(PERF_SAMPLE_BRANCH_NO_FLAGS |
2165 				     PERF_SAMPLE_BRANCH_NO_CYCLES);
2166 	if (perf_missing_features.group_read && evsel->core.attr.inherit)
2167 		evsel->core.attr.read_format &= ~(PERF_FORMAT_GROUP|PERF_FORMAT_ID);
2168 	if (perf_missing_features.ksymbol)
2169 		evsel->core.attr.ksymbol = 0;
2170 	if (perf_missing_features.bpf)
2171 		evsel->core.attr.bpf_event = 0;
2172 	if (perf_missing_features.branch_hw_idx)
2173 		evsel->core.attr.branch_sample_type &= ~PERF_SAMPLE_BRANCH_HW_INDEX;
2174 	if (perf_missing_features.sample_id_all)
2175 		evsel->core.attr.sample_id_all = 0;
2176 }
2177 
2178 int evsel__prepare_open(struct evsel *evsel, struct perf_cpu_map *cpus,
2179 			struct perf_thread_map *threads)
2180 {
2181 	int err;
2182 
2183 	err = __evsel__prepare_open(evsel, cpus, threads);
2184 	if (err)
2185 		return err;
2186 
2187 	evsel__disable_missing_features(evsel);
2188 
2189 	return err;
2190 }
2191 
2192 static bool __has_attr_feature(struct perf_event_attr *attr,
2193 			       struct perf_cpu cpu, unsigned long flags)
2194 {
2195 	int fd = syscall(SYS_perf_event_open, attr, /*pid=*/0, cpu.cpu,
2196 			 /*group_fd=*/-1, flags);
2197 	close(fd);
2198 
2199 	if (fd < 0) {
2200 		attr->exclude_kernel = 1;
2201 
2202 		fd = syscall(SYS_perf_event_open, attr, /*pid=*/0, cpu.cpu,
2203 			     /*group_fd=*/-1, flags);
2204 		close(fd);
2205 	}
2206 
2207 	if (fd < 0) {
2208 		attr->exclude_hv = 1;
2209 
2210 		fd = syscall(SYS_perf_event_open, attr, /*pid=*/0, cpu.cpu,
2211 			     /*group_fd=*/-1, flags);
2212 		close(fd);
2213 	}
2214 
2215 	if (fd < 0) {
2216 		attr->exclude_guest = 1;
2217 
2218 		fd = syscall(SYS_perf_event_open, attr, /*pid=*/0, cpu.cpu,
2219 			     /*group_fd=*/-1, flags);
2220 		close(fd);
2221 	}
2222 
2223 	attr->exclude_kernel = 0;
2224 	attr->exclude_guest = 0;
2225 	attr->exclude_hv = 0;
2226 
2227 	return fd >= 0;
2228 }
2229 
2230 static bool has_attr_feature(struct perf_event_attr *attr, unsigned long flags)
2231 {
2232 	struct perf_cpu cpu = {.cpu = -1};
2233 
2234 	return __has_attr_feature(attr, cpu, flags);
2235 }
2236 
2237 static void evsel__detect_missing_pmu_features(struct evsel *evsel)
2238 {
2239 	struct perf_event_attr attr = {
2240 		.type = evsel->core.attr.type,
2241 		.config = evsel->core.attr.config,
2242 		.disabled = 1,
2243 	};
2244 	struct perf_pmu *pmu = evsel->pmu;
2245 	int old_errno;
2246 
2247 	old_errno = errno;
2248 
2249 	if (pmu == NULL)
2250 		pmu = evsel->pmu = evsel__find_pmu(evsel);
2251 
2252 	if (pmu == NULL || pmu->missing_features.checked)
2253 		goto out;
2254 
2255 	/*
2256 	 * Must probe features in the order they were added to the
2257 	 * perf_event_attr interface.  These are kernel core limitation but
2258 	 * specific to PMUs with branch stack.  So we can detect with the given
2259 	 * hardware event and stop on the first one succeeded.
2260 	 */
2261 
2262 	/* Please add new feature detection here. */
2263 
2264 	attr.exclude_guest = 1;
2265 	if (has_attr_feature(&attr, /*flags=*/0))
2266 		goto found;
2267 	pmu->missing_features.exclude_guest = true;
2268 	pr_debug2("switching off exclude_guest for PMU %s\n", pmu->name);
2269 
2270 found:
2271 	pmu->missing_features.checked = true;
2272 out:
2273 	errno = old_errno;
2274 }
2275 
2276 static void evsel__detect_missing_brstack_features(struct evsel *evsel)
2277 {
2278 	static bool detection_done = false;
2279 	struct perf_event_attr attr = {
2280 		.type = evsel->core.attr.type,
2281 		.config = evsel->core.attr.config,
2282 		.disabled = 1,
2283 		.sample_type = PERF_SAMPLE_BRANCH_STACK,
2284 		.sample_period = 1000,
2285 	};
2286 	int old_errno;
2287 
2288 	if (detection_done)
2289 		return;
2290 
2291 	old_errno = errno;
2292 
2293 	/*
2294 	 * Must probe features in the order they were added to the
2295 	 * perf_event_attr interface.  These are PMU specific limitation
2296 	 * so we can detect with the given hardware event and stop on the
2297 	 * first one succeeded.
2298 	 */
2299 
2300 	/* Please add new feature detection here. */
2301 
2302 	attr.branch_sample_type = PERF_SAMPLE_BRANCH_COUNTERS;
2303 	if (has_attr_feature(&attr, /*flags=*/0))
2304 		goto found;
2305 	perf_missing_features.branch_counters = true;
2306 	pr_debug2("switching off branch counters support\n");
2307 
2308 	attr.branch_sample_type = PERF_SAMPLE_BRANCH_HW_INDEX;
2309 	if (has_attr_feature(&attr, /*flags=*/0))
2310 		goto found;
2311 	perf_missing_features.branch_hw_idx = true;
2312 	pr_debug2("switching off branch HW index support\n");
2313 
2314 	attr.branch_sample_type = PERF_SAMPLE_BRANCH_NO_CYCLES | PERF_SAMPLE_BRANCH_NO_FLAGS;
2315 	if (has_attr_feature(&attr, /*flags=*/0))
2316 		goto found;
2317 	perf_missing_features.lbr_flags = true;
2318 	pr_debug2_peo("switching off branch sample type no (cycles/flags)\n");
2319 
2320 found:
2321 	detection_done = true;
2322 	errno = old_errno;
2323 }
2324 
2325 static bool evsel__probe_aux_action(struct evsel *evsel, struct perf_cpu cpu)
2326 {
2327 	struct perf_event_attr attr = evsel->core.attr;
2328 	int old_errno = errno;
2329 
2330 	attr.disabled = 1;
2331 	attr.aux_start_paused = 1;
2332 
2333 	if (__has_attr_feature(&attr, cpu, /*flags=*/0)) {
2334 		errno = old_errno;
2335 		return true;
2336 	}
2337 
2338 	/*
2339 	 * EOPNOTSUPP means the kernel supports the feature but the PMU does
2340 	 * not, so keep that distinction if possible.
2341 	 */
2342 	if (errno != EOPNOTSUPP)
2343 		errno = old_errno;
2344 
2345 	return false;
2346 }
2347 
2348 static void evsel__detect_missing_aux_action_feature(struct evsel *evsel, struct perf_cpu cpu)
2349 {
2350 	static bool detection_done;
2351 	struct evsel *leader;
2352 
2353 	/*
2354 	 * Don't bother probing aux_action if it is not being used or has been
2355 	 * probed before.
2356 	 */
2357 	if (!evsel->core.attr.aux_action || detection_done)
2358 		return;
2359 
2360 	detection_done = true;
2361 
2362 	/*
2363 	 * The leader is an AUX area event. If it has failed, assume the feature
2364 	 * is not supported.
2365 	 */
2366 	leader = evsel__leader(evsel);
2367 	if (evsel == leader) {
2368 		perf_missing_features.aux_action = true;
2369 		return;
2370 	}
2371 
2372 	/*
2373 	 * AUX area event with aux_action must have been opened successfully
2374 	 * already, so feature is supported.
2375 	 */
2376 	if (leader->core.attr.aux_action)
2377 		return;
2378 
2379 	if (!evsel__probe_aux_action(leader, cpu))
2380 		perf_missing_features.aux_action = true;
2381 }
2382 
2383 static bool evsel__detect_missing_features(struct evsel *evsel, struct perf_cpu cpu)
2384 {
2385 	static bool detection_done = false;
2386 	struct perf_event_attr attr = {
2387 		.type = PERF_TYPE_SOFTWARE,
2388 		.config = PERF_COUNT_SW_TASK_CLOCK,
2389 		.disabled = 1,
2390 	};
2391 	int old_errno;
2392 
2393 	evsel__detect_missing_aux_action_feature(evsel, cpu);
2394 
2395 	evsel__detect_missing_pmu_features(evsel);
2396 
2397 	if (evsel__has_br_stack(evsel))
2398 		evsel__detect_missing_brstack_features(evsel);
2399 
2400 	if (detection_done)
2401 		goto check;
2402 
2403 	old_errno = errno;
2404 
2405 	/*
2406 	 * Must probe features in the order they were added to the
2407 	 * perf_event_attr interface.  These are kernel core limitation
2408 	 * not PMU-specific so we can detect with a software event and
2409 	 * stop on the first one succeeded.
2410 	 */
2411 
2412 	/* Please add new feature detection here. */
2413 
2414 	attr.inherit = true;
2415 	attr.sample_type = PERF_SAMPLE_READ;
2416 	if (has_attr_feature(&attr, /*flags=*/0))
2417 		goto found;
2418 	perf_missing_features.inherit_sample_read = true;
2419 	pr_debug2("Using PERF_SAMPLE_READ / :S modifier is not compatible with inherit, falling back to no-inherit.\n");
2420 	attr.inherit = false;
2421 	attr.sample_type = 0;
2422 
2423 	attr.read_format = PERF_FORMAT_LOST;
2424 	if (has_attr_feature(&attr, /*flags=*/0))
2425 		goto found;
2426 	perf_missing_features.read_lost = true;
2427 	pr_debug2("switching off PERF_FORMAT_LOST support\n");
2428 	attr.read_format = 0;
2429 
2430 	attr.sample_type = PERF_SAMPLE_WEIGHT_STRUCT;
2431 	if (has_attr_feature(&attr, /*flags=*/0))
2432 		goto found;
2433 	perf_missing_features.weight_struct = true;
2434 	pr_debug2("switching off weight struct support\n");
2435 	attr.sample_type = 0;
2436 
2437 	attr.sample_type = PERF_SAMPLE_CODE_PAGE_SIZE;
2438 	if (has_attr_feature(&attr, /*flags=*/0))
2439 		goto found;
2440 	perf_missing_features.code_page_size = true;
2441 	pr_debug2_peo("Kernel has no PERF_SAMPLE_CODE_PAGE_SIZE support\n");
2442 	attr.sample_type = 0;
2443 
2444 	attr.sample_type = PERF_SAMPLE_DATA_PAGE_SIZE;
2445 	if (has_attr_feature(&attr, /*flags=*/0))
2446 		goto found;
2447 	perf_missing_features.data_page_size = true;
2448 	pr_debug2_peo("Kernel has no PERF_SAMPLE_DATA_PAGE_SIZE support\n");
2449 	attr.sample_type = 0;
2450 
2451 	attr.cgroup = 1;
2452 	if (has_attr_feature(&attr, /*flags=*/0))
2453 		goto found;
2454 	perf_missing_features.cgroup = true;
2455 	pr_debug2_peo("Kernel has no cgroup sampling support\n");
2456 	attr.cgroup = 0;
2457 
2458 	attr.aux_output = 1;
2459 	if (has_attr_feature(&attr, /*flags=*/0))
2460 		goto found;
2461 	perf_missing_features.aux_output = true;
2462 	pr_debug2_peo("Kernel has no attr.aux_output support\n");
2463 	attr.aux_output = 0;
2464 
2465 	attr.bpf_event = 1;
2466 	if (has_attr_feature(&attr, /*flags=*/0))
2467 		goto found;
2468 	perf_missing_features.bpf = true;
2469 	pr_debug2_peo("switching off bpf_event\n");
2470 	attr.bpf_event = 0;
2471 
2472 	attr.ksymbol = 1;
2473 	if (has_attr_feature(&attr, /*flags=*/0))
2474 		goto found;
2475 	perf_missing_features.ksymbol = true;
2476 	pr_debug2_peo("switching off ksymbol\n");
2477 	attr.ksymbol = 0;
2478 
2479 	attr.write_backward = 1;
2480 	if (has_attr_feature(&attr, /*flags=*/0))
2481 		goto found;
2482 	perf_missing_features.write_backward = true;
2483 	pr_debug2_peo("switching off write_backward\n");
2484 	attr.write_backward = 0;
2485 
2486 	attr.use_clockid = 1;
2487 	attr.clockid = CLOCK_MONOTONIC;
2488 	if (has_attr_feature(&attr, /*flags=*/0))
2489 		goto found;
2490 	perf_missing_features.clockid = true;
2491 	pr_debug2_peo("switching off clockid\n");
2492 	attr.use_clockid = 0;
2493 	attr.clockid = 0;
2494 
2495 	if (has_attr_feature(&attr, /*flags=*/PERF_FLAG_FD_CLOEXEC))
2496 		goto found;
2497 	perf_missing_features.cloexec = true;
2498 	pr_debug2_peo("switching off cloexec flag\n");
2499 
2500 	attr.mmap2 = 1;
2501 	if (has_attr_feature(&attr, /*flags=*/0))
2502 		goto found;
2503 	perf_missing_features.mmap2 = true;
2504 	pr_debug2_peo("switching off mmap2\n");
2505 	attr.mmap2 = 0;
2506 
2507 	/* set this unconditionally? */
2508 	perf_missing_features.sample_id_all = true;
2509 	pr_debug2_peo("switching off sample_id_all\n");
2510 
2511 	attr.inherit = 1;
2512 	attr.read_format = PERF_FORMAT_GROUP;
2513 	if (has_attr_feature(&attr, /*flags=*/0))
2514 		goto found;
2515 	perf_missing_features.group_read = true;
2516 	pr_debug2_peo("switching off group read\n");
2517 	attr.inherit = 0;
2518 	attr.read_format = 0;
2519 
2520 found:
2521 	detection_done = true;
2522 	errno = old_errno;
2523 
2524 check:
2525 	if (evsel->core.attr.inherit &&
2526 	    (evsel->core.attr.sample_type & PERF_SAMPLE_READ) &&
2527 	    perf_missing_features.inherit_sample_read)
2528 		return true;
2529 
2530 	if ((evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_COUNTERS) &&
2531 	    perf_missing_features.branch_counters)
2532 		return true;
2533 
2534 	if ((evsel->core.attr.read_format & PERF_FORMAT_LOST) &&
2535 	    perf_missing_features.read_lost)
2536 		return true;
2537 
2538 	if ((evsel->core.attr.sample_type & PERF_SAMPLE_WEIGHT_STRUCT) &&
2539 	    perf_missing_features.weight_struct)
2540 		return true;
2541 
2542 	if (evsel->core.attr.use_clockid && evsel->core.attr.clockid != CLOCK_MONOTONIC &&
2543 	    !perf_missing_features.clockid) {
2544 		perf_missing_features.clockid_wrong = true;
2545 		return true;
2546 	}
2547 
2548 	if (evsel->core.attr.use_clockid && perf_missing_features.clockid)
2549 		return true;
2550 
2551 	if ((evsel->open_flags & PERF_FLAG_FD_CLOEXEC) &&
2552 	    perf_missing_features.cloexec)
2553 		return true;
2554 
2555 	if (evsel->core.attr.mmap2 && perf_missing_features.mmap2)
2556 		return true;
2557 
2558 	if ((evsel->core.attr.branch_sample_type & (PERF_SAMPLE_BRANCH_NO_FLAGS |
2559 						    PERF_SAMPLE_BRANCH_NO_CYCLES)) &&
2560 	    perf_missing_features.lbr_flags)
2561 		return true;
2562 
2563 	if (evsel->core.attr.inherit && (evsel->core.attr.read_format & PERF_FORMAT_GROUP) &&
2564 	    perf_missing_features.group_read)
2565 		return true;
2566 
2567 	if (evsel->core.attr.ksymbol && perf_missing_features.ksymbol)
2568 		return true;
2569 
2570 	if (evsel->core.attr.bpf_event && perf_missing_features.bpf)
2571 		return true;
2572 
2573 	if ((evsel->core.attr.branch_sample_type & PERF_SAMPLE_BRANCH_HW_INDEX) &&
2574 	    perf_missing_features.branch_hw_idx)
2575 		return true;
2576 
2577 	if (evsel->core.attr.sample_id_all && perf_missing_features.sample_id_all)
2578 		return true;
2579 
2580 	return false;
2581 }
2582 
2583 static int evsel__open_cpu(struct evsel *evsel, struct perf_cpu_map *cpus,
2584 		struct perf_thread_map *threads,
2585 		int start_cpu_map_idx, int end_cpu_map_idx)
2586 {
2587 	int idx, thread, nthreads;
2588 	int pid = -1, err, old_errno;
2589 	enum rlimit_action set_rlimit = NO_CHANGE;
2590 	struct perf_cpu cpu;
2591 
2592 	if (evsel__is_retire_lat(evsel))
2593 		return evsel__tpebs_open(evsel);
2594 
2595 	err = __evsel__prepare_open(evsel, cpus, threads);
2596 	if (err)
2597 		return err;
2598 
2599 	if (cpus == NULL)
2600 		cpus = empty_cpu_map;
2601 
2602 	if (threads == NULL)
2603 		threads = empty_thread_map;
2604 
2605 	nthreads = perf_thread_map__nr(threads);
2606 
2607 	if (evsel->cgrp)
2608 		pid = evsel->cgrp->fd;
2609 
2610 fallback_missing_features:
2611 	evsel__disable_missing_features(evsel);
2612 
2613 	pr_debug3("Opening: %s\n", evsel__name(evsel));
2614 	display_attr(&evsel->core.attr);
2615 
2616 	if (evsel__is_tool(evsel)) {
2617 		return evsel__tool_pmu_open(evsel, threads,
2618 					    start_cpu_map_idx,
2619 					    end_cpu_map_idx);
2620 	}
2621 	if (evsel__is_hwmon(evsel)) {
2622 		return evsel__hwmon_pmu_open(evsel, threads,
2623 					     start_cpu_map_idx,
2624 					     end_cpu_map_idx);
2625 	}
2626 	if (evsel__is_drm(evsel)) {
2627 		return evsel__drm_pmu_open(evsel, threads,
2628 					   start_cpu_map_idx,
2629 					   end_cpu_map_idx);
2630 	}
2631 
2632 	for (idx = start_cpu_map_idx; idx < end_cpu_map_idx; idx++) {
2633 		cpu = perf_cpu_map__cpu(cpus, idx);
2634 
2635 		for (thread = 0; thread < nthreads; thread++) {
2636 			int fd, group_fd;
2637 retry_open:
2638 			if (thread >= nthreads)
2639 				break;
2640 
2641 			if (!evsel->cgrp && !evsel->core.system_wide)
2642 				pid = perf_thread_map__pid(threads, thread);
2643 
2644 			group_fd = get_group_fd(evsel, idx, thread);
2645 
2646 			if (group_fd == -2) {
2647 				pr_debug("broken group leader for %s\n", evsel->name);
2648 				err = -EINVAL;
2649 				goto out_close;
2650 			}
2651 
2652 			/* Debug message used by test scripts */
2653 			pr_debug2_peo("sys_perf_event_open: pid %d  cpu %d  group_fd %d  flags %#lx",
2654 				pid, cpu.cpu, group_fd, evsel->open_flags);
2655 
2656 			fd = sys_perf_event_open(&evsel->core.attr, pid, cpu.cpu,
2657 						group_fd, evsel->open_flags);
2658 
2659 			FD(evsel, idx, thread) = fd;
2660 
2661 			if (fd < 0) {
2662 				err = -errno;
2663 
2664 				pr_debug2_peo("\nsys_perf_event_open failed, error %d\n",
2665 					  err);
2666 				goto try_fallback;
2667 			}
2668 
2669 			bpf_counter__install_pe(evsel, idx, fd);
2670 
2671 			if (unlikely(test_attr__enabled())) {
2672 				test_attr__open(&evsel->core.attr, pid, cpu,
2673 						fd, group_fd, evsel->open_flags);
2674 			}
2675 
2676 			/* Debug message used by test scripts */
2677 			pr_debug2_peo(" = %d\n", fd);
2678 
2679 			if (evsel->bpf_fd >= 0) {
2680 				int evt_fd = fd;
2681 				int bpf_fd = evsel->bpf_fd;
2682 
2683 				err = ioctl(evt_fd,
2684 					    PERF_EVENT_IOC_SET_BPF,
2685 					    bpf_fd);
2686 				if (err && errno != EEXIST) {
2687 					pr_err("failed to attach bpf fd %d: %s\n",
2688 					       bpf_fd, strerror(errno));
2689 					err = -EINVAL;
2690 					goto out_close;
2691 				}
2692 			}
2693 
2694 			set_rlimit = NO_CHANGE;
2695 
2696 			/*
2697 			 * If we succeeded but had to kill clockid, fail and
2698 			 * have evsel__open_strerror() print us a nice error.
2699 			 */
2700 			if (perf_missing_features.clockid ||
2701 			    perf_missing_features.clockid_wrong) {
2702 				err = -EINVAL;
2703 				goto out_close;
2704 			}
2705 		}
2706 	}
2707 
2708 	return 0;
2709 
2710 try_fallback:
2711 	if (evsel__ignore_missing_thread(evsel, perf_cpu_map__nr(cpus),
2712 					 idx, threads, thread, err)) {
2713 		/* We just removed 1 thread, so lower the upper nthreads limit. */
2714 		nthreads--;
2715 
2716 		/* ... and pretend like nothing have happened. */
2717 		err = 0;
2718 		goto retry_open;
2719 	}
2720 	/*
2721 	 * perf stat needs between 5 and 22 fds per CPU. When we run out
2722 	 * of them try to increase the limits.
2723 	 */
2724 	if (err == -EMFILE && rlimit__increase_nofile(&set_rlimit))
2725 		goto retry_open;
2726 
2727 	if (err == -EINVAL && evsel__detect_missing_features(evsel, cpu))
2728 		goto fallback_missing_features;
2729 
2730 	if (evsel__precise_ip_fallback(evsel))
2731 		goto retry_open;
2732 
2733 out_close:
2734 	if (err)
2735 		threads->err_thread = thread;
2736 
2737 	old_errno = errno;
2738 	do {
2739 		while (--thread >= 0) {
2740 			if (FD(evsel, idx, thread) >= 0)
2741 				close(FD(evsel, idx, thread));
2742 			FD(evsel, idx, thread) = -1;
2743 		}
2744 		thread = nthreads;
2745 	} while (--idx >= 0);
2746 	errno = old_errno;
2747 	return err;
2748 }
2749 
2750 int evsel__open(struct evsel *evsel, struct perf_cpu_map *cpus,
2751 		struct perf_thread_map *threads)
2752 {
2753 	return evsel__open_cpu(evsel, cpus, threads, 0, perf_cpu_map__nr(cpus));
2754 }
2755 
2756 void evsel__close(struct evsel *evsel)
2757 {
2758 	if (evsel__is_retire_lat(evsel))
2759 		evsel__tpebs_close(evsel);
2760 	perf_evsel__close(&evsel->core);
2761 	perf_evsel__free_id(&evsel->core);
2762 }
2763 
2764 int evsel__open_per_cpu_and_thread(struct evsel *evsel,
2765 				   struct perf_cpu_map *cpus, int cpu_map_idx,
2766 				   struct perf_thread_map *threads)
2767 {
2768 	if (cpu_map_idx == -1)
2769 		return evsel__open_cpu(evsel, cpus, threads, 0, perf_cpu_map__nr(cpus));
2770 
2771 	return evsel__open_cpu(evsel, cpus, threads, cpu_map_idx, cpu_map_idx + 1);
2772 }
2773 
2774 int evsel__open_per_cpu(struct evsel *evsel, struct perf_cpu_map *cpus, int cpu_map_idx)
2775 {
2776 	struct perf_thread_map *threads = thread_map__new_by_tid(-1);
2777 	int ret = evsel__open_per_cpu_and_thread(evsel, cpus, cpu_map_idx, threads);
2778 
2779 	perf_thread_map__put(threads);
2780 	return ret;
2781 }
2782 
2783 int evsel__open_per_thread(struct evsel *evsel, struct perf_thread_map *threads)
2784 {
2785 	struct perf_cpu_map *cpus = perf_cpu_map__new_any_cpu();
2786 	int ret = evsel__open_per_cpu_and_thread(evsel, cpus, -1, threads);
2787 
2788 	perf_cpu_map__put(cpus);
2789 	return ret;
2790 }
2791 
2792 static int perf_evsel__parse_id_sample(const struct evsel *evsel,
2793 				       const union perf_event *event,
2794 				       struct perf_sample *sample)
2795 {
2796 	u64 type = evsel->core.attr.sample_type;
2797 	const __u64 *array = event->sample.array;
2798 	bool swapped = evsel->needs_swap;
2799 	union u64_swap u;
2800 
2801 	array += ((event->header.size -
2802 		   sizeof(event->header)) / sizeof(u64)) - 1;
2803 
2804 	if (type & PERF_SAMPLE_IDENTIFIER) {
2805 		sample->id = *array;
2806 		array--;
2807 	}
2808 
2809 	if (type & PERF_SAMPLE_CPU) {
2810 		u.val64 = *array;
2811 		if (swapped) {
2812 			/* undo swap of u64, then swap on individual u32s */
2813 			u.val64 = bswap_64(u.val64);
2814 			u.val32[0] = bswap_32(u.val32[0]);
2815 		}
2816 
2817 		sample->cpu = u.val32[0];
2818 		array--;
2819 	}
2820 
2821 	if (type & PERF_SAMPLE_STREAM_ID) {
2822 		sample->stream_id = *array;
2823 		array--;
2824 	}
2825 
2826 	if (type & PERF_SAMPLE_ID) {
2827 		sample->id = *array;
2828 		array--;
2829 	}
2830 
2831 	if (type & PERF_SAMPLE_TIME) {
2832 		sample->time = *array;
2833 		array--;
2834 	}
2835 
2836 	if (type & PERF_SAMPLE_TID) {
2837 		u.val64 = *array;
2838 		if (swapped) {
2839 			/* undo swap of u64, then swap on individual u32s */
2840 			u.val64 = bswap_64(u.val64);
2841 			u.val32[0] = bswap_32(u.val32[0]);
2842 			u.val32[1] = bswap_32(u.val32[1]);
2843 		}
2844 
2845 		sample->pid = u.val32[0];
2846 		sample->tid = u.val32[1];
2847 		array--;
2848 	}
2849 
2850 	return 0;
2851 }
2852 
2853 static inline bool overflow(const void *endp, u16 max_size, const void *offset,
2854 			    u64 size)
2855 {
2856 	return size > max_size || offset + size > endp;
2857 }
2858 
2859 #define OVERFLOW_CHECK(offset, size, max_size)				\
2860 	do {								\
2861 		if (overflow(endp, (max_size), (offset), (size)))	\
2862 			return -EFAULT;					\
2863 	} while (0)
2864 
2865 #define OVERFLOW_CHECK_u64(offset) \
2866 	OVERFLOW_CHECK(offset, sizeof(u64), sizeof(u64))
2867 
2868 static int
2869 perf_event__check_size(union perf_event *event, unsigned int sample_size)
2870 {
2871 	/*
2872 	 * The evsel's sample_size is based on PERF_SAMPLE_MASK which includes
2873 	 * up to PERF_SAMPLE_PERIOD.  After that overflow() must be used to
2874 	 * check the format does not go past the end of the event.
2875 	 */
2876 	if (sample_size + sizeof(event->header) > event->header.size)
2877 		return -EFAULT;
2878 
2879 	return 0;
2880 }
2881 
2882 void __weak arch_perf_parse_sample_weight(struct perf_sample *data,
2883 					  const __u64 *array,
2884 					  u64 type __maybe_unused)
2885 {
2886 	data->weight = *array;
2887 }
2888 
2889 u64 evsel__bitfield_swap_branch_flags(u64 value)
2890 {
2891 	u64 new_val = 0;
2892 
2893 	/*
2894 	 * branch_flags
2895 	 * union {
2896 	 * 	u64 values;
2897 	 * 	struct {
2898 	 * 		mispred:1	//target mispredicted
2899 	 * 		predicted:1	//target predicted
2900 	 * 		in_tx:1		//in transaction
2901 	 * 		abort:1		//transaction abort
2902 	 * 		cycles:16	//cycle count to last branch
2903 	 * 		type:4		//branch type
2904 	 * 		spec:2		//branch speculation info
2905 	 * 		new_type:4	//additional branch type
2906 	 * 		priv:3		//privilege level
2907 	 * 		reserved:31
2908 	 * 	}
2909 	 * }
2910 	 *
2911 	 * Avoid bswap64() the entire branch_flag.value,
2912 	 * as it has variable bit-field sizes. Instead the
2913 	 * macro takes the bit-field position/size,
2914 	 * swaps it based on the host endianness.
2915 	 */
2916 	if (host_is_bigendian()) {
2917 		new_val = bitfield_swap(value, 0, 1);
2918 		new_val |= bitfield_swap(value, 1, 1);
2919 		new_val |= bitfield_swap(value, 2, 1);
2920 		new_val |= bitfield_swap(value, 3, 1);
2921 		new_val |= bitfield_swap(value, 4, 16);
2922 		new_val |= bitfield_swap(value, 20, 4);
2923 		new_val |= bitfield_swap(value, 24, 2);
2924 		new_val |= bitfield_swap(value, 26, 4);
2925 		new_val |= bitfield_swap(value, 30, 3);
2926 		new_val |= bitfield_swap(value, 33, 31);
2927 	} else {
2928 		new_val = bitfield_swap(value, 63, 1);
2929 		new_val |= bitfield_swap(value, 62, 1);
2930 		new_val |= bitfield_swap(value, 61, 1);
2931 		new_val |= bitfield_swap(value, 60, 1);
2932 		new_val |= bitfield_swap(value, 44, 16);
2933 		new_val |= bitfield_swap(value, 40, 4);
2934 		new_val |= bitfield_swap(value, 38, 2);
2935 		new_val |= bitfield_swap(value, 34, 4);
2936 		new_val |= bitfield_swap(value, 31, 3);
2937 		new_val |= bitfield_swap(value, 0, 31);
2938 	}
2939 
2940 	return new_val;
2941 }
2942 
2943 static inline bool evsel__has_branch_counters(const struct evsel *evsel)
2944 {
2945 	struct evsel *leader = evsel__leader(evsel);
2946 
2947 	/* The branch counters feature only supports group */
2948 	if (!leader || !evsel->evlist)
2949 		return false;
2950 
2951 	if (evsel->evlist->nr_br_cntr < 0)
2952 		evlist__update_br_cntr(evsel->evlist);
2953 
2954 	if (leader->br_cntr_nr > 0)
2955 		return true;
2956 
2957 	return false;
2958 }
2959 
2960 static int __set_offcpu_sample(struct perf_sample *data)
2961 {
2962 	u64 *array = data->raw_data;
2963 	u32 max_size = data->raw_size, *p32;
2964 	const void *endp = (void *)array + max_size;
2965 
2966 	if (array == NULL)
2967 		return -EFAULT;
2968 
2969 	OVERFLOW_CHECK_u64(array);
2970 	p32 = (void *)array++;
2971 	data->pid = p32[0];
2972 	data->tid = p32[1];
2973 
2974 	OVERFLOW_CHECK_u64(array);
2975 	data->period = *array++;
2976 
2977 	OVERFLOW_CHECK_u64(array);
2978 	data->callchain = (struct ip_callchain *)array++;
2979 	OVERFLOW_CHECK(array, data->callchain->nr * sizeof(u64), max_size);
2980 	data->ip = data->callchain->ips[1];
2981 	array += data->callchain->nr;
2982 
2983 	OVERFLOW_CHECK_u64(array);
2984 	data->cgroup = *array;
2985 
2986 	return 0;
2987 }
2988 
2989 int evsel__parse_sample(struct evsel *evsel, union perf_event *event,
2990 			struct perf_sample *data)
2991 {
2992 	u64 type = evsel->core.attr.sample_type;
2993 	bool swapped = evsel->needs_swap;
2994 	const __u64 *array;
2995 	u16 max_size = event->header.size;
2996 	const void *endp = (void *)event + max_size;
2997 	u64 sz;
2998 
2999 	/*
3000 	 * used for cross-endian analysis. See git commit 65014ab3
3001 	 * for why this goofiness is needed.
3002 	 */
3003 	union u64_swap u;
3004 
3005 	memset(data, 0, sizeof(*data));
3006 	data->cpu = data->pid = data->tid = -1;
3007 	data->stream_id = data->id = data->time = -1ULL;
3008 	data->period = evsel->core.attr.sample_period;
3009 	data->cpumode = event->header.misc & PERF_RECORD_MISC_CPUMODE_MASK;
3010 	data->misc    = event->header.misc;
3011 	data->data_src = PERF_MEM_DATA_SRC_NONE;
3012 	data->vcpu = -1;
3013 
3014 	if (event->header.type != PERF_RECORD_SAMPLE) {
3015 		if (!evsel->core.attr.sample_id_all)
3016 			return 0;
3017 		return perf_evsel__parse_id_sample(evsel, event, data);
3018 	}
3019 
3020 	array = event->sample.array;
3021 
3022 	if (perf_event__check_size(event, evsel->sample_size))
3023 		return -EFAULT;
3024 
3025 	if (type & PERF_SAMPLE_IDENTIFIER) {
3026 		data->id = *array;
3027 		array++;
3028 	}
3029 
3030 	if (type & PERF_SAMPLE_IP) {
3031 		data->ip = *array;
3032 		array++;
3033 	}
3034 
3035 	if (type & PERF_SAMPLE_TID) {
3036 		u.val64 = *array;
3037 		if (swapped) {
3038 			/* undo swap of u64, then swap on individual u32s */
3039 			u.val64 = bswap_64(u.val64);
3040 			u.val32[0] = bswap_32(u.val32[0]);
3041 			u.val32[1] = bswap_32(u.val32[1]);
3042 		}
3043 
3044 		data->pid = u.val32[0];
3045 		data->tid = u.val32[1];
3046 		array++;
3047 	}
3048 
3049 	if (type & PERF_SAMPLE_TIME) {
3050 		data->time = *array;
3051 		array++;
3052 	}
3053 
3054 	if (type & PERF_SAMPLE_ADDR) {
3055 		data->addr = *array;
3056 		array++;
3057 	}
3058 
3059 	if (type & PERF_SAMPLE_ID) {
3060 		data->id = *array;
3061 		array++;
3062 	}
3063 
3064 	if (type & PERF_SAMPLE_STREAM_ID) {
3065 		data->stream_id = *array;
3066 		array++;
3067 	}
3068 
3069 	if (type & PERF_SAMPLE_CPU) {
3070 
3071 		u.val64 = *array;
3072 		if (swapped) {
3073 			/* undo swap of u64, then swap on individual u32s */
3074 			u.val64 = bswap_64(u.val64);
3075 			u.val32[0] = bswap_32(u.val32[0]);
3076 		}
3077 
3078 		data->cpu = u.val32[0];
3079 		array++;
3080 	}
3081 
3082 	if (type & PERF_SAMPLE_PERIOD) {
3083 		data->period = *array;
3084 		array++;
3085 	}
3086 
3087 	if (type & PERF_SAMPLE_READ) {
3088 		u64 read_format = evsel->core.attr.read_format;
3089 
3090 		OVERFLOW_CHECK_u64(array);
3091 		if (read_format & PERF_FORMAT_GROUP)
3092 			data->read.group.nr = *array;
3093 		else
3094 			data->read.one.value = *array;
3095 
3096 		array++;
3097 
3098 		if (read_format & PERF_FORMAT_TOTAL_TIME_ENABLED) {
3099 			OVERFLOW_CHECK_u64(array);
3100 			data->read.time_enabled = *array;
3101 			array++;
3102 		}
3103 
3104 		if (read_format & PERF_FORMAT_TOTAL_TIME_RUNNING) {
3105 			OVERFLOW_CHECK_u64(array);
3106 			data->read.time_running = *array;
3107 			array++;
3108 		}
3109 
3110 		/* PERF_FORMAT_ID is forced for PERF_SAMPLE_READ */
3111 		if (read_format & PERF_FORMAT_GROUP) {
3112 			const u64 max_group_nr = UINT64_MAX /
3113 					sizeof(struct sample_read_value);
3114 
3115 			if (data->read.group.nr > max_group_nr)
3116 				return -EFAULT;
3117 
3118 			sz = data->read.group.nr * sample_read_value_size(read_format);
3119 			OVERFLOW_CHECK(array, sz, max_size);
3120 			data->read.group.values =
3121 					(struct sample_read_value *)array;
3122 			array = (void *)array + sz;
3123 		} else {
3124 			OVERFLOW_CHECK_u64(array);
3125 			data->read.one.id = *array;
3126 			array++;
3127 
3128 			if (read_format & PERF_FORMAT_LOST) {
3129 				OVERFLOW_CHECK_u64(array);
3130 				data->read.one.lost = *array;
3131 				array++;
3132 			}
3133 		}
3134 	}
3135 
3136 	if (type & PERF_SAMPLE_CALLCHAIN) {
3137 		const u64 max_callchain_nr = UINT64_MAX / sizeof(u64);
3138 
3139 		OVERFLOW_CHECK_u64(array);
3140 		data->callchain = (struct ip_callchain *)array++;
3141 		if (data->callchain->nr > max_callchain_nr)
3142 			return -EFAULT;
3143 		sz = data->callchain->nr * sizeof(u64);
3144 		OVERFLOW_CHECK(array, sz, max_size);
3145 		array = (void *)array + sz;
3146 	}
3147 
3148 	if (type & PERF_SAMPLE_RAW) {
3149 		OVERFLOW_CHECK_u64(array);
3150 		u.val64 = *array;
3151 
3152 		/*
3153 		 * Undo swap of u64, then swap on individual u32s,
3154 		 * get the size of the raw area and undo all of the
3155 		 * swap. The pevent interface handles endianness by
3156 		 * itself.
3157 		 */
3158 		if (swapped) {
3159 			u.val64 = bswap_64(u.val64);
3160 			u.val32[0] = bswap_32(u.val32[0]);
3161 			u.val32[1] = bswap_32(u.val32[1]);
3162 		}
3163 		data->raw_size = u.val32[0];
3164 
3165 		/*
3166 		 * The raw data is aligned on 64bits including the
3167 		 * u32 size, so it's safe to use mem_bswap_64.
3168 		 */
3169 		if (swapped)
3170 			mem_bswap_64((void *) array, data->raw_size);
3171 
3172 		array = (void *)array + sizeof(u32);
3173 
3174 		OVERFLOW_CHECK(array, data->raw_size, max_size);
3175 		data->raw_data = (void *)array;
3176 		array = (void *)array + data->raw_size;
3177 	}
3178 
3179 	if (type & PERF_SAMPLE_BRANCH_STACK) {
3180 		const u64 max_branch_nr = UINT64_MAX /
3181 					  sizeof(struct branch_entry);
3182 		struct branch_entry *e;
3183 		unsigned int i;
3184 
3185 		OVERFLOW_CHECK_u64(array);
3186 		data->branch_stack = (struct branch_stack *)array++;
3187 
3188 		if (data->branch_stack->nr > max_branch_nr)
3189 			return -EFAULT;
3190 
3191 		sz = data->branch_stack->nr * sizeof(struct branch_entry);
3192 		if (evsel__has_branch_hw_idx(evsel)) {
3193 			sz += sizeof(u64);
3194 			e = &data->branch_stack->entries[0];
3195 		} else {
3196 			data->no_hw_idx = true;
3197 			/*
3198 			 * if the PERF_SAMPLE_BRANCH_HW_INDEX is not applied,
3199 			 * only nr and entries[] will be output by kernel.
3200 			 */
3201 			e = (struct branch_entry *)&data->branch_stack->hw_idx;
3202 		}
3203 
3204 		if (swapped) {
3205 			/*
3206 			 * struct branch_flag does not have endian
3207 			 * specific bit field definition. And bswap
3208 			 * will not resolve the issue, since these
3209 			 * are bit fields.
3210 			 *
3211 			 * evsel__bitfield_swap_branch_flags() uses a
3212 			 * bitfield_swap macro to swap the bit position
3213 			 * based on the host endians.
3214 			 */
3215 			for (i = 0; i < data->branch_stack->nr; i++, e++)
3216 				e->flags.value = evsel__bitfield_swap_branch_flags(e->flags.value);
3217 		}
3218 
3219 		OVERFLOW_CHECK(array, sz, max_size);
3220 		array = (void *)array + sz;
3221 
3222 		if (evsel__has_branch_counters(evsel)) {
3223 			data->branch_stack_cntr = (u64 *)array;
3224 			sz = data->branch_stack->nr * sizeof(u64);
3225 
3226 			OVERFLOW_CHECK(array, sz, max_size);
3227 			array = (void *)array + sz;
3228 		}
3229 	}
3230 
3231 	if (type & PERF_SAMPLE_REGS_USER) {
3232 		struct regs_dump *regs = perf_sample__user_regs(data);
3233 
3234 		OVERFLOW_CHECK_u64(array);
3235 		regs->abi = *array;
3236 		array++;
3237 
3238 		if (regs->abi) {
3239 			u64 mask = evsel->core.attr.sample_regs_user;
3240 
3241 			sz = hweight64(mask) * sizeof(u64);
3242 			OVERFLOW_CHECK(array, sz, max_size);
3243 			regs->mask = mask;
3244 			regs->regs = (u64 *)array;
3245 			array = (void *)array + sz;
3246 		}
3247 	}
3248 
3249 	if (type & PERF_SAMPLE_STACK_USER) {
3250 		OVERFLOW_CHECK_u64(array);
3251 		sz = *array++;
3252 
3253 		data->user_stack.offset = ((char *)(array - 1)
3254 					  - (char *) event);
3255 
3256 		if (!sz) {
3257 			data->user_stack.size = 0;
3258 		} else {
3259 			OVERFLOW_CHECK(array, sz, max_size);
3260 			data->user_stack.data = (char *)array;
3261 			array = (void *)array + sz;
3262 			OVERFLOW_CHECK_u64(array);
3263 			data->user_stack.size = *array++;
3264 			if (WARN_ONCE(data->user_stack.size > sz,
3265 				      "user stack dump failure\n"))
3266 				return -EFAULT;
3267 		}
3268 	}
3269 
3270 	if (type & PERF_SAMPLE_WEIGHT_TYPE) {
3271 		OVERFLOW_CHECK_u64(array);
3272 		arch_perf_parse_sample_weight(data, array, type);
3273 		array++;
3274 	}
3275 
3276 	if (type & PERF_SAMPLE_DATA_SRC) {
3277 		OVERFLOW_CHECK_u64(array);
3278 		data->data_src = *array;
3279 		array++;
3280 	}
3281 
3282 	if (type & PERF_SAMPLE_TRANSACTION) {
3283 		OVERFLOW_CHECK_u64(array);
3284 		data->transaction = *array;
3285 		array++;
3286 	}
3287 
3288 	if (type & PERF_SAMPLE_REGS_INTR) {
3289 		struct regs_dump *regs = perf_sample__intr_regs(data);
3290 
3291 		OVERFLOW_CHECK_u64(array);
3292 		regs->abi = *array;
3293 		array++;
3294 
3295 		if (regs->abi != PERF_SAMPLE_REGS_ABI_NONE) {
3296 			u64 mask = evsel->core.attr.sample_regs_intr;
3297 
3298 			sz = hweight64(mask) * sizeof(u64);
3299 			OVERFLOW_CHECK(array, sz, max_size);
3300 			regs->mask = mask;
3301 			regs->regs = (u64 *)array;
3302 			array = (void *)array + sz;
3303 		}
3304 	}
3305 
3306 	data->phys_addr = 0;
3307 	if (type & PERF_SAMPLE_PHYS_ADDR) {
3308 		data->phys_addr = *array;
3309 		array++;
3310 	}
3311 
3312 	data->cgroup = 0;
3313 	if (type & PERF_SAMPLE_CGROUP) {
3314 		data->cgroup = *array;
3315 		array++;
3316 	}
3317 
3318 	data->data_page_size = 0;
3319 	if (type & PERF_SAMPLE_DATA_PAGE_SIZE) {
3320 		data->data_page_size = *array;
3321 		array++;
3322 	}
3323 
3324 	data->code_page_size = 0;
3325 	if (type & PERF_SAMPLE_CODE_PAGE_SIZE) {
3326 		data->code_page_size = *array;
3327 		array++;
3328 	}
3329 
3330 	if (type & PERF_SAMPLE_AUX) {
3331 		OVERFLOW_CHECK_u64(array);
3332 		sz = *array++;
3333 
3334 		OVERFLOW_CHECK(array, sz, max_size);
3335 		/* Undo swap of data */
3336 		if (swapped)
3337 			mem_bswap_64((char *)array, sz);
3338 		data->aux_sample.size = sz;
3339 		data->aux_sample.data = (char *)array;
3340 		array = (void *)array + sz;
3341 	}
3342 
3343 	if (evsel__is_offcpu_event(evsel))
3344 		return __set_offcpu_sample(data);
3345 
3346 	return 0;
3347 }
3348 
3349 int evsel__parse_sample_timestamp(struct evsel *evsel, union perf_event *event,
3350 				  u64 *timestamp)
3351 {
3352 	u64 type = evsel->core.attr.sample_type;
3353 	const __u64 *array;
3354 
3355 	if (!(type & PERF_SAMPLE_TIME))
3356 		return -1;
3357 
3358 	if (event->header.type != PERF_RECORD_SAMPLE) {
3359 		struct perf_sample data = {
3360 			.time = -1ULL,
3361 		};
3362 
3363 		if (!evsel->core.attr.sample_id_all)
3364 			return -1;
3365 		if (perf_evsel__parse_id_sample(evsel, event, &data))
3366 			return -1;
3367 
3368 		*timestamp = data.time;
3369 		return 0;
3370 	}
3371 
3372 	array = event->sample.array;
3373 
3374 	if (perf_event__check_size(event, evsel->sample_size))
3375 		return -EFAULT;
3376 
3377 	if (type & PERF_SAMPLE_IDENTIFIER)
3378 		array++;
3379 
3380 	if (type & PERF_SAMPLE_IP)
3381 		array++;
3382 
3383 	if (type & PERF_SAMPLE_TID)
3384 		array++;
3385 
3386 	if (type & PERF_SAMPLE_TIME)
3387 		*timestamp = *array;
3388 
3389 	return 0;
3390 }
3391 
3392 u16 evsel__id_hdr_size(const struct evsel *evsel)
3393 {
3394 	u64 sample_type = evsel->core.attr.sample_type;
3395 	u16 size = 0;
3396 
3397 	if (sample_type & PERF_SAMPLE_TID)
3398 		size += sizeof(u64);
3399 
3400 	if (sample_type & PERF_SAMPLE_TIME)
3401 		size += sizeof(u64);
3402 
3403 	if (sample_type & PERF_SAMPLE_ID)
3404 		size += sizeof(u64);
3405 
3406 	if (sample_type & PERF_SAMPLE_STREAM_ID)
3407 		size += sizeof(u64);
3408 
3409 	if (sample_type & PERF_SAMPLE_CPU)
3410 		size += sizeof(u64);
3411 
3412 	if (sample_type & PERF_SAMPLE_IDENTIFIER)
3413 		size += sizeof(u64);
3414 
3415 	return size;
3416 }
3417 
3418 #ifdef HAVE_LIBTRACEEVENT
3419 struct tep_format_field *evsel__field(struct evsel *evsel, const char *name)
3420 {
3421 	struct tep_event *tp_format = evsel__tp_format(evsel);
3422 
3423 	return tp_format ? tep_find_field(tp_format, name) : NULL;
3424 }
3425 
3426 struct tep_format_field *evsel__common_field(struct evsel *evsel, const char *name)
3427 {
3428 	struct tep_event *tp_format = evsel__tp_format(evsel);
3429 
3430 	return tp_format ? tep_find_common_field(tp_format, name) : NULL;
3431 }
3432 
3433 void *evsel__rawptr(struct evsel *evsel, struct perf_sample *sample, const char *name)
3434 {
3435 	struct tep_format_field *field = evsel__field(evsel, name);
3436 	int offset;
3437 
3438 	if (!field)
3439 		return NULL;
3440 
3441 	offset = field->offset;
3442 
3443 	if (field->flags & TEP_FIELD_IS_DYNAMIC) {
3444 		offset = *(int *)(sample->raw_data + field->offset);
3445 		offset &= 0xffff;
3446 		if (tep_field_is_relative(field->flags))
3447 			offset += field->offset + field->size;
3448 	}
3449 
3450 	return sample->raw_data + offset;
3451 }
3452 
3453 u64 format_field__intval(struct tep_format_field *field, struct perf_sample *sample,
3454 			 bool needs_swap)
3455 {
3456 	u64 value;
3457 	void *ptr = sample->raw_data + field->offset;
3458 
3459 	switch (field->size) {
3460 	case 1:
3461 		return *(u8 *)ptr;
3462 	case 2:
3463 		value = *(u16 *)ptr;
3464 		break;
3465 	case 4:
3466 		value = *(u32 *)ptr;
3467 		break;
3468 	case 8:
3469 		memcpy(&value, ptr, sizeof(u64));
3470 		break;
3471 	default:
3472 		return 0;
3473 	}
3474 
3475 	if (!needs_swap)
3476 		return value;
3477 
3478 	switch (field->size) {
3479 	case 2:
3480 		return bswap_16(value);
3481 	case 4:
3482 		return bswap_32(value);
3483 	case 8:
3484 		return bswap_64(value);
3485 	default:
3486 		return 0;
3487 	}
3488 
3489 	return 0;
3490 }
3491 
3492 u64 evsel__intval(struct evsel *evsel, struct perf_sample *sample, const char *name)
3493 {
3494 	struct tep_format_field *field = evsel__field(evsel, name);
3495 
3496 	return field ? format_field__intval(field, sample, evsel->needs_swap) : 0;
3497 }
3498 
3499 u64 evsel__intval_common(struct evsel *evsel, struct perf_sample *sample, const char *name)
3500 {
3501 	struct tep_format_field *field = evsel__common_field(evsel, name);
3502 
3503 	return field ? format_field__intval(field, sample, evsel->needs_swap) : 0;
3504 }
3505 
3506 char evsel__taskstate(struct evsel *evsel, struct perf_sample *sample, const char *name)
3507 {
3508 	static struct tep_format_field *prev_state_field;
3509 	static const char *states;
3510 	struct tep_format_field *field;
3511 	unsigned long long val;
3512 	unsigned int bit;
3513 	char state = '?'; /* '?' denotes unknown task state */
3514 
3515 	field = evsel__field(evsel, name);
3516 
3517 	if (!field)
3518 		return state;
3519 
3520 	if (!states || field != prev_state_field) {
3521 		states = parse_task_states(field);
3522 		if (!states)
3523 			return state;
3524 		prev_state_field = field;
3525 	}
3526 
3527 	/*
3528 	 * Note since the kernel exposes TASK_REPORT_MAX to userspace
3529 	 * to denote the 'preempted' state, we might as welll report
3530 	 * 'R' for this case, which make senses to users as well.
3531 	 *
3532 	 * We can change this if we have a good reason in the future.
3533 	 */
3534 	val = evsel__intval(evsel, sample, name);
3535 	bit = val ? ffs(val) : 0;
3536 	state = (!bit || bit > strlen(states)) ? 'R' : states[bit-1];
3537 	return state;
3538 }
3539 #endif
3540 
3541 bool evsel__fallback(struct evsel *evsel, struct target *target, int err,
3542 		     char *msg, size_t msgsize)
3543 {
3544 	int paranoid;
3545 
3546 	if ((err == ENOENT || err == ENXIO || err == ENODEV) &&
3547 	    evsel->core.attr.type   == PERF_TYPE_HARDWARE &&
3548 	    evsel->core.attr.config == PERF_COUNT_HW_CPU_CYCLES) {
3549 		/*
3550 		 * If it's cycles then fall back to hrtimer based cpu-clock sw
3551 		 * counter, which is always available even if no PMU support.
3552 		 *
3553 		 * PPC returns ENXIO until 2.6.37 (behavior changed with commit
3554 		 * b0a873e).
3555 		 */
3556 		evsel->core.attr.type   = PERF_TYPE_SOFTWARE;
3557 		evsel->core.attr.config = target__has_cpu(target)
3558 			? PERF_COUNT_SW_CPU_CLOCK
3559 			: PERF_COUNT_SW_TASK_CLOCK;
3560 		scnprintf(msg, msgsize,
3561 			"The cycles event is not supported, trying to fall back to %s",
3562 			target__has_cpu(target) ? "cpu-clock" : "task-clock");
3563 
3564 		zfree(&evsel->name);
3565 		return true;
3566 	} else if (err == EACCES && !evsel->core.attr.exclude_kernel &&
3567 		   (paranoid = perf_event_paranoid()) > 1) {
3568 		const char *name = evsel__name(evsel);
3569 		char *new_name;
3570 		const char *sep = ":";
3571 
3572 		/* If event has exclude user then don't exclude kernel. */
3573 		if (evsel->core.attr.exclude_user)
3574 			return false;
3575 
3576 		/* Is there already the separator in the name. */
3577 		if (strchr(name, '/') ||
3578 		    (strchr(name, ':') && !evsel->is_libpfm_event))
3579 			sep = "";
3580 
3581 		if (asprintf(&new_name, "%s%su", name, sep) < 0)
3582 			return false;
3583 
3584 		free(evsel->name);
3585 		evsel->name = new_name;
3586 		scnprintf(msg, msgsize, "kernel.perf_event_paranoid=%d, trying "
3587 			  "to fall back to excluding kernel and hypervisor "
3588 			  " samples", paranoid);
3589 		evsel->core.attr.exclude_kernel = 1;
3590 		evsel->core.attr.exclude_hv     = 1;
3591 
3592 		return true;
3593 	} else if (err == EOPNOTSUPP && !evsel->core.attr.exclude_guest &&
3594 		   !evsel->exclude_GH) {
3595 		const char *name = evsel__name(evsel);
3596 		char *new_name;
3597 		const char *sep = ":";
3598 
3599 		/* Is there already the separator in the name. */
3600 		if (strchr(name, '/') ||
3601 		    (strchr(name, ':') && !evsel->is_libpfm_event))
3602 			sep = "";
3603 
3604 		if (asprintf(&new_name, "%s%sH", name, sep) < 0)
3605 			return false;
3606 
3607 		free(evsel->name);
3608 		evsel->name = new_name;
3609 		/* Apple M1 requires exclude_guest */
3610 		scnprintf(msg, msgsize, "trying to fall back to excluding guest samples");
3611 		evsel->core.attr.exclude_guest = 1;
3612 
3613 		return true;
3614 	}
3615 
3616 	return false;
3617 }
3618 
3619 static bool find_process(const char *name)
3620 {
3621 	size_t len = strlen(name);
3622 	DIR *dir;
3623 	struct dirent *d;
3624 	int ret = -1;
3625 
3626 	dir = opendir(procfs__mountpoint());
3627 	if (!dir)
3628 		return false;
3629 
3630 	/* Walk through the directory. */
3631 	while (ret && (d = readdir(dir)) != NULL) {
3632 		char path[PATH_MAX];
3633 		char *data;
3634 		size_t size;
3635 
3636 		if ((d->d_type != DT_DIR) ||
3637 		     !strcmp(".", d->d_name) ||
3638 		     !strcmp("..", d->d_name))
3639 			continue;
3640 
3641 		scnprintf(path, sizeof(path), "%s/%s/comm",
3642 			  procfs__mountpoint(), d->d_name);
3643 
3644 		if (filename__read_str(path, &data, &size))
3645 			continue;
3646 
3647 		ret = strncmp(name, data, len);
3648 		free(data);
3649 	}
3650 
3651 	closedir(dir);
3652 	return ret ? false : true;
3653 }
3654 
3655 static int dump_perf_event_processes(char *msg, size_t size)
3656 {
3657 	DIR *proc_dir;
3658 	struct dirent *proc_entry;
3659 	int printed = 0;
3660 
3661 	proc_dir = opendir(procfs__mountpoint());
3662 	if (!proc_dir)
3663 		return 0;
3664 
3665 	/* Walk through the /proc directory. */
3666 	while ((proc_entry = readdir(proc_dir)) != NULL) {
3667 		char buf[256];
3668 		DIR *fd_dir;
3669 		struct dirent *fd_entry;
3670 		int fd_dir_fd;
3671 
3672 		if (proc_entry->d_type != DT_DIR ||
3673 		    !isdigit(proc_entry->d_name[0]) ||
3674 		    strlen(proc_entry->d_name) > sizeof(buf) - 4)
3675 			continue;
3676 
3677 		scnprintf(buf, sizeof(buf), "%s/fd", proc_entry->d_name);
3678 		fd_dir_fd = openat(dirfd(proc_dir), buf, O_DIRECTORY);
3679 		if (fd_dir_fd == -1)
3680 			continue;
3681 		fd_dir = fdopendir(fd_dir_fd);
3682 		if (!fd_dir) {
3683 			close(fd_dir_fd);
3684 			continue;
3685 		}
3686 		while ((fd_entry = readdir(fd_dir)) != NULL) {
3687 			ssize_t link_size;
3688 
3689 			if (fd_entry->d_type != DT_LNK)
3690 				continue;
3691 			link_size = readlinkat(fd_dir_fd, fd_entry->d_name, buf, sizeof(buf));
3692 			if (link_size < 0)
3693 				continue;
3694 			/* Take care as readlink doesn't null terminate the string. */
3695 			if (!strncmp(buf, "anon_inode:[perf_event]", link_size)) {
3696 				int cmdline_fd;
3697 				ssize_t cmdline_size;
3698 
3699 				scnprintf(buf, sizeof(buf), "%s/cmdline", proc_entry->d_name);
3700 				cmdline_fd = openat(dirfd(proc_dir), buf, O_RDONLY);
3701 				if (cmdline_fd == -1)
3702 					continue;
3703 				cmdline_size = read(cmdline_fd, buf, sizeof(buf) - 1);
3704 				close(cmdline_fd);
3705 				if (cmdline_size < 0)
3706 					continue;
3707 				buf[cmdline_size] = '\0';
3708 				for (ssize_t i = 0; i < cmdline_size; i++) {
3709 					if (buf[i] == '\0')
3710 						buf[i] = ' ';
3711 				}
3712 
3713 				if (printed == 0)
3714 					printed += scnprintf(msg, size, "Possible processes:\n");
3715 
3716 				printed += scnprintf(msg + printed, size - printed,
3717 						"%s %s\n", proc_entry->d_name, buf);
3718 				break;
3719 			}
3720 		}
3721 		closedir(fd_dir);
3722 	}
3723 	closedir(proc_dir);
3724 	return printed;
3725 }
3726 
3727 int __weak arch_evsel__open_strerror(struct evsel *evsel __maybe_unused,
3728 				     char *msg __maybe_unused,
3729 				     size_t size __maybe_unused)
3730 {
3731 	return 0;
3732 }
3733 
3734 int evsel__open_strerror(struct evsel *evsel, struct target *target,
3735 			 int err, char *msg, size_t size)
3736 {
3737 	char sbuf[STRERR_BUFSIZE];
3738 	int printed = 0, enforced = 0;
3739 	int ret;
3740 
3741 	switch (err) {
3742 	case EPERM:
3743 	case EACCES:
3744 		printed += scnprintf(msg + printed, size - printed,
3745 			"Access to performance monitoring and observability operations is limited.\n");
3746 
3747 		if (!sysfs__read_int("fs/selinux/enforce", &enforced)) {
3748 			if (enforced) {
3749 				printed += scnprintf(msg + printed, size - printed,
3750 					"Enforced MAC policy settings (SELinux) can limit access to performance\n"
3751 					"monitoring and observability operations. Inspect system audit records for\n"
3752 					"more perf_event access control information and adjusting the policy.\n");
3753 			}
3754 		}
3755 
3756 		if (err == EPERM)
3757 			printed += scnprintf(msg, size,
3758 				"No permission to enable %s event.\n\n", evsel__name(evsel));
3759 
3760 		return printed + scnprintf(msg + printed, size - printed,
3761 		 "Consider adjusting /proc/sys/kernel/perf_event_paranoid setting to open\n"
3762 		 "access to performance monitoring and observability operations for processes\n"
3763 		 "without CAP_PERFMON, CAP_SYS_PTRACE or CAP_SYS_ADMIN Linux capability.\n"
3764 		 "More information can be found at 'Perf events and tool security' document:\n"
3765 		 "https://www.kernel.org/doc/html/latest/admin-guide/perf-security.html\n"
3766 		 "perf_event_paranoid setting is %d:\n"
3767 		 "  -1: Allow use of (almost) all events by all users\n"
3768 		 "      Ignore mlock limit after perf_event_mlock_kb without CAP_IPC_LOCK\n"
3769 		 ">= 0: Disallow raw and ftrace function tracepoint access\n"
3770 		 ">= 1: Disallow CPU event access\n"
3771 		 ">= 2: Disallow kernel profiling\n"
3772 		 "To make the adjusted perf_event_paranoid setting permanent preserve it\n"
3773 		 "in /etc/sysctl.conf (e.g. kernel.perf_event_paranoid = <setting>)",
3774 		 perf_event_paranoid());
3775 	case ENOENT:
3776 		return scnprintf(msg, size, "The %s event is not supported.", evsel__name(evsel));
3777 	case EMFILE:
3778 		return scnprintf(msg, size, "%s",
3779 			 "Too many events are opened.\n"
3780 			 "Probably the maximum number of open file descriptors has been reached.\n"
3781 			 "Hint: Try again after reducing the number of events.\n"
3782 			 "Hint: Try increasing the limit with 'ulimit -n <limit>'");
3783 	case ENOMEM:
3784 		if (evsel__has_callchain(evsel) &&
3785 		    access("/proc/sys/kernel/perf_event_max_stack", F_OK) == 0)
3786 			return scnprintf(msg, size,
3787 					 "Not enough memory to setup event with callchain.\n"
3788 					 "Hint: Try tweaking /proc/sys/kernel/perf_event_max_stack\n"
3789 					 "Hint: Current value: %d", sysctl__max_stack());
3790 		break;
3791 	case ENODEV:
3792 		if (target->cpu_list)
3793 			return scnprintf(msg, size, "%s",
3794 	 "No such device - did you specify an out-of-range profile CPU?");
3795 		break;
3796 	case EOPNOTSUPP:
3797 		if (evsel->core.attr.sample_type & PERF_SAMPLE_BRANCH_STACK)
3798 			return scnprintf(msg, size,
3799 	"%s: PMU Hardware or event type doesn't support branch stack sampling.",
3800 					 evsel__name(evsel));
3801 		if (evsel->core.attr.aux_output)
3802 			return scnprintf(msg, size,
3803 	"%s: PMU Hardware doesn't support 'aux_output' feature",
3804 					 evsel__name(evsel));
3805 		if (evsel->core.attr.aux_action)
3806 			return scnprintf(msg, size,
3807 	"%s: PMU Hardware doesn't support 'aux_action' feature",
3808 					evsel__name(evsel));
3809 		if (evsel->core.attr.sample_period != 0)
3810 			return scnprintf(msg, size,
3811 	"%s: PMU Hardware doesn't support sampling/overflow-interrupts. Try 'perf stat'",
3812 					 evsel__name(evsel));
3813 		if (evsel->core.attr.precise_ip)
3814 			return scnprintf(msg, size, "%s",
3815 	"\'precise\' request may not be supported. Try removing 'p' modifier.");
3816 #if defined(__i386__) || defined(__x86_64__)
3817 		if (evsel->core.attr.type == PERF_TYPE_HARDWARE)
3818 			return scnprintf(msg, size, "%s",
3819 	"No hardware sampling interrupt available.\n");
3820 #endif
3821 		if (!target__has_cpu(target))
3822 			return scnprintf(msg, size,
3823 	"Unsupported event (%s) in per-thread mode, enable system wide with '-a'.",
3824 					evsel__name(evsel));
3825 		break;
3826 	case EBUSY:
3827 		if (find_process("oprofiled"))
3828 			return scnprintf(msg, size,
3829 	"The PMU counters are busy/taken by another profiler.\n"
3830 	"We found oprofile daemon running, please stop it and try again.");
3831 		printed += scnprintf(
3832 			msg, size,
3833 			"The PMU %s counters are busy and in use by another process.\n",
3834 			evsel->pmu ? evsel->pmu->name : "");
3835 		return printed + dump_perf_event_processes(msg + printed, size - printed);
3836 		break;
3837 	case EINVAL:
3838 		if (evsel->core.attr.sample_type & PERF_SAMPLE_CODE_PAGE_SIZE && perf_missing_features.code_page_size)
3839 			return scnprintf(msg, size, "Asking for the code page size isn't supported by this kernel.");
3840 		if (evsel->core.attr.sample_type & PERF_SAMPLE_DATA_PAGE_SIZE && perf_missing_features.data_page_size)
3841 			return scnprintf(msg, size, "Asking for the data page size isn't supported by this kernel.");
3842 		if (evsel->core.attr.write_backward && perf_missing_features.write_backward)
3843 			return scnprintf(msg, size, "Reading from overwrite event is not supported by this kernel.");
3844 		if (perf_missing_features.clockid)
3845 			return scnprintf(msg, size, "clockid feature not supported.");
3846 		if (perf_missing_features.clockid_wrong)
3847 			return scnprintf(msg, size, "wrong clockid (%d).", clockid);
3848 		if (perf_missing_features.aux_action)
3849 			return scnprintf(msg, size, "The 'aux_action' feature is not supported, update the kernel.");
3850 		if (perf_missing_features.aux_output)
3851 			return scnprintf(msg, size, "The 'aux_output' feature is not supported, update the kernel.");
3852 		if (!target__has_cpu(target))
3853 			return scnprintf(msg, size,
3854 	"Invalid event (%s) in per-thread mode, enable system wide with '-a'.",
3855 					evsel__name(evsel));
3856 
3857 		break;
3858 	case ENODATA:
3859 		return scnprintf(msg, size, "Cannot collect data source with the load latency event alone. "
3860 				 "Please add an auxiliary event in front of the load latency event.");
3861 	default:
3862 		break;
3863 	}
3864 
3865 	ret = arch_evsel__open_strerror(evsel, msg, size);
3866 	if (ret)
3867 		return ret;
3868 
3869 	return scnprintf(msg, size,
3870 	"The sys_perf_event_open() syscall returned with %d (%s) for event (%s).\n"
3871 	"\"dmesg | grep -i perf\" may provide additional information.\n",
3872 			 err, str_error_r(err, sbuf, sizeof(sbuf)), evsel__name(evsel));
3873 }
3874 
3875 struct perf_env *evsel__env(struct evsel *evsel)
3876 {
3877 	if (evsel && evsel->evlist && evsel->evlist->env)
3878 		return evsel->evlist->env;
3879 	return &perf_env;
3880 }
3881 
3882 static int store_evsel_ids(struct evsel *evsel, struct evlist *evlist)
3883 {
3884 	int cpu_map_idx, thread;
3885 
3886 	if (evsel__is_retire_lat(evsel))
3887 		return 0;
3888 
3889 	for (cpu_map_idx = 0; cpu_map_idx < xyarray__max_x(evsel->core.fd); cpu_map_idx++) {
3890 		for (thread = 0; thread < xyarray__max_y(evsel->core.fd);
3891 		     thread++) {
3892 			int fd = FD(evsel, cpu_map_idx, thread);
3893 
3894 			if (perf_evlist__id_add_fd(&evlist->core, &evsel->core,
3895 						   cpu_map_idx, thread, fd) < 0)
3896 				return -1;
3897 		}
3898 	}
3899 
3900 	return 0;
3901 }
3902 
3903 int evsel__store_ids(struct evsel *evsel, struct evlist *evlist)
3904 {
3905 	struct perf_cpu_map *cpus = evsel->core.cpus;
3906 	struct perf_thread_map *threads = evsel->core.threads;
3907 
3908 	if (perf_evsel__alloc_id(&evsel->core, perf_cpu_map__nr(cpus), threads->nr))
3909 		return -ENOMEM;
3910 
3911 	return store_evsel_ids(evsel, evlist);
3912 }
3913 
3914 void evsel__zero_per_pkg(struct evsel *evsel)
3915 {
3916 	struct hashmap_entry *cur;
3917 	size_t bkt;
3918 
3919 	if (evsel->per_pkg_mask) {
3920 		hashmap__for_each_entry(evsel->per_pkg_mask, cur, bkt)
3921 			zfree(&cur->pkey);
3922 
3923 		hashmap__clear(evsel->per_pkg_mask);
3924 	}
3925 }
3926 
3927 /**
3928  * evsel__is_hybrid - does the evsel have a known PMU that is hybrid. Note, this
3929  *                    will be false on hybrid systems for hardware and legacy
3930  *                    cache events.
3931  */
3932 bool evsel__is_hybrid(const struct evsel *evsel)
3933 {
3934 	if (!evsel->core.is_pmu_core)
3935 		return false;
3936 
3937 	return perf_pmus__num_core_pmus() > 1;
3938 }
3939 
3940 struct evsel *evsel__leader(const struct evsel *evsel)
3941 {
3942 	return container_of(evsel->core.leader, struct evsel, core);
3943 }
3944 
3945 bool evsel__has_leader(struct evsel *evsel, struct evsel *leader)
3946 {
3947 	return evsel->core.leader == &leader->core;
3948 }
3949 
3950 bool evsel__is_leader(struct evsel *evsel)
3951 {
3952 	return evsel__has_leader(evsel, evsel);
3953 }
3954 
3955 void evsel__set_leader(struct evsel *evsel, struct evsel *leader)
3956 {
3957 	evsel->core.leader = &leader->core;
3958 }
3959 
3960 int evsel__source_count(const struct evsel *evsel)
3961 {
3962 	struct evsel *pos;
3963 	int count = 0;
3964 
3965 	evlist__for_each_entry(evsel->evlist, pos) {
3966 		if (pos->metric_leader == evsel)
3967 			count++;
3968 	}
3969 	return count;
3970 }
3971 
3972 bool __weak arch_evsel__must_be_in_group(const struct evsel *evsel __maybe_unused)
3973 {
3974 	return false;
3975 }
3976 
3977 /*
3978  * Remove an event from a given group (leader).
3979  * Some events, e.g., perf metrics Topdown events,
3980  * must always be grouped. Ignore the events.
3981  */
3982 void evsel__remove_from_group(struct evsel *evsel, struct evsel *leader)
3983 {
3984 	if (!arch_evsel__must_be_in_group(evsel) && evsel != leader) {
3985 		evsel__set_leader(evsel, evsel);
3986 		evsel->core.nr_members = 0;
3987 		leader->core.nr_members--;
3988 	}
3989 }
3990 
3991 bool evsel__set_needs_uniquify(struct evsel *counter, const struct perf_stat_config *config)
3992 {
3993 	struct evsel *evsel;
3994 
3995 	if (counter->needs_uniquify) {
3996 		/* Already set. */
3997 		return true;
3998 	}
3999 
4000 	if (counter->use_config_name || counter->is_libpfm_event) {
4001 		/* Original name will be used. */
4002 		return false;
4003 	}
4004 
4005 	if (!config->hybrid_merge && evsel__is_hybrid(counter)) {
4006 		/* Unique hybrid counters necessary. */
4007 		counter->needs_uniquify = true;
4008 		return true;
4009 	}
4010 
4011 	if  (counter->core.attr.type < PERF_TYPE_MAX && counter->core.attr.type != PERF_TYPE_RAW) {
4012 		/* Legacy event, don't uniquify. */
4013 		return false;
4014 	}
4015 
4016 	if (counter->pmu && counter->pmu->is_core &&
4017 	    counter->alternate_hw_config != PERF_COUNT_HW_MAX) {
4018 		/* A sysfs or json event replacing a legacy event, don't uniquify. */
4019 		return false;
4020 	}
4021 
4022 	if (config->aggr_mode == AGGR_NONE) {
4023 		/* Always unique with no aggregation. */
4024 		counter->needs_uniquify = true;
4025 		return true;
4026 	}
4027 
4028 	if (counter->first_wildcard_match != NULL) {
4029 		/*
4030 		 * If stats are merged then only the first_wildcard_match is
4031 		 * displayed, there is no need to uniquify this evsel as the
4032 		 * name won't be shown.
4033 		 */
4034 		return false;
4035 	}
4036 
4037 	/*
4038 	 * Do other non-merged events in the evlist have the same name? If so
4039 	 * uniquify is necessary.
4040 	 */
4041 	evlist__for_each_entry(counter->evlist, evsel) {
4042 		if (evsel == counter || evsel->first_wildcard_match || evsel->pmu == counter->pmu)
4043 			continue;
4044 
4045 		if (evsel__name_is(counter, evsel__name(evsel))) {
4046 			counter->needs_uniquify = true;
4047 			return true;
4048 		}
4049 	}
4050 	return false;
4051 }
4052 
4053 void evsel__uniquify_counter(struct evsel *counter)
4054 {
4055 	const char *name, *pmu_name;
4056 	char *new_name, *config;
4057 	int ret;
4058 
4059 	/* No uniquification necessary. */
4060 	if (!counter->needs_uniquify)
4061 		return;
4062 
4063 	/* The evsel was already uniquified. */
4064 	if (counter->uniquified_name)
4065 		return;
4066 
4067 	/* Avoid checking to uniquify twice. */
4068 	counter->uniquified_name = true;
4069 
4070 	name = evsel__name(counter);
4071 	pmu_name = counter->pmu->name;
4072 	/* Already prefixed by the PMU name. */
4073 	if (!strncmp(name, pmu_name, strlen(pmu_name)))
4074 		return;
4075 
4076 	config = strchr(name, '/');
4077 	if (config) {
4078 		int len = config - name;
4079 
4080 		if (config[1] == '/') {
4081 			/* case: event// */
4082 			ret = asprintf(&new_name, "%s/%.*s/%s", pmu_name, len, name, config + 2);
4083 		} else {
4084 			/* case: event/.../ */
4085 			ret = asprintf(&new_name, "%s/%.*s,%s", pmu_name, len, name, config + 1);
4086 		}
4087 	} else {
4088 		config = strchr(name, ':');
4089 		if (config) {
4090 			/* case: event:.. */
4091 			int len = config - name;
4092 
4093 			ret = asprintf(&new_name, "%s/%.*s/%s", pmu_name, len, name, config + 1);
4094 		} else {
4095 			/* case: event */
4096 			ret = asprintf(&new_name, "%s/%s/", pmu_name, name);
4097 		}
4098 	}
4099 	if (ret > 0) {
4100 		free(counter->name);
4101 		counter->name = new_name;
4102 	} else {
4103 		/* ENOMEM from asprintf. */
4104 		counter->uniquified_name = false;
4105 	}
4106 }
4107 
4108 void evsel__warn_user_requested_cpus(struct evsel *evsel, struct perf_cpu_map *user_requested_cpus)
4109 {
4110 	struct perf_cpu_map *intersect, *online = NULL;
4111 	const struct perf_pmu *pmu = evsel__find_pmu(evsel);
4112 
4113 	if (pmu && pmu->is_core) {
4114 		intersect = perf_cpu_map__intersect(pmu->cpus, user_requested_cpus);
4115 	} else {
4116 		online = cpu_map__online();
4117 		intersect = perf_cpu_map__intersect(online, user_requested_cpus);
4118 	}
4119 	if (!perf_cpu_map__equal(intersect, user_requested_cpus)) {
4120 		char buf1[128];
4121 		char buf2[128];
4122 
4123 		cpu_map__snprint(user_requested_cpus, buf1, sizeof(buf1));
4124 		cpu_map__snprint(online ?: pmu->cpus, buf2, sizeof(buf2));
4125 		pr_warning("WARNING: A requested CPU in '%s' is not supported by PMU '%s' (CPUs %s) for event '%s'\n",
4126 			   buf1, pmu ? pmu->name : "cpu", buf2, evsel__name(evsel));
4127 	}
4128 	perf_cpu_map__put(intersect);
4129 	perf_cpu_map__put(online);
4130 }
4131