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