1 /* 2 * builtin-stat.c 3 * 4 * Builtin stat command: Give a precise performance counters summary 5 * overview about any workload, CPU or specific PID. 6 * 7 * Sample output: 8 9 $ perf stat ./hackbench 10 10 11 Time: 0.118 12 13 Performance counter stats for './hackbench 10': 14 15 1708.761321 task-clock # 11.037 CPUs utilized 16 41,190 context-switches # 0.024 M/sec 17 6,735 CPU-migrations # 0.004 M/sec 18 17,318 page-faults # 0.010 M/sec 19 5,205,202,243 cycles # 3.046 GHz 20 3,856,436,920 stalled-cycles-frontend # 74.09% frontend cycles idle 21 1,600,790,871 stalled-cycles-backend # 30.75% backend cycles idle 22 2,603,501,247 instructions # 0.50 insns per cycle 23 # 1.48 stalled cycles per insn 24 484,357,498 branches # 283.455 M/sec 25 6,388,934 branch-misses # 1.32% of all branches 26 27 0.154822978 seconds time elapsed 28 29 * 30 * Copyright (C) 2008-2011, Red Hat Inc, Ingo Molnar <mingo@redhat.com> 31 * 32 * Improvements and fixes by: 33 * 34 * Arjan van de Ven <arjan@linux.intel.com> 35 * Yanmin Zhang <yanmin.zhang@intel.com> 36 * Wu Fengguang <fengguang.wu@intel.com> 37 * Mike Galbraith <efault@gmx.de> 38 * Paul Mackerras <paulus@samba.org> 39 * Jaswinder Singh Rajput <jaswinder@kernel.org> 40 * 41 * Released under the GPL v2. (and only v2, not any later version) 42 */ 43 44 #include "perf.h" 45 #include "builtin.h" 46 #include "util/cgroup.h" 47 #include "util/util.h" 48 #include <subcmd/parse-options.h> 49 #include "util/parse-events.h" 50 #include "util/pmu.h" 51 #include "util/event.h" 52 #include "util/evlist.h" 53 #include "util/evsel.h" 54 #include "util/debug.h" 55 #include "util/drv_configs.h" 56 #include "util/color.h" 57 #include "util/stat.h" 58 #include "util/header.h" 59 #include "util/cpumap.h" 60 #include "util/thread.h" 61 #include "util/thread_map.h" 62 #include "util/counts.h" 63 #include "util/group.h" 64 #include "util/session.h" 65 #include "util/tool.h" 66 #include "util/group.h" 67 #include "util/string2.h" 68 #include "asm/bug.h" 69 70 #include <linux/time64.h> 71 #include <api/fs/fs.h> 72 #include <errno.h> 73 #include <signal.h> 74 #include <stdlib.h> 75 #include <sys/prctl.h> 76 #include <inttypes.h> 77 #include <locale.h> 78 #include <math.h> 79 #include <sys/types.h> 80 #include <sys/stat.h> 81 #include <sys/wait.h> 82 #include <unistd.h> 83 84 #include "sane_ctype.h" 85 86 #define DEFAULT_SEPARATOR " " 87 #define CNTR_NOT_SUPPORTED "<not supported>" 88 #define CNTR_NOT_COUNTED "<not counted>" 89 90 static void print_counters(struct timespec *ts, int argc, const char **argv); 91 92 /* Default events used for perf stat -T */ 93 static const char *transaction_attrs = { 94 "task-clock," 95 "{" 96 "instructions," 97 "cycles," 98 "cpu/cycles-t/," 99 "cpu/tx-start/," 100 "cpu/el-start/," 101 "cpu/cycles-ct/" 102 "}" 103 }; 104 105 /* More limited version when the CPU does not have all events. */ 106 static const char * transaction_limited_attrs = { 107 "task-clock," 108 "{" 109 "instructions," 110 "cycles," 111 "cpu/cycles-t/," 112 "cpu/tx-start/" 113 "}" 114 }; 115 116 static const char * topdown_attrs[] = { 117 "topdown-total-slots", 118 "topdown-slots-retired", 119 "topdown-recovery-bubbles", 120 "topdown-fetch-bubbles", 121 "topdown-slots-issued", 122 NULL, 123 }; 124 125 static struct perf_evlist *evsel_list; 126 127 static struct target target = { 128 .uid = UINT_MAX, 129 }; 130 131 typedef int (*aggr_get_id_t)(struct cpu_map *m, int cpu); 132 133 static int run_count = 1; 134 static bool no_inherit = false; 135 static volatile pid_t child_pid = -1; 136 static bool null_run = false; 137 static int detailed_run = 0; 138 static bool transaction_run; 139 static bool topdown_run = false; 140 static bool big_num = true; 141 static int big_num_opt = -1; 142 static const char *csv_sep = NULL; 143 static bool csv_output = false; 144 static bool group = false; 145 static const char *pre_cmd = NULL; 146 static const char *post_cmd = NULL; 147 static bool sync_run = false; 148 static unsigned int initial_delay = 0; 149 static unsigned int unit_width = 4; /* strlen("unit") */ 150 static bool forever = false; 151 static bool metric_only = false; 152 static bool force_metric_only = false; 153 static bool no_merge = false; 154 static struct timespec ref_time; 155 static struct cpu_map *aggr_map; 156 static aggr_get_id_t aggr_get_id; 157 static bool append_file; 158 static const char *output_name; 159 static int output_fd; 160 static int print_free_counters_hint; 161 162 struct perf_stat { 163 bool record; 164 struct perf_data_file file; 165 struct perf_session *session; 166 u64 bytes_written; 167 struct perf_tool tool; 168 bool maps_allocated; 169 struct cpu_map *cpus; 170 struct thread_map *threads; 171 enum aggr_mode aggr_mode; 172 }; 173 174 static struct perf_stat perf_stat; 175 #define STAT_RECORD perf_stat.record 176 177 static volatile int done = 0; 178 179 static struct perf_stat_config stat_config = { 180 .aggr_mode = AGGR_GLOBAL, 181 .scale = true, 182 }; 183 184 static inline void diff_timespec(struct timespec *r, struct timespec *a, 185 struct timespec *b) 186 { 187 r->tv_sec = a->tv_sec - b->tv_sec; 188 if (a->tv_nsec < b->tv_nsec) { 189 r->tv_nsec = a->tv_nsec + NSEC_PER_SEC - b->tv_nsec; 190 r->tv_sec--; 191 } else { 192 r->tv_nsec = a->tv_nsec - b->tv_nsec ; 193 } 194 } 195 196 static void perf_stat__reset_stats(void) 197 { 198 perf_evlist__reset_stats(evsel_list); 199 perf_stat__reset_shadow_stats(); 200 } 201 202 static int create_perf_stat_counter(struct perf_evsel *evsel) 203 { 204 struct perf_event_attr *attr = &evsel->attr; 205 206 if (stat_config.scale) 207 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | 208 PERF_FORMAT_TOTAL_TIME_RUNNING; 209 210 attr->inherit = !no_inherit; 211 212 /* 213 * Some events get initialized with sample_(period/type) set, 214 * like tracepoints. Clear it up for counting. 215 */ 216 attr->sample_period = 0; 217 218 /* 219 * But set sample_type to PERF_SAMPLE_IDENTIFIER, which should be harmless 220 * while avoiding that older tools show confusing messages. 221 * 222 * However for pipe sessions we need to keep it zero, 223 * because script's perf_evsel__check_attr is triggered 224 * by attr->sample_type != 0, and we can't run it on 225 * stat sessions. 226 */ 227 if (!(STAT_RECORD && perf_stat.file.is_pipe)) 228 attr->sample_type = PERF_SAMPLE_IDENTIFIER; 229 230 /* 231 * Disabling all counters initially, they will be enabled 232 * either manually by us or by kernel via enable_on_exec 233 * set later. 234 */ 235 if (perf_evsel__is_group_leader(evsel)) { 236 attr->disabled = 1; 237 238 /* 239 * In case of initial_delay we enable tracee 240 * events manually. 241 */ 242 if (target__none(&target) && !initial_delay) 243 attr->enable_on_exec = 1; 244 } 245 246 if (target__has_cpu(&target)) 247 return perf_evsel__open_per_cpu(evsel, perf_evsel__cpus(evsel)); 248 249 return perf_evsel__open_per_thread(evsel, evsel_list->threads); 250 } 251 252 /* 253 * Does the counter have nsecs as a unit? 254 */ 255 static inline int nsec_counter(struct perf_evsel *evsel) 256 { 257 if (perf_evsel__match(evsel, SOFTWARE, SW_CPU_CLOCK) || 258 perf_evsel__match(evsel, SOFTWARE, SW_TASK_CLOCK)) 259 return 1; 260 261 return 0; 262 } 263 264 static int process_synthesized_event(struct perf_tool *tool __maybe_unused, 265 union perf_event *event, 266 struct perf_sample *sample __maybe_unused, 267 struct machine *machine __maybe_unused) 268 { 269 if (perf_data_file__write(&perf_stat.file, event, event->header.size) < 0) { 270 pr_err("failed to write perf data, error: %m\n"); 271 return -1; 272 } 273 274 perf_stat.bytes_written += event->header.size; 275 return 0; 276 } 277 278 static int write_stat_round_event(u64 tm, u64 type) 279 { 280 return perf_event__synthesize_stat_round(NULL, tm, type, 281 process_synthesized_event, 282 NULL); 283 } 284 285 #define WRITE_STAT_ROUND_EVENT(time, interval) \ 286 write_stat_round_event(time, PERF_STAT_ROUND_TYPE__ ## interval) 287 288 #define SID(e, x, y) xyarray__entry(e->sample_id, x, y) 289 290 static int 291 perf_evsel__write_stat_event(struct perf_evsel *counter, u32 cpu, u32 thread, 292 struct perf_counts_values *count) 293 { 294 struct perf_sample_id *sid = SID(counter, cpu, thread); 295 296 return perf_event__synthesize_stat(NULL, cpu, thread, sid->id, count, 297 process_synthesized_event, NULL); 298 } 299 300 /* 301 * Read out the results of a single counter: 302 * do not aggregate counts across CPUs in system-wide mode 303 */ 304 static int read_counter(struct perf_evsel *counter) 305 { 306 int nthreads = thread_map__nr(evsel_list->threads); 307 int ncpus, cpu, thread; 308 309 if (target__has_cpu(&target)) 310 ncpus = perf_evsel__nr_cpus(counter); 311 else 312 ncpus = 1; 313 314 if (!counter->supported) 315 return -ENOENT; 316 317 if (counter->system_wide) 318 nthreads = 1; 319 320 for (thread = 0; thread < nthreads; thread++) { 321 for (cpu = 0; cpu < ncpus; cpu++) { 322 struct perf_counts_values *count; 323 324 count = perf_counts(counter->counts, cpu, thread); 325 if (perf_evsel__read(counter, cpu, thread, count)) { 326 counter->counts->scaled = -1; 327 perf_counts(counter->counts, cpu, thread)->ena = 0; 328 perf_counts(counter->counts, cpu, thread)->run = 0; 329 return -1; 330 } 331 332 if (STAT_RECORD) { 333 if (perf_evsel__write_stat_event(counter, cpu, thread, count)) { 334 pr_err("failed to write stat event\n"); 335 return -1; 336 } 337 } 338 339 if (verbose > 1) { 340 fprintf(stat_config.output, 341 "%s: %d: %" PRIu64 " %" PRIu64 " %" PRIu64 "\n", 342 perf_evsel__name(counter), 343 cpu, 344 count->val, count->ena, count->run); 345 } 346 } 347 } 348 349 return 0; 350 } 351 352 static void read_counters(void) 353 { 354 struct perf_evsel *counter; 355 int ret; 356 357 evlist__for_each_entry(evsel_list, counter) { 358 ret = read_counter(counter); 359 if (ret) 360 pr_debug("failed to read counter %s\n", counter->name); 361 362 if (ret == 0 && perf_stat_process_counter(&stat_config, counter)) 363 pr_warning("failed to process counter %s\n", counter->name); 364 } 365 } 366 367 static void process_interval(void) 368 { 369 struct timespec ts, rs; 370 371 read_counters(); 372 373 clock_gettime(CLOCK_MONOTONIC, &ts); 374 diff_timespec(&rs, &ts, &ref_time); 375 376 if (STAT_RECORD) { 377 if (WRITE_STAT_ROUND_EVENT(rs.tv_sec * NSEC_PER_SEC + rs.tv_nsec, INTERVAL)) 378 pr_err("failed to write stat round event\n"); 379 } 380 381 print_counters(&rs, 0, NULL); 382 } 383 384 static void enable_counters(void) 385 { 386 if (initial_delay) 387 usleep(initial_delay * USEC_PER_MSEC); 388 389 /* 390 * We need to enable counters only if: 391 * - we don't have tracee (attaching to task or cpu) 392 * - we have initial delay configured 393 */ 394 if (!target__none(&target) || initial_delay) 395 perf_evlist__enable(evsel_list); 396 } 397 398 static void disable_counters(void) 399 { 400 /* 401 * If we don't have tracee (attaching to task or cpu), counters may 402 * still be running. To get accurate group ratios, we must stop groups 403 * from counting before reading their constituent counters. 404 */ 405 if (!target__none(&target)) 406 perf_evlist__disable(evsel_list); 407 } 408 409 static volatile int workload_exec_errno; 410 411 /* 412 * perf_evlist__prepare_workload will send a SIGUSR1 413 * if the fork fails, since we asked by setting its 414 * want_signal to true. 415 */ 416 static void workload_exec_failed_signal(int signo __maybe_unused, siginfo_t *info, 417 void *ucontext __maybe_unused) 418 { 419 workload_exec_errno = info->si_value.sival_int; 420 } 421 422 static bool has_unit(struct perf_evsel *counter) 423 { 424 return counter->unit && *counter->unit; 425 } 426 427 static bool has_scale(struct perf_evsel *counter) 428 { 429 return counter->scale != 1; 430 } 431 432 static int perf_stat_synthesize_config(bool is_pipe) 433 { 434 struct perf_evsel *counter; 435 int err; 436 437 if (is_pipe) { 438 err = perf_event__synthesize_attrs(NULL, perf_stat.session, 439 process_synthesized_event); 440 if (err < 0) { 441 pr_err("Couldn't synthesize attrs.\n"); 442 return err; 443 } 444 } 445 446 /* 447 * Synthesize other events stuff not carried within 448 * attr event - unit, scale, name 449 */ 450 evlist__for_each_entry(evsel_list, counter) { 451 if (!counter->supported) 452 continue; 453 454 /* 455 * Synthesize unit and scale only if it's defined. 456 */ 457 if (has_unit(counter)) { 458 err = perf_event__synthesize_event_update_unit(NULL, counter, process_synthesized_event); 459 if (err < 0) { 460 pr_err("Couldn't synthesize evsel unit.\n"); 461 return err; 462 } 463 } 464 465 if (has_scale(counter)) { 466 err = perf_event__synthesize_event_update_scale(NULL, counter, process_synthesized_event); 467 if (err < 0) { 468 pr_err("Couldn't synthesize evsel scale.\n"); 469 return err; 470 } 471 } 472 473 if (counter->own_cpus) { 474 err = perf_event__synthesize_event_update_cpus(NULL, counter, process_synthesized_event); 475 if (err < 0) { 476 pr_err("Couldn't synthesize evsel scale.\n"); 477 return err; 478 } 479 } 480 481 /* 482 * Name is needed only for pipe output, 483 * perf.data carries event names. 484 */ 485 if (is_pipe) { 486 err = perf_event__synthesize_event_update_name(NULL, counter, process_synthesized_event); 487 if (err < 0) { 488 pr_err("Couldn't synthesize evsel name.\n"); 489 return err; 490 } 491 } 492 } 493 494 err = perf_event__synthesize_thread_map2(NULL, evsel_list->threads, 495 process_synthesized_event, 496 NULL); 497 if (err < 0) { 498 pr_err("Couldn't synthesize thread map.\n"); 499 return err; 500 } 501 502 err = perf_event__synthesize_cpu_map(NULL, evsel_list->cpus, 503 process_synthesized_event, NULL); 504 if (err < 0) { 505 pr_err("Couldn't synthesize thread map.\n"); 506 return err; 507 } 508 509 err = perf_event__synthesize_stat_config(NULL, &stat_config, 510 process_synthesized_event, NULL); 511 if (err < 0) { 512 pr_err("Couldn't synthesize config.\n"); 513 return err; 514 } 515 516 return 0; 517 } 518 519 #define FD(e, x, y) (*(int *)xyarray__entry(e->fd, x, y)) 520 521 static int __store_counter_ids(struct perf_evsel *counter, 522 struct cpu_map *cpus, 523 struct thread_map *threads) 524 { 525 int cpu, thread; 526 527 for (cpu = 0; cpu < cpus->nr; cpu++) { 528 for (thread = 0; thread < threads->nr; thread++) { 529 int fd = FD(counter, cpu, thread); 530 531 if (perf_evlist__id_add_fd(evsel_list, counter, 532 cpu, thread, fd) < 0) 533 return -1; 534 } 535 } 536 537 return 0; 538 } 539 540 static int store_counter_ids(struct perf_evsel *counter) 541 { 542 struct cpu_map *cpus = counter->cpus; 543 struct thread_map *threads = counter->threads; 544 545 if (perf_evsel__alloc_id(counter, cpus->nr, threads->nr)) 546 return -ENOMEM; 547 548 return __store_counter_ids(counter, cpus, threads); 549 } 550 551 static int __run_perf_stat(int argc, const char **argv) 552 { 553 int interval = stat_config.interval; 554 char msg[BUFSIZ]; 555 unsigned long long t0, t1; 556 struct perf_evsel *counter; 557 struct timespec ts; 558 size_t l; 559 int status = 0; 560 const bool forks = (argc > 0); 561 bool is_pipe = STAT_RECORD ? perf_stat.file.is_pipe : false; 562 struct perf_evsel_config_term *err_term; 563 564 if (interval) { 565 ts.tv_sec = interval / USEC_PER_MSEC; 566 ts.tv_nsec = (interval % USEC_PER_MSEC) * NSEC_PER_MSEC; 567 } else { 568 ts.tv_sec = 1; 569 ts.tv_nsec = 0; 570 } 571 572 if (forks) { 573 if (perf_evlist__prepare_workload(evsel_list, &target, argv, is_pipe, 574 workload_exec_failed_signal) < 0) { 575 perror("failed to prepare workload"); 576 return -1; 577 } 578 child_pid = evsel_list->workload.pid; 579 } 580 581 if (group) 582 perf_evlist__set_leader(evsel_list); 583 584 evlist__for_each_entry(evsel_list, counter) { 585 try_again: 586 if (create_perf_stat_counter(counter) < 0) { 587 /* 588 * PPC returns ENXIO for HW counters until 2.6.37 589 * (behavior changed with commit b0a873e). 590 */ 591 if (errno == EINVAL || errno == ENOSYS || 592 errno == ENOENT || errno == EOPNOTSUPP || 593 errno == ENXIO) { 594 if (verbose > 0) 595 ui__warning("%s event is not supported by the kernel.\n", 596 perf_evsel__name(counter)); 597 counter->supported = false; 598 599 if ((counter->leader != counter) || 600 !(counter->leader->nr_members > 1)) 601 continue; 602 } else if (perf_evsel__fallback(counter, errno, msg, sizeof(msg))) { 603 if (verbose > 0) 604 ui__warning("%s\n", msg); 605 goto try_again; 606 } 607 608 perf_evsel__open_strerror(counter, &target, 609 errno, msg, sizeof(msg)); 610 ui__error("%s\n", msg); 611 612 if (child_pid != -1) 613 kill(child_pid, SIGTERM); 614 615 return -1; 616 } 617 counter->supported = true; 618 619 l = strlen(counter->unit); 620 if (l > unit_width) 621 unit_width = l; 622 623 if (STAT_RECORD && store_counter_ids(counter)) 624 return -1; 625 } 626 627 if (perf_evlist__apply_filters(evsel_list, &counter)) { 628 error("failed to set filter \"%s\" on event %s with %d (%s)\n", 629 counter->filter, perf_evsel__name(counter), errno, 630 str_error_r(errno, msg, sizeof(msg))); 631 return -1; 632 } 633 634 if (perf_evlist__apply_drv_configs(evsel_list, &counter, &err_term)) { 635 error("failed to set config \"%s\" on event %s with %d (%s)\n", 636 err_term->val.drv_cfg, perf_evsel__name(counter), errno, 637 str_error_r(errno, msg, sizeof(msg))); 638 return -1; 639 } 640 641 if (STAT_RECORD) { 642 int err, fd = perf_data_file__fd(&perf_stat.file); 643 644 if (is_pipe) { 645 err = perf_header__write_pipe(perf_data_file__fd(&perf_stat.file)); 646 } else { 647 err = perf_session__write_header(perf_stat.session, evsel_list, 648 fd, false); 649 } 650 651 if (err < 0) 652 return err; 653 654 err = perf_stat_synthesize_config(is_pipe); 655 if (err < 0) 656 return err; 657 } 658 659 /* 660 * Enable counters and exec the command: 661 */ 662 t0 = rdclock(); 663 clock_gettime(CLOCK_MONOTONIC, &ref_time); 664 665 if (forks) { 666 perf_evlist__start_workload(evsel_list); 667 enable_counters(); 668 669 if (interval) { 670 while (!waitpid(child_pid, &status, WNOHANG)) { 671 nanosleep(&ts, NULL); 672 process_interval(); 673 } 674 } 675 wait(&status); 676 677 if (workload_exec_errno) { 678 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg)); 679 pr_err("Workload failed: %s\n", emsg); 680 return -1; 681 } 682 683 if (WIFSIGNALED(status)) 684 psignal(WTERMSIG(status), argv[0]); 685 } else { 686 enable_counters(); 687 while (!done) { 688 nanosleep(&ts, NULL); 689 if (interval) 690 process_interval(); 691 } 692 } 693 694 disable_counters(); 695 696 t1 = rdclock(); 697 698 update_stats(&walltime_nsecs_stats, t1 - t0); 699 700 /* 701 * Closing a group leader splits the group, and as we only disable 702 * group leaders, results in remaining events becoming enabled. To 703 * avoid arbitrary skew, we must read all counters before closing any 704 * group leaders. 705 */ 706 read_counters(); 707 perf_evlist__close(evsel_list); 708 709 return WEXITSTATUS(status); 710 } 711 712 static int run_perf_stat(int argc, const char **argv) 713 { 714 int ret; 715 716 if (pre_cmd) { 717 ret = system(pre_cmd); 718 if (ret) 719 return ret; 720 } 721 722 if (sync_run) 723 sync(); 724 725 ret = __run_perf_stat(argc, argv); 726 if (ret) 727 return ret; 728 729 if (post_cmd) { 730 ret = system(post_cmd); 731 if (ret) 732 return ret; 733 } 734 735 return ret; 736 } 737 738 static void print_running(u64 run, u64 ena) 739 { 740 if (csv_output) { 741 fprintf(stat_config.output, "%s%" PRIu64 "%s%.2f", 742 csv_sep, 743 run, 744 csv_sep, 745 ena ? 100.0 * run / ena : 100.0); 746 } else if (run != ena) { 747 fprintf(stat_config.output, " (%.2f%%)", 100.0 * run / ena); 748 } 749 } 750 751 static void print_noise_pct(double total, double avg) 752 { 753 double pct = rel_stddev_stats(total, avg); 754 755 if (csv_output) 756 fprintf(stat_config.output, "%s%.2f%%", csv_sep, pct); 757 else if (pct) 758 fprintf(stat_config.output, " ( +-%6.2f%% )", pct); 759 } 760 761 static void print_noise(struct perf_evsel *evsel, double avg) 762 { 763 struct perf_stat_evsel *ps; 764 765 if (run_count == 1) 766 return; 767 768 ps = evsel->priv; 769 print_noise_pct(stddev_stats(&ps->res_stats[0]), avg); 770 } 771 772 static void aggr_printout(struct perf_evsel *evsel, int id, int nr) 773 { 774 switch (stat_config.aggr_mode) { 775 case AGGR_CORE: 776 fprintf(stat_config.output, "S%d-C%*d%s%*d%s", 777 cpu_map__id_to_socket(id), 778 csv_output ? 0 : -8, 779 cpu_map__id_to_cpu(id), 780 csv_sep, 781 csv_output ? 0 : 4, 782 nr, 783 csv_sep); 784 break; 785 case AGGR_SOCKET: 786 fprintf(stat_config.output, "S%*d%s%*d%s", 787 csv_output ? 0 : -5, 788 id, 789 csv_sep, 790 csv_output ? 0 : 4, 791 nr, 792 csv_sep); 793 break; 794 case AGGR_NONE: 795 fprintf(stat_config.output, "CPU%*d%s", 796 csv_output ? 0 : -4, 797 perf_evsel__cpus(evsel)->map[id], csv_sep); 798 break; 799 case AGGR_THREAD: 800 fprintf(stat_config.output, "%*s-%*d%s", 801 csv_output ? 0 : 16, 802 thread_map__comm(evsel->threads, id), 803 csv_output ? 0 : -8, 804 thread_map__pid(evsel->threads, id), 805 csv_sep); 806 break; 807 case AGGR_GLOBAL: 808 case AGGR_UNSET: 809 default: 810 break; 811 } 812 } 813 814 struct outstate { 815 FILE *fh; 816 bool newline; 817 const char *prefix; 818 int nfields; 819 int id, nr; 820 struct perf_evsel *evsel; 821 }; 822 823 #define METRIC_LEN 35 824 825 static void new_line_std(void *ctx) 826 { 827 struct outstate *os = ctx; 828 829 os->newline = true; 830 } 831 832 static void do_new_line_std(struct outstate *os) 833 { 834 fputc('\n', os->fh); 835 fputs(os->prefix, os->fh); 836 aggr_printout(os->evsel, os->id, os->nr); 837 if (stat_config.aggr_mode == AGGR_NONE) 838 fprintf(os->fh, " "); 839 fprintf(os->fh, " "); 840 } 841 842 static void print_metric_std(void *ctx, const char *color, const char *fmt, 843 const char *unit, double val) 844 { 845 struct outstate *os = ctx; 846 FILE *out = os->fh; 847 int n; 848 bool newline = os->newline; 849 850 os->newline = false; 851 852 if (unit == NULL || fmt == NULL) { 853 fprintf(out, "%-*s", METRIC_LEN, ""); 854 return; 855 } 856 857 if (newline) 858 do_new_line_std(os); 859 860 n = fprintf(out, " # "); 861 if (color) 862 n += color_fprintf(out, color, fmt, val); 863 else 864 n += fprintf(out, fmt, val); 865 fprintf(out, " %-*s", METRIC_LEN - n - 1, unit); 866 } 867 868 static void new_line_csv(void *ctx) 869 { 870 struct outstate *os = ctx; 871 int i; 872 873 fputc('\n', os->fh); 874 if (os->prefix) 875 fprintf(os->fh, "%s%s", os->prefix, csv_sep); 876 aggr_printout(os->evsel, os->id, os->nr); 877 for (i = 0; i < os->nfields; i++) 878 fputs(csv_sep, os->fh); 879 } 880 881 static void print_metric_csv(void *ctx, 882 const char *color __maybe_unused, 883 const char *fmt, const char *unit, double val) 884 { 885 struct outstate *os = ctx; 886 FILE *out = os->fh; 887 char buf[64], *vals, *ends; 888 889 if (unit == NULL || fmt == NULL) { 890 fprintf(out, "%s%s%s%s", csv_sep, csv_sep, csv_sep, csv_sep); 891 return; 892 } 893 snprintf(buf, sizeof(buf), fmt, val); 894 ends = vals = ltrim(buf); 895 while (isdigit(*ends) || *ends == '.') 896 ends++; 897 *ends = 0; 898 while (isspace(*unit)) 899 unit++; 900 fprintf(out, "%s%s%s%s", csv_sep, vals, csv_sep, unit); 901 } 902 903 #define METRIC_ONLY_LEN 20 904 905 /* Filter out some columns that don't work well in metrics only mode */ 906 907 static bool valid_only_metric(const char *unit) 908 { 909 if (!unit) 910 return false; 911 if (strstr(unit, "/sec") || 912 strstr(unit, "hz") || 913 strstr(unit, "Hz") || 914 strstr(unit, "CPUs utilized")) 915 return false; 916 return true; 917 } 918 919 static const char *fixunit(char *buf, struct perf_evsel *evsel, 920 const char *unit) 921 { 922 if (!strncmp(unit, "of all", 6)) { 923 snprintf(buf, 1024, "%s %s", perf_evsel__name(evsel), 924 unit); 925 return buf; 926 } 927 return unit; 928 } 929 930 static void print_metric_only(void *ctx, const char *color, const char *fmt, 931 const char *unit, double val) 932 { 933 struct outstate *os = ctx; 934 FILE *out = os->fh; 935 int n; 936 char buf[1024]; 937 unsigned mlen = METRIC_ONLY_LEN; 938 939 if (!valid_only_metric(unit)) 940 return; 941 unit = fixunit(buf, os->evsel, unit); 942 if (color) 943 n = color_fprintf(out, color, fmt, val); 944 else 945 n = fprintf(out, fmt, val); 946 if (n > METRIC_ONLY_LEN) 947 n = METRIC_ONLY_LEN; 948 if (mlen < strlen(unit)) 949 mlen = strlen(unit) + 1; 950 fprintf(out, "%*s", mlen - n, ""); 951 } 952 953 static void print_metric_only_csv(void *ctx, const char *color __maybe_unused, 954 const char *fmt, 955 const char *unit, double val) 956 { 957 struct outstate *os = ctx; 958 FILE *out = os->fh; 959 char buf[64], *vals, *ends; 960 char tbuf[1024]; 961 962 if (!valid_only_metric(unit)) 963 return; 964 unit = fixunit(tbuf, os->evsel, unit); 965 snprintf(buf, sizeof buf, fmt, val); 966 ends = vals = ltrim(buf); 967 while (isdigit(*ends) || *ends == '.') 968 ends++; 969 *ends = 0; 970 fprintf(out, "%s%s", vals, csv_sep); 971 } 972 973 static void new_line_metric(void *ctx __maybe_unused) 974 { 975 } 976 977 static void print_metric_header(void *ctx, const char *color __maybe_unused, 978 const char *fmt __maybe_unused, 979 const char *unit, double val __maybe_unused) 980 { 981 struct outstate *os = ctx; 982 char tbuf[1024]; 983 984 if (!valid_only_metric(unit)) 985 return; 986 unit = fixunit(tbuf, os->evsel, unit); 987 if (csv_output) 988 fprintf(os->fh, "%s%s", unit, csv_sep); 989 else 990 fprintf(os->fh, "%-*s ", METRIC_ONLY_LEN, unit); 991 } 992 993 static void nsec_printout(int id, int nr, struct perf_evsel *evsel, double avg) 994 { 995 FILE *output = stat_config.output; 996 double msecs = avg / NSEC_PER_MSEC; 997 const char *fmt_v, *fmt_n; 998 char name[25]; 999 1000 fmt_v = csv_output ? "%.6f%s" : "%18.6f%s"; 1001 fmt_n = csv_output ? "%s" : "%-25s"; 1002 1003 aggr_printout(evsel, id, nr); 1004 1005 scnprintf(name, sizeof(name), "%s%s", 1006 perf_evsel__name(evsel), csv_output ? "" : " (msec)"); 1007 1008 fprintf(output, fmt_v, msecs, csv_sep); 1009 1010 if (csv_output) 1011 fprintf(output, "%s%s", evsel->unit, csv_sep); 1012 else 1013 fprintf(output, "%-*s%s", unit_width, evsel->unit, csv_sep); 1014 1015 fprintf(output, fmt_n, name); 1016 1017 if (evsel->cgrp) 1018 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name); 1019 } 1020 1021 static int first_shadow_cpu(struct perf_evsel *evsel, int id) 1022 { 1023 int i; 1024 1025 if (!aggr_get_id) 1026 return 0; 1027 1028 if (stat_config.aggr_mode == AGGR_NONE) 1029 return id; 1030 1031 if (stat_config.aggr_mode == AGGR_GLOBAL) 1032 return 0; 1033 1034 for (i = 0; i < perf_evsel__nr_cpus(evsel); i++) { 1035 int cpu2 = perf_evsel__cpus(evsel)->map[i]; 1036 1037 if (aggr_get_id(evsel_list->cpus, cpu2) == id) 1038 return cpu2; 1039 } 1040 return 0; 1041 } 1042 1043 static void abs_printout(int id, int nr, struct perf_evsel *evsel, double avg) 1044 { 1045 FILE *output = stat_config.output; 1046 double sc = evsel->scale; 1047 const char *fmt; 1048 1049 if (csv_output) { 1050 fmt = floor(sc) != sc ? "%.2f%s" : "%.0f%s"; 1051 } else { 1052 if (big_num) 1053 fmt = floor(sc) != sc ? "%'18.2f%s" : "%'18.0f%s"; 1054 else 1055 fmt = floor(sc) != sc ? "%18.2f%s" : "%18.0f%s"; 1056 } 1057 1058 aggr_printout(evsel, id, nr); 1059 1060 fprintf(output, fmt, avg, csv_sep); 1061 1062 if (evsel->unit) 1063 fprintf(output, "%-*s%s", 1064 csv_output ? 0 : unit_width, 1065 evsel->unit, csv_sep); 1066 1067 fprintf(output, "%-*s", csv_output ? 0 : 25, perf_evsel__name(evsel)); 1068 1069 if (evsel->cgrp) 1070 fprintf(output, "%s%s", csv_sep, evsel->cgrp->name); 1071 } 1072 1073 static void printout(int id, int nr, struct perf_evsel *counter, double uval, 1074 char *prefix, u64 run, u64 ena, double noise) 1075 { 1076 struct perf_stat_output_ctx out; 1077 struct outstate os = { 1078 .fh = stat_config.output, 1079 .prefix = prefix ? prefix : "", 1080 .id = id, 1081 .nr = nr, 1082 .evsel = counter, 1083 }; 1084 print_metric_t pm = print_metric_std; 1085 void (*nl)(void *); 1086 1087 if (metric_only) { 1088 nl = new_line_metric; 1089 if (csv_output) 1090 pm = print_metric_only_csv; 1091 else 1092 pm = print_metric_only; 1093 } else 1094 nl = new_line_std; 1095 1096 if (csv_output && !metric_only) { 1097 static int aggr_fields[] = { 1098 [AGGR_GLOBAL] = 0, 1099 [AGGR_THREAD] = 1, 1100 [AGGR_NONE] = 1, 1101 [AGGR_SOCKET] = 2, 1102 [AGGR_CORE] = 2, 1103 }; 1104 1105 pm = print_metric_csv; 1106 nl = new_line_csv; 1107 os.nfields = 3; 1108 os.nfields += aggr_fields[stat_config.aggr_mode]; 1109 if (counter->cgrp) 1110 os.nfields++; 1111 } 1112 if (run == 0 || ena == 0 || counter->counts->scaled == -1) { 1113 if (metric_only) { 1114 pm(&os, NULL, "", "", 0); 1115 return; 1116 } 1117 aggr_printout(counter, id, nr); 1118 1119 fprintf(stat_config.output, "%*s%s", 1120 csv_output ? 0 : 18, 1121 counter->supported ? CNTR_NOT_COUNTED : CNTR_NOT_SUPPORTED, 1122 csv_sep); 1123 1124 if (counter->supported) 1125 print_free_counters_hint = 1; 1126 1127 fprintf(stat_config.output, "%-*s%s", 1128 csv_output ? 0 : unit_width, 1129 counter->unit, csv_sep); 1130 1131 fprintf(stat_config.output, "%*s", 1132 csv_output ? 0 : -25, 1133 perf_evsel__name(counter)); 1134 1135 if (counter->cgrp) 1136 fprintf(stat_config.output, "%s%s", 1137 csv_sep, counter->cgrp->name); 1138 1139 if (!csv_output) 1140 pm(&os, NULL, NULL, "", 0); 1141 print_noise(counter, noise); 1142 print_running(run, ena); 1143 if (csv_output) 1144 pm(&os, NULL, NULL, "", 0); 1145 return; 1146 } 1147 1148 if (metric_only) 1149 /* nothing */; 1150 else if (nsec_counter(counter)) 1151 nsec_printout(id, nr, counter, uval); 1152 else 1153 abs_printout(id, nr, counter, uval); 1154 1155 out.print_metric = pm; 1156 out.new_line = nl; 1157 out.ctx = &os; 1158 out.force_header = false; 1159 1160 if (csv_output && !metric_only) { 1161 print_noise(counter, noise); 1162 print_running(run, ena); 1163 } 1164 1165 perf_stat__print_shadow_stats(counter, uval, 1166 first_shadow_cpu(counter, id), 1167 &out); 1168 if (!csv_output && !metric_only) { 1169 print_noise(counter, noise); 1170 print_running(run, ena); 1171 } 1172 } 1173 1174 static void aggr_update_shadow(void) 1175 { 1176 int cpu, s2, id, s; 1177 u64 val; 1178 struct perf_evsel *counter; 1179 1180 for (s = 0; s < aggr_map->nr; s++) { 1181 id = aggr_map->map[s]; 1182 evlist__for_each_entry(evsel_list, counter) { 1183 val = 0; 1184 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) { 1185 s2 = aggr_get_id(evsel_list->cpus, cpu); 1186 if (s2 != id) 1187 continue; 1188 val += perf_counts(counter->counts, cpu, 0)->val; 1189 } 1190 val = val * counter->scale; 1191 perf_stat__update_shadow_stats(counter, &val, 1192 first_shadow_cpu(counter, id)); 1193 } 1194 } 1195 } 1196 1197 static void collect_all_aliases(struct perf_evsel *counter, 1198 void (*cb)(struct perf_evsel *counter, void *data, 1199 bool first), 1200 void *data) 1201 { 1202 struct perf_evsel *alias; 1203 1204 alias = list_prepare_entry(counter, &(evsel_list->entries), node); 1205 list_for_each_entry_continue (alias, &evsel_list->entries, node) { 1206 if (strcmp(perf_evsel__name(alias), perf_evsel__name(counter)) || 1207 alias->scale != counter->scale || 1208 alias->cgrp != counter->cgrp || 1209 strcmp(alias->unit, counter->unit) || 1210 nsec_counter(alias) != nsec_counter(counter)) 1211 break; 1212 alias->merged_stat = true; 1213 cb(alias, data, false); 1214 } 1215 } 1216 1217 static bool collect_data(struct perf_evsel *counter, 1218 void (*cb)(struct perf_evsel *counter, void *data, 1219 bool first), 1220 void *data) 1221 { 1222 if (counter->merged_stat) 1223 return false; 1224 cb(counter, data, true); 1225 if (!no_merge) 1226 collect_all_aliases(counter, cb, data); 1227 return true; 1228 } 1229 1230 struct aggr_data { 1231 u64 ena, run, val; 1232 int id; 1233 int nr; 1234 int cpu; 1235 }; 1236 1237 static void aggr_cb(struct perf_evsel *counter, void *data, bool first) 1238 { 1239 struct aggr_data *ad = data; 1240 int cpu, s2; 1241 1242 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) { 1243 struct perf_counts_values *counts; 1244 1245 s2 = aggr_get_id(perf_evsel__cpus(counter), cpu); 1246 if (s2 != ad->id) 1247 continue; 1248 if (first) 1249 ad->nr++; 1250 counts = perf_counts(counter->counts, cpu, 0); 1251 /* 1252 * When any result is bad, make them all to give 1253 * consistent output in interval mode. 1254 */ 1255 if (counts->ena == 0 || counts->run == 0 || 1256 counter->counts->scaled == -1) { 1257 ad->ena = 0; 1258 ad->run = 0; 1259 break; 1260 } 1261 ad->val += counts->val; 1262 ad->ena += counts->ena; 1263 ad->run += counts->run; 1264 } 1265 } 1266 1267 static void print_aggr(char *prefix) 1268 { 1269 FILE *output = stat_config.output; 1270 struct perf_evsel *counter; 1271 int s, id, nr; 1272 double uval; 1273 u64 ena, run, val; 1274 bool first; 1275 1276 if (!(aggr_map || aggr_get_id)) 1277 return; 1278 1279 aggr_update_shadow(); 1280 1281 /* 1282 * With metric_only everything is on a single line. 1283 * Without each counter has its own line. 1284 */ 1285 for (s = 0; s < aggr_map->nr; s++) { 1286 struct aggr_data ad; 1287 if (prefix && metric_only) 1288 fprintf(output, "%s", prefix); 1289 1290 ad.id = id = aggr_map->map[s]; 1291 first = true; 1292 evlist__for_each_entry(evsel_list, counter) { 1293 ad.val = ad.ena = ad.run = 0; 1294 ad.nr = 0; 1295 if (!collect_data(counter, aggr_cb, &ad)) 1296 continue; 1297 nr = ad.nr; 1298 ena = ad.ena; 1299 run = ad.run; 1300 val = ad.val; 1301 if (first && metric_only) { 1302 first = false; 1303 aggr_printout(counter, id, nr); 1304 } 1305 if (prefix && !metric_only) 1306 fprintf(output, "%s", prefix); 1307 1308 uval = val * counter->scale; 1309 printout(id, nr, counter, uval, prefix, run, ena, 1.0); 1310 if (!metric_only) 1311 fputc('\n', output); 1312 } 1313 if (metric_only) 1314 fputc('\n', output); 1315 } 1316 } 1317 1318 static void print_aggr_thread(struct perf_evsel *counter, char *prefix) 1319 { 1320 FILE *output = stat_config.output; 1321 int nthreads = thread_map__nr(counter->threads); 1322 int ncpus = cpu_map__nr(counter->cpus); 1323 int cpu, thread; 1324 double uval; 1325 1326 for (thread = 0; thread < nthreads; thread++) { 1327 u64 ena = 0, run = 0, val = 0; 1328 1329 for (cpu = 0; cpu < ncpus; cpu++) { 1330 val += perf_counts(counter->counts, cpu, thread)->val; 1331 ena += perf_counts(counter->counts, cpu, thread)->ena; 1332 run += perf_counts(counter->counts, cpu, thread)->run; 1333 } 1334 1335 if (prefix) 1336 fprintf(output, "%s", prefix); 1337 1338 uval = val * counter->scale; 1339 printout(thread, 0, counter, uval, prefix, run, ena, 1.0); 1340 fputc('\n', output); 1341 } 1342 } 1343 1344 struct caggr_data { 1345 double avg, avg_enabled, avg_running; 1346 }; 1347 1348 static void counter_aggr_cb(struct perf_evsel *counter, void *data, 1349 bool first __maybe_unused) 1350 { 1351 struct caggr_data *cd = data; 1352 struct perf_stat_evsel *ps = counter->priv; 1353 1354 cd->avg += avg_stats(&ps->res_stats[0]); 1355 cd->avg_enabled += avg_stats(&ps->res_stats[1]); 1356 cd->avg_running += avg_stats(&ps->res_stats[2]); 1357 } 1358 1359 /* 1360 * Print out the results of a single counter: 1361 * aggregated counts in system-wide mode 1362 */ 1363 static void print_counter_aggr(struct perf_evsel *counter, char *prefix) 1364 { 1365 FILE *output = stat_config.output; 1366 double uval; 1367 struct caggr_data cd = { .avg = 0.0 }; 1368 1369 if (!collect_data(counter, counter_aggr_cb, &cd)) 1370 return; 1371 1372 if (prefix && !metric_only) 1373 fprintf(output, "%s", prefix); 1374 1375 uval = cd.avg * counter->scale; 1376 printout(-1, 0, counter, uval, prefix, cd.avg_running, cd.avg_enabled, cd.avg); 1377 if (!metric_only) 1378 fprintf(output, "\n"); 1379 } 1380 1381 static void counter_cb(struct perf_evsel *counter, void *data, 1382 bool first __maybe_unused) 1383 { 1384 struct aggr_data *ad = data; 1385 1386 ad->val += perf_counts(counter->counts, ad->cpu, 0)->val; 1387 ad->ena += perf_counts(counter->counts, ad->cpu, 0)->ena; 1388 ad->run += perf_counts(counter->counts, ad->cpu, 0)->run; 1389 } 1390 1391 /* 1392 * Print out the results of a single counter: 1393 * does not use aggregated count in system-wide 1394 */ 1395 static void print_counter(struct perf_evsel *counter, char *prefix) 1396 { 1397 FILE *output = stat_config.output; 1398 u64 ena, run, val; 1399 double uval; 1400 int cpu; 1401 1402 for (cpu = 0; cpu < perf_evsel__nr_cpus(counter); cpu++) { 1403 struct aggr_data ad = { .cpu = cpu }; 1404 1405 if (!collect_data(counter, counter_cb, &ad)) 1406 return; 1407 val = ad.val; 1408 ena = ad.ena; 1409 run = ad.run; 1410 1411 if (prefix) 1412 fprintf(output, "%s", prefix); 1413 1414 uval = val * counter->scale; 1415 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0); 1416 1417 fputc('\n', output); 1418 } 1419 } 1420 1421 static void print_no_aggr_metric(char *prefix) 1422 { 1423 int cpu; 1424 int nrcpus = 0; 1425 struct perf_evsel *counter; 1426 u64 ena, run, val; 1427 double uval; 1428 1429 nrcpus = evsel_list->cpus->nr; 1430 for (cpu = 0; cpu < nrcpus; cpu++) { 1431 bool first = true; 1432 1433 if (prefix) 1434 fputs(prefix, stat_config.output); 1435 evlist__for_each_entry(evsel_list, counter) { 1436 if (first) { 1437 aggr_printout(counter, cpu, 0); 1438 first = false; 1439 } 1440 val = perf_counts(counter->counts, cpu, 0)->val; 1441 ena = perf_counts(counter->counts, cpu, 0)->ena; 1442 run = perf_counts(counter->counts, cpu, 0)->run; 1443 1444 uval = val * counter->scale; 1445 printout(cpu, 0, counter, uval, prefix, run, ena, 1.0); 1446 } 1447 fputc('\n', stat_config.output); 1448 } 1449 } 1450 1451 static int aggr_header_lens[] = { 1452 [AGGR_CORE] = 18, 1453 [AGGR_SOCKET] = 12, 1454 [AGGR_NONE] = 6, 1455 [AGGR_THREAD] = 24, 1456 [AGGR_GLOBAL] = 0, 1457 }; 1458 1459 static const char *aggr_header_csv[] = { 1460 [AGGR_CORE] = "core,cpus,", 1461 [AGGR_SOCKET] = "socket,cpus", 1462 [AGGR_NONE] = "cpu,", 1463 [AGGR_THREAD] = "comm-pid,", 1464 [AGGR_GLOBAL] = "" 1465 }; 1466 1467 static void print_metric_headers(const char *prefix, bool no_indent) 1468 { 1469 struct perf_stat_output_ctx out; 1470 struct perf_evsel *counter; 1471 struct outstate os = { 1472 .fh = stat_config.output 1473 }; 1474 1475 if (prefix) 1476 fprintf(stat_config.output, "%s", prefix); 1477 1478 if (!csv_output && !no_indent) 1479 fprintf(stat_config.output, "%*s", 1480 aggr_header_lens[stat_config.aggr_mode], ""); 1481 if (csv_output) { 1482 if (stat_config.interval) 1483 fputs("time,", stat_config.output); 1484 fputs(aggr_header_csv[stat_config.aggr_mode], 1485 stat_config.output); 1486 } 1487 1488 /* Print metrics headers only */ 1489 evlist__for_each_entry(evsel_list, counter) { 1490 os.evsel = counter; 1491 out.ctx = &os; 1492 out.print_metric = print_metric_header; 1493 out.new_line = new_line_metric; 1494 out.force_header = true; 1495 os.evsel = counter; 1496 perf_stat__print_shadow_stats(counter, 0, 1497 0, 1498 &out); 1499 } 1500 fputc('\n', stat_config.output); 1501 } 1502 1503 static void print_interval(char *prefix, struct timespec *ts) 1504 { 1505 FILE *output = stat_config.output; 1506 static int num_print_interval; 1507 1508 sprintf(prefix, "%6lu.%09lu%s", ts->tv_sec, ts->tv_nsec, csv_sep); 1509 1510 if (num_print_interval == 0 && !csv_output) { 1511 switch (stat_config.aggr_mode) { 1512 case AGGR_SOCKET: 1513 fprintf(output, "# time socket cpus"); 1514 if (!metric_only) 1515 fprintf(output, " counts %*s events\n", unit_width, "unit"); 1516 break; 1517 case AGGR_CORE: 1518 fprintf(output, "# time core cpus"); 1519 if (!metric_only) 1520 fprintf(output, " counts %*s events\n", unit_width, "unit"); 1521 break; 1522 case AGGR_NONE: 1523 fprintf(output, "# time CPU"); 1524 if (!metric_only) 1525 fprintf(output, " counts %*s events\n", unit_width, "unit"); 1526 break; 1527 case AGGR_THREAD: 1528 fprintf(output, "# time comm-pid"); 1529 if (!metric_only) 1530 fprintf(output, " counts %*s events\n", unit_width, "unit"); 1531 break; 1532 case AGGR_GLOBAL: 1533 default: 1534 fprintf(output, "# time"); 1535 if (!metric_only) 1536 fprintf(output, " counts %*s events\n", unit_width, "unit"); 1537 case AGGR_UNSET: 1538 break; 1539 } 1540 } 1541 1542 if (num_print_interval == 0 && metric_only) 1543 print_metric_headers(" ", true); 1544 if (++num_print_interval == 25) 1545 num_print_interval = 0; 1546 } 1547 1548 static void print_header(int argc, const char **argv) 1549 { 1550 FILE *output = stat_config.output; 1551 int i; 1552 1553 fflush(stdout); 1554 1555 if (!csv_output) { 1556 fprintf(output, "\n"); 1557 fprintf(output, " Performance counter stats for "); 1558 if (target.system_wide) 1559 fprintf(output, "\'system wide"); 1560 else if (target.cpu_list) 1561 fprintf(output, "\'CPU(s) %s", target.cpu_list); 1562 else if (!target__has_task(&target)) { 1563 fprintf(output, "\'%s", argv ? argv[0] : "pipe"); 1564 for (i = 1; argv && (i < argc); i++) 1565 fprintf(output, " %s", argv[i]); 1566 } else if (target.pid) 1567 fprintf(output, "process id \'%s", target.pid); 1568 else 1569 fprintf(output, "thread id \'%s", target.tid); 1570 1571 fprintf(output, "\'"); 1572 if (run_count > 1) 1573 fprintf(output, " (%d runs)", run_count); 1574 fprintf(output, ":\n\n"); 1575 } 1576 } 1577 1578 static void print_footer(void) 1579 { 1580 FILE *output = stat_config.output; 1581 int n; 1582 1583 if (!null_run) 1584 fprintf(output, "\n"); 1585 fprintf(output, " %17.9f seconds time elapsed", 1586 avg_stats(&walltime_nsecs_stats) / NSEC_PER_SEC); 1587 if (run_count > 1) { 1588 fprintf(output, " "); 1589 print_noise_pct(stddev_stats(&walltime_nsecs_stats), 1590 avg_stats(&walltime_nsecs_stats)); 1591 } 1592 fprintf(output, "\n\n"); 1593 1594 if (print_free_counters_hint && 1595 sysctl__read_int("kernel/nmi_watchdog", &n) >= 0 && 1596 n > 0) 1597 fprintf(output, 1598 "Some events weren't counted. Try disabling the NMI watchdog:\n" 1599 " echo 0 > /proc/sys/kernel/nmi_watchdog\n" 1600 " perf stat ...\n" 1601 " echo 1 > /proc/sys/kernel/nmi_watchdog\n"); 1602 } 1603 1604 static void print_counters(struct timespec *ts, int argc, const char **argv) 1605 { 1606 int interval = stat_config.interval; 1607 struct perf_evsel *counter; 1608 char buf[64], *prefix = NULL; 1609 1610 /* Do not print anything if we record to the pipe. */ 1611 if (STAT_RECORD && perf_stat.file.is_pipe) 1612 return; 1613 1614 if (interval) 1615 print_interval(prefix = buf, ts); 1616 else 1617 print_header(argc, argv); 1618 1619 if (metric_only) { 1620 static int num_print_iv; 1621 1622 if (num_print_iv == 0 && !interval) 1623 print_metric_headers(prefix, false); 1624 if (num_print_iv++ == 25) 1625 num_print_iv = 0; 1626 if (stat_config.aggr_mode == AGGR_GLOBAL && prefix) 1627 fprintf(stat_config.output, "%s", prefix); 1628 } 1629 1630 switch (stat_config.aggr_mode) { 1631 case AGGR_CORE: 1632 case AGGR_SOCKET: 1633 print_aggr(prefix); 1634 break; 1635 case AGGR_THREAD: 1636 evlist__for_each_entry(evsel_list, counter) 1637 print_aggr_thread(counter, prefix); 1638 break; 1639 case AGGR_GLOBAL: 1640 evlist__for_each_entry(evsel_list, counter) 1641 print_counter_aggr(counter, prefix); 1642 if (metric_only) 1643 fputc('\n', stat_config.output); 1644 break; 1645 case AGGR_NONE: 1646 if (metric_only) 1647 print_no_aggr_metric(prefix); 1648 else { 1649 evlist__for_each_entry(evsel_list, counter) 1650 print_counter(counter, prefix); 1651 } 1652 break; 1653 case AGGR_UNSET: 1654 default: 1655 break; 1656 } 1657 1658 if (!interval && !csv_output) 1659 print_footer(); 1660 1661 fflush(stat_config.output); 1662 } 1663 1664 static volatile int signr = -1; 1665 1666 static void skip_signal(int signo) 1667 { 1668 if ((child_pid == -1) || stat_config.interval) 1669 done = 1; 1670 1671 signr = signo; 1672 /* 1673 * render child_pid harmless 1674 * won't send SIGTERM to a random 1675 * process in case of race condition 1676 * and fast PID recycling 1677 */ 1678 child_pid = -1; 1679 } 1680 1681 static void sig_atexit(void) 1682 { 1683 sigset_t set, oset; 1684 1685 /* 1686 * avoid race condition with SIGCHLD handler 1687 * in skip_signal() which is modifying child_pid 1688 * goal is to avoid send SIGTERM to a random 1689 * process 1690 */ 1691 sigemptyset(&set); 1692 sigaddset(&set, SIGCHLD); 1693 sigprocmask(SIG_BLOCK, &set, &oset); 1694 1695 if (child_pid != -1) 1696 kill(child_pid, SIGTERM); 1697 1698 sigprocmask(SIG_SETMASK, &oset, NULL); 1699 1700 if (signr == -1) 1701 return; 1702 1703 signal(signr, SIG_DFL); 1704 kill(getpid(), signr); 1705 } 1706 1707 static int stat__set_big_num(const struct option *opt __maybe_unused, 1708 const char *s __maybe_unused, int unset) 1709 { 1710 big_num_opt = unset ? 0 : 1; 1711 return 0; 1712 } 1713 1714 static int enable_metric_only(const struct option *opt __maybe_unused, 1715 const char *s __maybe_unused, int unset) 1716 { 1717 force_metric_only = true; 1718 metric_only = !unset; 1719 return 0; 1720 } 1721 1722 static const struct option stat_options[] = { 1723 OPT_BOOLEAN('T', "transaction", &transaction_run, 1724 "hardware transaction statistics"), 1725 OPT_CALLBACK('e', "event", &evsel_list, "event", 1726 "event selector. use 'perf list' to list available events", 1727 parse_events_option), 1728 OPT_CALLBACK(0, "filter", &evsel_list, "filter", 1729 "event filter", parse_filter), 1730 OPT_BOOLEAN('i', "no-inherit", &no_inherit, 1731 "child tasks do not inherit counters"), 1732 OPT_STRING('p', "pid", &target.pid, "pid", 1733 "stat events on existing process id"), 1734 OPT_STRING('t', "tid", &target.tid, "tid", 1735 "stat events on existing thread id"), 1736 OPT_BOOLEAN('a', "all-cpus", &target.system_wide, 1737 "system-wide collection from all CPUs"), 1738 OPT_BOOLEAN('g', "group", &group, 1739 "put the counters into a counter group"), 1740 OPT_BOOLEAN('c', "scale", &stat_config.scale, "scale/normalize counters"), 1741 OPT_INCR('v', "verbose", &verbose, 1742 "be more verbose (show counter open errors, etc)"), 1743 OPT_INTEGER('r', "repeat", &run_count, 1744 "repeat command and print average + stddev (max: 100, forever: 0)"), 1745 OPT_BOOLEAN('n', "null", &null_run, 1746 "null run - dont start any counters"), 1747 OPT_INCR('d', "detailed", &detailed_run, 1748 "detailed run - start a lot of events"), 1749 OPT_BOOLEAN('S', "sync", &sync_run, 1750 "call sync() before starting a run"), 1751 OPT_CALLBACK_NOOPT('B', "big-num", NULL, NULL, 1752 "print large numbers with thousands\' separators", 1753 stat__set_big_num), 1754 OPT_STRING('C', "cpu", &target.cpu_list, "cpu", 1755 "list of cpus to monitor in system-wide"), 1756 OPT_SET_UINT('A', "no-aggr", &stat_config.aggr_mode, 1757 "disable CPU count aggregation", AGGR_NONE), 1758 OPT_BOOLEAN(0, "no-merge", &no_merge, "Do not merge identical named events"), 1759 OPT_STRING('x', "field-separator", &csv_sep, "separator", 1760 "print counts with custom separator"), 1761 OPT_CALLBACK('G', "cgroup", &evsel_list, "name", 1762 "monitor event in cgroup name only", parse_cgroups), 1763 OPT_STRING('o', "output", &output_name, "file", "output file name"), 1764 OPT_BOOLEAN(0, "append", &append_file, "append to the output file"), 1765 OPT_INTEGER(0, "log-fd", &output_fd, 1766 "log output to fd, instead of stderr"), 1767 OPT_STRING(0, "pre", &pre_cmd, "command", 1768 "command to run prior to the measured command"), 1769 OPT_STRING(0, "post", &post_cmd, "command", 1770 "command to run after to the measured command"), 1771 OPT_UINTEGER('I', "interval-print", &stat_config.interval, 1772 "print counts at regular interval in ms (>= 10)"), 1773 OPT_SET_UINT(0, "per-socket", &stat_config.aggr_mode, 1774 "aggregate counts per processor socket", AGGR_SOCKET), 1775 OPT_SET_UINT(0, "per-core", &stat_config.aggr_mode, 1776 "aggregate counts per physical processor core", AGGR_CORE), 1777 OPT_SET_UINT(0, "per-thread", &stat_config.aggr_mode, 1778 "aggregate counts per thread", AGGR_THREAD), 1779 OPT_UINTEGER('D', "delay", &initial_delay, 1780 "ms to wait before starting measurement after program start"), 1781 OPT_CALLBACK_NOOPT(0, "metric-only", &metric_only, NULL, 1782 "Only print computed metrics. No raw values", enable_metric_only), 1783 OPT_BOOLEAN(0, "topdown", &topdown_run, 1784 "measure topdown level 1 statistics"), 1785 OPT_END() 1786 }; 1787 1788 static int perf_stat__get_socket(struct cpu_map *map, int cpu) 1789 { 1790 return cpu_map__get_socket(map, cpu, NULL); 1791 } 1792 1793 static int perf_stat__get_core(struct cpu_map *map, int cpu) 1794 { 1795 return cpu_map__get_core(map, cpu, NULL); 1796 } 1797 1798 static int cpu_map__get_max(struct cpu_map *map) 1799 { 1800 int i, max = -1; 1801 1802 for (i = 0; i < map->nr; i++) { 1803 if (map->map[i] > max) 1804 max = map->map[i]; 1805 } 1806 1807 return max; 1808 } 1809 1810 static struct cpu_map *cpus_aggr_map; 1811 1812 static int perf_stat__get_aggr(aggr_get_id_t get_id, struct cpu_map *map, int idx) 1813 { 1814 int cpu; 1815 1816 if (idx >= map->nr) 1817 return -1; 1818 1819 cpu = map->map[idx]; 1820 1821 if (cpus_aggr_map->map[cpu] == -1) 1822 cpus_aggr_map->map[cpu] = get_id(map, idx); 1823 1824 return cpus_aggr_map->map[cpu]; 1825 } 1826 1827 static int perf_stat__get_socket_cached(struct cpu_map *map, int idx) 1828 { 1829 return perf_stat__get_aggr(perf_stat__get_socket, map, idx); 1830 } 1831 1832 static int perf_stat__get_core_cached(struct cpu_map *map, int idx) 1833 { 1834 return perf_stat__get_aggr(perf_stat__get_core, map, idx); 1835 } 1836 1837 static int perf_stat_init_aggr_mode(void) 1838 { 1839 int nr; 1840 1841 switch (stat_config.aggr_mode) { 1842 case AGGR_SOCKET: 1843 if (cpu_map__build_socket_map(evsel_list->cpus, &aggr_map)) { 1844 perror("cannot build socket map"); 1845 return -1; 1846 } 1847 aggr_get_id = perf_stat__get_socket_cached; 1848 break; 1849 case AGGR_CORE: 1850 if (cpu_map__build_core_map(evsel_list->cpus, &aggr_map)) { 1851 perror("cannot build core map"); 1852 return -1; 1853 } 1854 aggr_get_id = perf_stat__get_core_cached; 1855 break; 1856 case AGGR_NONE: 1857 case AGGR_GLOBAL: 1858 case AGGR_THREAD: 1859 case AGGR_UNSET: 1860 default: 1861 break; 1862 } 1863 1864 /* 1865 * The evsel_list->cpus is the base we operate on, 1866 * taking the highest cpu number to be the size of 1867 * the aggregation translate cpumap. 1868 */ 1869 nr = cpu_map__get_max(evsel_list->cpus); 1870 cpus_aggr_map = cpu_map__empty_new(nr + 1); 1871 return cpus_aggr_map ? 0 : -ENOMEM; 1872 } 1873 1874 static void perf_stat__exit_aggr_mode(void) 1875 { 1876 cpu_map__put(aggr_map); 1877 cpu_map__put(cpus_aggr_map); 1878 aggr_map = NULL; 1879 cpus_aggr_map = NULL; 1880 } 1881 1882 static inline int perf_env__get_cpu(struct perf_env *env, struct cpu_map *map, int idx) 1883 { 1884 int cpu; 1885 1886 if (idx > map->nr) 1887 return -1; 1888 1889 cpu = map->map[idx]; 1890 1891 if (cpu >= env->nr_cpus_avail) 1892 return -1; 1893 1894 return cpu; 1895 } 1896 1897 static int perf_env__get_socket(struct cpu_map *map, int idx, void *data) 1898 { 1899 struct perf_env *env = data; 1900 int cpu = perf_env__get_cpu(env, map, idx); 1901 1902 return cpu == -1 ? -1 : env->cpu[cpu].socket_id; 1903 } 1904 1905 static int perf_env__get_core(struct cpu_map *map, int idx, void *data) 1906 { 1907 struct perf_env *env = data; 1908 int core = -1, cpu = perf_env__get_cpu(env, map, idx); 1909 1910 if (cpu != -1) { 1911 int socket_id = env->cpu[cpu].socket_id; 1912 1913 /* 1914 * Encode socket in upper 16 bits 1915 * core_id is relative to socket, and 1916 * we need a global id. So we combine 1917 * socket + core id. 1918 */ 1919 core = (socket_id << 16) | (env->cpu[cpu].core_id & 0xffff); 1920 } 1921 1922 return core; 1923 } 1924 1925 static int perf_env__build_socket_map(struct perf_env *env, struct cpu_map *cpus, 1926 struct cpu_map **sockp) 1927 { 1928 return cpu_map__build_map(cpus, sockp, perf_env__get_socket, env); 1929 } 1930 1931 static int perf_env__build_core_map(struct perf_env *env, struct cpu_map *cpus, 1932 struct cpu_map **corep) 1933 { 1934 return cpu_map__build_map(cpus, corep, perf_env__get_core, env); 1935 } 1936 1937 static int perf_stat__get_socket_file(struct cpu_map *map, int idx) 1938 { 1939 return perf_env__get_socket(map, idx, &perf_stat.session->header.env); 1940 } 1941 1942 static int perf_stat__get_core_file(struct cpu_map *map, int idx) 1943 { 1944 return perf_env__get_core(map, idx, &perf_stat.session->header.env); 1945 } 1946 1947 static int perf_stat_init_aggr_mode_file(struct perf_stat *st) 1948 { 1949 struct perf_env *env = &st->session->header.env; 1950 1951 switch (stat_config.aggr_mode) { 1952 case AGGR_SOCKET: 1953 if (perf_env__build_socket_map(env, evsel_list->cpus, &aggr_map)) { 1954 perror("cannot build socket map"); 1955 return -1; 1956 } 1957 aggr_get_id = perf_stat__get_socket_file; 1958 break; 1959 case AGGR_CORE: 1960 if (perf_env__build_core_map(env, evsel_list->cpus, &aggr_map)) { 1961 perror("cannot build core map"); 1962 return -1; 1963 } 1964 aggr_get_id = perf_stat__get_core_file; 1965 break; 1966 case AGGR_NONE: 1967 case AGGR_GLOBAL: 1968 case AGGR_THREAD: 1969 case AGGR_UNSET: 1970 default: 1971 break; 1972 } 1973 1974 return 0; 1975 } 1976 1977 static int topdown_filter_events(const char **attr, char **str, bool use_group) 1978 { 1979 int off = 0; 1980 int i; 1981 int len = 0; 1982 char *s; 1983 1984 for (i = 0; attr[i]; i++) { 1985 if (pmu_have_event("cpu", attr[i])) { 1986 len += strlen(attr[i]) + 1; 1987 attr[i - off] = attr[i]; 1988 } else 1989 off++; 1990 } 1991 attr[i - off] = NULL; 1992 1993 *str = malloc(len + 1 + 2); 1994 if (!*str) 1995 return -1; 1996 s = *str; 1997 if (i - off == 0) { 1998 *s = 0; 1999 return 0; 2000 } 2001 if (use_group) 2002 *s++ = '{'; 2003 for (i = 0; attr[i]; i++) { 2004 strcpy(s, attr[i]); 2005 s += strlen(s); 2006 *s++ = ','; 2007 } 2008 if (use_group) { 2009 s[-1] = '}'; 2010 *s = 0; 2011 } else 2012 s[-1] = 0; 2013 return 0; 2014 } 2015 2016 __weak bool arch_topdown_check_group(bool *warn) 2017 { 2018 *warn = false; 2019 return false; 2020 } 2021 2022 __weak void arch_topdown_group_warn(void) 2023 { 2024 } 2025 2026 /* 2027 * Add default attributes, if there were no attributes specified or 2028 * if -d/--detailed, -d -d or -d -d -d is used: 2029 */ 2030 static int add_default_attributes(void) 2031 { 2032 int err; 2033 struct perf_event_attr default_attrs0[] = { 2034 2035 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_TASK_CLOCK }, 2036 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CONTEXT_SWITCHES }, 2037 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_CPU_MIGRATIONS }, 2038 { .type = PERF_TYPE_SOFTWARE, .config = PERF_COUNT_SW_PAGE_FAULTS }, 2039 2040 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_CPU_CYCLES }, 2041 }; 2042 struct perf_event_attr frontend_attrs[] = { 2043 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_FRONTEND }, 2044 }; 2045 struct perf_event_attr backend_attrs[] = { 2046 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_STALLED_CYCLES_BACKEND }, 2047 }; 2048 struct perf_event_attr default_attrs1[] = { 2049 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_INSTRUCTIONS }, 2050 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_INSTRUCTIONS }, 2051 { .type = PERF_TYPE_HARDWARE, .config = PERF_COUNT_HW_BRANCH_MISSES }, 2052 2053 }; 2054 2055 /* 2056 * Detailed stats (-d), covering the L1 and last level data caches: 2057 */ 2058 struct perf_event_attr detailed_attrs[] = { 2059 2060 { .type = PERF_TYPE_HW_CACHE, 2061 .config = 2062 PERF_COUNT_HW_CACHE_L1D << 0 | 2063 (PERF_COUNT_HW_CACHE_OP_READ << 8) | 2064 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) }, 2065 2066 { .type = PERF_TYPE_HW_CACHE, 2067 .config = 2068 PERF_COUNT_HW_CACHE_L1D << 0 | 2069 (PERF_COUNT_HW_CACHE_OP_READ << 8) | 2070 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) }, 2071 2072 { .type = PERF_TYPE_HW_CACHE, 2073 .config = 2074 PERF_COUNT_HW_CACHE_LL << 0 | 2075 (PERF_COUNT_HW_CACHE_OP_READ << 8) | 2076 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) }, 2077 2078 { .type = PERF_TYPE_HW_CACHE, 2079 .config = 2080 PERF_COUNT_HW_CACHE_LL << 0 | 2081 (PERF_COUNT_HW_CACHE_OP_READ << 8) | 2082 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) }, 2083 }; 2084 2085 /* 2086 * Very detailed stats (-d -d), covering the instruction cache and the TLB caches: 2087 */ 2088 struct perf_event_attr very_detailed_attrs[] = { 2089 2090 { .type = PERF_TYPE_HW_CACHE, 2091 .config = 2092 PERF_COUNT_HW_CACHE_L1I << 0 | 2093 (PERF_COUNT_HW_CACHE_OP_READ << 8) | 2094 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) }, 2095 2096 { .type = PERF_TYPE_HW_CACHE, 2097 .config = 2098 PERF_COUNT_HW_CACHE_L1I << 0 | 2099 (PERF_COUNT_HW_CACHE_OP_READ << 8) | 2100 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) }, 2101 2102 { .type = PERF_TYPE_HW_CACHE, 2103 .config = 2104 PERF_COUNT_HW_CACHE_DTLB << 0 | 2105 (PERF_COUNT_HW_CACHE_OP_READ << 8) | 2106 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) }, 2107 2108 { .type = PERF_TYPE_HW_CACHE, 2109 .config = 2110 PERF_COUNT_HW_CACHE_DTLB << 0 | 2111 (PERF_COUNT_HW_CACHE_OP_READ << 8) | 2112 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) }, 2113 2114 { .type = PERF_TYPE_HW_CACHE, 2115 .config = 2116 PERF_COUNT_HW_CACHE_ITLB << 0 | 2117 (PERF_COUNT_HW_CACHE_OP_READ << 8) | 2118 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) }, 2119 2120 { .type = PERF_TYPE_HW_CACHE, 2121 .config = 2122 PERF_COUNT_HW_CACHE_ITLB << 0 | 2123 (PERF_COUNT_HW_CACHE_OP_READ << 8) | 2124 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) }, 2125 2126 }; 2127 2128 /* 2129 * Very, very detailed stats (-d -d -d), adding prefetch events: 2130 */ 2131 struct perf_event_attr very_very_detailed_attrs[] = { 2132 2133 { .type = PERF_TYPE_HW_CACHE, 2134 .config = 2135 PERF_COUNT_HW_CACHE_L1D << 0 | 2136 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) | 2137 (PERF_COUNT_HW_CACHE_RESULT_ACCESS << 16) }, 2138 2139 { .type = PERF_TYPE_HW_CACHE, 2140 .config = 2141 PERF_COUNT_HW_CACHE_L1D << 0 | 2142 (PERF_COUNT_HW_CACHE_OP_PREFETCH << 8) | 2143 (PERF_COUNT_HW_CACHE_RESULT_MISS << 16) }, 2144 }; 2145 2146 /* Set attrs if no event is selected and !null_run: */ 2147 if (null_run) 2148 return 0; 2149 2150 if (transaction_run) { 2151 if (pmu_have_event("cpu", "cycles-ct") && 2152 pmu_have_event("cpu", "el-start")) 2153 err = parse_events(evsel_list, transaction_attrs, NULL); 2154 else 2155 err = parse_events(evsel_list, transaction_limited_attrs, NULL); 2156 if (err) { 2157 fprintf(stderr, "Cannot set up transaction events\n"); 2158 return -1; 2159 } 2160 return 0; 2161 } 2162 2163 if (topdown_run) { 2164 char *str = NULL; 2165 bool warn = false; 2166 2167 if (stat_config.aggr_mode != AGGR_GLOBAL && 2168 stat_config.aggr_mode != AGGR_CORE) { 2169 pr_err("top down event configuration requires --per-core mode\n"); 2170 return -1; 2171 } 2172 stat_config.aggr_mode = AGGR_CORE; 2173 if (nr_cgroups || !target__has_cpu(&target)) { 2174 pr_err("top down event configuration requires system-wide mode (-a)\n"); 2175 return -1; 2176 } 2177 2178 if (!force_metric_only) 2179 metric_only = true; 2180 if (topdown_filter_events(topdown_attrs, &str, 2181 arch_topdown_check_group(&warn)) < 0) { 2182 pr_err("Out of memory\n"); 2183 return -1; 2184 } 2185 if (topdown_attrs[0] && str) { 2186 if (warn) 2187 arch_topdown_group_warn(); 2188 err = parse_events(evsel_list, str, NULL); 2189 if (err) { 2190 fprintf(stderr, 2191 "Cannot set up top down events %s: %d\n", 2192 str, err); 2193 free(str); 2194 return -1; 2195 } 2196 } else { 2197 fprintf(stderr, "System does not support topdown\n"); 2198 return -1; 2199 } 2200 free(str); 2201 } 2202 2203 if (!evsel_list->nr_entries) { 2204 if (target__has_cpu(&target)) 2205 default_attrs0[0].config = PERF_COUNT_SW_CPU_CLOCK; 2206 2207 if (perf_evlist__add_default_attrs(evsel_list, default_attrs0) < 0) 2208 return -1; 2209 if (pmu_have_event("cpu", "stalled-cycles-frontend")) { 2210 if (perf_evlist__add_default_attrs(evsel_list, 2211 frontend_attrs) < 0) 2212 return -1; 2213 } 2214 if (pmu_have_event("cpu", "stalled-cycles-backend")) { 2215 if (perf_evlist__add_default_attrs(evsel_list, 2216 backend_attrs) < 0) 2217 return -1; 2218 } 2219 if (perf_evlist__add_default_attrs(evsel_list, default_attrs1) < 0) 2220 return -1; 2221 } 2222 2223 /* Detailed events get appended to the event list: */ 2224 2225 if (detailed_run < 1) 2226 return 0; 2227 2228 /* Append detailed run extra attributes: */ 2229 if (perf_evlist__add_default_attrs(evsel_list, detailed_attrs) < 0) 2230 return -1; 2231 2232 if (detailed_run < 2) 2233 return 0; 2234 2235 /* Append very detailed run extra attributes: */ 2236 if (perf_evlist__add_default_attrs(evsel_list, very_detailed_attrs) < 0) 2237 return -1; 2238 2239 if (detailed_run < 3) 2240 return 0; 2241 2242 /* Append very, very detailed run extra attributes: */ 2243 return perf_evlist__add_default_attrs(evsel_list, very_very_detailed_attrs); 2244 } 2245 2246 static const char * const stat_record_usage[] = { 2247 "perf stat record [<options>]", 2248 NULL, 2249 }; 2250 2251 static void init_features(struct perf_session *session) 2252 { 2253 int feat; 2254 2255 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++) 2256 perf_header__set_feat(&session->header, feat); 2257 2258 perf_header__clear_feat(&session->header, HEADER_BUILD_ID); 2259 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA); 2260 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK); 2261 perf_header__clear_feat(&session->header, HEADER_AUXTRACE); 2262 } 2263 2264 static int __cmd_record(int argc, const char **argv) 2265 { 2266 struct perf_session *session; 2267 struct perf_data_file *file = &perf_stat.file; 2268 2269 argc = parse_options(argc, argv, stat_options, stat_record_usage, 2270 PARSE_OPT_STOP_AT_NON_OPTION); 2271 2272 if (output_name) 2273 file->path = output_name; 2274 2275 if (run_count != 1 || forever) { 2276 pr_err("Cannot use -r option with perf stat record.\n"); 2277 return -1; 2278 } 2279 2280 session = perf_session__new(file, false, NULL); 2281 if (session == NULL) { 2282 pr_err("Perf session creation failed.\n"); 2283 return -1; 2284 } 2285 2286 init_features(session); 2287 2288 session->evlist = evsel_list; 2289 perf_stat.session = session; 2290 perf_stat.record = true; 2291 return argc; 2292 } 2293 2294 static int process_stat_round_event(struct perf_tool *tool __maybe_unused, 2295 union perf_event *event, 2296 struct perf_session *session) 2297 { 2298 struct stat_round_event *stat_round = &event->stat_round; 2299 struct perf_evsel *counter; 2300 struct timespec tsh, *ts = NULL; 2301 const char **argv = session->header.env.cmdline_argv; 2302 int argc = session->header.env.nr_cmdline; 2303 2304 evlist__for_each_entry(evsel_list, counter) 2305 perf_stat_process_counter(&stat_config, counter); 2306 2307 if (stat_round->type == PERF_STAT_ROUND_TYPE__FINAL) 2308 update_stats(&walltime_nsecs_stats, stat_round->time); 2309 2310 if (stat_config.interval && stat_round->time) { 2311 tsh.tv_sec = stat_round->time / NSEC_PER_SEC; 2312 tsh.tv_nsec = stat_round->time % NSEC_PER_SEC; 2313 ts = &tsh; 2314 } 2315 2316 print_counters(ts, argc, argv); 2317 return 0; 2318 } 2319 2320 static 2321 int process_stat_config_event(struct perf_tool *tool, 2322 union perf_event *event, 2323 struct perf_session *session __maybe_unused) 2324 { 2325 struct perf_stat *st = container_of(tool, struct perf_stat, tool); 2326 2327 perf_event__read_stat_config(&stat_config, &event->stat_config); 2328 2329 if (cpu_map__empty(st->cpus)) { 2330 if (st->aggr_mode != AGGR_UNSET) 2331 pr_warning("warning: processing task data, aggregation mode not set\n"); 2332 return 0; 2333 } 2334 2335 if (st->aggr_mode != AGGR_UNSET) 2336 stat_config.aggr_mode = st->aggr_mode; 2337 2338 if (perf_stat.file.is_pipe) 2339 perf_stat_init_aggr_mode(); 2340 else 2341 perf_stat_init_aggr_mode_file(st); 2342 2343 return 0; 2344 } 2345 2346 static int set_maps(struct perf_stat *st) 2347 { 2348 if (!st->cpus || !st->threads) 2349 return 0; 2350 2351 if (WARN_ONCE(st->maps_allocated, "stats double allocation\n")) 2352 return -EINVAL; 2353 2354 perf_evlist__set_maps(evsel_list, st->cpus, st->threads); 2355 2356 if (perf_evlist__alloc_stats(evsel_list, true)) 2357 return -ENOMEM; 2358 2359 st->maps_allocated = true; 2360 return 0; 2361 } 2362 2363 static 2364 int process_thread_map_event(struct perf_tool *tool, 2365 union perf_event *event, 2366 struct perf_session *session __maybe_unused) 2367 { 2368 struct perf_stat *st = container_of(tool, struct perf_stat, tool); 2369 2370 if (st->threads) { 2371 pr_warning("Extra thread map event, ignoring.\n"); 2372 return 0; 2373 } 2374 2375 st->threads = thread_map__new_event(&event->thread_map); 2376 if (!st->threads) 2377 return -ENOMEM; 2378 2379 return set_maps(st); 2380 } 2381 2382 static 2383 int process_cpu_map_event(struct perf_tool *tool, 2384 union perf_event *event, 2385 struct perf_session *session __maybe_unused) 2386 { 2387 struct perf_stat *st = container_of(tool, struct perf_stat, tool); 2388 struct cpu_map *cpus; 2389 2390 if (st->cpus) { 2391 pr_warning("Extra cpu map event, ignoring.\n"); 2392 return 0; 2393 } 2394 2395 cpus = cpu_map__new_data(&event->cpu_map.data); 2396 if (!cpus) 2397 return -ENOMEM; 2398 2399 st->cpus = cpus; 2400 return set_maps(st); 2401 } 2402 2403 static const char * const stat_report_usage[] = { 2404 "perf stat report [<options>]", 2405 NULL, 2406 }; 2407 2408 static struct perf_stat perf_stat = { 2409 .tool = { 2410 .attr = perf_event__process_attr, 2411 .event_update = perf_event__process_event_update, 2412 .thread_map = process_thread_map_event, 2413 .cpu_map = process_cpu_map_event, 2414 .stat_config = process_stat_config_event, 2415 .stat = perf_event__process_stat_event, 2416 .stat_round = process_stat_round_event, 2417 }, 2418 .aggr_mode = AGGR_UNSET, 2419 }; 2420 2421 static int __cmd_report(int argc, const char **argv) 2422 { 2423 struct perf_session *session; 2424 const struct option options[] = { 2425 OPT_STRING('i', "input", &input_name, "file", "input file name"), 2426 OPT_SET_UINT(0, "per-socket", &perf_stat.aggr_mode, 2427 "aggregate counts per processor socket", AGGR_SOCKET), 2428 OPT_SET_UINT(0, "per-core", &perf_stat.aggr_mode, 2429 "aggregate counts per physical processor core", AGGR_CORE), 2430 OPT_SET_UINT('A', "no-aggr", &perf_stat.aggr_mode, 2431 "disable CPU count aggregation", AGGR_NONE), 2432 OPT_END() 2433 }; 2434 struct stat st; 2435 int ret; 2436 2437 argc = parse_options(argc, argv, options, stat_report_usage, 0); 2438 2439 if (!input_name || !strlen(input_name)) { 2440 if (!fstat(STDIN_FILENO, &st) && S_ISFIFO(st.st_mode)) 2441 input_name = "-"; 2442 else 2443 input_name = "perf.data"; 2444 } 2445 2446 perf_stat.file.path = input_name; 2447 perf_stat.file.mode = PERF_DATA_MODE_READ; 2448 2449 session = perf_session__new(&perf_stat.file, false, &perf_stat.tool); 2450 if (session == NULL) 2451 return -1; 2452 2453 perf_stat.session = session; 2454 stat_config.output = stderr; 2455 evsel_list = session->evlist; 2456 2457 ret = perf_session__process_events(session); 2458 if (ret) 2459 return ret; 2460 2461 perf_session__delete(session); 2462 return 0; 2463 } 2464 2465 static void setup_system_wide(int forks) 2466 { 2467 /* 2468 * Make system wide (-a) the default target if 2469 * no target was specified and one of following 2470 * conditions is met: 2471 * 2472 * - there's no workload specified 2473 * - there is workload specified but all requested 2474 * events are system wide events 2475 */ 2476 if (!target__none(&target)) 2477 return; 2478 2479 if (!forks) 2480 target.system_wide = true; 2481 else { 2482 struct perf_evsel *counter; 2483 2484 evlist__for_each_entry(evsel_list, counter) { 2485 if (!counter->system_wide) 2486 return; 2487 } 2488 2489 if (evsel_list->nr_entries) 2490 target.system_wide = true; 2491 } 2492 } 2493 2494 int cmd_stat(int argc, const char **argv) 2495 { 2496 const char * const stat_usage[] = { 2497 "perf stat [<options>] [<command>]", 2498 NULL 2499 }; 2500 int status = -EINVAL, run_idx; 2501 const char *mode; 2502 FILE *output = stderr; 2503 unsigned int interval; 2504 const char * const stat_subcommands[] = { "record", "report" }; 2505 2506 setlocale(LC_ALL, ""); 2507 2508 evsel_list = perf_evlist__new(); 2509 if (evsel_list == NULL) 2510 return -ENOMEM; 2511 2512 parse_events__shrink_config_terms(); 2513 argc = parse_options_subcommand(argc, argv, stat_options, stat_subcommands, 2514 (const char **) stat_usage, 2515 PARSE_OPT_STOP_AT_NON_OPTION); 2516 perf_stat__collect_metric_expr(evsel_list); 2517 perf_stat__init_shadow_stats(); 2518 2519 if (csv_sep) { 2520 csv_output = true; 2521 if (!strcmp(csv_sep, "\\t")) 2522 csv_sep = "\t"; 2523 } else 2524 csv_sep = DEFAULT_SEPARATOR; 2525 2526 if (argc && !strncmp(argv[0], "rec", 3)) { 2527 argc = __cmd_record(argc, argv); 2528 if (argc < 0) 2529 return -1; 2530 } else if (argc && !strncmp(argv[0], "rep", 3)) 2531 return __cmd_report(argc, argv); 2532 2533 interval = stat_config.interval; 2534 2535 /* 2536 * For record command the -o is already taken care of. 2537 */ 2538 if (!STAT_RECORD && output_name && strcmp(output_name, "-")) 2539 output = NULL; 2540 2541 if (output_name && output_fd) { 2542 fprintf(stderr, "cannot use both --output and --log-fd\n"); 2543 parse_options_usage(stat_usage, stat_options, "o", 1); 2544 parse_options_usage(NULL, stat_options, "log-fd", 0); 2545 goto out; 2546 } 2547 2548 if (metric_only && stat_config.aggr_mode == AGGR_THREAD) { 2549 fprintf(stderr, "--metric-only is not supported with --per-thread\n"); 2550 goto out; 2551 } 2552 2553 if (metric_only && run_count > 1) { 2554 fprintf(stderr, "--metric-only is not supported with -r\n"); 2555 goto out; 2556 } 2557 2558 if (output_fd < 0) { 2559 fprintf(stderr, "argument to --log-fd must be a > 0\n"); 2560 parse_options_usage(stat_usage, stat_options, "log-fd", 0); 2561 goto out; 2562 } 2563 2564 if (!output) { 2565 struct timespec tm; 2566 mode = append_file ? "a" : "w"; 2567 2568 output = fopen(output_name, mode); 2569 if (!output) { 2570 perror("failed to create output file"); 2571 return -1; 2572 } 2573 clock_gettime(CLOCK_REALTIME, &tm); 2574 fprintf(output, "# started on %s\n", ctime(&tm.tv_sec)); 2575 } else if (output_fd > 0) { 2576 mode = append_file ? "a" : "w"; 2577 output = fdopen(output_fd, mode); 2578 if (!output) { 2579 perror("Failed opening logfd"); 2580 return -errno; 2581 } 2582 } 2583 2584 stat_config.output = output; 2585 2586 /* 2587 * let the spreadsheet do the pretty-printing 2588 */ 2589 if (csv_output) { 2590 /* User explicitly passed -B? */ 2591 if (big_num_opt == 1) { 2592 fprintf(stderr, "-B option not supported with -x\n"); 2593 parse_options_usage(stat_usage, stat_options, "B", 1); 2594 parse_options_usage(NULL, stat_options, "x", 1); 2595 goto out; 2596 } else /* Nope, so disable big number formatting */ 2597 big_num = false; 2598 } else if (big_num_opt == 0) /* User passed --no-big-num */ 2599 big_num = false; 2600 2601 setup_system_wide(argc); 2602 2603 if (run_count < 0) { 2604 pr_err("Run count must be a positive number\n"); 2605 parse_options_usage(stat_usage, stat_options, "r", 1); 2606 goto out; 2607 } else if (run_count == 0) { 2608 forever = true; 2609 run_count = 1; 2610 } 2611 2612 if ((stat_config.aggr_mode == AGGR_THREAD) && !target__has_task(&target)) { 2613 fprintf(stderr, "The --per-thread option is only available " 2614 "when monitoring via -p -t options.\n"); 2615 parse_options_usage(NULL, stat_options, "p", 1); 2616 parse_options_usage(NULL, stat_options, "t", 1); 2617 goto out; 2618 } 2619 2620 /* 2621 * no_aggr, cgroup are for system-wide only 2622 * --per-thread is aggregated per thread, we dont mix it with cpu mode 2623 */ 2624 if (((stat_config.aggr_mode != AGGR_GLOBAL && 2625 stat_config.aggr_mode != AGGR_THREAD) || nr_cgroups) && 2626 !target__has_cpu(&target)) { 2627 fprintf(stderr, "both cgroup and no-aggregation " 2628 "modes only available in system-wide mode\n"); 2629 2630 parse_options_usage(stat_usage, stat_options, "G", 1); 2631 parse_options_usage(NULL, stat_options, "A", 1); 2632 parse_options_usage(NULL, stat_options, "a", 1); 2633 goto out; 2634 } 2635 2636 if (add_default_attributes()) 2637 goto out; 2638 2639 target__validate(&target); 2640 2641 if (perf_evlist__create_maps(evsel_list, &target) < 0) { 2642 if (target__has_task(&target)) { 2643 pr_err("Problems finding threads of monitor\n"); 2644 parse_options_usage(stat_usage, stat_options, "p", 1); 2645 parse_options_usage(NULL, stat_options, "t", 1); 2646 } else if (target__has_cpu(&target)) { 2647 perror("failed to parse CPUs map"); 2648 parse_options_usage(stat_usage, stat_options, "C", 1); 2649 parse_options_usage(NULL, stat_options, "a", 1); 2650 } 2651 goto out; 2652 } 2653 2654 /* 2655 * Initialize thread_map with comm names, 2656 * so we could print it out on output. 2657 */ 2658 if (stat_config.aggr_mode == AGGR_THREAD) 2659 thread_map__read_comms(evsel_list->threads); 2660 2661 if (interval && interval < 100) { 2662 if (interval < 10) { 2663 pr_err("print interval must be >= 10ms\n"); 2664 parse_options_usage(stat_usage, stat_options, "I", 1); 2665 goto out; 2666 } else 2667 pr_warning("print interval < 100ms. " 2668 "The overhead percentage could be high in some cases. " 2669 "Please proceed with caution.\n"); 2670 } 2671 2672 if (perf_evlist__alloc_stats(evsel_list, interval)) 2673 goto out; 2674 2675 if (perf_stat_init_aggr_mode()) 2676 goto out; 2677 2678 /* 2679 * We dont want to block the signals - that would cause 2680 * child tasks to inherit that and Ctrl-C would not work. 2681 * What we want is for Ctrl-C to work in the exec()-ed 2682 * task, but being ignored by perf stat itself: 2683 */ 2684 atexit(sig_atexit); 2685 if (!forever) 2686 signal(SIGINT, skip_signal); 2687 signal(SIGCHLD, skip_signal); 2688 signal(SIGALRM, skip_signal); 2689 signal(SIGABRT, skip_signal); 2690 2691 status = 0; 2692 for (run_idx = 0; forever || run_idx < run_count; run_idx++) { 2693 if (run_count != 1 && verbose > 0) 2694 fprintf(output, "[ perf stat: executing run #%d ... ]\n", 2695 run_idx + 1); 2696 2697 status = run_perf_stat(argc, argv); 2698 if (forever && status != -1) { 2699 print_counters(NULL, argc, argv); 2700 perf_stat__reset_stats(); 2701 } 2702 } 2703 2704 if (!forever && status != -1 && !interval) 2705 print_counters(NULL, argc, argv); 2706 2707 if (STAT_RECORD) { 2708 /* 2709 * We synthesize the kernel mmap record just so that older tools 2710 * don't emit warnings about not being able to resolve symbols 2711 * due to /proc/sys/kernel/kptr_restrict settings and instear provide 2712 * a saner message about no samples being in the perf.data file. 2713 * 2714 * This also serves to suppress a warning about f_header.data.size == 0 2715 * in header.c at the moment 'perf stat record' gets introduced, which 2716 * is not really needed once we start adding the stat specific PERF_RECORD_ 2717 * records, but the need to suppress the kptr_restrict messages in older 2718 * tools remain -acme 2719 */ 2720 int fd = perf_data_file__fd(&perf_stat.file); 2721 int err = perf_event__synthesize_kernel_mmap((void *)&perf_stat, 2722 process_synthesized_event, 2723 &perf_stat.session->machines.host); 2724 if (err) { 2725 pr_warning("Couldn't synthesize the kernel mmap record, harmless, " 2726 "older tools may produce warnings about this file\n."); 2727 } 2728 2729 if (!interval) { 2730 if (WRITE_STAT_ROUND_EVENT(walltime_nsecs_stats.max, FINAL)) 2731 pr_err("failed to write stat round event\n"); 2732 } 2733 2734 if (!perf_stat.file.is_pipe) { 2735 perf_stat.session->header.data_size += perf_stat.bytes_written; 2736 perf_session__write_header(perf_stat.session, evsel_list, fd, true); 2737 } 2738 2739 perf_session__delete(perf_stat.session); 2740 } 2741 2742 perf_stat__exit_aggr_mode(); 2743 perf_evlist__free_stats(evsel_list); 2744 out: 2745 perf_evlist__delete(evsel_list); 2746 return status; 2747 } 2748