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