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