1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3 * builtin-stat.c
4 *
5 * Builtin stat command: Give a precise performance counters summary
6 * overview about any workload, CPU or specific PID.
7 *
8 * Sample output:
9
10 $ perf stat ./hackbench 10
11
12 Time: 0.118
13
14 Performance counter stats for './hackbench 10':
15
16 1708.761321 task-clock # 11.037 CPUs utilized
17 41,190 context-switches # 0.024 M/sec
18 6,735 CPU-migrations # 0.004 M/sec
19 17,318 page-faults # 0.010 M/sec
20 5,205,202,243 cycles # 3.046 GHz
21 3,856,436,920 stalled-cycles-frontend # 74.09% frontend cycles idle
22 1,600,790,871 stalled-cycles-backend # 30.75% backend cycles idle
23 2,603,501,247 instructions # 0.50 insns per cycle
24 # 1.48 stalled cycles per insn
25 484,357,498 branches # 283.455 M/sec
26 6,388,934 branch-misses # 1.32% of all branches
27
28 0.154822978 seconds time elapsed
29
30 *
31 * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com>
32 *
33 * Improvements and fixes by:
34 *
35 * Arjan van de Ven <arjan@linux.intel.com>
36 * Yanmin Zhang <yanmin.zhang@intel.com>
37 * Wu Fengguang <fengguang.wu@intel.com>
38 * Mike Galbraith <efault@gmx.de>
39 * Paul Mackerras <paulus@samba.org>
40 * Jaswinder Singh Rajput <jaswinder@kernel.org>
41 */
42
43 #include "builtin.h"
44 #include "util/cgroup.h"
45 #include <subcmd/parse-options.h>
46 #include "util/parse-events.h"
47 #include "util/pmus.h"
48 #include "util/pmu.h"
49 #include "util/tool_pmu.h"
50 #include "util/event.h"
51 #include "util/evlist.h"
52 #include "util/evsel.h"
53 #include "util/debug.h"
54 #include "util/color.h"
55 #include "util/stat.h"
56 #include "util/header.h"
57 #include "util/cpumap.h"
58 #include "util/thread_map.h"
59 #include "util/counts.h"
60 #include "util/topdown.h"
61 #include "util/session.h"
62 #include "util/tool.h"
63 #include "util/string2.h"
64 #include "util/metricgroup.h"
65 #include "util/synthetic-events.h"
66 #include "util/target.h"
67 #include "util/time-utils.h"
68 #include "util/top.h"
69 #include "util/affinity.h"
70 #include "util/pfm.h"
71 #include "util/bpf_counter.h"
72 #include "util/iostat.h"
73 #include "util/util.h"
74 #include "util/intel-tpebs.h"
75 #include "asm/bug.h"
76
77 #include <linux/list_sort.h>
78 #include <linux/time64.h>
79 #include <linux/zalloc.h>
80 #include <api/fs/fs.h>
81 #include <errno.h>
82 #include <signal.h>
83 #include <stdlib.h>
84 #include <sys/prctl.h>
85 #include <inttypes.h>
86 #include <locale.h>
87 #include <math.h>
88 #include <sys/types.h>
89 #include <sys/stat.h>
90 #include <sys/wait.h>
91 #include <unistd.h>
92 #include <sys/time.h>
93 #include <sys/resource.h>
94 #include <linux/err.h>
95
96 #include <linux/ctype.h>
97 #include <perf/evlist.h>
98 #include <internal/threadmap.h>
99
100 #ifdef HAVE_BPF_SKEL
101 #include "util/bpf_skel/bperf_cgroup.h"
102 #endif
103
104 #define DEFAULT_SEPARATOR " "
105 #define FREEZE_ON_SMI_PATH "bus/event_source/devices/cpu/freeze_on_smi"
106
107 struct rusage_stats {
108 struct stats ru_utime_usec_stat;
109 struct stats ru_stime_usec_stat;
110 };
111
112 static void print_counters(struct timespec *ts, int argc, const char **argv);
113
114 static struct evlist *evsel_list;
115 static struct parse_events_option_args parse_events_option_args = {
116 .evlistp = &evsel_list,
117 };
118
119 static bool all_counters_use_bpf = true;
120
121 static struct target target;
122
123 static volatile sig_atomic_t child_pid = -1;
124 static int detailed_run = 0;
125 static bool transaction_run;
126 static bool topdown_run = false;
127 static bool smi_cost = false;
128 static bool smi_reset = false;
129 static int big_num_opt = -1;
130 static const char *pre_cmd = NULL;
131 static const char *post_cmd = NULL;
132 static bool sync_run = false;
133 static bool forever = false;
134 static bool force_metric_only = false;
135 static struct timespec ref_time;
136 static bool append_file;
137 static bool interval_count;
138 static const char *output_name;
139 static int output_fd;
140 static char *metrics;
141 static struct rusage_stats ru_stats;
142
143 struct perf_stat {
144 bool record;
145 struct perf_data data;
146 struct perf_session *session;
147 u64 bytes_written;
148 struct perf_tool tool;
149 bool maps_allocated;
150 struct perf_cpu_map *cpus;
151 struct perf_thread_map *threads;
152 enum aggr_mode aggr_mode;
153 u32 aggr_level;
154 };
155
156 static struct perf_stat perf_stat;
157 #define STAT_RECORD perf_stat.record
158
159 static volatile sig_atomic_t done = 0;
160
161 /* Options set from the command line. */
162 struct opt_aggr_mode {
163 bool node, socket, die, cluster, cache, core, thread, no_aggr;
164 };
165
166 /* Turn command line option into most generic aggregation mode setting. */
opt_aggr_mode_to_aggr_mode(struct opt_aggr_mode * opt_mode)167 static enum aggr_mode opt_aggr_mode_to_aggr_mode(struct opt_aggr_mode *opt_mode)
168 {
169 enum aggr_mode mode = AGGR_GLOBAL;
170
171 if (opt_mode->node)
172 mode = AGGR_NODE;
173 if (opt_mode->socket)
174 mode = AGGR_SOCKET;
175 if (opt_mode->die)
176 mode = AGGR_DIE;
177 if (opt_mode->cluster)
178 mode = AGGR_CLUSTER;
179 if (opt_mode->cache)
180 mode = AGGR_CACHE;
181 if (opt_mode->core)
182 mode = AGGR_CORE;
183 if (opt_mode->thread)
184 mode = AGGR_THREAD;
185 if (opt_mode->no_aggr)
186 mode = AGGR_NONE;
187 return mode;
188 }
189
evlist__check_cpu_maps(struct evlist * evlist)190 static void evlist__check_cpu_maps(struct evlist *evlist)
191 {
192 struct evsel *evsel, *warned_leader = NULL;
193
194 evlist__for_each_entry(evlist, evsel) {
195 struct evsel *leader = evsel__leader(evsel);
196
197 /* Check that leader matches cpus with each member. */
198 if (leader == evsel)
199 continue;
200 if (perf_cpu_map__equal(leader->core.cpus, evsel->core.cpus))
201 continue;
202
203 /* If there's mismatch disable the group and warn user. */
204 if (warned_leader != leader) {
205 char buf[200];
206
207 pr_warning("WARNING: grouped events cpus do not match.\n"
208 "Events with CPUs not matching the leader will "
209 "be removed from the group.\n");
210 evsel__group_desc(leader, buf, sizeof(buf));
211 pr_warning(" %s\n", buf);
212 warned_leader = leader;
213 }
214 if (verbose > 0) {
215 char buf[200];
216
217 cpu_map__snprint(leader->core.cpus, buf, sizeof(buf));
218 pr_warning(" %s: %s\n", leader->name, buf);
219 cpu_map__snprint(evsel->core.cpus, buf, sizeof(buf));
220 pr_warning(" %s: %s\n", evsel->name, buf);
221 }
222
223 evsel__remove_from_group(evsel, leader);
224 }
225 }
226
diff_timespec(struct timespec * r,struct timespec * a,struct timespec * b)227 static inline void diff_timespec(struct timespec *r, struct timespec *a,
228 struct timespec *b)
229 {
230 r->tv_sec = a->tv_sec - b->tv_sec;
231 if (a->tv_nsec < b->tv_nsec) {
232 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec;
233 r->tv_sec--;
234 } else {
235 r->tv_nsec = a->tv_nsec - b->tv_nsec ;
236 }
237 }
238
perf_stat__reset_stats(void)239 static void perf_stat__reset_stats(void)
240 {
241 evlist__reset_stats(evsel_list);
242 memset(stat_config.walltime_nsecs_stats, 0, sizeof(*stat_config.walltime_nsecs_stats));
243 }
244
process_synthesized_event(const struct perf_tool * tool __maybe_unused,union perf_event * event,struct perf_sample * sample __maybe_unused,struct machine * machine __maybe_unused)245 static int process_synthesized_event(const struct perf_tool *tool __maybe_unused,
246 union perf_event *event,
247 struct perf_sample *sample __maybe_unused,
248 struct machine *machine __maybe_unused)
249 {
250 if (perf_data__write(&perf_stat.data, event, event->header.size) < 0) {
251 pr_err("failed to write perf data, error: %m\n");
252 return -1;
253 }
254
255 perf_stat.bytes_written += event->header.size;
256 return 0;
257 }
258
write_stat_round_event(u64 tm,u64 type)259 static int write_stat_round_event(u64 tm, u64 type)
260 {
261 return perf_event__synthesize_stat_round(NULL, tm, type,
262 process_synthesized_event,
263 NULL);
264 }
265
266 #define WRITE_STAT_ROUND_EVENT(time, interval) \
267 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval)
268
269 #define SID(e, x, y) xyarray__entry(e->core.sample_id, x, y)
270
evsel__write_stat_event(struct evsel * counter,int cpu_map_idx,u32 thread,struct perf_counts_values * count)271 static int evsel__write_stat_event(struct evsel *counter, int cpu_map_idx, u32 thread,
272 struct perf_counts_values *count)
273 {
274 struct perf_sample_id *sid = SID(counter, cpu_map_idx, thread);
275 struct perf_cpu cpu = perf_cpu_map__cpu(evsel__cpus(counter), cpu_map_idx);
276
277 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count,
278 process_synthesized_event, NULL);
279 }
280
read_single_counter(struct evsel * counter,int cpu_map_idx,int thread)281 static int read_single_counter(struct evsel *counter, int cpu_map_idx, int thread)
282 {
283 int err = evsel__read_counter(counter, cpu_map_idx, thread);
284
285 /*
286 * Reading user and system time will fail when the process
287 * terminates. Use the wait4 values in that case.
288 */
289 if (err && cpu_map_idx == 0 &&
290 (evsel__tool_event(counter) == TOOL_PMU__EVENT_USER_TIME ||
291 evsel__tool_event(counter) == TOOL_PMU__EVENT_SYSTEM_TIME)) {
292 struct perf_counts_values *count =
293 perf_counts(counter->counts, cpu_map_idx, thread);
294 struct perf_counts_values *old_count = NULL;
295 u64 val;
296
297 if (counter->prev_raw_counts)
298 old_count = perf_counts(counter->prev_raw_counts, cpu_map_idx, thread);
299
300 if (evsel__tool_event(counter) == TOOL_PMU__EVENT_USER_TIME)
301 val = ru_stats.ru_utime_usec_stat.mean;
302 else
303 val = ru_stats.ru_stime_usec_stat.mean;
304
305 count->val = val;
306 if (old_count) {
307 count->run = old_count->run + 1;
308 count->ena = old_count->ena + 1;
309 } else {
310 count->run++;
311 count->ena++;
312 }
313 return 0;
314 }
315 return err;
316 }
317
318 /*
319 * Read out the results of a single counter:
320 * do not aggregate counts across CPUs in system-wide mode
321 */
read_counter_cpu(struct evsel * counter,int cpu_map_idx)322 static int read_counter_cpu(struct evsel *counter, int cpu_map_idx)
323 {
324 int nthreads = perf_thread_map__nr(evsel_list->core.threads);
325 int thread;
326
327 if (!counter->supported)
328 return -ENOENT;
329
330 for (thread = 0; thread < nthreads; thread++) {
331 struct perf_counts_values *count;
332
333 count = perf_counts(counter->counts, cpu_map_idx, thread);
334
335 /*
336 * The leader's group read loads data into its group members
337 * (via evsel__read_counter()) and sets their count->loaded.
338 */
339 if (!perf_counts__is_loaded(counter->counts, cpu_map_idx, thread) &&
340 read_single_counter(counter, cpu_map_idx, thread)) {
341 counter->counts->scaled = -1;
342 perf_counts(counter->counts, cpu_map_idx, thread)->ena = 0;
343 perf_counts(counter->counts, cpu_map_idx, thread)->run = 0;
344 return -1;
345 }
346
347 perf_counts__set_loaded(counter->counts, cpu_map_idx, thread, false);
348
349 if (STAT_RECORD) {
350 if (evsel__write_stat_event(counter, cpu_map_idx, thread, count)) {
351 pr_err("failed to write stat event\n");
352 return -1;
353 }
354 }
355
356 if (verbose > 1) {
357 fprintf(stat_config.output,
358 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
359 evsel__name(counter),
360 perf_cpu_map__cpu(evsel__cpus(counter),
361 cpu_map_idx).cpu,
362 count->val, count->ena, count->run);
363 }
364 }
365
366 return 0;
367 }
368
read_counters_with_affinity(void)369 static int read_counters_with_affinity(void)
370 {
371 struct evlist_cpu_iterator evlist_cpu_itr;
372
373 if (all_counters_use_bpf)
374 return 0;
375
376 evlist__for_each_cpu(evlist_cpu_itr, evsel_list) {
377 struct evsel *counter = evlist_cpu_itr.evsel;
378
379 if (evsel__is_bpf(counter))
380 continue;
381
382 if (evsel__is_tool(counter))
383 continue;
384
385 if (!counter->err)
386 counter->err = read_counter_cpu(counter, evlist_cpu_itr.cpu_map_idx);
387 }
388
389 return 0;
390 }
391
read_bpf_map_counters(void)392 static int read_bpf_map_counters(void)
393 {
394 struct evsel *counter;
395 int err;
396
397 evlist__for_each_entry(evsel_list, counter) {
398 if (!evsel__is_bpf(counter))
399 continue;
400
401 err = bpf_counter__read(counter);
402 if (err)
403 return err;
404 }
405 return 0;
406 }
407
read_tool_counters(void)408 static int read_tool_counters(void)
409 {
410 struct evsel *counter;
411
412 evlist__for_each_entry(evsel_list, counter) {
413 int idx;
414
415 if (!evsel__is_tool(counter))
416 continue;
417
418 perf_cpu_map__for_each_idx(idx, counter->core.cpus) {
419 if (!counter->err)
420 counter->err = read_counter_cpu(counter, idx);
421 }
422 }
423 return 0;
424 }
425
read_counters(void)426 static int read_counters(void)
427 {
428 int ret;
429
430 if (stat_config.stop_read_counter)
431 return 0;
432
433 // Read all BPF counters first.
434 ret = read_bpf_map_counters();
435 if (ret)
436 return ret;
437
438 // Read non-BPF and non-tool counters next.
439 ret = read_counters_with_affinity();
440 if (ret)
441 return ret;
442
443 // Read the tool counters last. This way the duration_time counter
444 // should always be greater than any other counter's enabled time.
445 return read_tool_counters();
446 }
447
process_counters(void)448 static void process_counters(void)
449 {
450 struct evsel *counter;
451
452 evlist__for_each_entry(evsel_list, counter) {
453 if (counter->err)
454 pr_debug("failed to read counter %s\n", counter->name);
455 if (counter->err == 0 && perf_stat_process_counter(&stat_config, counter))
456 pr_warning("failed to process counter %s\n", counter->name);
457 counter->err = 0;
458 }
459
460 perf_stat_merge_counters(&stat_config, evsel_list);
461 perf_stat_process_percore(&stat_config, evsel_list);
462 }
463
process_interval(void)464 static void process_interval(void)
465 {
466 struct timespec ts, rs;
467
468 clock_gettime(CLOCK_MONOTONIC, &ts);
469 diff_timespec(&rs, &ts, &ref_time);
470
471 evlist__reset_aggr_stats(evsel_list);
472
473 if (read_counters() == 0)
474 process_counters();
475
476 if (STAT_RECORD) {
477 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL))
478 pr_err("failed to write stat round event\n");
479 }
480
481 init_stats(stat_config.walltime_nsecs_stats);
482 update_stats(stat_config.walltime_nsecs_stats, stat_config.interval * 1000000ULL);
483 print_counters(&rs, 0, NULL);
484 }
485
handle_interval(unsigned int interval,int * times)486 static bool handle_interval(unsigned int interval, int *times)
487 {
488 if (interval) {
489 process_interval();
490 if (interval_count && !(--(*times)))
491 return true;
492 }
493 return false;
494 }
495
enable_counters(void)496 static int enable_counters(void)
497 {
498 struct evsel *evsel;
499 int err;
500
501 evlist__for_each_entry(evsel_list, evsel) {
502 if (!evsel__is_bpf(evsel))
503 continue;
504
505 err = bpf_counter__enable(evsel);
506 if (err)
507 return err;
508 }
509
510 if (!target__enable_on_exec(&target)) {
511 if (!all_counters_use_bpf)
512 evlist__enable(evsel_list);
513 }
514 return 0;
515 }
516
disable_counters(void)517 static void disable_counters(void)
518 {
519 struct evsel *counter;
520
521 /*
522 * If we don't have tracee (attaching to task or cpu), counters may
523 * still be running. To get accurate group ratios, we must stop groups
524 * from counting before reading their constituent counters.
525 */
526 if (!target__none(&target)) {
527 evlist__for_each_entry(evsel_list, counter)
528 bpf_counter__disable(counter);
529 if (!all_counters_use_bpf)
530 evlist__disable(evsel_list);
531 }
532 }
533
534 static volatile sig_atomic_t workload_exec_errno;
535
536 /*
537 * evlist__prepare_workload will send a SIGUSR1
538 * if the fork fails, since we asked by setting its
539 * want_signal to true.
540 */
workload_exec_failed_signal(int signo __maybe_unused,siginfo_t * info,void * ucontext __maybe_unused)541 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info,
542 void *ucontext __maybe_unused)
543 {
544 workload_exec_errno = info->si_value.sival_int;
545 }
546
evsel__should_store_id(struct evsel * counter)547 static bool evsel__should_store_id(struct evsel *counter)
548 {
549 return STAT_RECORD || counter->core.attr.read_format & PERF_FORMAT_ID;
550 }
551
is_target_alive(struct target * _target,struct perf_thread_map * threads)552 static bool is_target_alive(struct target *_target,
553 struct perf_thread_map *threads)
554 {
555 struct stat st;
556 int i;
557
558 if (!target__has_task(_target))
559 return true;
560
561 for (i = 0; i < threads->nr; i++) {
562 char path[PATH_MAX];
563
564 scnprintf(path, PATH_MAX, "%s/%d", procfs__mountpoint(),
565 threads->map[i].pid);
566
567 if (!stat(path, &st))
568 return true;
569 }
570
571 return false;
572 }
573
process_evlist(struct evlist * evlist,unsigned int interval)574 static void process_evlist(struct evlist *evlist, unsigned int interval)
575 {
576 enum evlist_ctl_cmd cmd = EVLIST_CTL_CMD_UNSUPPORTED;
577
578 if (evlist__ctlfd_process(evlist, &cmd) > 0) {
579 switch (cmd) {
580 case EVLIST_CTL_CMD_ENABLE:
581 fallthrough;
582 case EVLIST_CTL_CMD_DISABLE:
583 if (interval)
584 process_interval();
585 break;
586 case EVLIST_CTL_CMD_SNAPSHOT:
587 case EVLIST_CTL_CMD_ACK:
588 case EVLIST_CTL_CMD_UNSUPPORTED:
589 case EVLIST_CTL_CMD_EVLIST:
590 case EVLIST_CTL_CMD_STOP:
591 case EVLIST_CTL_CMD_PING:
592 default:
593 break;
594 }
595 }
596 }
597
compute_tts(struct timespec * time_start,struct timespec * time_stop,int * time_to_sleep)598 static void compute_tts(struct timespec *time_start, struct timespec *time_stop,
599 int *time_to_sleep)
600 {
601 int tts = *time_to_sleep;
602 struct timespec time_diff;
603
604 diff_timespec(&time_diff, time_stop, time_start);
605
606 tts -= time_diff.tv_sec * MSEC_PER_SEC +
607 time_diff.tv_nsec / NSEC_PER_MSEC;
608
609 if (tts < 0)
610 tts = 0;
611
612 *time_to_sleep = tts;
613 }
614
dispatch_events(bool forks,int timeout,int interval,int * times)615 static int dispatch_events(bool forks, int timeout, int interval, int *times)
616 {
617 int child_exited = 0, status = 0;
618 int time_to_sleep, sleep_time;
619 struct timespec time_start, time_stop;
620
621 if (interval)
622 sleep_time = interval;
623 else if (timeout)
624 sleep_time = timeout;
625 else
626 sleep_time = 1000;
627
628 time_to_sleep = sleep_time;
629
630 while (!done) {
631 if (forks)
632 child_exited = waitpid(child_pid, &status, WNOHANG);
633 else
634 child_exited = !is_target_alive(&target, evsel_list->core.threads) ? 1 : 0;
635
636 if (child_exited)
637 break;
638
639 clock_gettime(CLOCK_MONOTONIC, &time_start);
640 if (!(evlist__poll(evsel_list, time_to_sleep) > 0)) { /* poll timeout or EINTR */
641 if (timeout || handle_interval(interval, times))
642 break;
643 time_to_sleep = sleep_time;
644 } else { /* fd revent */
645 process_evlist(evsel_list, interval);
646 clock_gettime(CLOCK_MONOTONIC, &time_stop);
647 compute_tts(&time_start, &time_stop, &time_to_sleep);
648 }
649 }
650
651 return status;
652 }
653
654 enum counter_recovery {
655 COUNTER_SKIP,
656 COUNTER_RETRY,
657 };
658
stat_handle_error(struct evsel * counter,int err)659 static enum counter_recovery stat_handle_error(struct evsel *counter, int err)
660 {
661 char msg[BUFSIZ];
662
663 assert(!counter->supported);
664
665 /*
666 * PPC returns ENXIO for HW counters until 2.6.37
667 * (behavior changed with commit b0a873e).
668 */
669 if (err == EINVAL || err == ENOSYS || err == ENOENT || err == ENXIO) {
670 if (verbose > 0) {
671 evsel__open_strerror(counter, &target, err, msg, sizeof(msg));
672 ui__warning("%s event is not supported by the kernel.\n%s\n",
673 evsel__name(counter), msg);
674 }
675 return COUNTER_SKIP;
676 }
677 if (evsel__fallback(counter, &target, err, msg, sizeof(msg))) {
678 if (verbose > 0)
679 ui__warning("%s\n", msg);
680 counter->supported = true;
681 return COUNTER_RETRY;
682 }
683 if (target__has_per_thread(&target) && err != EOPNOTSUPP &&
684 evsel_list->core.threads && evsel_list->core.threads->err_thread != -1) {
685 /*
686 * For global --per-thread case, skip current
687 * error thread.
688 */
689 if (!thread_map__remove(evsel_list->core.threads,
690 evsel_list->core.threads->err_thread)) {
691 evsel_list->core.threads->err_thread = -1;
692 counter->supported = true;
693 return COUNTER_RETRY;
694 }
695 }
696 if (verbose > 0) {
697 evsel__open_strerror(counter, &target, err, msg, sizeof(msg));
698 ui__warning(err == EOPNOTSUPP
699 ? "%s event is not supported by the kernel.\n%s\n"
700 : "skipping event %s that kernel failed to open.\n%s\n",
701 evsel__name(counter), msg);
702 }
703 return COUNTER_SKIP;
704 }
705
create_perf_stat_counter(struct evsel * evsel,struct perf_stat_config * config,int cpu_map_idx)706 static int create_perf_stat_counter(struct evsel *evsel,
707 struct perf_stat_config *config,
708 int cpu_map_idx)
709 {
710 struct perf_event_attr *attr = &evsel->core.attr;
711 struct evsel *leader = evsel__leader(evsel);
712
713 /* Reset supported flag as creating a stat counter is retried. */
714 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED |
715 PERF_FORMAT_TOTAL_TIME_RUNNING;
716
717 /*
718 * The event is part of non trivial group, let's enable
719 * the group read (for leader) and ID retrieval for all
720 * members.
721 */
722 if (leader->core.nr_members > 1)
723 attr->read_format |= PERF_FORMAT_ID|PERF_FORMAT_GROUP;
724
725 attr->inherit = !config->no_inherit && list_empty(&evsel->bpf_counter_list);
726
727 /*
728 * Some events get initialized with sample_(period/type) set,
729 * like tracepoints. Clear it up for counting.
730 */
731 attr->sample_period = 0;
732
733 if (config->identifier)
734 attr->sample_type = PERF_SAMPLE_IDENTIFIER;
735
736 if (config->all_user) {
737 attr->exclude_kernel = 1;
738 attr->exclude_user = 0;
739 }
740
741 if (config->all_kernel) {
742 attr->exclude_kernel = 0;
743 attr->exclude_user = 1;
744 }
745
746 /*
747 * Disabling all counters initially, they will be enabled
748 * either manually by us or by kernel via enable_on_exec
749 * set later.
750 */
751 if (evsel__is_group_leader(evsel)) {
752 attr->disabled = 1;
753
754 if (target__enable_on_exec(&target))
755 attr->enable_on_exec = 1;
756 }
757
758 return evsel__open_per_cpu_and_thread(evsel, evsel__cpus(evsel), cpu_map_idx,
759 evsel->core.threads);
760 }
761
update_rusage_stats(const struct rusage * rusage)762 static void update_rusage_stats(const struct rusage *rusage)
763 {
764 const u64 us_to_ns = 1000;
765 const u64 s_to_ns = 1000000000;
766
767 update_stats(&ru_stats.ru_utime_usec_stat,
768 (rusage->ru_utime.tv_usec * us_to_ns + rusage->ru_utime.tv_sec * s_to_ns));
769 update_stats(&ru_stats.ru_stime_usec_stat,
770 (rusage->ru_stime.tv_usec * us_to_ns + rusage->ru_stime.tv_sec * s_to_ns));
771 }
772
__run_perf_stat(int argc,const char ** argv,int run_idx)773 static int __run_perf_stat(int argc, const char **argv, int run_idx)
774 {
775 int interval = stat_config.interval;
776 int times = stat_config.times;
777 int timeout = stat_config.timeout;
778 char msg[BUFSIZ];
779 unsigned long long t0, t1;
780 struct evsel *counter;
781 size_t l;
782 int status = 0;
783 const bool forks = (argc > 0);
784 bool is_pipe = STAT_RECORD ? perf_stat.data.is_pipe : false;
785 struct evlist_cpu_iterator evlist_cpu_itr;
786 int err, open_err = 0;
787 bool second_pass = false, has_supported_counters;
788
789 if (forks) {
790 if (evlist__prepare_workload(evsel_list, &target, argv, is_pipe, workload_exec_failed_signal) < 0) {
791 perror("failed to prepare workload");
792 return -1;
793 }
794 child_pid = evsel_list->workload.pid;
795 }
796
797 evlist__for_each_entry(evsel_list, counter) {
798 counter->reset_group = false;
799 if (bpf_counter__load(counter, &target)) {
800 err = -1;
801 goto err_out;
802 }
803 if (!(evsel__is_bperf(counter)))
804 all_counters_use_bpf = false;
805 }
806
807 evlist__reset_aggr_stats(evsel_list);
808
809 /*
810 * bperf calls evsel__open_per_cpu() in bperf__load(), so
811 * no need to call it again here.
812 */
813 if (!target.use_bpf) {
814 evlist__for_each_cpu(evlist_cpu_itr, evsel_list) {
815 counter = evlist_cpu_itr.evsel;
816
817 if (counter->reset_group || !counter->supported)
818 continue;
819 if (evsel__is_bperf(counter))
820 continue;
821
822 while (true) {
823 if (create_perf_stat_counter(counter, &stat_config,
824 evlist_cpu_itr.cpu_map_idx) == 0)
825 break;
826
827 open_err = errno;
828 /*
829 * Weak group failed. We cannot just undo this
830 * here because earlier CPUs might be in group
831 * mode, and the kernel doesn't support mixing
832 * group and non group reads. Defer it to later.
833 * Don't close here because we're in the wrong
834 * affinity.
835 */
836 if ((open_err == EINVAL || open_err == EBADF) &&
837 evsel__leader(counter) != counter &&
838 counter->weak_group) {
839 evlist__reset_weak_group(evsel_list, counter, false);
840 assert(counter->reset_group);
841 counter->supported = true;
842 second_pass = true;
843 break;
844 }
845
846 if (stat_handle_error(counter, open_err) != COUNTER_RETRY)
847 break;
848 }
849 }
850 }
851 if (second_pass) {
852 /*
853 * Now redo all the weak group after closing them,
854 * and also close errored counters.
855 */
856
857 /* First close errored or weak retry */
858 evlist__for_each_cpu(evlist_cpu_itr, evsel_list) {
859 counter = evlist_cpu_itr.evsel;
860
861 if (!counter->reset_group && counter->supported)
862 continue;
863
864 perf_evsel__close_cpu(&counter->core, evlist_cpu_itr.cpu_map_idx);
865 }
866 /* Now reopen weak */
867 evlist__for_each_cpu(evlist_cpu_itr, evsel_list) {
868 counter = evlist_cpu_itr.evsel;
869
870 if (!counter->reset_group)
871 continue;
872
873 while (true) {
874 pr_debug2("reopening weak %s\n", evsel__name(counter));
875 if (create_perf_stat_counter(counter, &stat_config,
876 evlist_cpu_itr.cpu_map_idx) == 0) {
877 evlist_cpu_iterator__exit(&evlist_cpu_itr);
878 break;
879 }
880 open_err = errno;
881 if (stat_handle_error(counter, open_err) != COUNTER_RETRY) {
882 evlist_cpu_iterator__exit(&evlist_cpu_itr);
883 break;
884 }
885 }
886 }
887 }
888
889 has_supported_counters = false;
890 evlist__for_each_entry(evsel_list, counter) {
891 if (!counter->supported) {
892 perf_evsel__free_fd(&counter->core);
893 continue;
894 }
895 has_supported_counters = true;
896
897 l = strlen(counter->unit);
898 if (l > stat_config.unit_width)
899 stat_config.unit_width = l;
900
901 if (evsel__should_store_id(counter) &&
902 evsel__store_ids(counter, evsel_list)) {
903 err = -1;
904 goto err_out;
905 }
906 }
907 if (!has_supported_counters && !stat_config.null_run) {
908 if (open_err) {
909 evsel__open_strerror(evlist__first(evsel_list), &target, open_err,
910 msg, sizeof(msg));
911 }
912 ui__error("No supported events found.\n%s\n", msg);
913
914 if (child_pid != -1)
915 kill(child_pid, SIGTERM);
916 err = -1;
917 goto err_out;
918 }
919
920 if (evlist__apply_filters(evsel_list, &counter, &target)) {
921 pr_err("failed to set filter \"%s\" on event %s: %m\n",
922 counter->filter, evsel__name(counter));
923 return -1;
924 }
925
926 if (STAT_RECORD) {
927 int fd = perf_data__fd(&perf_stat.data);
928
929 if (is_pipe) {
930 err = perf_header__write_pipe(perf_data__fd(&perf_stat.data));
931 } else {
932 err = perf_session__write_header(perf_stat.session, evsel_list,
933 fd, false);
934 }
935
936 if (err < 0)
937 goto err_out;
938
939 err = perf_event__synthesize_stat_events(&stat_config, NULL, evsel_list,
940 process_synthesized_event, is_pipe);
941 if (err < 0)
942 goto err_out;
943
944 }
945
946 if (target.initial_delay) {
947 pr_info(EVLIST_DISABLED_MSG);
948 } else {
949 err = enable_counters();
950 if (err) {
951 err = -1;
952 goto err_out;
953 }
954 }
955
956 /* Exec the command, if any */
957 if (forks)
958 evlist__start_workload(evsel_list);
959
960 if (target.initial_delay > 0) {
961 usleep(target.initial_delay * USEC_PER_MSEC);
962 err = enable_counters();
963 if (err) {
964 err = -1;
965 goto err_out;
966 }
967
968 pr_info(EVLIST_ENABLED_MSG);
969 }
970
971 t0 = rdclock();
972 clock_gettime(CLOCK_MONOTONIC, &ref_time);
973
974 if (forks) {
975 if (interval || timeout || evlist__ctlfd_initialized(evsel_list))
976 status = dispatch_events(forks, timeout, interval, ×);
977 if (child_pid != -1) {
978 if (timeout)
979 kill(child_pid, SIGTERM);
980 wait4(child_pid, &status, 0, &stat_config.ru_data);
981 }
982
983 if (workload_exec_errno) {
984 errno = workload_exec_errno;
985 pr_err("Workload failed: %m\n");
986 err = -1;
987 goto err_out;
988 }
989
990 if (WIFSIGNALED(status)) {
991 /*
992 * We want to indicate failure to stop a repeat run,
993 * hence negative. We want the value to be the exit code
994 * of perf, which for termination by a signal is 128
995 * plus the signal number.
996 */
997 err = 0 - (128 + WTERMSIG(status));
998 psignal(WTERMSIG(status), argv[0]);
999 } else {
1000 err = WEXITSTATUS(status);
1001 }
1002 } else {
1003 err = dispatch_events(forks, timeout, interval, ×);
1004 }
1005
1006 disable_counters();
1007
1008 t1 = rdclock();
1009
1010 if (stat_config.walltime_run_table)
1011 stat_config.walltime_run[run_idx] = t1 - t0;
1012
1013 if (interval && stat_config.summary) {
1014 stat_config.interval = 0;
1015 stat_config.stop_read_counter = true;
1016 init_stats(stat_config.walltime_nsecs_stats);
1017 update_stats(stat_config.walltime_nsecs_stats, t1 - t0);
1018
1019 evlist__copy_prev_raw_counts(evsel_list);
1020 evlist__reset_prev_raw_counts(evsel_list);
1021 evlist__reset_aggr_stats(evsel_list);
1022 } else {
1023 update_stats(stat_config.walltime_nsecs_stats, t1 - t0);
1024 update_rusage_stats(&stat_config.ru_data);
1025 }
1026
1027 /*
1028 * Closing a group leader splits the group, and as we only disable
1029 * group leaders, results in remaining events becoming enabled. To
1030 * avoid arbitrary skew, we must read all counters before closing any
1031 * group leaders.
1032 */
1033 if (read_counters() == 0)
1034 process_counters();
1035
1036 /*
1037 * We need to keep evsel_list alive, because it's processed
1038 * later the evsel_list will be closed after.
1039 */
1040 if (!STAT_RECORD)
1041 evlist__close(evsel_list);
1042
1043 return err;
1044
1045 err_out:
1046 if (forks)
1047 evlist__cancel_workload(evsel_list);
1048
1049 return err;
1050 }
1051
1052 /*
1053 * Returns -1 for fatal errors which signifies to not continue
1054 * when in repeat mode.
1055 *
1056 * Returns < -1 error codes when stat record is used. These
1057 * result in the stat information being displayed, but writing
1058 * to the file fails and is non fatal.
1059 */
run_perf_stat(int argc,const char ** argv,int run_idx)1060 static int run_perf_stat(int argc, const char **argv, int run_idx)
1061 {
1062 int ret;
1063
1064 if (pre_cmd) {
1065 ret = system(pre_cmd);
1066 if (ret)
1067 return ret;
1068 }
1069
1070 if (sync_run)
1071 sync();
1072
1073 ret = __run_perf_stat(argc, argv, run_idx);
1074 if (ret)
1075 return ret;
1076
1077 if (post_cmd) {
1078 ret = system(post_cmd);
1079 if (ret)
1080 return ret;
1081 }
1082
1083 return ret;
1084 }
1085
print_counters(struct timespec * ts,int argc,const char ** argv)1086 static void print_counters(struct timespec *ts, int argc, const char **argv)
1087 {
1088 /* Do not print anything if we record to the pipe. */
1089 if (STAT_RECORD && perf_stat.data.is_pipe)
1090 return;
1091 if (quiet)
1092 return;
1093
1094 evlist__print_counters(evsel_list, &stat_config, &target, ts, argc, argv);
1095 }
1096
1097 static volatile sig_atomic_t signr = -1;
1098
skip_signal(int signo)1099 static void skip_signal(int signo)
1100 {
1101 if ((child_pid == -1) || stat_config.interval)
1102 done = 1;
1103
1104 signr = signo;
1105 /*
1106 * render child_pid harmless
1107 * won't send SIGTERM to a random
1108 * process in case of race condition
1109 * and fast PID recycling
1110 */
1111 child_pid = -1;
1112 }
1113
sig_atexit(void)1114 static void sig_atexit(void)
1115 {
1116 sigset_t set, oset;
1117
1118 /*
1119 * avoid race condition with SIGCHLD handler
1120 * in skip_signal() which is modifying child_pid
1121 * goal is to avoid send SIGTERM to a random
1122 * process
1123 */
1124 sigemptyset(&set);
1125 sigaddset(&set, SIGCHLD);
1126 sigprocmask(SIG_BLOCK, &set, &oset);
1127
1128 if (child_pid != -1)
1129 kill(child_pid, SIGTERM);
1130
1131 sigprocmask(SIG_SETMASK, &oset, NULL);
1132
1133 if (signr == -1)
1134 return;
1135
1136 signal(signr, SIG_DFL);
1137 kill(getpid(), signr);
1138 }
1139
stat__set_big_num(const struct option * opt __maybe_unused,const char * s __maybe_unused,int unset)1140 static int stat__set_big_num(const struct option *opt __maybe_unused,
1141 const char *s __maybe_unused, int unset)
1142 {
1143 big_num_opt = unset ? 0 : 1;
1144 perf_stat__set_big_num(!unset);
1145 return 0;
1146 }
1147
enable_metric_only(const struct option * opt __maybe_unused,const char * s __maybe_unused,int unset)1148 static int enable_metric_only(const struct option *opt __maybe_unused,
1149 const char *s __maybe_unused, int unset)
1150 {
1151 force_metric_only = true;
1152 stat_config.metric_only = !unset;
1153 return 0;
1154 }
1155
append_metric_groups(const struct option * opt __maybe_unused,const char * str,int unset __maybe_unused)1156 static int append_metric_groups(const struct option *opt __maybe_unused,
1157 const char *str,
1158 int unset __maybe_unused)
1159 {
1160 if (metrics) {
1161 char *tmp;
1162
1163 if (asprintf(&tmp, "%s,%s", metrics, str) < 0)
1164 return -ENOMEM;
1165 free(metrics);
1166 metrics = tmp;
1167 } else {
1168 metrics = strdup(str);
1169 if (!metrics)
1170 return -ENOMEM;
1171 }
1172 return 0;
1173 }
1174
parse_control_option(const struct option * opt,const char * str,int unset __maybe_unused)1175 static int parse_control_option(const struct option *opt,
1176 const char *str,
1177 int unset __maybe_unused)
1178 {
1179 struct perf_stat_config *config = opt->value;
1180
1181 return evlist__parse_control(str, &config->ctl_fd, &config->ctl_fd_ack, &config->ctl_fd_close);
1182 }
1183
parse_stat_cgroups(const struct option * opt,const char * str,int unset)1184 static int parse_stat_cgroups(const struct option *opt,
1185 const char *str, int unset)
1186 {
1187 if (stat_config.cgroup_list) {
1188 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
1189 return -1;
1190 }
1191
1192 return parse_cgroups(opt, str, unset);
1193 }
1194
parse_cputype(const struct option * opt,const char * str,int unset __maybe_unused)1195 static int parse_cputype(const struct option *opt,
1196 const char *str,
1197 int unset __maybe_unused)
1198 {
1199 const struct perf_pmu *pmu;
1200 struct evlist *evlist = *(struct evlist **)opt->value;
1201
1202 if (!list_empty(&evlist->core.entries)) {
1203 fprintf(stderr, "Must define cputype before events/metrics\n");
1204 return -1;
1205 }
1206
1207 pmu = perf_pmus__pmu_for_pmu_filter(str);
1208 if (!pmu) {
1209 fprintf(stderr, "--cputype %s is not supported!\n", str);
1210 return -1;
1211 }
1212 parse_events_option_args.pmu_filter = pmu->name;
1213
1214 return 0;
1215 }
1216
parse_cache_level(const struct option * opt,const char * str,int unset __maybe_unused)1217 static int parse_cache_level(const struct option *opt,
1218 const char *str,
1219 int unset __maybe_unused)
1220 {
1221 int level;
1222 struct opt_aggr_mode *opt_aggr_mode = (struct opt_aggr_mode *)opt->value;
1223 u32 *aggr_level = (u32 *)opt->data;
1224
1225 /*
1226 * If no string is specified, aggregate based on the topology of
1227 * Last Level Cache (LLC). Since the LLC level can change from
1228 * architecture to architecture, set level greater than
1229 * MAX_CACHE_LVL which will be interpreted as LLC.
1230 */
1231 if (str == NULL) {
1232 level = MAX_CACHE_LVL + 1;
1233 goto out;
1234 }
1235
1236 /*
1237 * The format to specify cache level is LX or lX where X is the
1238 * cache level.
1239 */
1240 if (strlen(str) != 2 || (str[0] != 'l' && str[0] != 'L')) {
1241 pr_err("Cache level must be of form L[1-%d], or l[1-%d]\n",
1242 MAX_CACHE_LVL,
1243 MAX_CACHE_LVL);
1244 return -EINVAL;
1245 }
1246
1247 level = atoi(&str[1]);
1248 if (level < 1) {
1249 pr_err("Cache level must be of form L[1-%d], or l[1-%d]\n",
1250 MAX_CACHE_LVL,
1251 MAX_CACHE_LVL);
1252 return -EINVAL;
1253 }
1254
1255 if (level > MAX_CACHE_LVL) {
1256 pr_err("perf only supports max cache level of %d.\n"
1257 "Consider increasing MAX_CACHE_LVL\n", MAX_CACHE_LVL);
1258 return -EINVAL;
1259 }
1260 out:
1261 opt_aggr_mode->cache = true;
1262 *aggr_level = level;
1263 return 0;
1264 }
1265
1266 /**
1267 * Calculate the cache instance ID from the map in
1268 * /sys/devices/system/cpu/cpuX/cache/indexY/shared_cpu_list
1269 * Cache instance ID is the first CPU reported in the shared_cpu_list file.
1270 */
cpu__get_cache_id_from_map(struct perf_cpu cpu,char * map)1271 static int cpu__get_cache_id_from_map(struct perf_cpu cpu, char *map)
1272 {
1273 int id;
1274 struct perf_cpu_map *cpu_map = perf_cpu_map__new(map);
1275
1276 /*
1277 * If the map contains no CPU, consider the current CPU to
1278 * be the first online CPU in the cache domain else use the
1279 * first online CPU of the cache domain as the ID.
1280 */
1281 id = perf_cpu_map__min(cpu_map).cpu;
1282 if (id == -1)
1283 id = cpu.cpu;
1284
1285 /* Free the perf_cpu_map used to find the cache ID */
1286 perf_cpu_map__put(cpu_map);
1287
1288 return id;
1289 }
1290
1291 /**
1292 * cpu__get_cache_id - Returns 0 if successful in populating the
1293 * cache level and cache id. Cache level is read from
1294 * /sys/devices/system/cpu/cpuX/cache/indexY/level where as cache instance ID
1295 * is the first CPU reported by
1296 * /sys/devices/system/cpu/cpuX/cache/indexY/shared_cpu_list
1297 */
cpu__get_cache_details(struct perf_cpu cpu,struct perf_cache * cache)1298 static int cpu__get_cache_details(struct perf_cpu cpu, struct perf_cache *cache)
1299 {
1300 int ret = 0;
1301 u32 cache_level = stat_config.aggr_level;
1302 struct cpu_cache_level caches[MAX_CACHE_LVL];
1303 u32 i = 0, caches_cnt = 0;
1304
1305 cache->cache_lvl = (cache_level > MAX_CACHE_LVL) ? 0 : cache_level;
1306 cache->cache = -1;
1307
1308 ret = build_caches_for_cpu(cpu.cpu, caches, &caches_cnt);
1309 if (ret) {
1310 /*
1311 * If caches_cnt is not 0, cpu_cache_level data
1312 * was allocated when building the topology.
1313 * Free the allocated data before returning.
1314 */
1315 if (caches_cnt)
1316 goto free_caches;
1317
1318 return ret;
1319 }
1320
1321 if (!caches_cnt)
1322 return -1;
1323
1324 /*
1325 * Save the data for the highest level if no
1326 * level was specified by the user.
1327 */
1328 if (cache_level > MAX_CACHE_LVL) {
1329 int max_level_index = 0;
1330
1331 for (i = 1; i < caches_cnt; ++i) {
1332 if (caches[i].level > caches[max_level_index].level)
1333 max_level_index = i;
1334 }
1335
1336 cache->cache_lvl = caches[max_level_index].level;
1337 cache->cache = cpu__get_cache_id_from_map(cpu, caches[max_level_index].map);
1338
1339 /* Reset i to 0 to free entire caches[] */
1340 i = 0;
1341 goto free_caches;
1342 }
1343
1344 for (i = 0; i < caches_cnt; ++i) {
1345 if (caches[i].level == cache_level) {
1346 cache->cache_lvl = cache_level;
1347 cache->cache = cpu__get_cache_id_from_map(cpu, caches[i].map);
1348 }
1349
1350 cpu_cache_level__free(&caches[i]);
1351 }
1352
1353 free_caches:
1354 /*
1355 * Free all the allocated cpu_cache_level data.
1356 */
1357 while (i < caches_cnt)
1358 cpu_cache_level__free(&caches[i++]);
1359
1360 return ret;
1361 }
1362
1363 /**
1364 * aggr_cpu_id__cache - Create an aggr_cpu_id with cache instache ID, cache
1365 * level, die and socket populated with the cache instache ID, cache level,
1366 * die and socket for cpu. The function signature is compatible with
1367 * aggr_cpu_id_get_t.
1368 */
aggr_cpu_id__cache(struct perf_cpu cpu,void * data)1369 static struct aggr_cpu_id aggr_cpu_id__cache(struct perf_cpu cpu, void *data)
1370 {
1371 int ret;
1372 struct aggr_cpu_id id;
1373 struct perf_cache cache;
1374
1375 id = aggr_cpu_id__die(cpu, data);
1376 if (aggr_cpu_id__is_empty(&id))
1377 return id;
1378
1379 ret = cpu__get_cache_details(cpu, &cache);
1380 if (ret)
1381 return id;
1382
1383 id.cache_lvl = cache.cache_lvl;
1384 id.cache = cache.cache;
1385 return id;
1386 }
1387
1388 static const char *const aggr_mode__string[] = {
1389 [AGGR_CORE] = "core",
1390 [AGGR_CACHE] = "cache",
1391 [AGGR_CLUSTER] = "cluster",
1392 [AGGR_DIE] = "die",
1393 [AGGR_GLOBAL] = "global",
1394 [AGGR_NODE] = "node",
1395 [AGGR_NONE] = "none",
1396 [AGGR_SOCKET] = "socket",
1397 [AGGR_THREAD] = "thread",
1398 [AGGR_UNSET] = "unset",
1399 };
1400
perf_stat__get_socket(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1401 static struct aggr_cpu_id perf_stat__get_socket(struct perf_stat_config *config __maybe_unused,
1402 struct perf_cpu cpu)
1403 {
1404 return aggr_cpu_id__socket(cpu, /*data=*/NULL);
1405 }
1406
perf_stat__get_die(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1407 static struct aggr_cpu_id perf_stat__get_die(struct perf_stat_config *config __maybe_unused,
1408 struct perf_cpu cpu)
1409 {
1410 return aggr_cpu_id__die(cpu, /*data=*/NULL);
1411 }
1412
perf_stat__get_cache_id(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1413 static struct aggr_cpu_id perf_stat__get_cache_id(struct perf_stat_config *config __maybe_unused,
1414 struct perf_cpu cpu)
1415 {
1416 return aggr_cpu_id__cache(cpu, /*data=*/NULL);
1417 }
1418
perf_stat__get_cluster(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1419 static struct aggr_cpu_id perf_stat__get_cluster(struct perf_stat_config *config __maybe_unused,
1420 struct perf_cpu cpu)
1421 {
1422 return aggr_cpu_id__cluster(cpu, /*data=*/NULL);
1423 }
1424
perf_stat__get_core(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1425 static struct aggr_cpu_id perf_stat__get_core(struct perf_stat_config *config __maybe_unused,
1426 struct perf_cpu cpu)
1427 {
1428 return aggr_cpu_id__core(cpu, /*data=*/NULL);
1429 }
1430
perf_stat__get_node(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1431 static struct aggr_cpu_id perf_stat__get_node(struct perf_stat_config *config __maybe_unused,
1432 struct perf_cpu cpu)
1433 {
1434 return aggr_cpu_id__node(cpu, /*data=*/NULL);
1435 }
1436
perf_stat__get_global(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1437 static struct aggr_cpu_id perf_stat__get_global(struct perf_stat_config *config __maybe_unused,
1438 struct perf_cpu cpu)
1439 {
1440 return aggr_cpu_id__global(cpu, /*data=*/NULL);
1441 }
1442
perf_stat__get_cpu(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1443 static struct aggr_cpu_id perf_stat__get_cpu(struct perf_stat_config *config __maybe_unused,
1444 struct perf_cpu cpu)
1445 {
1446 return aggr_cpu_id__cpu(cpu, /*data=*/NULL);
1447 }
1448
perf_stat__get_aggr(struct perf_stat_config * config,aggr_get_id_t get_id,struct perf_cpu cpu)1449 static struct aggr_cpu_id perf_stat__get_aggr(struct perf_stat_config *config,
1450 aggr_get_id_t get_id, struct perf_cpu cpu)
1451 {
1452 struct aggr_cpu_id id;
1453
1454 /* per-process mode - should use global aggr mode */
1455 if (cpu.cpu == -1 || cpu.cpu >= config->cpus_aggr_map->nr)
1456 return get_id(config, cpu);
1457
1458 if (aggr_cpu_id__is_empty(&config->cpus_aggr_map->map[cpu.cpu]))
1459 config->cpus_aggr_map->map[cpu.cpu] = get_id(config, cpu);
1460
1461 id = config->cpus_aggr_map->map[cpu.cpu];
1462 return id;
1463 }
1464
perf_stat__get_socket_cached(struct perf_stat_config * config,struct perf_cpu cpu)1465 static struct aggr_cpu_id perf_stat__get_socket_cached(struct perf_stat_config *config,
1466 struct perf_cpu cpu)
1467 {
1468 return perf_stat__get_aggr(config, perf_stat__get_socket, cpu);
1469 }
1470
perf_stat__get_die_cached(struct perf_stat_config * config,struct perf_cpu cpu)1471 static struct aggr_cpu_id perf_stat__get_die_cached(struct perf_stat_config *config,
1472 struct perf_cpu cpu)
1473 {
1474 return perf_stat__get_aggr(config, perf_stat__get_die, cpu);
1475 }
1476
perf_stat__get_cluster_cached(struct perf_stat_config * config,struct perf_cpu cpu)1477 static struct aggr_cpu_id perf_stat__get_cluster_cached(struct perf_stat_config *config,
1478 struct perf_cpu cpu)
1479 {
1480 return perf_stat__get_aggr(config, perf_stat__get_cluster, cpu);
1481 }
1482
perf_stat__get_cache_id_cached(struct perf_stat_config * config,struct perf_cpu cpu)1483 static struct aggr_cpu_id perf_stat__get_cache_id_cached(struct perf_stat_config *config,
1484 struct perf_cpu cpu)
1485 {
1486 return perf_stat__get_aggr(config, perf_stat__get_cache_id, cpu);
1487 }
1488
perf_stat__get_core_cached(struct perf_stat_config * config,struct perf_cpu cpu)1489 static struct aggr_cpu_id perf_stat__get_core_cached(struct perf_stat_config *config,
1490 struct perf_cpu cpu)
1491 {
1492 return perf_stat__get_aggr(config, perf_stat__get_core, cpu);
1493 }
1494
perf_stat__get_node_cached(struct perf_stat_config * config,struct perf_cpu cpu)1495 static struct aggr_cpu_id perf_stat__get_node_cached(struct perf_stat_config *config,
1496 struct perf_cpu cpu)
1497 {
1498 return perf_stat__get_aggr(config, perf_stat__get_node, cpu);
1499 }
1500
perf_stat__get_global_cached(struct perf_stat_config * config,struct perf_cpu cpu)1501 static struct aggr_cpu_id perf_stat__get_global_cached(struct perf_stat_config *config,
1502 struct perf_cpu cpu)
1503 {
1504 return perf_stat__get_aggr(config, perf_stat__get_global, cpu);
1505 }
1506
perf_stat__get_cpu_cached(struct perf_stat_config * config,struct perf_cpu cpu)1507 static struct aggr_cpu_id perf_stat__get_cpu_cached(struct perf_stat_config *config,
1508 struct perf_cpu cpu)
1509 {
1510 return perf_stat__get_aggr(config, perf_stat__get_cpu, cpu);
1511 }
1512
aggr_mode__get_aggr(enum aggr_mode aggr_mode)1513 static aggr_cpu_id_get_t aggr_mode__get_aggr(enum aggr_mode aggr_mode)
1514 {
1515 switch (aggr_mode) {
1516 case AGGR_SOCKET:
1517 return aggr_cpu_id__socket;
1518 case AGGR_DIE:
1519 return aggr_cpu_id__die;
1520 case AGGR_CLUSTER:
1521 return aggr_cpu_id__cluster;
1522 case AGGR_CACHE:
1523 return aggr_cpu_id__cache;
1524 case AGGR_CORE:
1525 return aggr_cpu_id__core;
1526 case AGGR_NODE:
1527 return aggr_cpu_id__node;
1528 case AGGR_NONE:
1529 return aggr_cpu_id__cpu;
1530 case AGGR_GLOBAL:
1531 return aggr_cpu_id__global;
1532 case AGGR_THREAD:
1533 case AGGR_UNSET:
1534 case AGGR_MAX:
1535 default:
1536 return NULL;
1537 }
1538 }
1539
aggr_mode__get_id(enum aggr_mode aggr_mode)1540 static aggr_get_id_t aggr_mode__get_id(enum aggr_mode aggr_mode)
1541 {
1542 switch (aggr_mode) {
1543 case AGGR_SOCKET:
1544 return perf_stat__get_socket_cached;
1545 case AGGR_DIE:
1546 return perf_stat__get_die_cached;
1547 case AGGR_CLUSTER:
1548 return perf_stat__get_cluster_cached;
1549 case AGGR_CACHE:
1550 return perf_stat__get_cache_id_cached;
1551 case AGGR_CORE:
1552 return perf_stat__get_core_cached;
1553 case AGGR_NODE:
1554 return perf_stat__get_node_cached;
1555 case AGGR_NONE:
1556 return perf_stat__get_cpu_cached;
1557 case AGGR_GLOBAL:
1558 return perf_stat__get_global_cached;
1559 case AGGR_THREAD:
1560 case AGGR_UNSET:
1561 case AGGR_MAX:
1562 default:
1563 return NULL;
1564 }
1565 }
1566
perf_stat_init_aggr_mode(void)1567 static int perf_stat_init_aggr_mode(void)
1568 {
1569 int nr;
1570 aggr_cpu_id_get_t get_id = aggr_mode__get_aggr(stat_config.aggr_mode);
1571
1572 if (get_id) {
1573 bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1574 stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1575 get_id, /*data=*/NULL, needs_sort);
1576 if (!stat_config.aggr_map) {
1577 pr_err("cannot build %s map\n", aggr_mode__string[stat_config.aggr_mode]);
1578 return -1;
1579 }
1580 stat_config.aggr_get_id = aggr_mode__get_id(stat_config.aggr_mode);
1581 }
1582
1583 if (stat_config.aggr_mode == AGGR_THREAD) {
1584 nr = perf_thread_map__nr(evsel_list->core.threads);
1585 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1586 if (stat_config.aggr_map == NULL)
1587 return -ENOMEM;
1588
1589 for (int s = 0; s < nr; s++) {
1590 struct aggr_cpu_id id = aggr_cpu_id__empty();
1591
1592 id.thread_idx = s;
1593 stat_config.aggr_map->map[s] = id;
1594 }
1595 return 0;
1596 }
1597
1598 /*
1599 * The evsel_list->cpus is the base we operate on,
1600 * taking the highest cpu number to be the size of
1601 * the aggregation translate cpumap.
1602 */
1603 nr = perf_cpu_map__max(evsel_list->core.all_cpus).cpu + 1;
1604 stat_config.cpus_aggr_map = cpu_aggr_map__empty_new(nr);
1605 return stat_config.cpus_aggr_map ? 0 : -ENOMEM;
1606 }
1607
cpu_aggr_map__delete(struct cpu_aggr_map * map)1608 static void cpu_aggr_map__delete(struct cpu_aggr_map *map)
1609 {
1610 free(map);
1611 }
1612
perf_stat__exit_aggr_mode(void)1613 static void perf_stat__exit_aggr_mode(void)
1614 {
1615 cpu_aggr_map__delete(stat_config.aggr_map);
1616 cpu_aggr_map__delete(stat_config.cpus_aggr_map);
1617 stat_config.aggr_map = NULL;
1618 stat_config.cpus_aggr_map = NULL;
1619 }
1620
perf_env__get_socket_aggr_by_cpu(struct perf_cpu cpu,void * data)1621 static struct aggr_cpu_id perf_env__get_socket_aggr_by_cpu(struct perf_cpu cpu, void *data)
1622 {
1623 struct perf_env *env = data;
1624 struct aggr_cpu_id id = aggr_cpu_id__empty();
1625
1626 if (cpu.cpu != -1)
1627 id.socket = env->cpu[cpu.cpu].socket_id;
1628
1629 return id;
1630 }
1631
perf_env__get_die_aggr_by_cpu(struct perf_cpu cpu,void * data)1632 static struct aggr_cpu_id perf_env__get_die_aggr_by_cpu(struct perf_cpu cpu, void *data)
1633 {
1634 struct perf_env *env = data;
1635 struct aggr_cpu_id id = aggr_cpu_id__empty();
1636
1637 if (cpu.cpu != -1) {
1638 /*
1639 * die_id is relative to socket, so start
1640 * with the socket ID and then add die to
1641 * make a unique ID.
1642 */
1643 id.socket = env->cpu[cpu.cpu].socket_id;
1644 id.die = env->cpu[cpu.cpu].die_id;
1645 }
1646
1647 return id;
1648 }
1649
perf_env__get_cache_id_for_cpu(struct perf_cpu cpu,struct perf_env * env,u32 cache_level,struct aggr_cpu_id * id)1650 static void perf_env__get_cache_id_for_cpu(struct perf_cpu cpu, struct perf_env *env,
1651 u32 cache_level, struct aggr_cpu_id *id)
1652 {
1653 int i;
1654 int caches_cnt = env->caches_cnt;
1655 struct cpu_cache_level *caches = env->caches;
1656
1657 id->cache_lvl = (cache_level > MAX_CACHE_LVL) ? 0 : cache_level;
1658 id->cache = -1;
1659
1660 if (!caches_cnt)
1661 return;
1662
1663 for (i = caches_cnt - 1; i > -1; --i) {
1664 struct perf_cpu_map *cpu_map;
1665 int map_contains_cpu;
1666
1667 /*
1668 * If user has not specified a level, find the fist level with
1669 * the cpu in the map. Since building the map is expensive, do
1670 * this only if levels match.
1671 */
1672 if (cache_level <= MAX_CACHE_LVL && caches[i].level != cache_level)
1673 continue;
1674
1675 cpu_map = perf_cpu_map__new(caches[i].map);
1676 map_contains_cpu = perf_cpu_map__idx(cpu_map, cpu);
1677 perf_cpu_map__put(cpu_map);
1678
1679 if (map_contains_cpu != -1) {
1680 id->cache_lvl = caches[i].level;
1681 id->cache = cpu__get_cache_id_from_map(cpu, caches[i].map);
1682 return;
1683 }
1684 }
1685 }
1686
perf_env__get_cache_aggr_by_cpu(struct perf_cpu cpu,void * data)1687 static struct aggr_cpu_id perf_env__get_cache_aggr_by_cpu(struct perf_cpu cpu,
1688 void *data)
1689 {
1690 struct perf_env *env = data;
1691 struct aggr_cpu_id id = aggr_cpu_id__empty();
1692
1693 if (cpu.cpu != -1) {
1694 u32 cache_level = (perf_stat.aggr_level) ?: stat_config.aggr_level;
1695
1696 id.socket = env->cpu[cpu.cpu].socket_id;
1697 id.die = env->cpu[cpu.cpu].die_id;
1698 perf_env__get_cache_id_for_cpu(cpu, env, cache_level, &id);
1699 }
1700
1701 return id;
1702 }
1703
perf_env__get_cluster_aggr_by_cpu(struct perf_cpu cpu,void * data)1704 static struct aggr_cpu_id perf_env__get_cluster_aggr_by_cpu(struct perf_cpu cpu,
1705 void *data)
1706 {
1707 struct perf_env *env = data;
1708 struct aggr_cpu_id id = aggr_cpu_id__empty();
1709
1710 if (cpu.cpu != -1) {
1711 id.socket = env->cpu[cpu.cpu].socket_id;
1712 id.die = env->cpu[cpu.cpu].die_id;
1713 id.cluster = env->cpu[cpu.cpu].cluster_id;
1714 }
1715
1716 return id;
1717 }
1718
perf_env__get_core_aggr_by_cpu(struct perf_cpu cpu,void * data)1719 static struct aggr_cpu_id perf_env__get_core_aggr_by_cpu(struct perf_cpu cpu, void *data)
1720 {
1721 struct perf_env *env = data;
1722 struct aggr_cpu_id id = aggr_cpu_id__empty();
1723
1724 if (cpu.cpu != -1) {
1725 /*
1726 * core_id is relative to socket, die and cluster, we need a
1727 * global id. So we set socket, die id, cluster id and core id.
1728 */
1729 id.socket = env->cpu[cpu.cpu].socket_id;
1730 id.die = env->cpu[cpu.cpu].die_id;
1731 id.cluster = env->cpu[cpu.cpu].cluster_id;
1732 id.core = env->cpu[cpu.cpu].core_id;
1733 }
1734
1735 return id;
1736 }
1737
perf_env__get_cpu_aggr_by_cpu(struct perf_cpu cpu,void * data)1738 static struct aggr_cpu_id perf_env__get_cpu_aggr_by_cpu(struct perf_cpu cpu, void *data)
1739 {
1740 struct perf_env *env = data;
1741 struct aggr_cpu_id id = aggr_cpu_id__empty();
1742
1743 if (cpu.cpu != -1) {
1744 /*
1745 * core_id is relative to socket and die,
1746 * we need a global id. So we set
1747 * socket, die id and core id
1748 */
1749 id.socket = env->cpu[cpu.cpu].socket_id;
1750 id.die = env->cpu[cpu.cpu].die_id;
1751 id.core = env->cpu[cpu.cpu].core_id;
1752 id.cpu = cpu;
1753 }
1754
1755 return id;
1756 }
1757
perf_env__get_node_aggr_by_cpu(struct perf_cpu cpu,void * data)1758 static struct aggr_cpu_id perf_env__get_node_aggr_by_cpu(struct perf_cpu cpu, void *data)
1759 {
1760 struct aggr_cpu_id id = aggr_cpu_id__empty();
1761
1762 id.node = perf_env__numa_node(data, cpu);
1763 return id;
1764 }
1765
perf_env__get_global_aggr_by_cpu(struct perf_cpu cpu __maybe_unused,void * data __maybe_unused)1766 static struct aggr_cpu_id perf_env__get_global_aggr_by_cpu(struct perf_cpu cpu __maybe_unused,
1767 void *data __maybe_unused)
1768 {
1769 struct aggr_cpu_id id = aggr_cpu_id__empty();
1770
1771 /* it always aggregates to the cpu 0 */
1772 id.cpu = (struct perf_cpu){ .cpu = 0 };
1773 return id;
1774 }
1775
perf_stat__get_socket_file(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1776 static struct aggr_cpu_id perf_stat__get_socket_file(struct perf_stat_config *config __maybe_unused,
1777 struct perf_cpu cpu)
1778 {
1779 return perf_env__get_socket_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1780 }
perf_stat__get_die_file(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1781 static struct aggr_cpu_id perf_stat__get_die_file(struct perf_stat_config *config __maybe_unused,
1782 struct perf_cpu cpu)
1783 {
1784 return perf_env__get_die_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1785 }
1786
perf_stat__get_cluster_file(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1787 static struct aggr_cpu_id perf_stat__get_cluster_file(struct perf_stat_config *config __maybe_unused,
1788 struct perf_cpu cpu)
1789 {
1790 return perf_env__get_cluster_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1791 }
1792
perf_stat__get_cache_file(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1793 static struct aggr_cpu_id perf_stat__get_cache_file(struct perf_stat_config *config __maybe_unused,
1794 struct perf_cpu cpu)
1795 {
1796 return perf_env__get_cache_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1797 }
1798
perf_stat__get_core_file(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1799 static struct aggr_cpu_id perf_stat__get_core_file(struct perf_stat_config *config __maybe_unused,
1800 struct perf_cpu cpu)
1801 {
1802 return perf_env__get_core_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1803 }
1804
perf_stat__get_cpu_file(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1805 static struct aggr_cpu_id perf_stat__get_cpu_file(struct perf_stat_config *config __maybe_unused,
1806 struct perf_cpu cpu)
1807 {
1808 return perf_env__get_cpu_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1809 }
1810
perf_stat__get_node_file(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1811 static struct aggr_cpu_id perf_stat__get_node_file(struct perf_stat_config *config __maybe_unused,
1812 struct perf_cpu cpu)
1813 {
1814 return perf_env__get_node_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1815 }
1816
perf_stat__get_global_file(struct perf_stat_config * config __maybe_unused,struct perf_cpu cpu)1817 static struct aggr_cpu_id perf_stat__get_global_file(struct perf_stat_config *config __maybe_unused,
1818 struct perf_cpu cpu)
1819 {
1820 return perf_env__get_global_aggr_by_cpu(cpu, perf_session__env(perf_stat.session));
1821 }
1822
aggr_mode__get_aggr_file(enum aggr_mode aggr_mode)1823 static aggr_cpu_id_get_t aggr_mode__get_aggr_file(enum aggr_mode aggr_mode)
1824 {
1825 switch (aggr_mode) {
1826 case AGGR_SOCKET:
1827 return perf_env__get_socket_aggr_by_cpu;
1828 case AGGR_DIE:
1829 return perf_env__get_die_aggr_by_cpu;
1830 case AGGR_CLUSTER:
1831 return perf_env__get_cluster_aggr_by_cpu;
1832 case AGGR_CACHE:
1833 return perf_env__get_cache_aggr_by_cpu;
1834 case AGGR_CORE:
1835 return perf_env__get_core_aggr_by_cpu;
1836 case AGGR_NODE:
1837 return perf_env__get_node_aggr_by_cpu;
1838 case AGGR_GLOBAL:
1839 return perf_env__get_global_aggr_by_cpu;
1840 case AGGR_NONE:
1841 return perf_env__get_cpu_aggr_by_cpu;
1842 case AGGR_THREAD:
1843 case AGGR_UNSET:
1844 case AGGR_MAX:
1845 default:
1846 return NULL;
1847 }
1848 }
1849
aggr_mode__get_id_file(enum aggr_mode aggr_mode)1850 static aggr_get_id_t aggr_mode__get_id_file(enum aggr_mode aggr_mode)
1851 {
1852 switch (aggr_mode) {
1853 case AGGR_SOCKET:
1854 return perf_stat__get_socket_file;
1855 case AGGR_DIE:
1856 return perf_stat__get_die_file;
1857 case AGGR_CLUSTER:
1858 return perf_stat__get_cluster_file;
1859 case AGGR_CACHE:
1860 return perf_stat__get_cache_file;
1861 case AGGR_CORE:
1862 return perf_stat__get_core_file;
1863 case AGGR_NODE:
1864 return perf_stat__get_node_file;
1865 case AGGR_GLOBAL:
1866 return perf_stat__get_global_file;
1867 case AGGR_NONE:
1868 return perf_stat__get_cpu_file;
1869 case AGGR_THREAD:
1870 case AGGR_UNSET:
1871 case AGGR_MAX:
1872 default:
1873 return NULL;
1874 }
1875 }
1876
perf_stat_init_aggr_mode_file(struct perf_stat * st)1877 static int perf_stat_init_aggr_mode_file(struct perf_stat *st)
1878 {
1879 struct perf_env *env = perf_session__env(st->session);
1880 aggr_cpu_id_get_t get_id = aggr_mode__get_aggr_file(stat_config.aggr_mode);
1881 bool needs_sort = stat_config.aggr_mode != AGGR_NONE;
1882
1883 if (stat_config.aggr_mode == AGGR_THREAD) {
1884 int nr = perf_thread_map__nr(evsel_list->core.threads);
1885
1886 stat_config.aggr_map = cpu_aggr_map__empty_new(nr);
1887 if (stat_config.aggr_map == NULL)
1888 return -ENOMEM;
1889
1890 for (int s = 0; s < nr; s++) {
1891 struct aggr_cpu_id id = aggr_cpu_id__empty();
1892
1893 id.thread_idx = s;
1894 stat_config.aggr_map->map[s] = id;
1895 }
1896 return 0;
1897 }
1898
1899 if (!get_id)
1900 return 0;
1901
1902 stat_config.aggr_map = cpu_aggr_map__new(evsel_list->core.user_requested_cpus,
1903 get_id, env, needs_sort);
1904 if (!stat_config.aggr_map) {
1905 pr_err("cannot build %s map\n", aggr_mode__string[stat_config.aggr_mode]);
1906 return -1;
1907 }
1908 stat_config.aggr_get_id = aggr_mode__get_id_file(stat_config.aggr_mode);
1909 return 0;
1910 }
1911
default_evlist_evsel_cmp(void * priv __maybe_unused,const struct list_head * l,const struct list_head * r)1912 static int default_evlist_evsel_cmp(void *priv __maybe_unused,
1913 const struct list_head *l,
1914 const struct list_head *r)
1915 {
1916 const struct perf_evsel *lhs_core = container_of(l, struct perf_evsel, node);
1917 const struct evsel *lhs = container_of(lhs_core, struct evsel, core);
1918 const struct perf_evsel *rhs_core = container_of(r, struct perf_evsel, node);
1919 const struct evsel *rhs = container_of(rhs_core, struct evsel, core);
1920
1921 if (evsel__leader(lhs) == evsel__leader(rhs)) {
1922 /* Within the same group, respect the original order. */
1923 return lhs_core->idx - rhs_core->idx;
1924 }
1925
1926 /* Sort default metrics evsels first, and default show events before those. */
1927 if (lhs->default_metricgroup != rhs->default_metricgroup)
1928 return lhs->default_metricgroup ? -1 : 1;
1929
1930 if (lhs->default_show_events != rhs->default_show_events)
1931 return lhs->default_show_events ? -1 : 1;
1932
1933 /* Sort by PMU type (prefers legacy types first). */
1934 if (lhs->pmu != rhs->pmu)
1935 return lhs->pmu->type - rhs->pmu->type;
1936
1937 /* Sort by name. */
1938 return strcmp(evsel__name((struct evsel *)lhs), evsel__name((struct evsel *)rhs));
1939 }
1940
1941 /*
1942 * Add default events, if there were no attributes specified or
1943 * if -d/--detailed, -d -d or -d -d -d is used:
1944 */
add_default_events(void)1945 static int add_default_events(void)
1946 {
1947 const char *pmu = parse_events_option_args.pmu_filter ?: "all";
1948 struct parse_events_error err;
1949 struct evlist *evlist = evlist__new();
1950 struct evsel *evsel;
1951 int ret = 0;
1952
1953 if (!evlist)
1954 return -ENOMEM;
1955
1956 parse_events_error__init(&err);
1957
1958 /* Set attrs if no event is selected and !null_run: */
1959 if (stat_config.null_run)
1960 goto out;
1961
1962 if (transaction_run) {
1963 /* Handle -T as -M transaction. Once platform specific metrics
1964 * support has been added to the json files, all architectures
1965 * will use this approach. To determine transaction support
1966 * on an architecture test for such a metric name.
1967 */
1968 if (!metricgroup__has_metric_or_groups(pmu, "transaction")) {
1969 pr_err("Missing transaction metrics\n");
1970 ret = -1;
1971 goto out;
1972 }
1973 ret = metricgroup__parse_groups(evlist, pmu, "transaction",
1974 stat_config.metric_no_group,
1975 stat_config.metric_no_merge,
1976 stat_config.metric_no_threshold,
1977 stat_config.user_requested_cpu_list,
1978 stat_config.system_wide,
1979 stat_config.hardware_aware_grouping);
1980 goto out;
1981 }
1982
1983 if (smi_cost) {
1984 int smi;
1985
1986 if (sysfs__read_int(FREEZE_ON_SMI_PATH, &smi) < 0) {
1987 pr_err("freeze_on_smi is not supported.\n");
1988 ret = -1;
1989 goto out;
1990 }
1991
1992 if (!smi) {
1993 if (sysfs__write_int(FREEZE_ON_SMI_PATH, 1) < 0) {
1994 pr_err("Failed to set freeze_on_smi.\n");
1995 ret = -1;
1996 goto out;
1997 }
1998 smi_reset = true;
1999 }
2000
2001 if (!metricgroup__has_metric_or_groups(pmu, "smi")) {
2002 pr_err("Missing smi metrics\n");
2003 ret = -1;
2004 goto out;
2005 }
2006
2007 if (!force_metric_only)
2008 stat_config.metric_only = true;
2009
2010 ret = metricgroup__parse_groups(evlist, pmu, "smi",
2011 stat_config.metric_no_group,
2012 stat_config.metric_no_merge,
2013 stat_config.metric_no_threshold,
2014 stat_config.user_requested_cpu_list,
2015 stat_config.system_wide,
2016 stat_config.hardware_aware_grouping);
2017 goto out;
2018 }
2019
2020 if (topdown_run) {
2021 unsigned int max_level = metricgroups__topdown_max_level();
2022 char str[] = "TopdownL1";
2023
2024 if (!force_metric_only)
2025 stat_config.metric_only = true;
2026
2027 if (!max_level) {
2028 pr_err("Topdown requested but the topdown metric groups aren't present.\n"
2029 "(See perf list the metric groups have names like TopdownL1)\n");
2030 ret = -1;
2031 goto out;
2032 }
2033 if (stat_config.topdown_level > max_level) {
2034 pr_err("Invalid top-down metrics level. The max level is %u.\n", max_level);
2035 ret = -1;
2036 goto out;
2037 } else if (!stat_config.topdown_level) {
2038 stat_config.topdown_level = 1;
2039 }
2040 if (!stat_config.interval && !stat_config.metric_only) {
2041 fprintf(stat_config.output,
2042 "Topdown accuracy may decrease when measuring long periods.\n"
2043 "Please print the result regularly, e.g. -I1000\n");
2044 }
2045 str[8] = stat_config.topdown_level + '0';
2046 if (metricgroup__parse_groups(evlist,
2047 pmu, str,
2048 /*metric_no_group=*/false,
2049 /*metric_no_merge=*/false,
2050 /*metric_no_threshold=*/true,
2051 stat_config.user_requested_cpu_list,
2052 stat_config.system_wide,
2053 stat_config.hardware_aware_grouping) < 0) {
2054 ret = -1;
2055 goto out;
2056 }
2057 }
2058
2059 if (!stat_config.topdown_level)
2060 stat_config.topdown_level = 1;
2061
2062 if (!evlist->core.nr_entries && !evsel_list->core.nr_entries) {
2063 /*
2064 * Add Default metrics. To minimize multiplexing, don't request
2065 * threshold computation, but it will be computed if the events
2066 * are present.
2067 */
2068 const char *default_metricgroup_names[] = {
2069 "Default", "Default2", "Default3", "Default4",
2070 };
2071
2072 for (size_t i = 0; i < ARRAY_SIZE(default_metricgroup_names); i++) {
2073 struct evlist *metric_evlist;
2074
2075 if (!metricgroup__has_metric_or_groups(pmu, default_metricgroup_names[i]))
2076 continue;
2077
2078 if ((int)i > detailed_run)
2079 break;
2080
2081 metric_evlist = evlist__new();
2082 if (!metric_evlist) {
2083 ret = -ENOMEM;
2084 break;
2085 }
2086 if (metricgroup__parse_groups(metric_evlist, pmu, default_metricgroup_names[i],
2087 /*metric_no_group=*/false,
2088 /*metric_no_merge=*/false,
2089 /*metric_no_threshold=*/true,
2090 stat_config.user_requested_cpu_list,
2091 stat_config.system_wide,
2092 stat_config.hardware_aware_grouping) < 0) {
2093 evlist__delete(metric_evlist);
2094 ret = -1;
2095 break;
2096 }
2097
2098 evlist__for_each_entry(metric_evlist, evsel)
2099 evsel->default_metricgroup = true;
2100
2101 evlist__splice_list_tail(evlist, &metric_evlist->core.entries);
2102 metricgroup__copy_metric_events(evlist, /*cgrp=*/NULL,
2103 &evlist->metric_events,
2104 &metric_evlist->metric_events);
2105 evlist__delete(metric_evlist);
2106 }
2107 list_sort(/*priv=*/NULL, &evlist->core.entries, default_evlist_evsel_cmp);
2108
2109 }
2110 out:
2111 if (!ret) {
2112 evlist__for_each_entry(evlist, evsel) {
2113 /*
2114 * Make at least one event non-skippable so fatal errors are visible.
2115 * 'cycles' always used to be default and non-skippable, so use that.
2116 */
2117 if (!evsel__match(evsel, HARDWARE, HW_CPU_CYCLES))
2118 evsel->skippable = true;
2119 }
2120 }
2121 parse_events_error__exit(&err);
2122 evlist__splice_list_tail(evsel_list, &evlist->core.entries);
2123 metricgroup__copy_metric_events(evsel_list, /*cgrp=*/NULL,
2124 &evsel_list->metric_events,
2125 &evlist->metric_events);
2126 evlist__delete(evlist);
2127 return ret;
2128 }
2129
2130 static const char * const stat_record_usage[] = {
2131 "perf stat record [<options>]",
2132 NULL,
2133 };
2134
init_features(struct perf_session * session)2135 static void init_features(struct perf_session *session)
2136 {
2137 int feat;
2138
2139 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++)
2140 perf_header__set_feat(&session->header, feat);
2141
2142 perf_header__clear_feat(&session->header, HEADER_DIR_FORMAT);
2143 perf_header__clear_feat(&session->header, HEADER_BUILD_ID);
2144 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA);
2145 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK);
2146 perf_header__clear_feat(&session->header, HEADER_AUXTRACE);
2147 }
2148
__cmd_record(const struct option stat_options[],struct opt_aggr_mode * opt_mode,int argc,const char ** argv)2149 static int __cmd_record(const struct option stat_options[], struct opt_aggr_mode *opt_mode,
2150 int argc, const char **argv)
2151 {
2152 struct perf_session *session;
2153 struct perf_data *data = &perf_stat.data;
2154
2155 argc = parse_options(argc, argv, stat_options, stat_record_usage,
2156 PARSE_OPT_STOP_AT_NON_OPTION);
2157 stat_config.aggr_mode = opt_aggr_mode_to_aggr_mode(opt_mode);
2158
2159 if (output_name)
2160 data->path = output_name;
2161
2162 if (stat_config.run_count != 1 || forever) {
2163 pr_err("Cannot use -r option with perf stat record.\n");
2164 return -1;
2165 }
2166
2167 session = perf_session__new(data, NULL);
2168 if (IS_ERR(session)) {
2169 pr_err("Perf session creation failed\n");
2170 return PTR_ERR(session);
2171 }
2172
2173 init_features(session);
2174
2175 session->evlist = evsel_list;
2176 perf_stat.session = session;
2177 perf_stat.record = true;
2178 return argc;
2179 }
2180
process_stat_round_event(const struct perf_tool * tool __maybe_unused,struct perf_session * session,union perf_event * event)2181 static int process_stat_round_event(const struct perf_tool *tool __maybe_unused,
2182 struct perf_session *session,
2183 union perf_event *event)
2184 {
2185 struct perf_record_stat_round *stat_round = &event->stat_round;
2186 struct timespec tsh, *ts = NULL;
2187 struct perf_env *env = perf_session__env(session);
2188 const char **argv = env->cmdline_argv;
2189 int argc = env->nr_cmdline;
2190
2191 process_counters();
2192
2193 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL)
2194 update_stats(stat_config.walltime_nsecs_stats, stat_round->time);
2195
2196 if (stat_config.interval && stat_round->time) {
2197 tsh.tv_sec = stat_round->time / NSEC_PER_SEC;
2198 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC;
2199 ts = &tsh;
2200 }
2201
2202 print_counters(ts, argc, argv);
2203 return 0;
2204 }
2205
2206 static
process_stat_config_event(const struct perf_tool * tool,struct perf_session * session,union perf_event * event)2207 int process_stat_config_event(const struct perf_tool *tool,
2208 struct perf_session *session,
2209 union perf_event *event)
2210 {
2211 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2212
2213 perf_event__read_stat_config(&stat_config, &event->stat_config);
2214
2215 if (perf_cpu_map__is_empty(st->cpus)) {
2216 if (st->aggr_mode != AGGR_UNSET)
2217 pr_warning("warning: processing task data, aggregation mode not set\n");
2218 } else if (st->aggr_mode != AGGR_UNSET) {
2219 stat_config.aggr_mode = st->aggr_mode;
2220 }
2221
2222 if (perf_stat.data.is_pipe)
2223 perf_stat_init_aggr_mode();
2224 else
2225 perf_stat_init_aggr_mode_file(st);
2226
2227 if (stat_config.aggr_map) {
2228 int nr_aggr = stat_config.aggr_map->nr;
2229
2230 if (evlist__alloc_aggr_stats(session->evlist, nr_aggr) < 0) {
2231 pr_err("cannot allocate aggr counts\n");
2232 return -1;
2233 }
2234 }
2235 return 0;
2236 }
2237
set_maps(struct perf_stat * st)2238 static int set_maps(struct perf_stat *st)
2239 {
2240 if (!st->cpus || !st->threads)
2241 return 0;
2242
2243 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n"))
2244 return -EINVAL;
2245
2246 perf_evlist__set_maps(&evsel_list->core, st->cpus, st->threads);
2247
2248 if (evlist__alloc_stats(&stat_config, evsel_list, /*alloc_raw=*/true))
2249 return -ENOMEM;
2250
2251 st->maps_allocated = true;
2252 return 0;
2253 }
2254
2255 static
process_thread_map_event(const struct perf_tool * tool,struct perf_session * session __maybe_unused,union perf_event * event)2256 int process_thread_map_event(const struct perf_tool *tool,
2257 struct perf_session *session __maybe_unused,
2258 union perf_event *event)
2259 {
2260 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2261
2262 if (st->threads) {
2263 pr_warning("Extra thread map event, ignoring.\n");
2264 return 0;
2265 }
2266
2267 st->threads = thread_map__new_event(&event->thread_map);
2268 if (!st->threads)
2269 return -ENOMEM;
2270
2271 return set_maps(st);
2272 }
2273
2274 static
process_cpu_map_event(const struct perf_tool * tool,struct perf_session * session __maybe_unused,union perf_event * event)2275 int process_cpu_map_event(const struct perf_tool *tool,
2276 struct perf_session *session __maybe_unused,
2277 union perf_event *event)
2278 {
2279 struct perf_stat *st = container_of(tool, struct perf_stat, tool);
2280 struct perf_cpu_map *cpus;
2281
2282 if (st->cpus) {
2283 pr_warning("Extra cpu map event, ignoring.\n");
2284 return 0;
2285 }
2286
2287 cpus = cpu_map__new_data(&event->cpu_map.data);
2288 if (!cpus)
2289 return -ENOMEM;
2290
2291 st->cpus = cpus;
2292 return set_maps(st);
2293 }
2294
2295 static const char * const stat_report_usage[] = {
2296 "perf stat report [<options>]",
2297 NULL,
2298 };
2299
2300 static struct perf_stat perf_stat = {
2301 .aggr_mode = AGGR_UNSET,
2302 .aggr_level = 0,
2303 };
2304
__cmd_report(int argc,const char ** argv)2305 static int __cmd_report(int argc, const char **argv)
2306 {
2307 struct perf_session *session;
2308 const struct option options[] = {
2309 OPT_STRING('i', "input", &input_name, "file", "input file name"),
2310 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode,
2311 "aggregate counts per processor socket", AGGR_SOCKET),
2312 OPT_SET_UINT(0, "per-die", &perf_stat.aggr_mode,
2313 "aggregate counts per processor die", AGGR_DIE),
2314 OPT_SET_UINT(0, "per-cluster", &perf_stat.aggr_mode,
2315 "aggregate counts perf processor cluster", AGGR_CLUSTER),
2316 OPT_CALLBACK_OPTARG(0, "per-cache", &perf_stat.aggr_mode, &perf_stat.aggr_level,
2317 "cache level",
2318 "aggregate count at this cache level (Default: LLC)",
2319 parse_cache_level),
2320 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode,
2321 "aggregate counts per physical processor core", AGGR_CORE),
2322 OPT_SET_UINT(0, "per-node", &perf_stat.aggr_mode,
2323 "aggregate counts per numa node", AGGR_NODE),
2324 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode,
2325 "disable CPU count aggregation", AGGR_NONE),
2326 OPT_END()
2327 };
2328 struct stat st;
2329 int ret;
2330
2331 argc = parse_options(argc, argv, options, stat_report_usage, 0);
2332
2333 if (!input_name || !strlen(input_name)) {
2334 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode))
2335 input_name = "-";
2336 else
2337 input_name = "perf.data";
2338 }
2339
2340 perf_stat.data.path = input_name;
2341 perf_stat.data.mode = PERF_DATA_MODE_READ;
2342
2343 perf_tool__init(&perf_stat.tool, /*ordered_events=*/false);
2344 perf_stat.tool.attr = perf_event__process_attr;
2345 perf_stat.tool.event_update = perf_event__process_event_update;
2346 perf_stat.tool.thread_map = process_thread_map_event;
2347 perf_stat.tool.cpu_map = process_cpu_map_event;
2348 perf_stat.tool.stat_config = process_stat_config_event;
2349 perf_stat.tool.stat = perf_event__process_stat_event;
2350 perf_stat.tool.stat_round = process_stat_round_event;
2351
2352 session = perf_session__new(&perf_stat.data, &perf_stat.tool);
2353 if (IS_ERR(session))
2354 return PTR_ERR(session);
2355
2356 perf_stat.session = session;
2357 stat_config.output = stderr;
2358 evlist__delete(evsel_list);
2359 evsel_list = session->evlist;
2360
2361 ret = perf_session__process_events(session);
2362 if (ret)
2363 return ret;
2364
2365 perf_session__delete(session);
2366 return 0;
2367 }
2368
setup_system_wide(int forks)2369 static void setup_system_wide(int forks)
2370 {
2371 /*
2372 * Make system wide (-a) the default target if
2373 * no target was specified and one of following
2374 * conditions is met:
2375 *
2376 * - there's no workload specified
2377 * - there is workload specified but all requested
2378 * events are system wide events
2379 */
2380 if (!target__none(&target))
2381 return;
2382
2383 if (!forks)
2384 target.system_wide = true;
2385 else {
2386 struct evsel *counter;
2387
2388 evlist__for_each_entry(evsel_list, counter) {
2389 if (!counter->core.requires_cpu &&
2390 !evsel__name_is(counter, "duration_time")) {
2391 return;
2392 }
2393 }
2394
2395 if (evsel_list->core.nr_entries)
2396 target.system_wide = true;
2397 }
2398 }
2399
2400 #ifdef HAVE_ARCH_X86_64_SUPPORT
parse_tpebs_mode(const struct option * opt,const char * str,int unset __maybe_unused)2401 static int parse_tpebs_mode(const struct option *opt, const char *str,
2402 int unset __maybe_unused)
2403 {
2404 enum tpebs_mode *mode = opt->value;
2405
2406 if (!strcasecmp("mean", str)) {
2407 *mode = TPEBS_MODE__MEAN;
2408 return 0;
2409 }
2410 if (!strcasecmp("min", str)) {
2411 *mode = TPEBS_MODE__MIN;
2412 return 0;
2413 }
2414 if (!strcasecmp("max", str)) {
2415 *mode = TPEBS_MODE__MAX;
2416 return 0;
2417 }
2418 if (!strcasecmp("last", str)) {
2419 *mode = TPEBS_MODE__LAST;
2420 return 0;
2421 }
2422 return -1;
2423 }
2424 #endif // HAVE_ARCH_X86_64_SUPPORT
2425
cmd_stat(int argc,const char ** argv)2426 int cmd_stat(int argc, const char **argv)
2427 {
2428 struct opt_aggr_mode opt_mode = {};
2429 bool affinity = true, affinity_set = false;
2430 struct option stat_options[] = {
2431 OPT_BOOLEAN('T', "transaction", &transaction_run,
2432 "hardware transaction statistics"),
2433 OPT_CALLBACK('e', "event", &parse_events_option_args, "event",
2434 "event selector. use 'perf list' to list available events",
2435 parse_events_option),
2436 OPT_CALLBACK(0, "filter", &evsel_list, "filter",
2437 "event filter", parse_filter),
2438 OPT_BOOLEAN('i', "no-inherit", &stat_config.no_inherit,
2439 "child tasks do not inherit counters"),
2440 OPT_STRING('p', "pid", &target.pid, "pid",
2441 "stat events on existing process id"),
2442 OPT_STRING('t', "tid", &target.tid, "tid",
2443 "stat events on existing thread id"),
2444 #ifdef HAVE_BPF_SKEL
2445 OPT_STRING('b', "bpf-prog", &target.bpf_str, "bpf-prog-id",
2446 "stat events on existing bpf program id"),
2447 OPT_BOOLEAN(0, "bpf-counters", &target.use_bpf,
2448 "use bpf program to count events"),
2449 OPT_STRING(0, "bpf-attr-map", &target.attr_map, "attr-map-path",
2450 "path to perf_event_attr map"),
2451 #endif
2452 OPT_BOOLEAN('a', "all-cpus", &target.system_wide,
2453 "system-wide collection from all CPUs"),
2454 OPT_BOOLEAN(0, "scale", &stat_config.scale,
2455 "Use --no-scale to disable counter scaling for multiplexing"),
2456 OPT_INCR('v', "verbose", &verbose,
2457 "be more verbose (show counter open errors, etc)"),
2458 OPT_INTEGER('r', "repeat", &stat_config.run_count,
2459 "repeat command and print average + stddev (max: 100, forever: 0)"),
2460 OPT_BOOLEAN(0, "table", &stat_config.walltime_run_table,
2461 "display details about each run (only with -r option)"),
2462 OPT_BOOLEAN('n', "null", &stat_config.null_run,
2463 "null run - dont start any counters"),
2464 OPT_INCR('d', "detailed", &detailed_run,
2465 "detailed run - start a lot of events"),
2466 OPT_BOOLEAN('S', "sync", &sync_run,
2467 "call sync() before starting a run"),
2468 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL,
2469 "print large numbers with thousands\' separators",
2470 stat__set_big_num),
2471 OPT_STRING('C', "cpu", &target.cpu_list, "cpu",
2472 "list of cpus to monitor in system-wide"),
2473 OPT_BOOLEAN('A', "no-aggr", &opt_mode.no_aggr,
2474 "disable aggregation across CPUs or PMUs"),
2475 OPT_BOOLEAN(0, "no-merge", &opt_mode.no_aggr,
2476 "disable aggregation the same as -A or -no-aggr"),
2477 OPT_BOOLEAN(0, "hybrid-merge", &stat_config.hybrid_merge,
2478 "Merge identical named hybrid events"),
2479 OPT_STRING('x', "field-separator", &stat_config.csv_sep, "separator",
2480 "print counts with custom separator"),
2481 OPT_BOOLEAN('j', "json-output", &stat_config.json_output,
2482 "print counts in JSON format"),
2483 OPT_CALLBACK('G', "cgroup", &evsel_list, "name",
2484 "monitor event in cgroup name only", parse_stat_cgroups),
2485 OPT_STRING(0, "for-each-cgroup", &stat_config.cgroup_list, "name",
2486 "expand events for each cgroup"),
2487 OPT_STRING('o', "output", &output_name, "file", "output file name"),
2488 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"),
2489 OPT_INTEGER(0, "log-fd", &output_fd,
2490 "log output to fd, instead of stderr"),
2491 OPT_STRING(0, "pre", &pre_cmd, "command",
2492 "command to run prior to the measured command"),
2493 OPT_STRING(0, "post", &post_cmd, "command",
2494 "command to run after to the measured command"),
2495 OPT_UINTEGER('I', "interval-print", &stat_config.interval,
2496 "print counts at regular interval in ms "
2497 "(overhead is possible for values <= 100ms)"),
2498 OPT_INTEGER(0, "interval-count", &stat_config.times,
2499 "print counts for fixed number of times"),
2500 OPT_BOOLEAN(0, "interval-clear", &stat_config.interval_clear,
2501 "clear screen in between new interval"),
2502 OPT_UINTEGER(0, "timeout", &stat_config.timeout,
2503 "stop workload and print counts after a timeout period in ms (>= 10ms)"),
2504 OPT_BOOLEAN(0, "per-socket", &opt_mode.socket,
2505 "aggregate counts per processor socket"),
2506 OPT_BOOLEAN(0, "per-die", &opt_mode.die, "aggregate counts per processor die"),
2507 OPT_BOOLEAN(0, "per-cluster", &opt_mode.cluster,
2508 "aggregate counts per processor cluster"),
2509 OPT_CALLBACK_OPTARG(0, "per-cache", &opt_mode, &stat_config.aggr_level,
2510 "cache level", "aggregate count at this cache level (Default: LLC)",
2511 parse_cache_level),
2512 OPT_BOOLEAN(0, "per-core", &opt_mode.core,
2513 "aggregate counts per physical processor core"),
2514 OPT_BOOLEAN(0, "per-thread", &opt_mode.thread, "aggregate counts per thread"),
2515 OPT_BOOLEAN(0, "per-node", &opt_mode.node, "aggregate counts per numa node"),
2516 OPT_INTEGER('D', "delay", &target.initial_delay,
2517 "ms to wait before starting measurement after program start (-1: start with events disabled)"),
2518 OPT_CALLBACK_NOOPT(0, "metric-only", &stat_config.metric_only, NULL,
2519 "Only print computed metrics. No raw values", enable_metric_only),
2520 OPT_BOOLEAN(0, "metric-no-group", &stat_config.metric_no_group,
2521 "don't group metric events, impacts multiplexing"),
2522 OPT_BOOLEAN(0, "metric-no-merge", &stat_config.metric_no_merge,
2523 "don't try to share events between metrics in a group"),
2524 OPT_BOOLEAN(0, "metric-no-threshold", &stat_config.metric_no_threshold,
2525 "disable adding events for the metric threshold calculation"),
2526 OPT_BOOLEAN(0, "topdown", &topdown_run,
2527 "measure top-down statistics"),
2528 #ifdef HAVE_ARCH_X86_64_SUPPORT
2529 OPT_BOOLEAN(0, "record-tpebs", &tpebs_recording,
2530 "enable recording for tpebs when retire_latency required"),
2531 OPT_CALLBACK(0, "tpebs-mode", &tpebs_mode, "tpebs-mode",
2532 "Mode of TPEBS recording: mean, min or max",
2533 parse_tpebs_mode),
2534 #endif
2535 OPT_UINTEGER(0, "td-level", &stat_config.topdown_level,
2536 "Set the metrics level for the top-down statistics (0: max level)"),
2537 OPT_BOOLEAN(0, "smi-cost", &smi_cost,
2538 "measure SMI cost"),
2539 OPT_CALLBACK('M', "metrics", &evsel_list, "metric/metric group list",
2540 "monitor specified metrics or metric groups (separated by ,)",
2541 append_metric_groups),
2542 OPT_BOOLEAN_FLAG(0, "all-kernel", &stat_config.all_kernel,
2543 "Configure all used events to run in kernel space.",
2544 PARSE_OPT_EXCLUSIVE),
2545 OPT_BOOLEAN_FLAG(0, "all-user", &stat_config.all_user,
2546 "Configure all used events to run in user space.",
2547 PARSE_OPT_EXCLUSIVE),
2548 OPT_BOOLEAN(0, "percore-show-thread", &stat_config.percore_show_thread,
2549 "Use with 'percore' event qualifier to show the event "
2550 "counts of one hardware thread by sum up total hardware "
2551 "threads of same physical core"),
2552 OPT_BOOLEAN(0, "summary", &stat_config.summary,
2553 "print summary for interval mode"),
2554 OPT_BOOLEAN(0, "no-csv-summary", &stat_config.no_csv_summary,
2555 "don't print 'summary' for CSV summary output"),
2556 OPT_BOOLEAN(0, "quiet", &quiet,
2557 "don't print any output, messages or warnings (useful with record)"),
2558 OPT_BOOLEAN_SET(0, "affinity", &affinity, &affinity_set,
2559 "enable (default) or disable affinity optimizations to reduce IPIs"),
2560 OPT_CALLBACK(0, "cputype", &evsel_list, "hybrid cpu type",
2561 "Only enable events on applying cpu with this type "
2562 "for hybrid platform (e.g. core or atom)",
2563 parse_cputype),
2564 #ifdef HAVE_LIBPFM
2565 OPT_CALLBACK(0, "pfm-events", &evsel_list, "event",
2566 "libpfm4 event selector. use 'perf list' to list available events",
2567 parse_libpfm_events_option),
2568 #endif
2569 OPT_CALLBACK(0, "control", &stat_config, "fd:ctl-fd[,ack-fd] or fifo:ctl-fifo[,ack-fifo]",
2570 "Listen on ctl-fd descriptor for command to control measurement ('enable': enable events, 'disable': disable events).\n"
2571 "\t\t\t Optionally send control command completion ('ack\\n') to ack-fd descriptor.\n"
2572 "\t\t\t Alternatively, ctl-fifo / ack-fifo will be opened and used as ctl-fd / ack-fd.",
2573 parse_control_option),
2574 OPT_CALLBACK_OPTARG(0, "iostat", &evsel_list, &stat_config, "default",
2575 "measure I/O performance metrics provided by arch/platform",
2576 iostat_parse),
2577 OPT_END()
2578 };
2579 const char * const stat_usage[] = {
2580 "perf stat [<options>] [<command>]",
2581 NULL
2582 };
2583 int status = -EINVAL, run_idx, err;
2584 const char *mode;
2585 FILE *output = stderr;
2586 unsigned int interval, timeout;
2587 const char * const stat_subcommands[] = { "record", "report" };
2588 char errbuf[BUFSIZ];
2589 struct evsel *counter;
2590
2591 setlocale(LC_ALL, "");
2592
2593 evsel_list = evlist__new();
2594 if (evsel_list == NULL)
2595 return -ENOMEM;
2596
2597 parse_events__shrink_config_terms();
2598
2599 /* String-parsing callback-based options would segfault when negated */
2600 set_option_flag(stat_options, 'e', "event", PARSE_OPT_NONEG);
2601 set_option_flag(stat_options, 'M', "metrics", PARSE_OPT_NONEG);
2602 set_option_flag(stat_options, 'G', "cgroup", PARSE_OPT_NONEG);
2603
2604 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands,
2605 (const char **) stat_usage,
2606 PARSE_OPT_STOP_AT_NON_OPTION);
2607
2608 stat_config.aggr_mode = opt_aggr_mode_to_aggr_mode(&opt_mode);
2609
2610 if (stat_config.csv_sep) {
2611 stat_config.csv_output = true;
2612 if (!strcmp(stat_config.csv_sep, "\\t"))
2613 stat_config.csv_sep = "\t";
2614 } else
2615 stat_config.csv_sep = DEFAULT_SEPARATOR;
2616
2617 if (affinity_set)
2618 evsel_list->no_affinity = !affinity;
2619
2620 if (argc && strlen(argv[0]) > 2 && strstarts("record", argv[0])) {
2621 argc = __cmd_record(stat_options, &opt_mode, argc, argv);
2622 if (argc < 0)
2623 return -1;
2624 } else if (argc && strlen(argv[0]) > 2 && strstarts("report", argv[0]))
2625 return __cmd_report(argc, argv);
2626
2627 interval = stat_config.interval;
2628 timeout = stat_config.timeout;
2629
2630 /*
2631 * For record command the -o is already taken care of.
2632 */
2633 if (!STAT_RECORD && output_name && strcmp(output_name, "-"))
2634 output = NULL;
2635
2636 if (output_name && output_fd) {
2637 fprintf(stderr, "cannot use both --output and --log-fd\n");
2638 parse_options_usage(stat_usage, stat_options, "o", 1);
2639 parse_options_usage(NULL, stat_options, "log-fd", 0);
2640 goto out;
2641 }
2642
2643 if (stat_config.metric_only && stat_config.aggr_mode == AGGR_THREAD) {
2644 fprintf(stderr, "--metric-only is not supported with --per-thread\n");
2645 goto out;
2646 }
2647
2648 if (stat_config.metric_only && stat_config.run_count > 1) {
2649 fprintf(stderr, "--metric-only is not supported with -r\n");
2650 goto out;
2651 }
2652
2653 if (stat_config.csv_output || (stat_config.metric_only && stat_config.json_output)) {
2654 /*
2655 * Current CSV and metric-only JSON output doesn't display the
2656 * metric threshold so don't compute it.
2657 */
2658 stat_config.metric_no_threshold = true;
2659 }
2660
2661 if (stat_config.walltime_run_table && stat_config.run_count <= 1) {
2662 fprintf(stderr, "--table is only supported with -r\n");
2663 parse_options_usage(stat_usage, stat_options, "r", 1);
2664 parse_options_usage(NULL, stat_options, "table", 0);
2665 goto out;
2666 }
2667
2668 if (output_fd < 0) {
2669 fprintf(stderr, "argument to --log-fd must be a > 0\n");
2670 parse_options_usage(stat_usage, stat_options, "log-fd", 0);
2671 goto out;
2672 }
2673
2674 if (!output && !quiet) {
2675 struct timespec tm;
2676 mode = append_file ? "a" : "w";
2677
2678 output = fopen(output_name, mode);
2679 if (!output) {
2680 perror("failed to create output file");
2681 return -1;
2682 }
2683 if (!stat_config.json_output) {
2684 clock_gettime(CLOCK_REALTIME, &tm);
2685 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec));
2686 }
2687 } else if (output_fd > 0) {
2688 mode = append_file ? "a" : "w";
2689 output = fdopen(output_fd, mode);
2690 if (!output) {
2691 perror("Failed opening logfd");
2692 return -errno;
2693 }
2694 }
2695
2696 if (stat_config.interval_clear && !isatty(fileno(output))) {
2697 fprintf(stderr, "--interval-clear does not work with output\n");
2698 parse_options_usage(stat_usage, stat_options, "o", 1);
2699 parse_options_usage(NULL, stat_options, "log-fd", 0);
2700 parse_options_usage(NULL, stat_options, "interval-clear", 0);
2701 return -1;
2702 }
2703
2704 stat_config.output = output;
2705
2706 /*
2707 * let the spreadsheet do the pretty-printing
2708 */
2709 if (stat_config.csv_output) {
2710 /* User explicitly passed -B? */
2711 if (big_num_opt == 1) {
2712 fprintf(stderr, "-B option not supported with -x\n");
2713 parse_options_usage(stat_usage, stat_options, "B", 1);
2714 parse_options_usage(NULL, stat_options, "x", 1);
2715 goto out;
2716 } else /* Nope, so disable big number formatting */
2717 stat_config.big_num = false;
2718 } else if (big_num_opt == 0) /* User passed --no-big-num */
2719 stat_config.big_num = false;
2720
2721 target.inherit = !stat_config.no_inherit;
2722 err = target__validate(&target);
2723 if (err) {
2724 target__strerror(&target, err, errbuf, BUFSIZ);
2725 pr_warning("%s\n", errbuf);
2726 }
2727
2728 setup_system_wide(argc);
2729
2730 /*
2731 * Display user/system times only for single
2732 * run and when there's specified tracee.
2733 */
2734 if ((stat_config.run_count == 1) && target__none(&target))
2735 stat_config.ru_display = true;
2736
2737 if (stat_config.run_count < 0) {
2738 pr_err("Run count must be a positive number\n");
2739 parse_options_usage(stat_usage, stat_options, "r", 1);
2740 goto out;
2741 } else if (stat_config.run_count == 0) {
2742 forever = true;
2743 stat_config.run_count = 1;
2744 }
2745
2746 if (stat_config.walltime_run_table) {
2747 stat_config.walltime_run = zalloc(stat_config.run_count * sizeof(stat_config.walltime_run[0]));
2748 if (!stat_config.walltime_run) {
2749 pr_err("failed to setup -r option");
2750 goto out;
2751 }
2752 }
2753
2754 if ((stat_config.aggr_mode == AGGR_THREAD) &&
2755 !target__has_task(&target)) {
2756 if (!target.system_wide || target.cpu_list) {
2757 fprintf(stderr, "The --per-thread option is only "
2758 "available when monitoring via -p -t -a "
2759 "options or only --per-thread.\n");
2760 parse_options_usage(NULL, stat_options, "p", 1);
2761 parse_options_usage(NULL, stat_options, "t", 1);
2762 goto out;
2763 }
2764 }
2765
2766 /*
2767 * no_aggr, cgroup are for system-wide only
2768 * --per-thread is aggregated per thread, we dont mix it with cpu mode
2769 */
2770 if (((stat_config.aggr_mode != AGGR_GLOBAL &&
2771 stat_config.aggr_mode != AGGR_THREAD) ||
2772 (nr_cgroups || stat_config.cgroup_list)) &&
2773 !target__has_cpu(&target)) {
2774 fprintf(stderr, "both cgroup and no-aggregation "
2775 "modes only available in system-wide mode\n");
2776
2777 parse_options_usage(stat_usage, stat_options, "G", 1);
2778 parse_options_usage(NULL, stat_options, "A", 1);
2779 parse_options_usage(NULL, stat_options, "a", 1);
2780 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2781 goto out;
2782 }
2783
2784 if (stat_config.iostat_run) {
2785 status = iostat_prepare(evsel_list, &stat_config);
2786 if (status)
2787 goto out;
2788 if (iostat_mode == IOSTAT_LIST) {
2789 iostat_list(evsel_list, &stat_config);
2790 goto out;
2791 } else if (verbose > 0)
2792 iostat_list(evsel_list, &stat_config);
2793 if (iostat_mode == IOSTAT_RUN && !target__has_cpu(&target))
2794 target.system_wide = true;
2795 }
2796
2797 if ((stat_config.aggr_mode == AGGR_THREAD) && (target.system_wide))
2798 target.per_thread = true;
2799
2800 stat_config.system_wide = target.system_wide;
2801 if (target.cpu_list) {
2802 stat_config.user_requested_cpu_list = strdup(target.cpu_list);
2803 if (!stat_config.user_requested_cpu_list) {
2804 status = -ENOMEM;
2805 goto out;
2806 }
2807 }
2808
2809 /*
2810 * Metric parsing needs to be delayed as metrics may optimize events
2811 * knowing the target is system-wide.
2812 */
2813 if (metrics) {
2814 const char *pmu = parse_events_option_args.pmu_filter ?: "all";
2815 int ret = metricgroup__parse_groups(evsel_list, pmu, metrics,
2816 stat_config.metric_no_group,
2817 stat_config.metric_no_merge,
2818 stat_config.metric_no_threshold,
2819 stat_config.user_requested_cpu_list,
2820 stat_config.system_wide,
2821 stat_config.hardware_aware_grouping);
2822
2823 zfree(&metrics);
2824 if (ret) {
2825 status = ret;
2826 goto out;
2827 }
2828 }
2829
2830 if (add_default_events())
2831 goto out;
2832
2833 if (stat_config.cgroup_list) {
2834 if (nr_cgroups > 0) {
2835 pr_err("--cgroup and --for-each-cgroup cannot be used together\n");
2836 parse_options_usage(stat_usage, stat_options, "G", 1);
2837 parse_options_usage(NULL, stat_options, "for-each-cgroup", 0);
2838 goto out;
2839 }
2840
2841 if (evlist__expand_cgroup(evsel_list, stat_config.cgroup_list, true) < 0) {
2842 parse_options_usage(stat_usage, stat_options,
2843 "for-each-cgroup", 0);
2844 goto out;
2845 }
2846 }
2847 #ifdef HAVE_BPF_SKEL
2848 if (target.use_bpf && nr_cgroups &&
2849 (evsel_list->core.nr_entries / nr_cgroups) > BPERF_CGROUP__MAX_EVENTS) {
2850 pr_warning("Disabling BPF counters due to more events (%d) than the max (%d)\n",
2851 evsel_list->core.nr_entries / nr_cgroups, BPERF_CGROUP__MAX_EVENTS);
2852 target.use_bpf = false;
2853 }
2854 #endif // HAVE_BPF_SKEL
2855 evlist__warn_user_requested_cpus(evsel_list, target.cpu_list);
2856
2857 evlist__for_each_entry(evsel_list, counter) {
2858 /*
2859 * Setup BPF counters to require CPUs as any(-1) isn't
2860 * supported. evlist__create_maps below will propagate this
2861 * information to the evsels. Note, evsel__is_bperf isn't yet
2862 * set up, and this change must happen early, so directly use
2863 * the bpf_counter variable and target information.
2864 */
2865 if ((counter->bpf_counter || target.use_bpf) && !target__has_cpu(&target))
2866 counter->core.requires_cpu = true;
2867 }
2868
2869 if (evlist__create_maps(evsel_list, &target) < 0) {
2870 if (target__has_task(&target)) {
2871 pr_err("Problems finding threads of monitor\n");
2872 parse_options_usage(stat_usage, stat_options, "p", 1);
2873 parse_options_usage(NULL, stat_options, "t", 1);
2874 } else if (target__has_cpu(&target)) {
2875 perror("failed to parse CPUs map");
2876 parse_options_usage(stat_usage, stat_options, "C", 1);
2877 parse_options_usage(NULL, stat_options, "a", 1);
2878 }
2879 goto out;
2880 }
2881
2882 evlist__check_cpu_maps(evsel_list);
2883
2884 /*
2885 * Initialize thread_map with comm names,
2886 * so we could print it out on output.
2887 */
2888 if (stat_config.aggr_mode == AGGR_THREAD) {
2889 thread_map__read_comms(evsel_list->core.threads);
2890 }
2891
2892 if (stat_config.aggr_mode == AGGR_NODE)
2893 cpu__setup_cpunode_map();
2894
2895 if (stat_config.times && interval)
2896 interval_count = true;
2897 else if (stat_config.times && !interval) {
2898 pr_err("interval-count option should be used together with "
2899 "interval-print.\n");
2900 parse_options_usage(stat_usage, stat_options, "interval-count", 0);
2901 parse_options_usage(stat_usage, stat_options, "I", 1);
2902 goto out;
2903 }
2904
2905 if (timeout && timeout < 100) {
2906 if (timeout < 10) {
2907 pr_err("timeout must be >= 10ms.\n");
2908 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2909 goto out;
2910 } else
2911 pr_warning("timeout < 100ms. "
2912 "The overhead percentage could be high in some cases. "
2913 "Please proceed with caution.\n");
2914 }
2915 if (timeout && interval) {
2916 pr_err("timeout option is not supported with interval-print.\n");
2917 parse_options_usage(stat_usage, stat_options, "timeout", 0);
2918 parse_options_usage(stat_usage, stat_options, "I", 1);
2919 goto out;
2920 }
2921
2922 if (perf_stat_init_aggr_mode())
2923 goto out;
2924
2925 if (evlist__alloc_stats(&stat_config, evsel_list, interval))
2926 goto out;
2927
2928 /*
2929 * Set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless
2930 * while avoiding that older tools show confusing messages.
2931 *
2932 * However for pipe sessions we need to keep it zero,
2933 * because script's perf_evsel__check_attr is triggered
2934 * by attr->sample_type != 0, and we can't run it on
2935 * stat sessions.
2936 */
2937 stat_config.identifier = !(STAT_RECORD && perf_stat.data.is_pipe);
2938
2939 /*
2940 * We dont want to block the signals - that would cause
2941 * child tasks to inherit that and Ctrl-C would not work.
2942 * What we want is for Ctrl-C to work in the exec()-ed
2943 * task, but being ignored by perf stat itself:
2944 */
2945 atexit(sig_atexit);
2946 if (!forever)
2947 signal(SIGINT, skip_signal);
2948 signal(SIGCHLD, skip_signal);
2949 signal(SIGALRM, skip_signal);
2950 signal(SIGABRT, skip_signal);
2951
2952 if (evlist__initialize_ctlfd(evsel_list, stat_config.ctl_fd, stat_config.ctl_fd_ack))
2953 goto out;
2954
2955 /* Enable ignoring missing threads when -p option is defined. */
2956 evlist__first(evsel_list)->ignore_missing_thread = target.pid;
2957 status = 0;
2958 for (run_idx = 0; forever || run_idx < stat_config.run_count; run_idx++) {
2959 if (stat_config.run_count != 1 && verbose > 0)
2960 fprintf(output, "[ perf stat: executing run #%d ... ]\n",
2961 run_idx + 1);
2962
2963 if (run_idx != 0)
2964 evlist__reset_prev_raw_counts(evsel_list);
2965
2966 status = run_perf_stat(argc, argv, run_idx);
2967 if (status < 0)
2968 break;
2969
2970 if (forever && !interval) {
2971 print_counters(NULL, argc, argv);
2972 perf_stat__reset_stats();
2973 }
2974 }
2975
2976 if (!forever && status != -1 && (!interval || stat_config.summary)) {
2977 if (stat_config.run_count > 1)
2978 evlist__copy_res_stats(&stat_config, evsel_list);
2979 print_counters(NULL, argc, argv);
2980 }
2981
2982 evlist__finalize_ctlfd(evsel_list);
2983
2984 if (STAT_RECORD) {
2985 /*
2986 * We synthesize the kernel mmap record just so that older tools
2987 * don't emit warnings about not being able to resolve symbols
2988 * due to /proc/sys/kernel/kptr_restrict settings and instead provide
2989 * a saner message about no samples being in the perf.data file.
2990 *
2991 * This also serves to suppress a warning about f_header.data.size == 0
2992 * in header.c at the moment 'perf stat record' gets introduced, which
2993 * is not really needed once we start adding the stat specific PERF_RECORD_
2994 * records, but the need to suppress the kptr_restrict messages in older
2995 * tools remain -acme
2996 */
2997 int fd = perf_data__fd(&perf_stat.data);
2998
2999 err = perf_event__synthesize_kernel_mmap((void *)&perf_stat,
3000 process_synthesized_event,
3001 &perf_stat.session->machines.host);
3002 if (err) {
3003 pr_warning("Couldn't synthesize the kernel mmap record, harmless, "
3004 "older tools may produce warnings about this file\n.");
3005 }
3006
3007 if (!interval) {
3008 if (WRITE_STAT_ROUND_EVENT(stat_config.walltime_nsecs_stats->max, FINAL))
3009 pr_err("failed to write stat round event\n");
3010 }
3011
3012 if (!perf_stat.data.is_pipe) {
3013 perf_stat.session->header.data_size += perf_stat.bytes_written;
3014 perf_session__write_header(perf_stat.session, evsel_list, fd, true);
3015 }
3016
3017 evlist__close(evsel_list);
3018 perf_session__delete(perf_stat.session);
3019 }
3020
3021 perf_stat__exit_aggr_mode();
3022 evlist__free_stats(evsel_list);
3023 out:
3024 if (stat_config.iostat_run)
3025 iostat_release(evsel_list);
3026
3027 zfree(&stat_config.walltime_run);
3028 zfree(&stat_config.user_requested_cpu_list);
3029
3030 if (smi_cost && smi_reset)
3031 sysfs__write_int(FREEZE_ON_SMI_PATH, 0);
3032
3033 evlist__delete(evsel_list);
3034
3035 evlist__close_control(stat_config.ctl_fd, stat_config.ctl_fd_ack, &stat_config.ctl_fd_close);
3036
3037 /* Only the low byte of status becomes the exit code. */
3038 return abs(status);
3039 }
3040