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