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