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