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