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