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