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