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