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