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