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