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