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