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