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