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