1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * builtin-record.c 4 * 5 * Builtin record command: Record the profile of a workload 6 * (or a CPU, or a PID) into the perf.data output file - for 7 * later analysis via perf report. 8 */ 9 #include "builtin.h" 10 11 #include "util/build-id.h" 12 #include <subcmd/parse-options.h> 13 #include <internal/xyarray.h> 14 #include "util/parse-events.h" 15 #include "util/config.h" 16 17 #include "util/arm64-frame-pointer-unwind-support.h" 18 #include "util/callchain.h" 19 #include "util/cgroup.h" 20 #include "util/header.h" 21 #include "util/event.h" 22 #include "util/evlist.h" 23 #include "util/evsel.h" 24 #include "util/debug.h" 25 #include "util/mmap.h" 26 #include "util/mutex.h" 27 #include "util/target.h" 28 #include "util/session.h" 29 #include "util/tool.h" 30 #include "util/stat.h" 31 #include "util/symbol.h" 32 #include "util/record.h" 33 #include "util/cpumap.h" 34 #include "util/thread_map.h" 35 #include "util/data.h" 36 #include "util/perf_regs.h" 37 #include "util/auxtrace.h" 38 #include "util/tsc.h" 39 #include "util/parse-branch-options.h" 40 #include "util/parse-regs-options.h" 41 #include "util/perf_api_probe.h" 42 #include "util/trigger.h" 43 #include "util/perf-hooks.h" 44 #include "util/synthetic-events.h" 45 #include "util/time-utils.h" 46 #include "util/units.h" 47 #include "util/bpf-event.h" 48 #include "util/util.h" 49 #include "util/pfm.h" 50 #include "util/pmu.h" 51 #include "util/pmus.h" 52 #include "util/clockid.h" 53 #include "util/off_cpu.h" 54 #include "util/bpf-filter.h" 55 #include "util/strbuf.h" 56 #include "asm/bug.h" 57 #include "perf.h" 58 #include "cputopo.h" 59 #include "dwarf-regs.h" 60 61 #include <errno.h> 62 #include <inttypes.h> 63 #include <locale.h> 64 #include <poll.h> 65 #include <pthread.h> 66 #include <unistd.h> 67 #include <string.h> 68 #ifndef HAVE_GETTID 69 #include <syscall.h> 70 #endif 71 #include <sched.h> 72 #include <signal.h> 73 #ifdef HAVE_EVENTFD_SUPPORT 74 #include <sys/eventfd.h> 75 #endif 76 #include <sys/mman.h> 77 #include <sys/wait.h> 78 #include <sys/types.h> 79 #include <sys/stat.h> 80 #include <fcntl.h> 81 #include <linux/err.h> 82 #include <linux/string.h> 83 #include <linux/time64.h> 84 #include <linux/zalloc.h> 85 #include <linux/bitmap.h> 86 #include <sys/time.h> 87 88 struct switch_output { 89 bool enabled; 90 bool signal; 91 unsigned long size; 92 unsigned long time; 93 const char *str; 94 bool set; 95 char **filenames; 96 int num_files; 97 int cur_file; 98 }; 99 100 struct thread_mask { 101 struct mmap_cpu_mask maps; 102 struct mmap_cpu_mask affinity; 103 }; 104 105 struct record_thread { 106 pid_t tid; 107 struct thread_mask *mask; 108 struct { 109 int msg[2]; 110 int ack[2]; 111 } pipes; 112 struct fdarray pollfd; 113 int ctlfd_pos; 114 int nr_mmaps; 115 struct mmap **maps; 116 struct mmap **overwrite_maps; 117 struct record *rec; 118 unsigned long long samples; 119 unsigned long waking; 120 u64 bytes_written; 121 u64 bytes_transferred; 122 u64 bytes_compressed; 123 }; 124 125 static __thread struct record_thread *thread; 126 127 enum thread_msg { 128 THREAD_MSG__UNDEFINED = 0, 129 THREAD_MSG__READY, 130 THREAD_MSG__MAX, 131 }; 132 133 static const char *thread_msg_tags[THREAD_MSG__MAX] = { 134 "UNDEFINED", "READY" 135 }; 136 137 enum thread_spec { 138 THREAD_SPEC__UNDEFINED = 0, 139 THREAD_SPEC__CPU, 140 THREAD_SPEC__CORE, 141 THREAD_SPEC__PACKAGE, 142 THREAD_SPEC__NUMA, 143 THREAD_SPEC__USER, 144 THREAD_SPEC__MAX, 145 }; 146 147 static const char *thread_spec_tags[THREAD_SPEC__MAX] = { 148 "undefined", "cpu", "core", "package", "numa", "user" 149 }; 150 151 struct pollfd_index_map { 152 int evlist_pollfd_index; 153 int thread_pollfd_index; 154 }; 155 156 struct record { 157 struct perf_tool tool; 158 struct record_opts opts; 159 u64 bytes_written; 160 u64 thread_bytes_written; 161 struct perf_data data; 162 struct auxtrace_record *itr; 163 struct evlist *evlist; 164 struct perf_session *session; 165 struct evlist *sb_evlist; 166 pthread_t thread_id; 167 int realtime_prio; 168 bool latency; 169 bool switch_output_event_set; 170 bool no_buildid; 171 bool no_buildid_set; 172 bool no_buildid_cache; 173 bool no_buildid_cache_set; 174 bool buildid_all; 175 bool buildid_mmap; 176 bool buildid_mmap_set; 177 bool timestamp_filename; 178 bool timestamp_boundary; 179 bool off_cpu; 180 const char *filter_action; 181 const char *uid_str; 182 struct switch_output switch_output; 183 unsigned long long samples; 184 unsigned long output_max_size; /* = 0: unlimited */ 185 struct perf_debuginfod debuginfod; 186 int nr_threads; 187 struct thread_mask *thread_masks; 188 struct record_thread *thread_data; 189 struct pollfd_index_map *index_map; 190 size_t index_map_sz; 191 size_t index_map_cnt; 192 }; 193 194 static volatile int done; 195 196 static volatile int auxtrace_record__snapshot_started; 197 static DEFINE_TRIGGER(auxtrace_snapshot_trigger); 198 static DEFINE_TRIGGER(switch_output_trigger); 199 200 static const char *affinity_tags[PERF_AFFINITY_MAX] = { 201 "SYS", "NODE", "CPU" 202 }; 203 204 static int build_id__process_mmap(const struct perf_tool *tool, union perf_event *event, 205 struct perf_sample *sample, struct machine *machine); 206 static int build_id__process_mmap2(const struct perf_tool *tool, union perf_event *event, 207 struct perf_sample *sample, struct machine *machine); 208 static int process_timestamp_boundary(const struct perf_tool *tool, 209 union perf_event *event, 210 struct perf_sample *sample, 211 struct machine *machine); 212 213 #ifndef HAVE_GETTID 214 static inline pid_t gettid(void) 215 { 216 return (pid_t)syscall(__NR_gettid); 217 } 218 #endif 219 220 static int record__threads_enabled(struct record *rec) 221 { 222 return rec->opts.threads_spec; 223 } 224 225 static bool switch_output_signal(struct record *rec) 226 { 227 return rec->switch_output.signal && 228 trigger_is_ready(&switch_output_trigger); 229 } 230 231 static bool switch_output_size(struct record *rec) 232 { 233 return rec->switch_output.size && 234 trigger_is_ready(&switch_output_trigger) && 235 (rec->bytes_written >= rec->switch_output.size); 236 } 237 238 static bool switch_output_time(struct record *rec) 239 { 240 return rec->switch_output.time && 241 trigger_is_ready(&switch_output_trigger); 242 } 243 244 static u64 record__bytes_written(struct record *rec) 245 { 246 return rec->bytes_written + rec->thread_bytes_written; 247 } 248 249 static bool record__output_max_size_exceeded(struct record *rec) 250 { 251 return rec->output_max_size && 252 (record__bytes_written(rec) >= rec->output_max_size); 253 } 254 255 static int record__write(struct record *rec, struct mmap *map __maybe_unused, 256 void *bf, size_t size) 257 { 258 struct perf_data_file *file = &rec->session->data->file; 259 260 if (map && map->file) 261 file = map->file; 262 263 if (perf_data_file__write(file, bf, size) < 0) { 264 pr_err("failed to write perf data, error: %m\n"); 265 return -1; 266 } 267 268 if (map && map->file) { 269 thread->bytes_written += size; 270 rec->thread_bytes_written += size; 271 } else { 272 rec->bytes_written += size; 273 } 274 275 if (record__output_max_size_exceeded(rec) && !done) { 276 fprintf(stderr, "[ perf record: perf size limit reached (%" PRIu64 " KB)," 277 " stopping session ]\n", 278 record__bytes_written(rec) >> 10); 279 done = 1; 280 } 281 282 if (switch_output_size(rec)) 283 trigger_hit(&switch_output_trigger); 284 285 return 0; 286 } 287 288 static int record__aio_enabled(struct record *rec); 289 static int record__comp_enabled(struct record *rec); 290 static ssize_t zstd_compress(struct perf_session *session, struct mmap *map, 291 void *dst, size_t dst_size, void *src, size_t src_size); 292 293 #ifdef HAVE_AIO_SUPPORT 294 static int record__aio_write(struct aiocb *cblock, int trace_fd, 295 void *buf, size_t size, off_t off) 296 { 297 int rc; 298 299 cblock->aio_fildes = trace_fd; 300 cblock->aio_buf = buf; 301 cblock->aio_nbytes = size; 302 cblock->aio_offset = off; 303 cblock->aio_sigevent.sigev_notify = SIGEV_NONE; 304 305 do { 306 rc = aio_write(cblock); 307 if (rc == 0) { 308 break; 309 } else if (errno != EAGAIN) { 310 cblock->aio_fildes = -1; 311 pr_err("failed to queue perf data, error: %m\n"); 312 break; 313 } 314 } while (1); 315 316 return rc; 317 } 318 319 static int record__aio_complete(struct mmap *md, struct aiocb *cblock) 320 { 321 void *rem_buf; 322 off_t rem_off; 323 size_t rem_size; 324 int rc, aio_errno; 325 ssize_t aio_ret, written; 326 327 aio_errno = aio_error(cblock); 328 if (aio_errno == EINPROGRESS) 329 return 0; 330 331 written = aio_ret = aio_return(cblock); 332 if (aio_ret < 0) { 333 if (aio_errno != EINTR) 334 pr_err("failed to write perf data, error: %m\n"); 335 written = 0; 336 } 337 338 rem_size = cblock->aio_nbytes - written; 339 340 if (rem_size == 0) { 341 cblock->aio_fildes = -1; 342 /* 343 * md->refcount is incremented in record__aio_pushfn() for 344 * every aio write request started in record__aio_push() so 345 * decrement it because the request is now complete. 346 */ 347 perf_mmap__put(&md->core); 348 rc = 1; 349 } else { 350 /* 351 * aio write request may require restart with the 352 * remainder if the kernel didn't write whole 353 * chunk at once. 354 */ 355 rem_off = cblock->aio_offset + written; 356 rem_buf = (void *)(cblock->aio_buf + written); 357 record__aio_write(cblock, cblock->aio_fildes, 358 rem_buf, rem_size, rem_off); 359 rc = 0; 360 } 361 362 return rc; 363 } 364 365 static int record__aio_sync(struct mmap *md, bool sync_all) 366 { 367 struct aiocb **aiocb = md->aio.aiocb; 368 struct aiocb *cblocks = md->aio.cblocks; 369 struct timespec timeout = { 0, 1000 * 1000 * 1 }; /* 1ms */ 370 int i, do_suspend; 371 372 do { 373 do_suspend = 0; 374 for (i = 0; i < md->aio.nr_cblocks; ++i) { 375 if (cblocks[i].aio_fildes == -1 || record__aio_complete(md, &cblocks[i])) { 376 if (sync_all) 377 aiocb[i] = NULL; 378 else 379 return i; 380 } else { 381 /* 382 * Started aio write is not complete yet 383 * so it has to be waited before the 384 * next allocation. 385 */ 386 aiocb[i] = &cblocks[i]; 387 do_suspend = 1; 388 } 389 } 390 if (!do_suspend) 391 return -1; 392 393 while (aio_suspend((const struct aiocb **)aiocb, md->aio.nr_cblocks, &timeout)) { 394 if (!(errno == EAGAIN || errno == EINTR)) 395 pr_err("failed to sync perf data, error: %m\n"); 396 } 397 } while (1); 398 } 399 400 struct record_aio { 401 struct record *rec; 402 void *data; 403 size_t size; 404 }; 405 406 static int record__aio_pushfn(struct mmap *map, void *to, void *buf, size_t size) 407 { 408 struct record_aio *aio = to; 409 410 /* 411 * map->core.base data pointed by buf is copied into free map->aio.data[] buffer 412 * to release space in the kernel buffer as fast as possible, calling 413 * perf_mmap__consume() from perf_mmap__push() function. 414 * 415 * That lets the kernel to proceed with storing more profiling data into 416 * the kernel buffer earlier than other per-cpu kernel buffers are handled. 417 * 418 * Coping can be done in two steps in case the chunk of profiling data 419 * crosses the upper bound of the kernel buffer. In this case we first move 420 * part of data from map->start till the upper bound and then the remainder 421 * from the beginning of the kernel buffer till the end of the data chunk. 422 */ 423 424 if (record__comp_enabled(aio->rec)) { 425 ssize_t compressed = zstd_compress(aio->rec->session, NULL, aio->data + aio->size, 426 mmap__mmap_len(map) - aio->size, 427 buf, size); 428 if (compressed < 0) 429 return (int)compressed; 430 431 size = compressed; 432 } else { 433 memcpy(aio->data + aio->size, buf, size); 434 } 435 436 if (!aio->size) { 437 /* 438 * Increment map->refcount to guard map->aio.data[] buffer 439 * from premature deallocation because map object can be 440 * released earlier than aio write request started on 441 * map->aio.data[] buffer is complete. 442 * 443 * perf_mmap__put() is done at record__aio_complete() 444 * after started aio request completion or at record__aio_push() 445 * if the request failed to start. 446 */ 447 perf_mmap__get(&map->core); 448 } 449 450 aio->size += size; 451 452 return size; 453 } 454 455 static int record__aio_push(struct record *rec, struct mmap *map, off_t *off) 456 { 457 int ret, idx; 458 int trace_fd = perf_data__fd(rec->session->data); 459 struct record_aio aio = { .rec = rec, .size = 0 }; 460 461 /* 462 * Call record__aio_sync() to wait till map->aio.data[] buffer 463 * becomes available after previous aio write operation. 464 */ 465 466 idx = record__aio_sync(map, false); 467 aio.data = map->aio.data[idx]; 468 ret = perf_mmap__push(map, &aio, record__aio_pushfn); 469 if (ret != 0) /* ret > 0 - no data, ret < 0 - error */ 470 return ret; 471 472 rec->samples++; 473 ret = record__aio_write(&(map->aio.cblocks[idx]), trace_fd, aio.data, aio.size, *off); 474 if (!ret) { 475 *off += aio.size; 476 rec->bytes_written += aio.size; 477 if (switch_output_size(rec)) 478 trigger_hit(&switch_output_trigger); 479 } else { 480 /* 481 * Decrement map->refcount incremented in record__aio_pushfn() 482 * back if record__aio_write() operation failed to start, otherwise 483 * map->refcount is decremented in record__aio_complete() after 484 * aio write operation finishes successfully. 485 */ 486 perf_mmap__put(&map->core); 487 } 488 489 return ret; 490 } 491 492 static off_t record__aio_get_pos(int trace_fd) 493 { 494 return lseek(trace_fd, 0, SEEK_CUR); 495 } 496 497 static void record__aio_set_pos(int trace_fd, off_t pos) 498 { 499 lseek(trace_fd, pos, SEEK_SET); 500 } 501 502 static void record__aio_mmap_read_sync(struct record *rec) 503 { 504 int i; 505 struct evlist *evlist = rec->evlist; 506 struct mmap *maps = evlist__mmap(evlist); 507 508 if (!record__aio_enabled(rec)) 509 return; 510 511 for (i = 0; i < evlist__core(evlist)->nr_mmaps; i++) { 512 struct mmap *map = &maps[i]; 513 514 if (map->core.base) 515 record__aio_sync(map, true); 516 } 517 } 518 519 static int nr_cblocks_default = 1; 520 static int nr_cblocks_max = 4; 521 522 static int record__aio_parse(const struct option *opt, 523 const char *str, 524 int unset) 525 { 526 struct record_opts *opts = (struct record_opts *)opt->value; 527 528 if (unset) { 529 opts->nr_cblocks = 0; 530 } else { 531 if (str) 532 opts->nr_cblocks = strtol(str, NULL, 0); 533 if (!opts->nr_cblocks) 534 opts->nr_cblocks = nr_cblocks_default; 535 } 536 537 return 0; 538 } 539 #else /* HAVE_AIO_SUPPORT */ 540 static int nr_cblocks_max = 0; 541 542 static int record__aio_push(struct record *rec __maybe_unused, struct mmap *map __maybe_unused, 543 off_t *off __maybe_unused) 544 { 545 return -1; 546 } 547 548 static off_t record__aio_get_pos(int trace_fd __maybe_unused) 549 { 550 return -1; 551 } 552 553 static void record__aio_set_pos(int trace_fd __maybe_unused, off_t pos __maybe_unused) 554 { 555 } 556 557 static void record__aio_mmap_read_sync(struct record *rec __maybe_unused) 558 { 559 } 560 #endif 561 562 static int record__aio_enabled(struct record *rec) 563 { 564 return rec->opts.nr_cblocks > 0; 565 } 566 567 #define MMAP_FLUSH_DEFAULT 1 568 static int record__mmap_flush_parse(const struct option *opt, 569 const char *str, 570 int unset) 571 { 572 int flush_max; 573 struct record_opts *opts = (struct record_opts *)opt->value; 574 static struct parse_tag tags[] = { 575 { .tag = 'B', .mult = 1 }, 576 { .tag = 'K', .mult = 1 << 10 }, 577 { .tag = 'M', .mult = 1 << 20 }, 578 { .tag = 'G', .mult = 1 << 30 }, 579 { .tag = 0 }, 580 }; 581 582 if (unset) 583 return 0; 584 585 if (str) { 586 opts->mmap_flush = parse_tag_value(str, tags); 587 if (opts->mmap_flush == (int)-1) 588 opts->mmap_flush = strtol(str, NULL, 0); 589 } 590 591 if (!opts->mmap_flush) 592 opts->mmap_flush = MMAP_FLUSH_DEFAULT; 593 594 flush_max = evlist__mmap_size(opts->mmap_pages); 595 flush_max /= 4; 596 if (opts->mmap_flush > flush_max) 597 opts->mmap_flush = flush_max; 598 599 return 0; 600 } 601 602 #ifdef HAVE_ZSTD_SUPPORT 603 static unsigned int comp_level_default = 1; 604 605 static int record__parse_comp_level(const struct option *opt, const char *str, int unset) 606 { 607 struct record_opts *opts = opt->value; 608 609 if (unset) { 610 opts->comp_level = 0; 611 } else { 612 if (str) 613 opts->comp_level = strtol(str, NULL, 0); 614 if (!opts->comp_level) 615 opts->comp_level = comp_level_default; 616 } 617 618 return 0; 619 } 620 #endif 621 static unsigned int comp_level_max = 22; 622 623 static int record__comp_enabled(struct record *rec) 624 { 625 return rec->opts.comp_level > 0; 626 } 627 628 static int process_synthesized_event(const struct perf_tool *tool, 629 union perf_event *event, 630 struct perf_sample *sample __maybe_unused, 631 struct machine *machine __maybe_unused) 632 { 633 struct record *rec = container_of(tool, struct record, tool); 634 return record__write(rec, NULL, event, event->header.size); 635 } 636 637 static struct mutex synth_lock; 638 639 static int process_locked_synthesized_event(const struct perf_tool *tool, 640 union perf_event *event, 641 struct perf_sample *sample __maybe_unused, 642 struct machine *machine __maybe_unused) 643 { 644 int ret; 645 646 mutex_lock(&synth_lock); 647 ret = process_synthesized_event(tool, event, sample, machine); 648 mutex_unlock(&synth_lock); 649 return ret; 650 } 651 652 static int record__pushfn(struct mmap *map, void *to, void *bf, size_t size) 653 { 654 struct record *rec = to; 655 656 if (record__comp_enabled(rec)) { 657 ssize_t compressed = zstd_compress(rec->session, map, map->data, 658 mmap__mmap_len(map), bf, size); 659 660 if (compressed < 0) 661 return (int)compressed; 662 663 thread->samples++; 664 return record__write(rec, map, map->data, compressed); 665 } 666 667 thread->samples++; 668 return record__write(rec, map, bf, size); 669 } 670 671 static volatile sig_atomic_t signr = -1; 672 static volatile sig_atomic_t child_finished; 673 #ifdef HAVE_EVENTFD_SUPPORT 674 static volatile sig_atomic_t done_fd = -1; 675 #endif 676 677 static void sig_handler(int sig) 678 { 679 if (sig == SIGCHLD) 680 child_finished = 1; 681 else 682 signr = sig; 683 684 done = 1; 685 #ifdef HAVE_EVENTFD_SUPPORT 686 if (done_fd >= 0) { 687 u64 tmp = 1; 688 int orig_errno = errno; 689 690 /* 691 * It is possible for this signal handler to run after done is 692 * checked in the main loop, but before the perf counter fds are 693 * polled. If this happens, the poll() will continue to wait 694 * even though done is set, and will only break out if either 695 * another signal is received, or the counters are ready for 696 * read. To ensure the poll() doesn't sleep when done is set, 697 * use an eventfd (done_fd) to wake up the poll(). 698 */ 699 if (write(done_fd, &tmp, sizeof(tmp)) < 0) 700 pr_err("failed to signal wakeup fd, error: %m\n"); 701 702 errno = orig_errno; 703 } 704 #endif // HAVE_EVENTFD_SUPPORT 705 } 706 707 static void sigsegv_handler(int sig) 708 { 709 perf_hooks__recover(); 710 sighandler_dump_stack(sig); 711 } 712 713 static void record__sig_exit(void) 714 { 715 if (signr == -1) 716 return; 717 718 signal(signr, SIG_DFL); 719 raise(signr); 720 } 721 722 static int record__process_auxtrace(const struct perf_tool *tool, 723 struct mmap *map, 724 union perf_event *event, void *data1, 725 size_t len1, void *data2, size_t len2) 726 { 727 struct record *rec = container_of(tool, struct record, tool); 728 struct perf_data *data = &rec->data; 729 size_t padding; 730 u8 pad[8] = {0}; 731 732 if (!perf_data__is_pipe(data) && perf_data__is_single_file(data)) { 733 off_t file_offset; 734 int fd = perf_data__fd(data); 735 int err; 736 737 file_offset = lseek(fd, 0, SEEK_CUR); 738 if (file_offset == -1) 739 return -1; 740 err = auxtrace_index__auxtrace_event(&rec->session->auxtrace_index, 741 event, file_offset); 742 if (err) 743 return err; 744 } 745 746 /* event.auxtrace.size includes padding, see __auxtrace_mmap__read() */ 747 padding = (len1 + len2) & 7; 748 if (padding) 749 padding = 8 - padding; 750 751 record__write(rec, map, event, event->header.size); 752 record__write(rec, map, data1, len1); 753 if (len2) 754 record__write(rec, map, data2, len2); 755 record__write(rec, map, &pad, padding); 756 757 return 0; 758 } 759 760 static int record__auxtrace_mmap_read(struct record *rec, 761 struct mmap *map) 762 { 763 int ret; 764 765 ret = auxtrace_mmap__read(map, rec->itr, 766 perf_session__env(rec->session), 767 &rec->tool, 768 record__process_auxtrace); 769 if (ret < 0) 770 return ret; 771 772 if (ret) 773 rec->samples++; 774 775 return 0; 776 } 777 778 static int record__auxtrace_mmap_read_snapshot(struct record *rec, 779 struct mmap *map) 780 { 781 int ret; 782 783 ret = auxtrace_mmap__read_snapshot(map, rec->itr, 784 perf_session__env(rec->session), 785 &rec->tool, 786 record__process_auxtrace, 787 rec->opts.auxtrace_snapshot_size); 788 if (ret < 0) 789 return ret; 790 791 if (ret) 792 rec->samples++; 793 794 return 0; 795 } 796 797 static int record__auxtrace_read_snapshot_all(struct record *rec) 798 { 799 int i; 800 int rc = 0; 801 802 for (i = 0; i < evlist__core(rec->evlist)->nr_mmaps; i++) { 803 struct mmap *map = &evlist__mmap(rec->evlist)[i]; 804 805 if (!map->auxtrace_mmap.base) 806 continue; 807 808 if (record__auxtrace_mmap_read_snapshot(rec, map) != 0) { 809 rc = -1; 810 goto out; 811 } 812 } 813 out: 814 return rc; 815 } 816 817 static void record__read_auxtrace_snapshot(struct record *rec, bool on_exit) 818 { 819 pr_debug("Recording AUX area tracing snapshot\n"); 820 if (record__auxtrace_read_snapshot_all(rec) < 0) { 821 trigger_error(&auxtrace_snapshot_trigger); 822 } else { 823 if (auxtrace_record__snapshot_finish(rec->itr, on_exit)) 824 trigger_error(&auxtrace_snapshot_trigger); 825 else 826 trigger_ready(&auxtrace_snapshot_trigger); 827 } 828 } 829 830 static int record__auxtrace_snapshot_exit(struct record *rec) 831 { 832 if (trigger_is_error(&auxtrace_snapshot_trigger)) 833 return 0; 834 835 if (!auxtrace_record__snapshot_started && 836 auxtrace_record__snapshot_start(rec->itr)) 837 return -1; 838 839 record__read_auxtrace_snapshot(rec, true); 840 if (trigger_is_error(&auxtrace_snapshot_trigger)) 841 return -1; 842 843 return 0; 844 } 845 846 static int record__auxtrace_init(struct record *rec) 847 { 848 int err; 849 850 if ((rec->opts.auxtrace_snapshot_opts || rec->opts.auxtrace_sample_opts) 851 && record__threads_enabled(rec)) { 852 pr_err("AUX area tracing options are not available in parallel streaming mode.\n"); 853 return -EINVAL; 854 } 855 856 if (!rec->itr) { 857 err = -EINVAL; 858 rec->itr = auxtrace_record__init(rec->evlist, &err); 859 if (err) 860 return err; 861 } 862 863 err = auxtrace_parse_snapshot_options(rec->itr, &rec->opts, 864 rec->opts.auxtrace_snapshot_opts); 865 if (err) 866 return err; 867 868 err = auxtrace_parse_sample_options(rec->itr, rec->evlist, &rec->opts, 869 rec->opts.auxtrace_sample_opts); 870 if (err) 871 return err; 872 873 err = auxtrace_parse_aux_action(rec->evlist); 874 if (err) 875 return err; 876 877 return auxtrace_parse_filters(rec->evlist); 878 } 879 880 static int record__config_text_poke(struct evlist *evlist) 881 { 882 struct evsel *evsel; 883 884 /* Nothing to do if text poke is already configured */ 885 evlist__for_each_entry(evlist, evsel) { 886 if (evsel->core.attr.text_poke) 887 return 0; 888 } 889 890 evsel = evlist__add_dummy_on_all_cpus(evlist); 891 if (!evsel) 892 return -ENOMEM; 893 894 evsel->core.attr.text_poke = 1; 895 evsel->core.attr.ksymbol = 1; 896 evsel->immediate = true; 897 evsel__set_sample_bit(evsel, TIME); 898 899 return 0; 900 } 901 902 static int record__config_off_cpu(struct record *rec) 903 { 904 return off_cpu_prepare(rec->evlist, &rec->opts.target, &rec->opts); 905 } 906 907 static bool record__tracking_system_wide(struct record *rec) 908 { 909 struct evlist *evlist = rec->evlist; 910 struct evsel *evsel; 911 912 /* 913 * If non-dummy evsel exists, system_wide sideband is need to 914 * help parse sample information. 915 * For example, PERF_EVENT_MMAP event to help parse symbol, 916 * and PERF_EVENT_COMM event to help parse task executable name. 917 */ 918 evlist__for_each_entry(evlist, evsel) { 919 if (!evsel__is_dummy_event(evsel)) 920 return true; 921 } 922 923 return false; 924 } 925 926 static int record__config_tracking_events(struct record *rec) 927 { 928 struct record_opts *opts = &rec->opts; 929 struct evlist *evlist = rec->evlist; 930 bool system_wide = false; 931 struct evsel *evsel; 932 933 /* 934 * For initial_delay, system wide or a hybrid system, we need to add 935 * tracking event so that we can track PERF_RECORD_MMAP to cover the 936 * delay of waiting or event synthesis. 937 */ 938 if (opts->target.initial_delay || target__has_cpu(&opts->target) || 939 perf_pmus__num_core_pmus() > 1) { 940 /* 941 * User space tasks can migrate between CPUs, so when tracing 942 * selected CPUs, sideband for all CPUs is still needed. 943 */ 944 if (!!opts->target.cpu_list && record__tracking_system_wide(rec)) 945 system_wide = true; 946 947 evsel = evlist__findnew_tracking_event(evlist, system_wide); 948 if (!evsel) 949 return -ENOMEM; 950 951 /* 952 * Enable the tracking event when the process is forked for 953 * initial_delay, immediately for system wide. 954 */ 955 if (opts->target.initial_delay && !evsel->immediate && 956 !target__has_cpu(&opts->target)) 957 evsel->core.attr.enable_on_exec = 1; 958 else 959 evsel->immediate = 1; 960 } 961 962 return 0; 963 } 964 965 static bool record__kcore_readable(struct machine *machine) 966 { 967 char kcore[PATH_MAX]; 968 int fd; 969 970 scnprintf(kcore, sizeof(kcore), "%s/proc/kcore", machine->root_dir); 971 972 fd = open(kcore, O_RDONLY); 973 if (fd < 0) 974 return false; 975 976 close(fd); 977 978 return true; 979 } 980 981 static int record__kcore_copy(struct machine *machine, struct perf_data *data) 982 { 983 char from_dir[PATH_MAX]; 984 char kcore_dir[PATH_MAX]; 985 int ret; 986 987 snprintf(from_dir, sizeof(from_dir), "%s/proc", machine->root_dir); 988 989 ret = perf_data__make_kcore_dir(data, kcore_dir, sizeof(kcore_dir)); 990 if (ret) 991 return ret; 992 993 return kcore_copy(from_dir, kcore_dir); 994 } 995 996 static void record__thread_data_init_pipes(struct record_thread *thread_data) 997 { 998 thread_data->pipes.msg[0] = -1; 999 thread_data->pipes.msg[1] = -1; 1000 thread_data->pipes.ack[0] = -1; 1001 thread_data->pipes.ack[1] = -1; 1002 } 1003 1004 static int record__thread_data_open_pipes(struct record_thread *thread_data) 1005 { 1006 if (pipe(thread_data->pipes.msg)) 1007 return -EINVAL; 1008 1009 if (pipe(thread_data->pipes.ack)) { 1010 close(thread_data->pipes.msg[0]); 1011 thread_data->pipes.msg[0] = -1; 1012 close(thread_data->pipes.msg[1]); 1013 thread_data->pipes.msg[1] = -1; 1014 return -EINVAL; 1015 } 1016 1017 pr_debug2("thread_data[%p]: msg=[%d,%d], ack=[%d,%d]\n", thread_data, 1018 thread_data->pipes.msg[0], thread_data->pipes.msg[1], 1019 thread_data->pipes.ack[0], thread_data->pipes.ack[1]); 1020 1021 return 0; 1022 } 1023 1024 static void record__thread_data_close_pipes(struct record_thread *thread_data) 1025 { 1026 if (thread_data->pipes.msg[0] != -1) { 1027 close(thread_data->pipes.msg[0]); 1028 thread_data->pipes.msg[0] = -1; 1029 } 1030 if (thread_data->pipes.msg[1] != -1) { 1031 close(thread_data->pipes.msg[1]); 1032 thread_data->pipes.msg[1] = -1; 1033 } 1034 if (thread_data->pipes.ack[0] != -1) { 1035 close(thread_data->pipes.ack[0]); 1036 thread_data->pipes.ack[0] = -1; 1037 } 1038 if (thread_data->pipes.ack[1] != -1) { 1039 close(thread_data->pipes.ack[1]); 1040 thread_data->pipes.ack[1] = -1; 1041 } 1042 } 1043 1044 static bool evlist__per_thread(struct evlist *evlist) 1045 { 1046 return cpu_map__is_dummy(evlist__core(evlist)->user_requested_cpus); 1047 } 1048 1049 static int record__thread_data_init_maps(struct record_thread *thread_data, struct evlist *evlist) 1050 { 1051 int m, tm, nr_mmaps = evlist__core(evlist)->nr_mmaps; 1052 struct mmap *mmap = evlist__mmap(evlist); 1053 struct mmap *overwrite_mmap = evlist__overwrite_mmap(evlist); 1054 struct perf_cpu_map *cpus = evlist__core(evlist)->all_cpus; 1055 bool per_thread = evlist__per_thread(evlist); 1056 1057 if (per_thread) 1058 thread_data->nr_mmaps = nr_mmaps; 1059 else 1060 thread_data->nr_mmaps = bitmap_weight(thread_data->mask->maps.bits, 1061 thread_data->mask->maps.nbits); 1062 if (mmap) { 1063 thread_data->maps = calloc(thread_data->nr_mmaps, sizeof(struct mmap *)); 1064 if (!thread_data->maps) 1065 return -ENOMEM; 1066 } 1067 if (overwrite_mmap) { 1068 thread_data->overwrite_maps = calloc(thread_data->nr_mmaps, sizeof(struct mmap *)); 1069 if (!thread_data->overwrite_maps) { 1070 zfree(&thread_data->maps); 1071 return -ENOMEM; 1072 } 1073 } 1074 pr_debug2("thread_data[%p]: nr_mmaps=%d, maps=%p, ow_maps=%p\n", thread_data, 1075 thread_data->nr_mmaps, thread_data->maps, thread_data->overwrite_maps); 1076 1077 for (m = 0, tm = 0; m < nr_mmaps && tm < thread_data->nr_mmaps; m++) { 1078 if (per_thread || 1079 test_bit(perf_cpu_map__cpu(cpus, m).cpu, thread_data->mask->maps.bits)) { 1080 if (thread_data->maps) { 1081 thread_data->maps[tm] = &mmap[m]; 1082 pr_debug2("thread_data[%p]: cpu%d: maps[%d] -> mmap[%d]\n", 1083 thread_data, perf_cpu_map__cpu(cpus, m).cpu, tm, m); 1084 } 1085 if (thread_data->overwrite_maps) { 1086 thread_data->overwrite_maps[tm] = &overwrite_mmap[m]; 1087 pr_debug2("thread_data[%p]: cpu%d: ow_maps[%d] -> ow_mmap[%d]\n", 1088 thread_data, perf_cpu_map__cpu(cpus, m).cpu, tm, m); 1089 } 1090 tm++; 1091 } 1092 } 1093 1094 return 0; 1095 } 1096 1097 static int record__thread_data_init_pollfd(struct record_thread *thread_data, struct evlist *evlist) 1098 { 1099 int f, tm, pos; 1100 struct mmap *map, *overwrite_map; 1101 1102 fdarray__init(&thread_data->pollfd, 64); 1103 1104 for (tm = 0; tm < thread_data->nr_mmaps; tm++) { 1105 map = thread_data->maps ? thread_data->maps[tm] : NULL; 1106 overwrite_map = thread_data->overwrite_maps ? 1107 thread_data->overwrite_maps[tm] : NULL; 1108 1109 for (f = 0; f < evlist__core(evlist)->pollfd.nr; f++) { 1110 void *ptr = evlist__core(evlist)->pollfd.priv[f].ptr; 1111 1112 if ((map && ptr == map) || (overwrite_map && ptr == overwrite_map)) { 1113 pos = fdarray__dup_entry_from(&thread_data->pollfd, f, 1114 &evlist__core(evlist)->pollfd); 1115 if (pos < 0) 1116 return pos; 1117 pr_debug2("thread_data[%p]: pollfd[%d] <- event_fd=%d\n", 1118 thread_data, pos, 1119 evlist__core(evlist)->pollfd.entries[f].fd); 1120 } 1121 } 1122 } 1123 1124 return 0; 1125 } 1126 1127 static void record__free_thread_data(struct record *rec) 1128 { 1129 int t; 1130 struct record_thread *thread_data = rec->thread_data; 1131 1132 if (thread_data == NULL) 1133 return; 1134 1135 for (t = 0; t < rec->nr_threads; t++) { 1136 record__thread_data_close_pipes(&thread_data[t]); 1137 zfree(&thread_data[t].maps); 1138 zfree(&thread_data[t].overwrite_maps); 1139 fdarray__exit(&thread_data[t].pollfd); 1140 } 1141 1142 zfree(&rec->thread_data); 1143 } 1144 1145 static int record__map_thread_evlist_pollfd_indexes(struct record *rec, 1146 int evlist_pollfd_index, 1147 int thread_pollfd_index) 1148 { 1149 size_t x = rec->index_map_cnt; 1150 1151 if (realloc_array_as_needed(rec->index_map, rec->index_map_sz, x, NULL)) 1152 return -ENOMEM; 1153 rec->index_map[x].evlist_pollfd_index = evlist_pollfd_index; 1154 rec->index_map[x].thread_pollfd_index = thread_pollfd_index; 1155 rec->index_map_cnt += 1; 1156 return 0; 1157 } 1158 1159 static int record__update_evlist_pollfd_from_thread(struct record *rec, 1160 struct evlist *evlist, 1161 struct record_thread *thread_data) 1162 { 1163 struct pollfd *e_entries = evlist__core(evlist)->pollfd.entries; 1164 struct pollfd *t_entries = thread_data->pollfd.entries; 1165 int err = 0; 1166 size_t i; 1167 1168 for (i = 0; i < rec->index_map_cnt; i++) { 1169 int e_pos = rec->index_map[i].evlist_pollfd_index; 1170 int t_pos = rec->index_map[i].thread_pollfd_index; 1171 1172 if (e_entries[e_pos].fd == -1 || e_entries[e_pos].events == 0) { 1173 /* 1174 * If the control file descriptor was closed, then evlist__ctlfd_process() 1175 * will have called evlist__finalize_ctlfd() on the PREVIOUS loop iteration 1176 * to cleanly set the core evlist's e_entries[e_pos].fd to -1. 1177 * 1178 * Since nonfilterable items are skipped by fdarray__filter(), the 1179 * thread's local t_entries[t_pos] retains its original state. 1180 * We must explicitly propagate the finalized -1 state to t_entries 1181 * BEFORE evaluating the strict equivalence check below. 1182 */ 1183 t_entries[t_pos].fd = -1; 1184 t_entries[t_pos].events = 0; 1185 } 1186 1187 if (e_entries[e_pos].fd != t_entries[t_pos].fd || 1188 e_entries[e_pos].events != t_entries[t_pos].events) { 1189 pr_err("Thread and evlist pollfd index mismatch\n"); 1190 err = -EINVAL; 1191 continue; 1192 } 1193 e_entries[e_pos].revents = t_entries[t_pos].revents; 1194 } 1195 return err; 1196 } 1197 1198 static int record__dup_non_perf_events(struct record *rec, 1199 struct evlist *evlist, 1200 struct record_thread *thread_data) 1201 { 1202 struct fdarray *fda = &evlist__core(evlist)->pollfd; 1203 int i, ret; 1204 1205 for (i = 0; i < fda->nr; i++) { 1206 if (!(fda->priv[i].flags & fdarray_flag__non_perf_event)) 1207 continue; 1208 ret = fdarray__dup_entry_from(&thread_data->pollfd, i, fda); 1209 if (ret < 0) { 1210 pr_err("Failed to duplicate descriptor in main thread pollfd\n"); 1211 return ret; 1212 } 1213 pr_debug2("thread_data[%p]: pollfd[%d] <- non_perf_event fd=%d\n", 1214 thread_data, ret, fda->entries[i].fd); 1215 ret = record__map_thread_evlist_pollfd_indexes(rec, i, ret); 1216 if (ret < 0) { 1217 pr_err("Failed to map thread and evlist pollfd indexes\n"); 1218 return ret; 1219 } 1220 } 1221 return 0; 1222 } 1223 1224 static int record__alloc_thread_data(struct record *rec, struct evlist *evlist) 1225 { 1226 int t, ret; 1227 struct record_thread *thread_data; 1228 1229 rec->thread_data = calloc(rec->nr_threads, sizeof(*(rec->thread_data))); 1230 if (!rec->thread_data) { 1231 pr_err("Failed to allocate thread data\n"); 1232 return -ENOMEM; 1233 } 1234 thread_data = rec->thread_data; 1235 1236 for (t = 0; t < rec->nr_threads; t++) 1237 record__thread_data_init_pipes(&thread_data[t]); 1238 1239 for (t = 0; t < rec->nr_threads; t++) { 1240 thread_data[t].rec = rec; 1241 thread_data[t].mask = &rec->thread_masks[t]; 1242 ret = record__thread_data_init_maps(&thread_data[t], evlist); 1243 if (ret) { 1244 pr_err("Failed to initialize thread[%d] maps\n", t); 1245 goto out_free; 1246 } 1247 ret = record__thread_data_init_pollfd(&thread_data[t], evlist); 1248 if (ret) { 1249 pr_err("Failed to initialize thread[%d] pollfd\n", t); 1250 goto out_free; 1251 } 1252 if (t) { 1253 thread_data[t].tid = -1; 1254 ret = record__thread_data_open_pipes(&thread_data[t]); 1255 if (ret) { 1256 pr_err("Failed to open thread[%d] communication pipes\n", t); 1257 goto out_free; 1258 } 1259 ret = fdarray__add(&thread_data[t].pollfd, thread_data[t].pipes.msg[0], 1260 POLLIN | POLLERR | POLLHUP, fdarray_flag__nonfilterable); 1261 if (ret < 0) { 1262 pr_err("Failed to add descriptor to thread[%d] pollfd\n", t); 1263 goto out_free; 1264 } 1265 thread_data[t].ctlfd_pos = ret; 1266 pr_debug2("thread_data[%p]: pollfd[%d] <- ctl_fd=%d\n", 1267 thread_data, thread_data[t].ctlfd_pos, 1268 thread_data[t].pipes.msg[0]); 1269 } else { 1270 thread_data[t].tid = gettid(); 1271 1272 ret = record__dup_non_perf_events(rec, evlist, &thread_data[t]); 1273 if (ret < 0) 1274 goto out_free; 1275 1276 thread_data[t].ctlfd_pos = -1; /* Not used */ 1277 } 1278 } 1279 1280 return 0; 1281 1282 out_free: 1283 record__free_thread_data(rec); 1284 1285 return ret; 1286 } 1287 1288 static int record__mmap_evlist(struct record *rec, 1289 struct evlist *evlist) 1290 { 1291 int i, ret; 1292 struct record_opts *opts = &rec->opts; 1293 bool auxtrace_overwrite = opts->auxtrace_snapshot_mode || 1294 opts->auxtrace_sample_mode; 1295 1296 if (opts->affinity != PERF_AFFINITY_SYS) 1297 cpu__setup_cpunode_map(); 1298 1299 if (evlist__mmap_ex(evlist, opts->mmap_pages, 1300 opts->auxtrace_mmap_pages, 1301 auxtrace_overwrite, 1302 opts->nr_cblocks, opts->affinity, 1303 opts->mmap_flush, opts->comp_level) < 0) { 1304 if (errno == EPERM) { 1305 pr_err("Permission error mapping pages.\n" 1306 "Consider increasing " 1307 "/proc/sys/kernel/perf_event_mlock_kb,\n" 1308 "or try again with a smaller value of -m/--mmap_pages.\n" 1309 "(current value: %u,%u)\n", 1310 opts->mmap_pages, opts->auxtrace_mmap_pages); 1311 return -errno; 1312 } else { 1313 pr_err("failed to mmap: %m\n"); 1314 if (errno) 1315 return -errno; 1316 else 1317 return -EINVAL; 1318 } 1319 } 1320 1321 if (evlist__initialize_ctlfd(evlist, opts->ctl_fd, opts->ctl_fd_ack)) 1322 return -1; 1323 1324 ret = record__alloc_thread_data(rec, evlist); 1325 if (ret) 1326 return ret; 1327 1328 if (record__threads_enabled(rec)) { 1329 ret = perf_data__create_dir(&rec->data, evlist__core(evlist)->nr_mmaps); 1330 if (ret) { 1331 errno = -ret; 1332 pr_err("Failed to create data directory: %m\n"); 1333 return ret; 1334 } 1335 for (i = 0; i < evlist__core(evlist)->nr_mmaps; i++) { 1336 if (evlist__mmap(evlist)) 1337 evlist__mmap(evlist)[i].file = &rec->data.dir.files[i]; 1338 if (evlist__overwrite_mmap(evlist)) 1339 evlist__overwrite_mmap(evlist)[i].file = &rec->data.dir.files[i]; 1340 } 1341 } 1342 1343 return 0; 1344 } 1345 1346 static int record__mmap(struct record *rec) 1347 { 1348 return record__mmap_evlist(rec, rec->evlist); 1349 } 1350 1351 static int record__open(struct record *rec) 1352 { 1353 char msg[BUFSIZ]; 1354 struct evsel *pos; 1355 struct evlist *evlist = rec->evlist; 1356 struct perf_session *session = rec->session; 1357 struct record_opts *opts = &rec->opts; 1358 int rc = 0; 1359 bool skipped = false; 1360 bool removed_tracking = false; 1361 1362 evlist__for_each_entry(evlist, pos) { 1363 if (removed_tracking) { 1364 /* 1365 * Normally the head of the list has tracking enabled 1366 * for sideband data like mmaps. If this event is 1367 * removed, make sure to add tracking to the next 1368 * processed event. 1369 */ 1370 if (!pos->tracking) { 1371 pos->tracking = true; 1372 evsel__config(pos, opts, &callchain_param); 1373 } 1374 removed_tracking = false; 1375 } 1376 try_again: 1377 if (evsel__open(pos, pos->core.cpus, pos->core.threads) < 0) { 1378 bool report_error = true; 1379 1380 if (evsel__fallback(pos, &opts->target, errno, msg, sizeof(msg))) { 1381 if (verbose > 0) 1382 ui__warning("%s\n", msg); 1383 goto try_again; 1384 } 1385 if ((errno == EINVAL || errno == EBADF) && 1386 pos->core.leader != &pos->core && 1387 pos->weak_group) { 1388 pos = evlist__reset_weak_group(evlist, pos, true); 1389 goto try_again; 1390 } 1391 #if defined(__aarch64__) || defined(__arm__) 1392 if (strstr(evsel__name(pos), "cycles")) { 1393 struct evsel *pos2; 1394 /* 1395 * Unfortunately ARM has many events named 1396 * "cycles" on PMUs like the system-level (L3) 1397 * cache which don't support sampling. Only 1398 * display such failures to open when there is 1399 * only 1 cycles event or verbose is enabled. 1400 */ 1401 evlist__for_each_entry(evlist, pos2) { 1402 if (pos2 == pos) 1403 continue; 1404 if (strstr(evsel__name(pos2), "cycles")) { 1405 report_error = false; 1406 break; 1407 } 1408 } 1409 } 1410 #endif 1411 if (report_error || verbose > 0) { 1412 evsel__open_strerror(pos, &opts->target, errno, msg, sizeof(msg)); 1413 ui__error("Failure to open event '%s' on PMU '%s' which will be " 1414 "removed.\n%s\n", 1415 evsel__name(pos), evsel__pmu_name(pos), msg); 1416 } 1417 if (pos->tracking) 1418 removed_tracking = true; 1419 pos->skippable = true; 1420 skipped = true; 1421 } 1422 } 1423 1424 if (skipped) { 1425 struct evsel *tmp; 1426 int idx = 0; 1427 bool evlist_empty = true; 1428 1429 /* Remove evsels that failed to open and update indices. */ 1430 evlist__for_each_entry_safe(evlist, tmp, pos) { 1431 if (pos->skippable) { 1432 evlist__remove(evlist, pos); 1433 continue; 1434 } 1435 1436 /* 1437 * Note, dummy events may be command line parsed or 1438 * added by the tool. We care about supporting `perf 1439 * record -e dummy` which may be used as a permission 1440 * check. Dummy events that are added to the command 1441 * line and opened along with other events that fail, 1442 * will still fail as if the dummy events were tool 1443 * added events for the sake of code simplicity. 1444 */ 1445 if (!evsel__is_dummy_event(pos)) 1446 evlist_empty = false; 1447 } 1448 evlist__for_each_entry(evlist, pos) { 1449 pos->core.idx = idx++; 1450 } 1451 /* If list is empty then fail. */ 1452 if (evlist_empty) { 1453 ui__error("Failure to open any events for recording.\n"); 1454 rc = -1; 1455 goto out; 1456 } 1457 } 1458 if (symbol_conf.kptr_restrict && !evlist__exclude_kernel(evlist)) { 1459 pr_warning( 1460 "WARNING: Kernel address maps (/proc/{kallsyms,modules}) are restricted,\n" 1461 "check /proc/sys/kernel/kptr_restrict and /proc/sys/kernel/perf_event_paranoid.\n\n" 1462 "Samples in kernel functions may not be resolved if a suitable vmlinux\n" 1463 "file is not found in the buildid cache or in the vmlinux path.\n\n" 1464 "Samples in kernel modules won't be resolved at all.\n\n" 1465 "If some relocation was applied (e.g. kexec) symbols may be misresolved\n" 1466 "even with a suitable vmlinux or kallsyms file.\n\n"); 1467 } 1468 1469 if (evlist__apply_filters(evlist, &pos, &opts->target)) { 1470 pr_err("failed to set filter \"%s\" on event %s: %m\n", 1471 pos->filter ?: "BPF", evsel__name(pos)); 1472 rc = -1; 1473 goto out; 1474 } 1475 1476 rc = record__mmap(rec); 1477 if (rc) 1478 goto out; 1479 1480 session->evlist = evlist; 1481 perf_session__set_id_hdr_size(session); 1482 out: 1483 return rc; 1484 } 1485 1486 static void set_timestamp_boundary(struct record *rec, u64 sample_time) 1487 { 1488 if (evlist__first_sample_time(rec->evlist) == 0) 1489 evlist__set_first_sample_time(rec->evlist, sample_time); 1490 1491 if (sample_time) 1492 evlist__set_last_sample_time(rec->evlist, sample_time); 1493 } 1494 1495 static int process_sample_event(const struct perf_tool *tool, 1496 union perf_event *event, 1497 struct perf_sample *sample, 1498 struct machine *machine) 1499 { 1500 struct record *rec = container_of(tool, struct record, tool); 1501 1502 set_timestamp_boundary(rec, sample->time); 1503 1504 if (rec->buildid_all) 1505 return 0; 1506 1507 rec->samples++; 1508 return build_id__mark_dso_hit(tool, event, sample, machine); 1509 } 1510 1511 static int process_buildids(struct record *rec) 1512 { 1513 struct perf_session *session = rec->session; 1514 1515 if (perf_data__size(&rec->data) == 0) 1516 return 0; 1517 1518 /* A single DSO is needed and not all inline frames. */ 1519 symbol_conf.inline_name = false; 1520 /* 1521 * During this process, it'll load kernel map and replace the 1522 * dso->long_name to a real pathname it found. In this case 1523 * we prefer the vmlinux path like 1524 * /lib/modules/3.16.4/build/vmlinux 1525 * 1526 * rather than build-id path (in debug directory). 1527 * $HOME/.debug/.build-id/f0/6e17aa50adf4d00b88925e03775de107611551 1528 */ 1529 symbol_conf.ignore_vmlinux_buildid = true; 1530 /* 1531 * If --buildid-all is given, it marks all DSO regardless of hits, 1532 * so no need to process samples. But if timestamp_boundary is enabled, 1533 * it still needs to walk on all samples to get the timestamps of 1534 * first/last samples. 1535 */ 1536 if (rec->buildid_all && !rec->timestamp_boundary) 1537 rec->tool.sample = process_event_sample_stub; 1538 1539 return perf_session__process_events(session); 1540 } 1541 1542 static void perf_event__synthesize_guest_os(struct machine *machine, void *data) 1543 { 1544 int err; 1545 struct perf_tool *tool = data; 1546 /* 1547 *As for guest kernel when processing subcommand record&report, 1548 *we arrange module mmap prior to guest kernel mmap and trigger 1549 *a preload dso because default guest module symbols are loaded 1550 *from guest kallsyms instead of /lib/modules/XXX/XXX. This 1551 *method is used to avoid symbol missing when the first addr is 1552 *in module instead of in guest kernel. 1553 */ 1554 err = perf_event__synthesize_modules(tool, process_synthesized_event, 1555 machine); 1556 if (err < 0) 1557 pr_err("Couldn't record guest kernel [%d]'s reference" 1558 " relocation symbol.\n", machine->pid); 1559 1560 /* 1561 * We use _stext for guest kernel because guest kernel's /proc/kallsyms 1562 * have no _text sometimes. 1563 */ 1564 err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event, 1565 machine); 1566 if (err < 0) 1567 pr_err("Couldn't record guest kernel [%d]'s reference" 1568 " relocation symbol.\n", machine->pid); 1569 } 1570 1571 static struct perf_event_header finished_round_event = { 1572 .size = sizeof(struct perf_event_header), 1573 .type = PERF_RECORD_FINISHED_ROUND, 1574 }; 1575 1576 static struct perf_event_header finished_init_event = { 1577 .size = sizeof(struct perf_event_header), 1578 .type = PERF_RECORD_FINISHED_INIT, 1579 }; 1580 1581 static void record__adjust_affinity(struct record *rec, struct mmap *map) 1582 { 1583 if (map->core.cpu.cpu >= 0 && rec->opts.affinity != PERF_AFFINITY_SYS && 1584 !bitmap_equal(thread->mask->affinity.bits, map->affinity_mask.bits, 1585 thread->mask->affinity.nbits)) { 1586 bitmap_zero(thread->mask->affinity.bits, thread->mask->affinity.nbits); 1587 bitmap_or(thread->mask->affinity.bits, thread->mask->affinity.bits, 1588 map->affinity_mask.bits, thread->mask->affinity.nbits); 1589 sched_setaffinity(0, MMAP_CPU_MASK_BYTES(&thread->mask->affinity), 1590 (cpu_set_t *)thread->mask->affinity.bits); 1591 if (verbose == 2) { 1592 pr_debug("threads[%d]: running on cpu%d: ", thread->tid, sched_getcpu()); 1593 mmap_cpu_mask__scnprintf(&thread->mask->affinity, "affinity"); 1594 } 1595 } 1596 } 1597 1598 /* 1599 * Called once with data_size == 0 to start a record, then once with 1600 * data_size == compressed payload size to finalize and 8-byte-pad it 1601 * (unaligned records trip ASan in the reader). 1602 * Returns the bytes written, or -1 if it won't fit. 1603 */ 1604 static ssize_t process_comp_header(void *record, size_t dst_size, 1605 size_t data_size) 1606 { 1607 struct perf_record_compressed2 *event = record; 1608 size_t size = sizeof(*event); 1609 1610 if (data_size) { 1611 size_t padding; 1612 1613 event->data_size = data_size; 1614 event->header.size = PERF_ALIGN(size + data_size, sizeof(u64)); 1615 padding = event->header.size - size - data_size; 1616 if (padding > dst_size) 1617 return -1; 1618 memset(record + size + data_size, 0, padding); 1619 return padding; 1620 } 1621 1622 if (size > dst_size) 1623 return -1; 1624 1625 event->header.type = PERF_RECORD_COMPRESSED2; 1626 event->header.size = size; 1627 event->data_size = 0; 1628 1629 return size; 1630 } 1631 1632 static ssize_t zstd_compress(struct perf_session *session, struct mmap *map, 1633 void *dst, size_t dst_size, void *src, size_t src_size) 1634 { 1635 ssize_t compressed; 1636 /* 1637 * Reserve space so per-record PERF_ALIGN() padding keeps header.size 1638 * within u16. 1639 */ 1640 size_t max_record_size = PERF_SAMPLE_MAX_SIZE 1641 - sizeof(struct perf_record_compressed2) - sizeof(u64); 1642 struct zstd_data *zstd_data = &session->zstd_data; 1643 1644 if (map && map->file) 1645 zstd_data = &map->zstd_data; 1646 1647 compressed = zstd_compress_stream_to_records(zstd_data, dst, dst_size, src, src_size, 1648 max_record_size, process_comp_header); 1649 if (compressed < 0) 1650 return compressed; 1651 1652 if (map && map->file) { 1653 thread->bytes_transferred += src_size; 1654 thread->bytes_compressed += compressed; 1655 } else { 1656 session->bytes_transferred += src_size; 1657 session->bytes_compressed += compressed; 1658 } 1659 1660 return compressed; 1661 } 1662 1663 static int record__mmap_read_evlist(struct record *rec, struct evlist *evlist, 1664 bool overwrite, bool synch) 1665 { 1666 u64 bytes_written = rec->bytes_written; 1667 int i; 1668 int rc = 0; 1669 int nr_mmaps; 1670 struct mmap **maps; 1671 int trace_fd = perf_data__fd(&rec->data); 1672 off_t off = 0; 1673 1674 if (!evlist) 1675 return 0; 1676 1677 nr_mmaps = thread->nr_mmaps; 1678 maps = overwrite ? thread->overwrite_maps : thread->maps; 1679 1680 if (!maps) 1681 return 0; 1682 1683 if (overwrite && evlist__bkw_mmap_state(evlist) != BKW_MMAP_DATA_PENDING) 1684 return 0; 1685 1686 if (record__aio_enabled(rec)) 1687 off = record__aio_get_pos(trace_fd); 1688 1689 for (i = 0; i < nr_mmaps; i++) { 1690 u64 flush = 0; 1691 struct mmap *map = maps[i]; 1692 1693 if (map->core.base) { 1694 record__adjust_affinity(rec, map); 1695 if (synch) { 1696 flush = map->core.flush; 1697 map->core.flush = 1; 1698 } 1699 if (!record__aio_enabled(rec)) { 1700 if (perf_mmap__push(map, rec, record__pushfn) < 0) { 1701 if (synch) 1702 map->core.flush = flush; 1703 rc = -1; 1704 goto out; 1705 } 1706 } else { 1707 if (record__aio_push(rec, map, &off) < 0) { 1708 record__aio_set_pos(trace_fd, off); 1709 if (synch) 1710 map->core.flush = flush; 1711 rc = -1; 1712 goto out; 1713 } 1714 } 1715 if (synch) 1716 map->core.flush = flush; 1717 } 1718 1719 if (map->auxtrace_mmap.base && !rec->opts.auxtrace_snapshot_mode && 1720 !rec->opts.auxtrace_sample_mode && 1721 record__auxtrace_mmap_read(rec, map) != 0) { 1722 rc = -1; 1723 goto out; 1724 } 1725 } 1726 1727 if (record__aio_enabled(rec)) 1728 record__aio_set_pos(trace_fd, off); 1729 1730 /* 1731 * Mark the round finished in case we wrote 1732 * at least one event. 1733 * 1734 * No need for round events in directory mode, 1735 * because per-cpu maps and files have data 1736 * sorted by kernel. 1737 */ 1738 if (!record__threads_enabled(rec) && bytes_written != rec->bytes_written) 1739 rc = record__write(rec, NULL, &finished_round_event, sizeof(finished_round_event)); 1740 1741 if (overwrite) 1742 evlist__toggle_bkw_mmap(evlist, BKW_MMAP_EMPTY); 1743 out: 1744 return rc; 1745 } 1746 1747 static int record__mmap_read_all(struct record *rec, bool synch) 1748 { 1749 int err; 1750 1751 err = record__mmap_read_evlist(rec, rec->evlist, false, synch); 1752 if (err) 1753 return err; 1754 1755 return record__mmap_read_evlist(rec, rec->evlist, true, synch); 1756 } 1757 1758 static void record__thread_munmap_filtered(struct fdarray *fda, int fd, 1759 void *arg __maybe_unused) 1760 { 1761 struct perf_mmap *map = fda->priv[fd].ptr; 1762 1763 if (map) 1764 perf_mmap__put(map); 1765 } 1766 1767 static void *record__thread(void *arg) 1768 { 1769 enum thread_msg msg = THREAD_MSG__READY; 1770 bool terminate = false; 1771 struct fdarray *pollfd; 1772 int err, ctlfd_pos; 1773 1774 thread = arg; 1775 thread->tid = gettid(); 1776 1777 err = write(thread->pipes.ack[1], &msg, sizeof(msg)); 1778 if (err == -1) 1779 pr_warning("threads[%d]: failed to notify on start: %m\n", thread->tid); 1780 1781 pr_debug("threads[%d]: started on cpu%d\n", thread->tid, sched_getcpu()); 1782 1783 pollfd = &thread->pollfd; 1784 ctlfd_pos = thread->ctlfd_pos; 1785 1786 for (;;) { 1787 unsigned long long hits = thread->samples; 1788 1789 if (record__mmap_read_all(thread->rec, false) < 0 || terminate) 1790 break; 1791 1792 if (hits == thread->samples) { 1793 1794 err = fdarray__poll(pollfd, -1); 1795 /* 1796 * Propagate error, only if there's any. Ignore positive 1797 * number of returned events and interrupt error. 1798 */ 1799 if (err > 0 || (err < 0 && errno == EINTR)) 1800 err = 0; 1801 thread->waking++; 1802 1803 if (fdarray__filter(pollfd, POLLERR | POLLHUP, 1804 record__thread_munmap_filtered, NULL) == 0) 1805 break; 1806 } 1807 1808 if (pollfd->entries[ctlfd_pos].revents & POLLHUP) { 1809 terminate = true; 1810 close(thread->pipes.msg[0]); 1811 thread->pipes.msg[0] = -1; 1812 pollfd->entries[ctlfd_pos].fd = -1; 1813 pollfd->entries[ctlfd_pos].events = 0; 1814 } 1815 1816 pollfd->entries[ctlfd_pos].revents = 0; 1817 } 1818 record__mmap_read_all(thread->rec, true); 1819 1820 err = write(thread->pipes.ack[1], &msg, sizeof(msg)); 1821 if (err == -1) 1822 pr_warning("threads[%d]: failed to notify on termination: %m\n", thread->tid); 1823 1824 return NULL; 1825 } 1826 1827 static void record__init_features(struct record *rec) 1828 { 1829 struct perf_session *session = rec->session; 1830 int feat; 1831 1832 for (feat = HEADER_FIRST_FEATURE; feat < HEADER_LAST_FEATURE; feat++) 1833 perf_header__set_feat(&session->header, feat); 1834 1835 if (rec->no_buildid) 1836 perf_header__clear_feat(&session->header, HEADER_BUILD_ID); 1837 1838 if (!have_tracepoints(&evlist__core(rec->evlist)->entries)) 1839 perf_header__clear_feat(&session->header, HEADER_TRACING_DATA); 1840 1841 if (!rec->opts.branch_stack) 1842 perf_header__clear_feat(&session->header, HEADER_BRANCH_STACK); 1843 1844 if (!rec->opts.full_auxtrace) 1845 perf_header__clear_feat(&session->header, HEADER_AUXTRACE); 1846 1847 if (!(rec->opts.use_clockid && rec->opts.clockid_res_ns)) 1848 perf_header__clear_feat(&session->header, HEADER_CLOCKID); 1849 1850 if (!rec->opts.use_clockid) 1851 perf_header__clear_feat(&session->header, HEADER_CLOCK_DATA); 1852 1853 if (!record__threads_enabled(rec)) 1854 perf_header__clear_feat(&session->header, HEADER_DIR_FORMAT); 1855 1856 if (!record__comp_enabled(rec)) 1857 perf_header__clear_feat(&session->header, HEADER_COMPRESSED); 1858 1859 perf_header__clear_feat(&session->header, HEADER_STAT); 1860 } 1861 1862 static void 1863 record__finish_output(struct record *rec) 1864 { 1865 int i; 1866 struct perf_data *data = &rec->data; 1867 int fd = perf_data__fd(data); 1868 1869 if (data->is_pipe) { 1870 /* Just to display approx. size */ 1871 data->file.size = rec->bytes_written; 1872 return; 1873 } 1874 1875 rec->session->header.data_size += rec->bytes_written; 1876 data->file.size = perf_data__seek(data, 0, SEEK_CUR); 1877 if (record__threads_enabled(rec)) { 1878 for (i = 0; i < data->dir.nr; i++) { 1879 data->dir.files[i].size = 1880 perf_data_file__seek(&data->dir.files[i], 0, SEEK_CUR); 1881 } 1882 } 1883 1884 /* Buildid scanning disabled or build ID in kernel and synthesized map events. */ 1885 if (!rec->no_buildid || !rec->no_buildid_cache) { 1886 process_buildids(rec); 1887 1888 if (rec->buildid_all) 1889 perf_session__dsos_hit_all(rec->session); 1890 } 1891 perf_session__write_header(rec->session, rec->evlist, fd, true); 1892 perf_session__cache_build_ids(rec->session); 1893 } 1894 1895 static int record__synthesize_workload(struct record *rec, bool tail) 1896 { 1897 int err; 1898 struct perf_thread_map *thread_map; 1899 bool needs_mmap = rec->opts.synth & PERF_SYNTH_MMAP; 1900 1901 if (rec->opts.tail_synthesize != tail) 1902 return 0; 1903 1904 thread_map = thread_map__new_by_tid(evlist__workload_pid(rec->evlist)); 1905 if (thread_map == NULL) 1906 return -1; 1907 1908 err = perf_event__synthesize_thread_map(&rec->tool, thread_map, 1909 process_synthesized_event, 1910 &rec->session->machines.host, 1911 needs_mmap, 1912 rec->opts.record_data_mmap); 1913 perf_thread_map__put(thread_map); 1914 return err; 1915 } 1916 1917 static int write_finished_init(struct record *rec, bool tail) 1918 { 1919 if (rec->opts.tail_synthesize != tail) 1920 return 0; 1921 1922 return record__write(rec, NULL, &finished_init_event, sizeof(finished_init_event)); 1923 } 1924 1925 static int record__synthesize(struct record *rec, bool tail); 1926 1927 static int 1928 record__switch_output(struct record *rec, bool at_exit) 1929 { 1930 struct perf_data *data = &rec->data; 1931 char *new_filename = NULL; 1932 int fd, err; 1933 1934 /* Same Size: "2015122520103046"*/ 1935 char timestamp[] = "InvalidTimestamp"; 1936 1937 record__aio_mmap_read_sync(rec); 1938 1939 write_finished_init(rec, true); 1940 1941 record__synthesize(rec, true); 1942 if (target__none(&rec->opts.target)) 1943 record__synthesize_workload(rec, true); 1944 1945 rec->samples = 0; 1946 record__finish_output(rec); 1947 err = fetch_current_timestamp(timestamp, sizeof(timestamp)); 1948 if (err) { 1949 pr_err("Failed to get current timestamp\n"); 1950 return -EINVAL; 1951 } 1952 1953 fd = perf_data__switch(data, timestamp, 1954 rec->session->header.data_offset, 1955 at_exit, &new_filename); 1956 if (fd >= 0 && !at_exit) { 1957 rec->bytes_written = 0; 1958 rec->session->header.data_size = 0; 1959 } 1960 1961 if (!quiet) { 1962 fprintf(stderr, "[ perf record: Dump %s.%s ]\n", 1963 data->path, timestamp); 1964 } 1965 1966 if (rec->switch_output.num_files) { 1967 int n = rec->switch_output.cur_file + 1; 1968 1969 if (n >= rec->switch_output.num_files) 1970 n = 0; 1971 rec->switch_output.cur_file = n; 1972 if (rec->switch_output.filenames[n]) { 1973 remove(rec->switch_output.filenames[n]); 1974 zfree(&rec->switch_output.filenames[n]); 1975 } 1976 rec->switch_output.filenames[n] = new_filename; 1977 } else { 1978 free(new_filename); 1979 } 1980 1981 /* Output tracking events */ 1982 if (!at_exit) { 1983 record__synthesize(rec, false); 1984 1985 /* 1986 * In 'perf record --switch-output' without -a, 1987 * record__synthesize() in record__switch_output() won't 1988 * generate tracking events because there's no thread_map 1989 * in evlist. Which causes newly created perf.data doesn't 1990 * contain map and comm information. 1991 * Create a fake thread_map and directly call 1992 * perf_event__synthesize_thread_map() for those events. 1993 */ 1994 if (target__none(&rec->opts.target)) 1995 record__synthesize_workload(rec, false); 1996 write_finished_init(rec, false); 1997 } 1998 return fd; 1999 } 2000 2001 static void __record__save_lost_samples(struct record *rec, struct evsel *evsel, 2002 struct perf_record_lost_samples *lost, 2003 int cpu_idx, int thread_idx, u64 lost_count, 2004 u16 misc_flag) 2005 { 2006 struct perf_sample_id *sid; 2007 struct perf_sample sample; 2008 int id_hdr_size; 2009 2010 perf_sample__init(&sample, /*all=*/true); 2011 lost->lost = lost_count; 2012 if (evsel->core.ids) { 2013 sid = xyarray__entry(evsel->core.sample_id, cpu_idx, thread_idx); 2014 sample.id = sid->id; 2015 } 2016 2017 id_hdr_size = perf_event__synthesize_id_sample((void *)(lost + 1), 2018 evsel->core.attr.sample_type, &sample); 2019 lost->header.size = sizeof(*lost) + id_hdr_size; 2020 lost->header.misc = misc_flag; 2021 record__write(rec, NULL, lost, lost->header.size); 2022 perf_sample__exit(&sample); 2023 } 2024 2025 static void record__read_lost_samples(struct record *rec) 2026 { 2027 struct perf_session *session = rec->session; 2028 struct perf_record_lost_samples_and_ids lost; 2029 struct evsel *evsel; 2030 2031 /* there was an error during record__open */ 2032 if (session->evlist == NULL) 2033 return; 2034 2035 evlist__for_each_entry(session->evlist, evsel) { 2036 struct xyarray *xy = evsel->core.sample_id; 2037 u64 lost_count; 2038 2039 if (xy == NULL || evsel->core.fd == NULL) 2040 continue; 2041 if (xyarray__max_x(evsel->core.fd) != xyarray__max_x(xy) || 2042 xyarray__max_y(evsel->core.fd) != xyarray__max_y(xy)) { 2043 pr_debug("Unmatched FD vs. sample ID: skip reading LOST count\n"); 2044 continue; 2045 } 2046 2047 for (int x = 0; x < xyarray__max_x(xy); x++) { 2048 for (int y = 0; y < xyarray__max_y(xy); y++) { 2049 struct perf_counts_values count; 2050 2051 if (perf_evsel__read(&evsel->core, x, y, &count) < 0) { 2052 pr_debug("read LOST count failed\n"); 2053 return; 2054 } 2055 2056 if (count.lost) { 2057 memset(&lost, 0, sizeof(lost)); 2058 lost.lost.header.type = PERF_RECORD_LOST_SAMPLES; 2059 __record__save_lost_samples(rec, evsel, &lost.lost, 2060 x, y, count.lost, 0); 2061 } 2062 } 2063 } 2064 2065 lost_count = perf_bpf_filter__lost_count(evsel); 2066 if (lost_count) { 2067 memset(&lost, 0, sizeof(lost)); 2068 lost.lost.header.type = PERF_RECORD_LOST_SAMPLES; 2069 __record__save_lost_samples(rec, evsel, &lost.lost, 0, 0, lost_count, 2070 PERF_RECORD_MISC_LOST_SAMPLES_BPF); 2071 } 2072 } 2073 } 2074 2075 static volatile sig_atomic_t workload_exec_errno; 2076 2077 /* 2078 * evlist__prepare_workload will send a SIGUSR1 2079 * if the fork fails, since we asked by setting its 2080 * want_signal to true. 2081 */ 2082 static void workload_exec_failed_signal(int signo __maybe_unused, 2083 siginfo_t *info, 2084 void *ucontext __maybe_unused) 2085 { 2086 workload_exec_errno = info->si_value.sival_int; 2087 done = 1; 2088 child_finished = 1; 2089 } 2090 2091 static void snapshot_sig_handler(int sig); 2092 static void alarm_sig_handler(int sig); 2093 2094 static const struct perf_event_mmap_page *evlist__pick_pc(struct evlist *evlist) 2095 { 2096 if (evlist) { 2097 if (evlist__mmap(evlist) && evlist__mmap(evlist)[0].core.base) 2098 return evlist__mmap(evlist)[0].core.base; 2099 if (evlist__overwrite_mmap(evlist) && evlist__overwrite_mmap(evlist)[0].core.base) 2100 return evlist__overwrite_mmap(evlist)[0].core.base; 2101 } 2102 return NULL; 2103 } 2104 2105 static const struct perf_event_mmap_page *record__pick_pc(struct record *rec) 2106 { 2107 const struct perf_event_mmap_page *pc = evlist__pick_pc(rec->evlist); 2108 if (pc) 2109 return pc; 2110 return NULL; 2111 } 2112 2113 static int record__synthesize(struct record *rec, bool tail) 2114 { 2115 struct perf_session *session = rec->session; 2116 struct machine *machine = &session->machines.host; 2117 struct perf_data *data = &rec->data; 2118 struct record_opts *opts = &rec->opts; 2119 struct perf_tool *tool = &rec->tool; 2120 int err = 0; 2121 event_op f = process_synthesized_event; 2122 2123 if (rec->opts.tail_synthesize != tail) 2124 return 0; 2125 2126 if (data->is_pipe) { 2127 err = perf_event__synthesize_for_pipe(tool, session, data, 2128 process_synthesized_event); 2129 if (err < 0) 2130 goto out; 2131 2132 rec->bytes_written += err; 2133 } 2134 2135 err = perf_event__synth_time_conv(record__pick_pc(rec), tool, 2136 process_synthesized_event, machine); 2137 if (err) 2138 goto out; 2139 2140 /* Synthesize id_index before auxtrace_info */ 2141 err = perf_event__synthesize_id_index(tool, 2142 process_synthesized_event, 2143 session->evlist, machine); 2144 if (err) 2145 goto out; 2146 2147 if (rec->opts.full_auxtrace) { 2148 err = perf_event__synthesize_auxtrace_info(rec->itr, tool, 2149 session, process_synthesized_event); 2150 if (err) 2151 goto out; 2152 } 2153 2154 if (!evlist__exclude_kernel(rec->evlist)) { 2155 err = perf_event__synthesize_kernel_mmap(tool, process_synthesized_event, 2156 machine); 2157 WARN_ONCE(err < 0, "Couldn't record kernel reference relocation symbol\n" 2158 "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n" 2159 "Check /proc/kallsyms permission or run as root.\n"); 2160 2161 err = perf_event__synthesize_modules(tool, process_synthesized_event, 2162 machine); 2163 WARN_ONCE(err < 0, "Couldn't record kernel module information.\n" 2164 "Symbol resolution may be skewed if relocation was used (e.g. kexec).\n" 2165 "Check /proc/modules permission or run as root.\n"); 2166 } 2167 2168 if (perf_guest) { 2169 machines__process_guests(&session->machines, 2170 perf_event__synthesize_guest_os, tool); 2171 } 2172 2173 err = perf_event__synthesize_extra_attr(&rec->tool, 2174 rec->evlist, 2175 process_synthesized_event, 2176 data->is_pipe); 2177 if (err) 2178 goto out; 2179 2180 err = perf_event__synthesize_thread_map2(&rec->tool, evlist__core(rec->evlist)->threads, 2181 process_synthesized_event, 2182 NULL); 2183 if (err < 0) { 2184 pr_err("Couldn't synthesize thread map.\n"); 2185 return err; 2186 } 2187 2188 err = perf_event__synthesize_cpu_map(&rec->tool, evlist__core(rec->evlist)->all_cpus, 2189 process_synthesized_event, NULL); 2190 if (err < 0) { 2191 pr_err("Couldn't synthesize cpu map.\n"); 2192 return err; 2193 } 2194 2195 err = perf_event__synthesize_bpf_events(session, process_synthesized_event, 2196 machine, opts); 2197 if (err < 0) { 2198 pr_warning("Couldn't synthesize bpf events.\n"); 2199 err = 0; 2200 } 2201 2202 if (rec->opts.synth & PERF_SYNTH_CGROUP) { 2203 err = perf_event__synthesize_cgroups(tool, process_synthesized_event, 2204 machine); 2205 if (err < 0) { 2206 pr_warning("Couldn't synthesize cgroup events.\n"); 2207 err = 0; 2208 } 2209 } 2210 2211 if (rec->opts.nr_threads_synthesize > 1) { 2212 mutex_init(&synth_lock); 2213 perf_set_multithreaded(); 2214 f = process_locked_synthesized_event; 2215 } 2216 2217 if (rec->opts.synth & PERF_SYNTH_TASK) { 2218 bool needs_mmap = rec->opts.synth & PERF_SYNTH_MMAP; 2219 2220 err = __machine__synthesize_threads(machine, tool, &opts->target, 2221 evlist__core(rec->evlist)->threads, 2222 f, needs_mmap, opts->record_data_mmap, 2223 rec->opts.nr_threads_synthesize); 2224 } 2225 2226 if (rec->opts.nr_threads_synthesize > 1) { 2227 perf_set_singlethreaded(); 2228 mutex_destroy(&synth_lock); 2229 } 2230 2231 out: 2232 return err; 2233 } 2234 2235 static void record__synthesize_final_bpf_metadata(struct record *rec __maybe_unused) 2236 { 2237 #ifdef HAVE_LIBBPF_SUPPORT 2238 perf_event__synthesize_final_bpf_metadata(rec->session, 2239 process_synthesized_event); 2240 #endif 2241 } 2242 2243 static int record__process_signal_event(union perf_event *event __maybe_unused, void *data) 2244 { 2245 struct record *rec = data; 2246 pthread_kill(rec->thread_id, SIGUSR2); 2247 return 0; 2248 } 2249 2250 static int record__setup_sb_evlist(struct record *rec) 2251 { 2252 struct record_opts *opts = &rec->opts; 2253 2254 if (rec->sb_evlist != NULL) { 2255 /* 2256 * We get here if --switch-output-event populated the 2257 * sb_evlist, so associate a callback that will send a SIGUSR2 2258 * to the main thread. 2259 */ 2260 evlist__set_cb(rec->sb_evlist, record__process_signal_event, rec); 2261 rec->thread_id = pthread_self(); 2262 } 2263 #ifdef HAVE_LIBBPF_SUPPORT 2264 if (!opts->no_bpf_event) { 2265 if (rec->sb_evlist == NULL) { 2266 rec->sb_evlist = evlist__new(); 2267 2268 if (rec->sb_evlist == NULL) { 2269 pr_err("Couldn't create side band evlist.\n."); 2270 return -1; 2271 } 2272 } 2273 2274 if (evlist__add_bpf_sb_event(rec->sb_evlist, perf_session__env(rec->session))) { 2275 pr_err("Couldn't ask for PERF_RECORD_BPF_EVENT side band events.\n."); 2276 evlist__put(rec->sb_evlist); 2277 rec->sb_evlist = NULL; 2278 return -1; 2279 } 2280 } 2281 #endif 2282 if (evlist__start_sb_thread(rec->sb_evlist, &rec->opts.target)) { 2283 pr_debug("Couldn't start the BPF side band thread:\nBPF programs starting from now on won't be annotatable\n"); 2284 opts->no_bpf_event = true; 2285 } 2286 2287 return 0; 2288 } 2289 2290 static int record__init_clock(struct record *rec) 2291 { 2292 struct perf_session *session = rec->session; 2293 struct timespec ref_clockid; 2294 struct timeval ref_tod; 2295 struct perf_env *env = perf_session__env(session); 2296 u64 ref; 2297 2298 if (!rec->opts.use_clockid) 2299 return 0; 2300 2301 if (rec->opts.use_clockid && rec->opts.clockid_res_ns) 2302 env->clock.clockid_res_ns = rec->opts.clockid_res_ns; 2303 2304 env->clock.clockid = rec->opts.clockid; 2305 2306 if (gettimeofday(&ref_tod, NULL) != 0) { 2307 pr_err("gettimeofday failed, cannot set reference time.\n"); 2308 return -1; 2309 } 2310 2311 if (clock_gettime(rec->opts.clockid, &ref_clockid)) { 2312 pr_err("clock_gettime failed, cannot set reference time.\n"); 2313 return -1; 2314 } 2315 2316 ref = (u64) ref_tod.tv_sec * NSEC_PER_SEC + 2317 (u64) ref_tod.tv_usec * NSEC_PER_USEC; 2318 2319 env->clock.tod_ns = ref; 2320 2321 ref = (u64) ref_clockid.tv_sec * NSEC_PER_SEC + 2322 (u64) ref_clockid.tv_nsec; 2323 2324 env->clock.clockid_ns = ref; 2325 return 0; 2326 } 2327 2328 static void hit_auxtrace_snapshot_trigger(struct record *rec) 2329 { 2330 if (trigger_is_ready(&auxtrace_snapshot_trigger)) { 2331 trigger_hit(&auxtrace_snapshot_trigger); 2332 auxtrace_record__snapshot_started = 1; 2333 if (auxtrace_record__snapshot_start(rec->itr)) 2334 trigger_error(&auxtrace_snapshot_trigger); 2335 } 2336 } 2337 2338 static int record__terminate_thread(struct record_thread *thread_data) 2339 { 2340 int err; 2341 enum thread_msg ack = THREAD_MSG__UNDEFINED; 2342 pid_t tid = thread_data->tid; 2343 2344 close(thread_data->pipes.msg[1]); 2345 thread_data->pipes.msg[1] = -1; 2346 err = read(thread_data->pipes.ack[0], &ack, sizeof(ack)); 2347 if (err > 0) 2348 pr_debug2("threads[%d]: sent %s\n", tid, thread_msg_tags[ack]); 2349 else 2350 pr_warning("threads[%d]: failed to receive termination notification from %d\n", 2351 thread->tid, tid); 2352 2353 return 0; 2354 } 2355 2356 static int record__start_threads(struct record *rec) 2357 { 2358 int t, tt, err, ret = 0, nr_threads = rec->nr_threads; 2359 struct record_thread *thread_data = rec->thread_data; 2360 sigset_t full, mask; 2361 pthread_t handle; 2362 pthread_attr_t attrs; 2363 2364 thread = &thread_data[0]; 2365 2366 if (!record__threads_enabled(rec)) 2367 return 0; 2368 2369 sigfillset(&full); 2370 if (sigprocmask(SIG_SETMASK, &full, &mask)) { 2371 pr_err("Failed to block signals on threads start: %m\n"); 2372 return -1; 2373 } 2374 2375 pthread_attr_init(&attrs); 2376 pthread_attr_setdetachstate(&attrs, PTHREAD_CREATE_DETACHED); 2377 2378 for (t = 1; t < nr_threads; t++) { 2379 enum thread_msg msg = THREAD_MSG__UNDEFINED; 2380 2381 #ifdef HAVE_PTHREAD_ATTR_SETAFFINITY_NP 2382 pthread_attr_setaffinity_np(&attrs, 2383 MMAP_CPU_MASK_BYTES(&(thread_data[t].mask->affinity)), 2384 (cpu_set_t *)(thread_data[t].mask->affinity.bits)); 2385 #endif 2386 if (pthread_create(&handle, &attrs, record__thread, &thread_data[t])) { 2387 for (tt = 1; tt < t; tt++) 2388 record__terminate_thread(&thread_data[t]); 2389 pr_err("Failed to start threads: %m\n"); 2390 ret = -1; 2391 goto out_err; 2392 } 2393 2394 err = read(thread_data[t].pipes.ack[0], &msg, sizeof(msg)); 2395 if (err > 0) 2396 pr_debug2("threads[%d]: sent %s\n", rec->thread_data[t].tid, 2397 thread_msg_tags[msg]); 2398 else 2399 pr_warning("threads[%d]: failed to receive start notification from %d\n", 2400 thread->tid, rec->thread_data[t].tid); 2401 } 2402 2403 sched_setaffinity(0, MMAP_CPU_MASK_BYTES(&thread->mask->affinity), 2404 (cpu_set_t *)thread->mask->affinity.bits); 2405 2406 pr_debug("threads[%d]: started on cpu%d\n", thread->tid, sched_getcpu()); 2407 2408 out_err: 2409 pthread_attr_destroy(&attrs); 2410 2411 if (sigprocmask(SIG_SETMASK, &mask, NULL)) { 2412 pr_err("Failed to unblock signals on threads start: %m\n"); 2413 ret = -1; 2414 } 2415 2416 return ret; 2417 } 2418 2419 static int record__stop_threads(struct record *rec) 2420 { 2421 int t; 2422 struct record_thread *thread_data = rec->thread_data; 2423 2424 for (t = 1; t < rec->nr_threads; t++) 2425 record__terminate_thread(&thread_data[t]); 2426 2427 for (t = 0; t < rec->nr_threads; t++) { 2428 rec->samples += thread_data[t].samples; 2429 if (!record__threads_enabled(rec)) 2430 continue; 2431 rec->session->bytes_transferred += thread_data[t].bytes_transferred; 2432 rec->session->bytes_compressed += thread_data[t].bytes_compressed; 2433 pr_debug("threads[%d]: samples=%lld, wakes=%ld, ", thread_data[t].tid, 2434 thread_data[t].samples, thread_data[t].waking); 2435 if (thread_data[t].bytes_transferred && thread_data[t].bytes_compressed) 2436 pr_debug("transferred=%" PRIu64 ", compressed=%" PRIu64 "\n", 2437 thread_data[t].bytes_transferred, thread_data[t].bytes_compressed); 2438 else 2439 pr_debug("written=%" PRIu64 "\n", thread_data[t].bytes_written); 2440 } 2441 2442 return 0; 2443 } 2444 2445 static unsigned long record__waking(struct record *rec) 2446 { 2447 int t; 2448 unsigned long waking = 0; 2449 struct record_thread *thread_data = rec->thread_data; 2450 2451 for (t = 0; t < rec->nr_threads; t++) 2452 waking += thread_data[t].waking; 2453 2454 return waking; 2455 } 2456 2457 static int __cmd_record(struct record *rec, int argc, const char **argv) 2458 { 2459 int err; 2460 int status = 0; 2461 const bool forks = argc > 0; 2462 struct perf_tool *tool = &rec->tool; 2463 struct record_opts *opts = &rec->opts; 2464 struct perf_data *data = &rec->data; 2465 struct perf_session *session; 2466 bool disabled = false, draining = false; 2467 int fd; 2468 float ratio = 0; 2469 enum evlist_ctl_cmd cmd = EVLIST_CTL_CMD_UNSUPPORTED; 2470 struct perf_env *env; 2471 2472 atexit(record__sig_exit); 2473 signal(SIGCHLD, sig_handler); 2474 signal(SIGINT, sig_handler); 2475 signal(SIGTERM, sig_handler); 2476 signal(SIGSEGV, sigsegv_handler); 2477 2478 if (rec->opts.record_cgroup) { 2479 #ifndef HAVE_FILE_HANDLE 2480 pr_err("cgroup tracking is not supported\n"); 2481 return -1; 2482 #endif 2483 } 2484 2485 if (rec->opts.auxtrace_snapshot_mode || rec->switch_output.enabled) { 2486 signal(SIGUSR2, snapshot_sig_handler); 2487 if (rec->opts.auxtrace_snapshot_mode) 2488 trigger_on(&auxtrace_snapshot_trigger); 2489 if (rec->switch_output.enabled) 2490 trigger_on(&switch_output_trigger); 2491 } else { 2492 signal(SIGUSR2, SIG_IGN); 2493 } 2494 2495 perf_tool__init(tool, /*ordered_events=*/true); 2496 tool->sample = process_sample_event; 2497 tool->fork = perf_event__process_fork; 2498 tool->exit = perf_event__process_exit; 2499 tool->comm = perf_event__process_comm; 2500 tool->namespaces = perf_event__process_namespaces; 2501 tool->mmap = build_id__process_mmap; 2502 tool->mmap2 = build_id__process_mmap2; 2503 tool->itrace_start = process_timestamp_boundary; 2504 tool->aux = process_timestamp_boundary; 2505 tool->namespace_events = rec->opts.record_namespaces; 2506 tool->cgroup_events = rec->opts.record_cgroup; 2507 session = perf_session__new(data, tool); 2508 if (IS_ERR(session)) { 2509 pr_err("Perf session creation failed.\n"); 2510 return PTR_ERR(session); 2511 } 2512 env = perf_session__env(session); 2513 if (record__threads_enabled(rec)) { 2514 if (perf_data__is_pipe(&rec->data)) { 2515 pr_err("Parallel trace streaming is not available in pipe mode.\n"); 2516 return -1; 2517 } 2518 if (rec->opts.full_auxtrace) { 2519 pr_err("Parallel trace streaming is not available in AUX area tracing mode.\n"); 2520 return -1; 2521 } 2522 } 2523 2524 fd = perf_data__fd(data); 2525 rec->session = session; 2526 2527 if (zstd_init(&session->zstd_data, rec->opts.comp_level) < 0) { 2528 pr_err("Compression initialization failed.\n"); 2529 return -1; 2530 } 2531 #ifdef HAVE_EVENTFD_SUPPORT 2532 done_fd = eventfd(0, EFD_NONBLOCK); 2533 if (done_fd < 0) { 2534 pr_err("Failed to create wakeup eventfd, error: %m\n"); 2535 status = -1; 2536 goto out_delete_session; 2537 } 2538 err = evlist__add_wakeup_eventfd(rec->evlist, done_fd); 2539 if (err < 0) { 2540 pr_err("Failed to add wakeup eventfd to poll list\n"); 2541 status = err; 2542 goto out_delete_session; 2543 } 2544 #endif // HAVE_EVENTFD_SUPPORT 2545 2546 env->comp_type = PERF_COMP_ZSTD; 2547 env->comp_level = rec->opts.comp_level; 2548 2549 if (rec->opts.kcore && 2550 !record__kcore_readable(&session->machines.host)) { 2551 pr_err("ERROR: kcore is not readable.\n"); 2552 return -1; 2553 } 2554 2555 if (record__init_clock(rec)) 2556 return -1; 2557 2558 record__init_features(rec); 2559 2560 if (forks) { 2561 err = evlist__prepare_workload(rec->evlist, &opts->target, argv, data->is_pipe, 2562 workload_exec_failed_signal); 2563 if (err < 0) { 2564 pr_err("Couldn't run the workload!\n"); 2565 status = err; 2566 goto out_delete_session; 2567 } 2568 } 2569 2570 /* 2571 * If we have just single event and are sending data 2572 * through pipe, we need to force the ids allocation, 2573 * because we synthesize event name through the pipe 2574 * and need the id for that. 2575 */ 2576 if (data->is_pipe && evlist__nr_entries(rec->evlist) == 1) 2577 rec->opts.sample_id = true; 2578 2579 if (rec->timestamp_filename && perf_data__is_pipe(data)) { 2580 rec->timestamp_filename = false; 2581 pr_warning("WARNING: --timestamp-filename option is not available in pipe mode.\n"); 2582 } 2583 2584 /* 2585 * Use global stat_config that is zero meaning aggr_mode is AGGR_NONE 2586 * and hybrid_merge is false. 2587 */ 2588 evlist__uniquify_evsel_names(rec->evlist, &stat_config); 2589 2590 evlist__config(rec->evlist, opts, &callchain_param); 2591 2592 /* Debug message used by test scripts */ 2593 pr_debug3("perf record opening and mmapping events\n"); 2594 if (record__open(rec) != 0) { 2595 err = -1; 2596 goto out_free_threads; 2597 } 2598 /* Debug message used by test scripts */ 2599 pr_debug3("perf record done opening and mmapping events\n"); 2600 env->comp_mmap_len = evlist__core(session->evlist)->mmap_len; 2601 2602 if (rec->opts.kcore) { 2603 err = record__kcore_copy(&session->machines.host, data); 2604 if (err) { 2605 pr_err("ERROR: Failed to copy kcore\n"); 2606 goto out_free_threads; 2607 } 2608 } 2609 2610 /* 2611 * Normally perf_session__new would do this, but it doesn't have the 2612 * evlist. 2613 */ 2614 if (rec->tool.ordered_events && !evlist__sample_id_all(rec->evlist)) { 2615 pr_warning("WARNING: No sample_id_all support, falling back to unordered processing\n"); 2616 rec->tool.ordered_events = false; 2617 } 2618 2619 if (evlist__nr_groups(rec->evlist) == 0) 2620 perf_header__clear_feat(&session->header, HEADER_GROUP_DESC); 2621 2622 if (data->is_pipe) { 2623 err = perf_header__write_pipe(fd); 2624 if (err < 0) 2625 goto out_free_threads; 2626 } else { 2627 err = perf_session__write_header(session, rec->evlist, fd, false); 2628 if (err < 0) 2629 goto out_free_threads; 2630 } 2631 2632 err = -1; 2633 if (!rec->no_buildid 2634 && !perf_header__has_feat(&session->header, HEADER_BUILD_ID)) { 2635 pr_err("Couldn't generate buildids. " 2636 "Use --no-buildid to profile anyway.\n"); 2637 goto out_free_threads; 2638 } 2639 2640 if (!evlist__needs_bpf_sb_event(rec->evlist)) 2641 opts->no_bpf_event = true; 2642 2643 err = record__setup_sb_evlist(rec); 2644 if (err) 2645 goto out_free_threads; 2646 2647 err = record__synthesize(rec, false); 2648 if (err < 0) 2649 goto out_free_threads; 2650 2651 if (rec->realtime_prio) { 2652 struct sched_param param; 2653 2654 param.sched_priority = rec->realtime_prio; 2655 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) { 2656 pr_err("Could not set realtime priority.\n"); 2657 err = -1; 2658 goto out_free_threads; 2659 } 2660 } 2661 2662 if (record__start_threads(rec)) 2663 goto out_free_threads; 2664 2665 /* 2666 * When perf is starting the traced process, all the events 2667 * (apart from group members) have enable_on_exec=1 set, 2668 * so don't spoil it by prematurely enabling them. 2669 */ 2670 if (!target__none(&opts->target) && !opts->target.initial_delay) 2671 evlist__enable(rec->evlist); 2672 2673 /* 2674 * offcpu-time does not call execve, so enable_on_exe wouldn't work 2675 * when recording a workload, do it manually 2676 */ 2677 if (rec->off_cpu) 2678 evlist__enable_evsel(rec->evlist, (char *)OFFCPU_EVENT); 2679 2680 /* 2681 * Let the child rip 2682 */ 2683 if (forks) { 2684 struct machine *machine = &session->machines.host; 2685 union perf_event *event; 2686 pid_t tgid; 2687 2688 event = malloc(sizeof(event->comm) + machine->id_hdr_size); 2689 if (event == NULL) { 2690 err = -ENOMEM; 2691 goto out_child; 2692 } 2693 2694 /* 2695 * Some H/W events are generated before COMM event 2696 * which is emitted during exec(), so perf script 2697 * cannot see a correct process name for those events. 2698 * Synthesize COMM event to prevent it. 2699 */ 2700 tgid = perf_event__synthesize_comm(tool, event, 2701 evlist__workload_pid(rec->evlist), 2702 process_synthesized_event, 2703 machine); 2704 free(event); 2705 2706 if (tgid == -1) 2707 goto out_child; 2708 2709 event = malloc(sizeof(event->namespaces) + 2710 (NR_NAMESPACES * sizeof(struct perf_ns_link_info)) + 2711 machine->id_hdr_size); 2712 if (event == NULL) { 2713 err = -ENOMEM; 2714 goto out_child; 2715 } 2716 2717 /* 2718 * Synthesize NAMESPACES event for the command specified. 2719 */ 2720 perf_event__synthesize_namespaces(tool, event, 2721 evlist__workload_pid(rec->evlist), 2722 tgid, process_synthesized_event, 2723 machine); 2724 free(event); 2725 2726 evlist__start_workload(rec->evlist); 2727 } 2728 2729 if (opts->target.initial_delay) { 2730 pr_info(EVLIST_DISABLED_MSG); 2731 if (opts->target.initial_delay > 0) { 2732 usleep(opts->target.initial_delay * USEC_PER_MSEC); 2733 evlist__enable(rec->evlist); 2734 pr_info(EVLIST_ENABLED_MSG); 2735 } 2736 } 2737 2738 err = event_enable_timer__start(evlist__event_enable_timer(rec->evlist)); 2739 if (err) 2740 goto out_child; 2741 2742 /* Debug message used by test scripts */ 2743 pr_debug3("perf record has started\n"); 2744 fflush(stderr); 2745 2746 trigger_ready(&auxtrace_snapshot_trigger); 2747 trigger_ready(&switch_output_trigger); 2748 perf_hooks__invoke_record_start(); 2749 2750 /* 2751 * Must write FINISHED_INIT so it will be seen after all other 2752 * synthesized user events, but before any regular events. 2753 */ 2754 err = write_finished_init(rec, false); 2755 if (err < 0) 2756 goto out_child; 2757 2758 for (;;) { 2759 unsigned long long hits = thread->samples; 2760 2761 /* 2762 * rec->evlist->bkw_mmap_state is possible to be 2763 * BKW_MMAP_EMPTY here: when done == true and 2764 * hits != rec->samples in previous round. 2765 * 2766 * evlist__toggle_bkw_mmap ensure we never 2767 * convert BKW_MMAP_EMPTY to BKW_MMAP_DATA_PENDING. 2768 */ 2769 if (trigger_is_hit(&switch_output_trigger) || done || draining) 2770 evlist__toggle_bkw_mmap(rec->evlist, BKW_MMAP_DATA_PENDING); 2771 2772 if (record__mmap_read_all(rec, false) < 0) { 2773 trigger_error(&auxtrace_snapshot_trigger); 2774 trigger_error(&switch_output_trigger); 2775 err = -1; 2776 goto out_child_no_flush; 2777 } 2778 2779 if (auxtrace_record__snapshot_started) { 2780 auxtrace_record__snapshot_started = 0; 2781 if (!trigger_is_error(&auxtrace_snapshot_trigger)) 2782 record__read_auxtrace_snapshot(rec, false); 2783 if (trigger_is_error(&auxtrace_snapshot_trigger)) { 2784 pr_err("AUX area tracing snapshot failed\n"); 2785 err = -1; 2786 goto out_child; 2787 } 2788 } 2789 2790 if (trigger_is_hit(&switch_output_trigger)) { 2791 /* 2792 * If switch_output_trigger is hit, the data in 2793 * overwritable ring buffer should have been collected, 2794 * so bkw_mmap_state should be set to BKW_MMAP_EMPTY. 2795 * 2796 * If SIGUSR2 raise after or during record__mmap_read_all(), 2797 * record__mmap_read_all() didn't collect data from 2798 * overwritable ring buffer. Read again. 2799 */ 2800 if (evlist__bkw_mmap_state(rec->evlist) == BKW_MMAP_RUNNING) 2801 continue; 2802 trigger_ready(&switch_output_trigger); 2803 2804 /* 2805 * Reenable events in overwrite ring buffer after 2806 * record__mmap_read_all(): we should have collected 2807 * data from it. 2808 */ 2809 evlist__toggle_bkw_mmap(rec->evlist, BKW_MMAP_RUNNING); 2810 2811 if (!quiet) 2812 fprintf(stderr, "[ perf record: dump data: Woken up %ld times ]\n", 2813 record__waking(rec)); 2814 thread->waking = 0; 2815 fd = record__switch_output(rec, false); 2816 if (fd < 0) { 2817 pr_err("Failed to switch to new file\n"); 2818 trigger_error(&switch_output_trigger); 2819 err = fd; 2820 goto out_child; 2821 } 2822 2823 /* re-arm the alarm */ 2824 if (rec->switch_output.time) 2825 alarm(rec->switch_output.time); 2826 } 2827 2828 if (hits == thread->samples) { 2829 if (done || draining) 2830 break; 2831 err = fdarray__poll(&thread->pollfd, -1); 2832 /* 2833 * Propagate error, only if there's any. Ignore positive 2834 * number of returned events and interrupt error. 2835 */ 2836 if (err > 0 || (err < 0 && errno == EINTR)) 2837 err = 0; 2838 thread->waking++; 2839 2840 if (fdarray__filter(&thread->pollfd, POLLERR | POLLHUP, 2841 record__thread_munmap_filtered, NULL) == 0) 2842 draining = true; 2843 2844 err = record__update_evlist_pollfd_from_thread(rec, rec->evlist, thread); 2845 if (err) 2846 goto out_child; 2847 } 2848 2849 if (evlist__ctlfd_process(rec->evlist, &cmd) > 0) { 2850 switch (cmd) { 2851 case EVLIST_CTL_CMD_SNAPSHOT: 2852 hit_auxtrace_snapshot_trigger(rec); 2853 evlist__ctlfd_ack(rec->evlist); 2854 break; 2855 case EVLIST_CTL_CMD_STOP: 2856 done = 1; 2857 break; 2858 case EVLIST_CTL_CMD_ACK: 2859 case EVLIST_CTL_CMD_UNSUPPORTED: 2860 case EVLIST_CTL_CMD_ENABLE: 2861 case EVLIST_CTL_CMD_DISABLE: 2862 case EVLIST_CTL_CMD_EVLIST: 2863 case EVLIST_CTL_CMD_PING: 2864 default: 2865 break; 2866 } 2867 } 2868 2869 err = event_enable_timer__process(evlist__event_enable_timer(rec->evlist)); 2870 if (err < 0) 2871 goto out_child; 2872 if (err) { 2873 err = 0; 2874 done = 1; 2875 } 2876 2877 /* 2878 * When perf is starting the traced process, at the end events 2879 * die with the process and we wait for that. Thus no need to 2880 * disable events in this case. 2881 */ 2882 if (done && !disabled && !target__none(&opts->target)) { 2883 trigger_off(&auxtrace_snapshot_trigger); 2884 evlist__disable(rec->evlist); 2885 disabled = true; 2886 } 2887 } 2888 2889 trigger_off(&auxtrace_snapshot_trigger); 2890 trigger_off(&switch_output_trigger); 2891 2892 record__synthesize_final_bpf_metadata(rec); 2893 2894 if (opts->auxtrace_snapshot_on_exit) 2895 record__auxtrace_snapshot_exit(rec); 2896 2897 if (forks && workload_exec_errno) { 2898 char msg[STRERR_BUFSIZE]; 2899 const char *emsg = str_error_r(workload_exec_errno, msg, sizeof(msg)); 2900 struct strbuf sb = STRBUF_INIT; 2901 2902 evlist__format_evsels(rec->evlist, &sb, 2048); 2903 2904 pr_err("Failed to collect '%s' for the '%s' workload: %s\n", 2905 sb.buf, argv[0], emsg); 2906 strbuf_release(&sb); 2907 err = -1; 2908 goto out_child; 2909 } 2910 2911 if (!quiet) 2912 fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", 2913 record__waking(rec)); 2914 2915 write_finished_init(rec, true); 2916 2917 if (target__none(&rec->opts.target)) 2918 record__synthesize_workload(rec, true); 2919 2920 out_child: 2921 evlist__disable(rec->evlist); 2922 record__stop_threads(rec); 2923 record__mmap_read_all(rec, true); 2924 goto out_free_threads; 2925 out_child_no_flush: 2926 /* mmap read already failed — retrying would just fail again */ 2927 evlist__disable(rec->evlist); 2928 record__stop_threads(rec); 2929 out_free_threads: 2930 record__free_thread_data(rec); 2931 evlist__finalize_ctlfd(rec->evlist); 2932 record__aio_mmap_read_sync(rec); 2933 2934 if (rec->session->bytes_transferred && rec->session->bytes_compressed) { 2935 ratio = (float)rec->session->bytes_transferred/(float)rec->session->bytes_compressed; 2936 env->comp_ratio = ratio + 0.5; 2937 } 2938 2939 if (forks) { 2940 int exit_status; 2941 2942 if (!child_finished) 2943 kill(evlist__workload_pid(rec->evlist), SIGTERM); 2944 2945 wait(&exit_status); 2946 2947 if (err < 0) 2948 status = err; 2949 else if (WIFEXITED(exit_status)) 2950 status = WEXITSTATUS(exit_status); 2951 else if (WIFSIGNALED(exit_status)) 2952 signr = WTERMSIG(exit_status); 2953 } else 2954 status = err; 2955 2956 if (rec->off_cpu) 2957 rec->bytes_written += off_cpu_write(rec->session); 2958 2959 record__read_lost_samples(rec); 2960 /* this will be recalculated during process_buildids() */ 2961 rec->samples = 0; 2962 2963 if (!err) { 2964 record__synthesize(rec, true); 2965 if (!rec->timestamp_filename) { 2966 record__finish_output(rec); 2967 } else { 2968 fd = record__switch_output(rec, true); 2969 if (fd < 0) { 2970 status = fd; 2971 goto out_delete_session; 2972 } 2973 } 2974 } 2975 2976 perf_hooks__invoke_record_end(); 2977 2978 if (!err && !quiet) { 2979 char samples[128]; 2980 const char *postfix = rec->timestamp_filename ? 2981 ".<timestamp>" : ""; 2982 2983 if (rec->samples && !rec->opts.full_auxtrace) 2984 scnprintf(samples, sizeof(samples), 2985 " (%" PRIu64 " samples)", rec->samples); 2986 else 2987 samples[0] = '\0'; 2988 2989 fprintf(stderr, "[ perf record: Captured and wrote %.3f MB %s%s%s", 2990 perf_data__size(data) / 1024.0 / 1024.0, 2991 data->path, postfix, samples); 2992 if (ratio) { 2993 fprintf(stderr, ", compressed (original %.3f MB, ratio is %.3f)", 2994 rec->session->bytes_transferred / 1024.0 / 1024.0, 2995 ratio); 2996 } 2997 fprintf(stderr, " ]\n"); 2998 } 2999 3000 out_delete_session: 3001 #ifdef HAVE_EVENTFD_SUPPORT 3002 if (done_fd >= 0) { 3003 fd = done_fd; 3004 done_fd = -1; 3005 3006 close(fd); 3007 } 3008 #endif 3009 zstd_fini(&session->zstd_data); 3010 if (!opts->no_bpf_event) 3011 evlist__stop_sb_thread(rec->sb_evlist); 3012 3013 perf_session__delete(session); 3014 return status; 3015 } 3016 3017 static int record_parse_callchain_opt(const struct option *opt, 3018 const char *arg, 3019 int unset) 3020 { 3021 return record_opts__parse_callchain(opt->value, &callchain_param, arg, unset); 3022 } 3023 3024 static int record_callchain_opt(const struct option *opt, 3025 const char *arg __maybe_unused, 3026 int unset) 3027 { 3028 /* 3029 * The -g option only sets the callchain if not already configured by 3030 * .perfconfig. It does, however, enable it. 3031 */ 3032 if (callchain_param.record_mode != CALLCHAIN_NONE) { 3033 callchain_param.enabled = true; 3034 return 0; 3035 } 3036 3037 return record_opts__parse_callchain(opt->value, &callchain_param, 3038 EM_HOST != EM_S390 ? "fp" : "dwarf", 3039 unset); 3040 } 3041 3042 3043 static int perf_record_config(const char *var, const char *value, void *cb) 3044 { 3045 struct record *rec = cb; 3046 3047 if (!strcmp(var, "record.build-id")) { 3048 if (!strcmp(value, "cache")) 3049 rec->no_buildid_cache = false; 3050 else if (!strcmp(value, "no-cache")) 3051 rec->no_buildid_cache = true; 3052 else if (!strcmp(value, "skip")) 3053 rec->no_buildid = rec->no_buildid_cache = true; 3054 else if (!strcmp(value, "mmap")) 3055 rec->buildid_mmap = true; 3056 else if (!strcmp(value, "no-mmap")) 3057 rec->buildid_mmap = false; 3058 else 3059 return -1; 3060 return 0; 3061 } 3062 if (!strcmp(var, "record.call-graph")) { 3063 var = "call-graph.record-mode"; 3064 return perf_default_config(var, value, cb); 3065 } 3066 #ifdef HAVE_AIO_SUPPORT 3067 if (!strcmp(var, "record.aio")) { 3068 rec->opts.nr_cblocks = strtol(value, NULL, 0); 3069 if (!rec->opts.nr_cblocks) 3070 rec->opts.nr_cblocks = nr_cblocks_default; 3071 } 3072 #endif 3073 if (!strcmp(var, "record.debuginfod")) { 3074 rec->debuginfod.urls = strdup(value); 3075 if (!rec->debuginfod.urls) 3076 return -ENOMEM; 3077 rec->debuginfod.set = true; 3078 } 3079 3080 return 0; 3081 } 3082 3083 static int record__parse_event_enable_time(const struct option *opt, const char *str, int unset) 3084 { 3085 struct record *rec = (struct record *)opt->value; 3086 3087 return evlist__parse_event_enable_time(rec->evlist, &rec->opts, str, unset); 3088 } 3089 3090 static int record__parse_affinity(const struct option *opt, const char *str, int unset) 3091 { 3092 struct record_opts *opts = (struct record_opts *)opt->value; 3093 3094 if (unset || !str) 3095 return 0; 3096 3097 if (!strcasecmp(str, "node")) 3098 opts->affinity = PERF_AFFINITY_NODE; 3099 else if (!strcasecmp(str, "cpu")) 3100 opts->affinity = PERF_AFFINITY_CPU; 3101 3102 return 0; 3103 } 3104 3105 static int record__mmap_cpu_mask_alloc(struct mmap_cpu_mask *mask, int nr_bits) 3106 { 3107 mask->nbits = nr_bits; 3108 mask->bits = bitmap_zalloc(mask->nbits); 3109 if (!mask->bits) 3110 return -ENOMEM; 3111 3112 return 0; 3113 } 3114 3115 static void record__mmap_cpu_mask_free(struct mmap_cpu_mask *mask) 3116 { 3117 bitmap_free(mask->bits); 3118 mask->bits = NULL; 3119 mask->nbits = 0; 3120 } 3121 3122 static int record__thread_mask_alloc(struct thread_mask *mask, int nr_bits) 3123 { 3124 int ret; 3125 3126 ret = record__mmap_cpu_mask_alloc(&mask->maps, nr_bits); 3127 if (ret) { 3128 mask->affinity.bits = NULL; 3129 return ret; 3130 } 3131 3132 ret = record__mmap_cpu_mask_alloc(&mask->affinity, nr_bits); 3133 if (ret) { 3134 record__mmap_cpu_mask_free(&mask->maps); 3135 mask->maps.bits = NULL; 3136 } 3137 3138 return ret; 3139 } 3140 3141 static void record__thread_mask_free(struct thread_mask *mask) 3142 { 3143 record__mmap_cpu_mask_free(&mask->maps); 3144 record__mmap_cpu_mask_free(&mask->affinity); 3145 } 3146 3147 static int record__parse_threads(const struct option *opt, const char *str, int unset) 3148 { 3149 int s; 3150 struct record_opts *opts = opt->value; 3151 3152 if (unset || !str || !strlen(str)) { 3153 opts->threads_spec = THREAD_SPEC__CPU; 3154 } else { 3155 for (s = 1; s < THREAD_SPEC__MAX; s++) { 3156 if (s == THREAD_SPEC__USER) { 3157 opts->threads_user_spec = strdup(str); 3158 if (!opts->threads_user_spec) 3159 return -ENOMEM; 3160 opts->threads_spec = THREAD_SPEC__USER; 3161 break; 3162 } 3163 if (!strncasecmp(str, thread_spec_tags[s], strlen(thread_spec_tags[s]))) { 3164 opts->threads_spec = s; 3165 break; 3166 } 3167 } 3168 } 3169 3170 if (opts->threads_spec == THREAD_SPEC__USER) 3171 pr_debug("threads_spec: %s\n", opts->threads_user_spec); 3172 else 3173 pr_debug("threads_spec: %s\n", thread_spec_tags[opts->threads_spec]); 3174 3175 return 0; 3176 } 3177 3178 static int parse_output_max_size(const struct option *opt, 3179 const char *str, int unset) 3180 { 3181 unsigned long *s = (unsigned long *)opt->value; 3182 static struct parse_tag tags_size[] = { 3183 { .tag = 'B', .mult = 1 }, 3184 { .tag = 'K', .mult = 1 << 10 }, 3185 { .tag = 'M', .mult = 1 << 20 }, 3186 { .tag = 'G', .mult = 1 << 30 }, 3187 { .tag = 0 }, 3188 }; 3189 unsigned long val; 3190 3191 if (unset) { 3192 *s = 0; 3193 return 0; 3194 } 3195 3196 val = parse_tag_value(str, tags_size); 3197 if (val != (unsigned long) -1) { 3198 *s = val; 3199 return 0; 3200 } 3201 3202 return -1; 3203 } 3204 3205 static int record__parse_mmap_pages(const struct option *opt, 3206 const char *str, 3207 int unset __maybe_unused) 3208 { 3209 struct record_opts *opts = opt->value; 3210 char *s, *p; 3211 unsigned int mmap_pages; 3212 int ret; 3213 3214 if (!str) 3215 return -EINVAL; 3216 3217 s = strdup(str); 3218 if (!s) 3219 return -ENOMEM; 3220 3221 p = strchr(s, ','); 3222 if (p) 3223 *p = '\0'; 3224 3225 if (*s) { 3226 ret = __evlist__parse_mmap_pages(&mmap_pages, s); 3227 if (ret) 3228 goto out_free; 3229 opts->mmap_pages = mmap_pages; 3230 } 3231 3232 if (!p) { 3233 ret = 0; 3234 goto out_free; 3235 } 3236 3237 ret = __evlist__parse_mmap_pages(&mmap_pages, p + 1); 3238 if (ret) 3239 goto out_free; 3240 3241 opts->auxtrace_mmap_pages = mmap_pages; 3242 3243 out_free: 3244 free(s); 3245 return ret; 3246 } 3247 3248 static int record__parse_off_cpu_thresh(const struct option *opt, 3249 const char *str, 3250 int unset __maybe_unused) 3251 { 3252 struct record_opts *opts = opt->value; 3253 char *endptr; 3254 u64 off_cpu_thresh_ms; 3255 3256 if (!str) 3257 return -EINVAL; 3258 3259 off_cpu_thresh_ms = strtoull(str, &endptr, 10); 3260 3261 /* the threshold isn't string "0", yet strtoull() returns 0, parsing failed */ 3262 if (*endptr || (off_cpu_thresh_ms == 0 && strcmp(str, "0"))) 3263 return -EINVAL; 3264 else 3265 opts->off_cpu_thresh_ns = off_cpu_thresh_ms * NSEC_PER_MSEC; 3266 3267 return 0; 3268 } 3269 3270 static int parse_control_option(const struct option *opt, 3271 const char *str, 3272 int unset __maybe_unused) 3273 { 3274 struct record_opts *opts = opt->value; 3275 3276 return evlist__parse_control(str, &opts->ctl_fd, &opts->ctl_fd_ack, &opts->ctl_fd_close); 3277 } 3278 3279 static void switch_output_size_warn(struct record *rec) 3280 { 3281 u64 wakeup_size = evlist__mmap_size(rec->opts.mmap_pages); 3282 struct switch_output *s = &rec->switch_output; 3283 3284 wakeup_size /= 2; 3285 3286 if (s->size < wakeup_size) { 3287 char buf[100]; 3288 3289 unit_number__scnprintf(buf, sizeof(buf), wakeup_size); 3290 pr_warning("WARNING: switch-output data size lower than " 3291 "wakeup kernel buffer size (%s) " 3292 "expect bigger perf.data sizes\n", buf); 3293 } 3294 } 3295 3296 static int switch_output_setup(struct record *rec) 3297 { 3298 struct switch_output *s = &rec->switch_output; 3299 static struct parse_tag tags_size[] = { 3300 { .tag = 'B', .mult = 1 }, 3301 { .tag = 'K', .mult = 1 << 10 }, 3302 { .tag = 'M', .mult = 1 << 20 }, 3303 { .tag = 'G', .mult = 1 << 30 }, 3304 { .tag = 0 }, 3305 }; 3306 static struct parse_tag tags_time[] = { 3307 { .tag = 's', .mult = 1 }, 3308 { .tag = 'm', .mult = 60 }, 3309 { .tag = 'h', .mult = 60*60 }, 3310 { .tag = 'd', .mult = 60*60*24 }, 3311 { .tag = 0 }, 3312 }; 3313 unsigned long val; 3314 3315 /* 3316 * If we're using --switch-output-events, then we imply its 3317 * --switch-output=signal, as we'll send a SIGUSR2 from the side band 3318 * thread to its parent. 3319 */ 3320 if (rec->switch_output_event_set) { 3321 if (record__threads_enabled(rec)) { 3322 pr_warning("WARNING: --switch-output-event option is not available in parallel streaming mode.\n"); 3323 return 0; 3324 } 3325 goto do_signal; 3326 } 3327 3328 if (!s->set) 3329 return 0; 3330 3331 if (record__threads_enabled(rec)) { 3332 pr_warning("WARNING: --switch-output option is not available in parallel streaming mode.\n"); 3333 return 0; 3334 } 3335 3336 if (!strcmp(s->str, "signal")) { 3337 do_signal: 3338 s->signal = true; 3339 pr_debug("switch-output with SIGUSR2 signal\n"); 3340 goto enabled; 3341 } 3342 3343 val = parse_tag_value(s->str, tags_size); 3344 if (val != (unsigned long) -1) { 3345 s->size = val; 3346 pr_debug("switch-output with %s size threshold\n", s->str); 3347 goto enabled; 3348 } 3349 3350 val = parse_tag_value(s->str, tags_time); 3351 if (val != (unsigned long) -1) { 3352 s->time = val; 3353 pr_debug("switch-output with %s time threshold (%lu seconds)\n", 3354 s->str, s->time); 3355 goto enabled; 3356 } 3357 3358 return -1; 3359 3360 enabled: 3361 rec->timestamp_filename = true; 3362 s->enabled = true; 3363 3364 if (s->size && !rec->opts.no_buffering) 3365 switch_output_size_warn(rec); 3366 3367 return 0; 3368 } 3369 3370 static const char * const __record_usage[] = { 3371 "perf record [<options>] [<command>]", 3372 "perf record [<options>] -- <command> [<options>]", 3373 NULL 3374 }; 3375 const char * const *record_usage = __record_usage; 3376 3377 static int build_id__process_mmap(const struct perf_tool *tool, union perf_event *event, 3378 struct perf_sample *sample, struct machine *machine) 3379 { 3380 /* 3381 * We already have the kernel maps, put in place via perf_session__create_kernel_maps() 3382 * no need to add them twice. 3383 */ 3384 if (!(event->header.misc & PERF_RECORD_MISC_USER)) 3385 return 0; 3386 return perf_event__process_mmap(tool, event, sample, machine); 3387 } 3388 3389 static int build_id__process_mmap2(const struct perf_tool *tool, union perf_event *event, 3390 struct perf_sample *sample, struct machine *machine) 3391 { 3392 /* 3393 * We already have the kernel maps, put in place via perf_session__create_kernel_maps() 3394 * no need to add them twice. 3395 */ 3396 if (!(event->header.misc & PERF_RECORD_MISC_USER)) 3397 return 0; 3398 3399 return perf_event__process_mmap2(tool, event, sample, machine); 3400 } 3401 3402 static int process_timestamp_boundary(const struct perf_tool *tool, 3403 union perf_event *event __maybe_unused, 3404 struct perf_sample *sample, 3405 struct machine *machine __maybe_unused) 3406 { 3407 struct record *rec = container_of(tool, struct record, tool); 3408 3409 set_timestamp_boundary(rec, sample->time); 3410 return 0; 3411 } 3412 3413 static int parse_record_synth_option(const struct option *opt, 3414 const char *str, 3415 int unset __maybe_unused) 3416 { 3417 struct record_opts *opts = opt->value; 3418 char *p = strdup(str); 3419 3420 if (p == NULL) 3421 return -1; 3422 3423 opts->synth = parse_synth_opt(p); 3424 free(p); 3425 3426 if (opts->synth < 0) { 3427 pr_err("Invalid synth option: %s\n", str); 3428 return -1; 3429 } 3430 return 0; 3431 } 3432 3433 /* 3434 * XXX Ideally would be local to cmd_record() and passed to a record__new 3435 * because we need to have access to it in record__exit, that is called 3436 * after cmd_record() exits, but since record_options need to be accessible to 3437 * builtin-script, leave it here. 3438 * 3439 * At least we don't ouch it in all the other functions here directly. 3440 * 3441 * Just say no to tons of global variables, sigh. 3442 */ 3443 static struct record record = { 3444 .opts = { 3445 .sample_time = true, 3446 .mmap_pages = UINT_MAX, 3447 .user_freq = UINT_MAX, 3448 .user_interval = ULLONG_MAX, 3449 .freq = 4000, 3450 .target = { 3451 .uses_mmap = true, 3452 .default_per_cpu = true, 3453 }, 3454 .mmap_flush = MMAP_FLUSH_DEFAULT, 3455 .nr_threads_synthesize = 1, 3456 .ctl_fd = -1, 3457 .ctl_fd_ack = -1, 3458 .synth = PERF_SYNTH_ALL, 3459 .off_cpu_thresh_ns = OFFCPU_THRESH, 3460 }, 3461 .buildid_mmap = true, 3462 }; 3463 3464 const char record_callchain_help[] = CALLCHAIN_RECORD_HELP 3465 "\n\t\t\t\tDefault: fp"; 3466 3467 static bool dry_run; 3468 3469 static struct parse_events_option_args parse_events_option_args = { 3470 .evlistp = &record.evlist, 3471 }; 3472 3473 static struct parse_events_option_args switch_output_parse_events_option_args = { 3474 .evlistp = &record.sb_evlist, 3475 }; 3476 3477 /* 3478 * XXX Will stay a global variable till we fix builtin-script.c to stop messing 3479 * with it and switch to use the library functions in perf_evlist that came 3480 * from builtin-record.c, i.e. use record_opts, 3481 * evlist__prepare_workload, etc instead of fork+exec'in 'perf record', 3482 * using pipes, etc. 3483 */ 3484 static struct option __record_options[] = { 3485 OPT_CALLBACK('e', "event", &parse_events_option_args, "event", 3486 "event selector. use 'perf list' to list available events", 3487 parse_events_option), 3488 OPT_CALLBACK(0, "filter", &record.evlist, "filter", 3489 "event filter", parse_filter), 3490 OPT_BOOLEAN(0, "latency", &record.latency, 3491 "Enable data collection for latency profiling.\n" 3492 "\t\t\t Use perf report --latency for latency-centric profile."), 3493 OPT_CALLBACK_NOOPT(0, "exclude-perf", &record.evlist, 3494 NULL, "don't record events from perf itself", 3495 exclude_perf), 3496 OPT_STRING('p', "pid", &record.opts.target.pid, "pid", 3497 "record events on existing process id"), 3498 OPT_STRING('t', "tid", &record.opts.target.tid, "tid", 3499 "record events on existing thread id"), 3500 OPT_INTEGER('r', "realtime", &record.realtime_prio, 3501 "collect data with this RT SCHED_FIFO priority"), 3502 OPT_BOOLEAN(0, "no-buffering", &record.opts.no_buffering, 3503 "collect data without buffering"), 3504 OPT_BOOLEAN('R', "raw-samples", &record.opts.raw_samples, 3505 "collect raw sample records from all opened counters"), 3506 OPT_BOOLEAN('a', "all-cpus", &record.opts.target.system_wide, 3507 "system-wide collection from all CPUs"), 3508 OPT_STRING('C', "cpu", &record.opts.target.cpu_list, "cpu", 3509 "list of cpus to monitor"), 3510 OPT_U64('c', "count", &record.opts.user_interval, "event period to sample"), 3511 OPT_STRING('o', "output", &record.data.path, "file", 3512 "output file name"), 3513 OPT_BOOLEAN_SET('i', "no-inherit", &record.opts.no_inherit, 3514 &record.opts.no_inherit_set, 3515 "child tasks do not inherit counters"), 3516 OPT_BOOLEAN(0, "tail-synthesize", &record.opts.tail_synthesize, 3517 "synthesize non-sample events at the end of output"), 3518 OPT_BOOLEAN(0, "overwrite", &record.opts.overwrite, "use overwrite mode"), 3519 OPT_BOOLEAN(0, "no-bpf-event", &record.opts.no_bpf_event, "do not record bpf events"), 3520 OPT_BOOLEAN(0, "strict-freq", &record.opts.strict_freq, 3521 "Fail if the specified frequency can't be used"), 3522 OPT_CALLBACK('F', "freq", &record.opts, "freq or 'max'", 3523 "profile at this frequency", 3524 record__parse_freq), 3525 OPT_CALLBACK('m', "mmap-pages", &record.opts, "pages[,pages]", 3526 "number of mmap data pages and AUX area tracing mmap pages", 3527 record__parse_mmap_pages), 3528 OPT_CALLBACK(0, "mmap-flush", &record.opts, "number", 3529 "Minimal number of bytes that is extracted from mmap data pages (default: 1)", 3530 record__mmap_flush_parse), 3531 OPT_CALLBACK_NOOPT('g', NULL, &record.opts, 3532 NULL, "enables call-graph recording" , 3533 &record_callchain_opt), 3534 OPT_CALLBACK(0, "call-graph", &record.opts, 3535 "record_mode[,record_size]", record_callchain_help, 3536 &record_parse_callchain_opt), 3537 OPT_INCR('v', "verbose", &verbose, 3538 "be more verbose (show counter open errors, etc)"), 3539 OPT_BOOLEAN('q', "quiet", &quiet, "don't print any warnings or messages"), 3540 OPT_BOOLEAN('s', "stat", &record.opts.inherit_stat, 3541 "per thread counts"), 3542 OPT_BOOLEAN('d', "data", &record.opts.sample_address, "Record the sample addresses"), 3543 OPT_BOOLEAN(0, "phys-data", &record.opts.sample_phys_addr, 3544 "Record the sample physical addresses"), 3545 OPT_BOOLEAN(0, "data-page-size", &record.opts.sample_data_page_size, 3546 "Record the sampled data address data page size"), 3547 OPT_BOOLEAN(0, "code-page-size", &record.opts.sample_code_page_size, 3548 "Record the sampled code address (ip) page size"), 3549 OPT_BOOLEAN(0, "sample-mem-info", &record.opts.sample_data_src, 3550 "Record the data source for memory operations"), 3551 OPT_BOOLEAN(0, "sample-cpu", &record.opts.sample_cpu, "Record the sample cpu"), 3552 OPT_BOOLEAN(0, "sample-identifier", &record.opts.sample_identifier, 3553 "Record the sample identifier"), 3554 OPT_BOOLEAN_SET('T', "timestamp", &record.opts.sample_time, 3555 &record.opts.sample_time_set, 3556 "Record the sample timestamps"), 3557 OPT_BOOLEAN_SET('P', "period", &record.opts.period, &record.opts.period_set, 3558 "Record the sample period"), 3559 OPT_BOOLEAN('n', "no-samples", &record.opts.no_samples, 3560 "don't sample"), 3561 OPT_BOOLEAN_SET('N', "no-buildid-cache", &record.no_buildid_cache, 3562 &record.no_buildid_cache_set, 3563 "do not update the buildid cache"), 3564 OPT_BOOLEAN_SET('B', "no-buildid", &record.no_buildid, 3565 &record.no_buildid_set, 3566 "do not collect buildids in perf.data"), 3567 OPT_CALLBACK('G', "cgroup", &record.evlist, "name", 3568 "monitor event in cgroup name only", 3569 parse_cgroups), 3570 OPT_CALLBACK('D', "delay", &record, "ms", 3571 "ms to wait before starting measurement after program start (-1: start with events disabled), " 3572 "or ranges of time to enable events e.g. '-D 10-20,30-40'", 3573 record__parse_event_enable_time), 3574 OPT_BOOLEAN(0, "kcore", &record.opts.kcore, "copy /proc/kcore"), 3575 OPT_STRING('u', "uid", &record.uid_str, "user", "user to profile"), 3576 3577 OPT_CALLBACK_NOOPT('b', "branch-any", &record.opts.branch_stack, 3578 "branch any", "sample any taken branches", 3579 parse_branch_stack), 3580 3581 OPT_CALLBACK('j', "branch-filter", &record.opts.branch_stack, 3582 "branch filter mask", "branch stack filter modes", 3583 parse_branch_stack), 3584 OPT_BOOLEAN('W', "weight", &record.opts.sample_weight, 3585 "sample by weight (on special events only)"), 3586 OPT_BOOLEAN(0, "transaction", &record.opts.sample_transaction, 3587 "sample transaction flags (special events only)"), 3588 OPT_BOOLEAN(0, "per-thread", &record.opts.target.per_thread, 3589 "use per-thread mmaps"), 3590 OPT_CALLBACK_OPTARG('I', "intr-regs", &record.opts.sample_intr_regs, NULL, "any register", 3591 "sample selected machine registers on interrupt," 3592 " use '-I?' to list register names", parse_intr_regs), 3593 OPT_CALLBACK_OPTARG(0, "user-regs", &record.opts.sample_user_regs, NULL, "any register", 3594 "sample selected machine registers in user space," 3595 " use '--user-regs=?' to list register names", parse_user_regs), 3596 OPT_BOOLEAN(0, "running-time", &record.opts.running_time, 3597 "Record running/enabled time of read (:S) events"), 3598 OPT_CALLBACK('k', "clockid", &record.opts, 3599 "clockid", "clockid to use for events, see clock_gettime()", 3600 parse_clockid), 3601 OPT_STRING_OPTARG('S', "snapshot", &record.opts.auxtrace_snapshot_opts, 3602 "opts", "AUX area tracing Snapshot Mode", ""), 3603 OPT_STRING_OPTARG(0, "aux-sample", &record.opts.auxtrace_sample_opts, 3604 "opts", "sample AUX area", ""), 3605 OPT_UINTEGER(0, "proc-map-timeout", &proc_map_timeout, 3606 "per thread proc mmap processing timeout in ms"), 3607 OPT_BOOLEAN(0, "namespaces", &record.opts.record_namespaces, 3608 "Record namespaces events"), 3609 OPT_BOOLEAN(0, "all-cgroups", &record.opts.record_cgroup, 3610 "Record cgroup events"), 3611 OPT_BOOLEAN_SET(0, "switch-events", &record.opts.record_switch_events, 3612 &record.opts.record_switch_events_set, 3613 "Record context switch events"), 3614 OPT_BOOLEAN_FLAG(0, "all-kernel", &record.opts.all_kernel, 3615 "Configure all used events to run in kernel space.", 3616 PARSE_OPT_EXCLUSIVE), 3617 OPT_BOOLEAN_FLAG(0, "all-user", &record.opts.all_user, 3618 "Configure all used events to run in user space.", 3619 PARSE_OPT_EXCLUSIVE), 3620 OPT_BOOLEAN(0, "kernel-callchains", &record.opts.kernel_callchains, 3621 "collect kernel callchains"), 3622 OPT_BOOLEAN(0, "user-callchains", &record.opts.user_callchains, 3623 "collect user callchains"), 3624 OPT_STRING(0, "vmlinux", &symbol_conf.vmlinux_name, 3625 "file", "vmlinux pathname"), 3626 OPT_BOOLEAN(0, "buildid-all", &record.buildid_all, 3627 "Record build-id of all DSOs regardless of hits"), 3628 OPT_BOOLEAN_SET(0, "buildid-mmap", &record.buildid_mmap, &record.buildid_mmap_set, 3629 "Record build-id in mmap events and skip build-id processing."), 3630 OPT_BOOLEAN(0, "timestamp-filename", &record.timestamp_filename, 3631 "append timestamp to output filename"), 3632 OPT_BOOLEAN(0, "timestamp-boundary", &record.timestamp_boundary, 3633 "Record timestamp boundary (time of first/last samples)"), 3634 OPT_STRING_OPTARG_SET(0, "switch-output", &record.switch_output.str, 3635 &record.switch_output.set, "signal or size[BKMG] or time[smhd]", 3636 "Switch output when receiving SIGUSR2 (signal) or cross a size or time threshold", 3637 "signal"), 3638 OPT_CALLBACK_SET(0, "switch-output-event", &switch_output_parse_events_option_args, 3639 &record.switch_output_event_set, "switch output event", 3640 "switch output event selector. use 'perf list' to list available events", 3641 parse_events_option_new_evlist), 3642 OPT_INTEGER(0, "switch-max-files", &record.switch_output.num_files, 3643 "Limit number of switch output generated files"), 3644 OPT_BOOLEAN(0, "dry-run", &dry_run, 3645 "Parse options then exit"), 3646 #ifdef HAVE_AIO_SUPPORT 3647 OPT_CALLBACK_OPTARG(0, "aio", &record.opts, 3648 &nr_cblocks_default, "n", "Use <n> control blocks in asynchronous trace writing mode (default: 1, max: 4)", 3649 record__aio_parse), 3650 #endif 3651 OPT_CALLBACK(0, "affinity", &record.opts, "node|cpu", 3652 "Set affinity mask of trace reading thread to NUMA node cpu mask or cpu of processed mmap buffer", 3653 record__parse_affinity), 3654 #ifdef HAVE_ZSTD_SUPPORT 3655 OPT_CALLBACK_OPTARG('z', "compression-level", &record.opts, &comp_level_default, "n", 3656 "Compress records using specified level (default: 1 - fastest compression, 22 - greatest compression)", 3657 record__parse_comp_level), 3658 #endif 3659 OPT_CALLBACK(0, "max-size", &record.output_max_size, 3660 "size", "Limit the maximum size of the output file", parse_output_max_size), 3661 OPT_UINTEGER(0, "num-thread-synthesize", 3662 &record.opts.nr_threads_synthesize, 3663 "number of threads to run for event synthesis"), 3664 #ifdef HAVE_LIBPFM 3665 OPT_CALLBACK(0, "pfm-events", &record.evlist, "event", 3666 "libpfm4 event selector. use 'perf list' to list available events", 3667 parse_libpfm_events_option), 3668 #endif 3669 OPT_CALLBACK(0, "control", &record.opts, "fd:ctl-fd[,ack-fd] or fifo:ctl-fifo[,ack-fifo]", 3670 "Listen on ctl-fd descriptor for command to control measurement ('enable': enable events, 'disable': disable events,\n" 3671 "\t\t\t 'snapshot': AUX area tracing snapshot).\n" 3672 "\t\t\t Optionally send control command completion ('ack\\n') to ack-fd descriptor.\n" 3673 "\t\t\t Alternatively, ctl-fifo / ack-fifo will be opened and used as ctl-fd / ack-fd.", 3674 parse_control_option), 3675 OPT_CALLBACK(0, "synth", &record.opts, "no|all|task|mmap|cgroup", 3676 "Fine-tune event synthesis: default=all", parse_record_synth_option), 3677 OPT_STRING_OPTARG_SET(0, "debuginfod", &record.debuginfod.urls, 3678 &record.debuginfod.set, "debuginfod urls", 3679 "Enable debuginfod data retrieval from DEBUGINFOD_URLS or specified urls", 3680 "system"), 3681 OPT_CALLBACK_OPTARG(0, "threads", &record.opts, NULL, "spec", 3682 "write collected trace data into several data files using parallel threads", 3683 record__parse_threads), 3684 OPT_BOOLEAN(0, "off-cpu", &record.off_cpu, "Enable off-cpu analysis"), 3685 OPT_STRING(0, "setup-filter", &record.filter_action, "pin|unpin", 3686 "BPF filter action"), 3687 OPT_CALLBACK(0, "off-cpu-thresh", &record.opts, "ms", 3688 "Dump off-cpu samples if off-cpu time exceeds this threshold (in milliseconds). (Default: 500ms)", 3689 record__parse_off_cpu_thresh), 3690 OPT_BOOLEAN_SET(0, "data-mmap", &record.opts.record_data_mmap, 3691 &record.opts.record_data_mmap_set, 3692 "Record mmap events for non-executable mappings"), 3693 OPT_END() 3694 }; 3695 3696 struct option *record_options = __record_options; 3697 3698 static int record__mmap_cpu_mask_init(struct mmap_cpu_mask *mask, struct perf_cpu_map *cpus) 3699 { 3700 struct perf_cpu cpu; 3701 unsigned int idx; 3702 3703 if (cpu_map__is_dummy(cpus)) 3704 return 0; 3705 3706 perf_cpu_map__for_each_cpu_skip_any(cpu, idx, cpus) { 3707 /* Return ENODEV if the CPU index is outside the mask. */ 3708 if ((unsigned long)cpu.cpu >= mask->nbits) 3709 return -ENODEV; 3710 __set_bit(cpu.cpu, mask->bits); 3711 } 3712 3713 return 0; 3714 } 3715 3716 static int record__mmap_cpu_mask_init_spec(struct mmap_cpu_mask *mask, const char *mask_spec) 3717 { 3718 struct perf_cpu_map *cpus; 3719 3720 cpus = perf_cpu_map__new(mask_spec); 3721 if (!cpus) 3722 return -ENOMEM; 3723 3724 bitmap_zero(mask->bits, mask->nbits); 3725 if (record__mmap_cpu_mask_init(mask, cpus)) 3726 return -ENODEV; 3727 3728 perf_cpu_map__put(cpus); 3729 3730 return 0; 3731 } 3732 3733 static void record__free_thread_masks(struct record *rec, int nr_threads) 3734 { 3735 int t; 3736 3737 if (rec->thread_masks) 3738 for (t = 0; t < nr_threads; t++) 3739 record__thread_mask_free(&rec->thread_masks[t]); 3740 3741 zfree(&rec->thread_masks); 3742 } 3743 3744 static int record__alloc_thread_masks(struct record *rec, int nr_threads, int nr_bits) 3745 { 3746 int t, ret; 3747 3748 rec->thread_masks = calloc(nr_threads, sizeof(*(rec->thread_masks))); 3749 if (!rec->thread_masks) { 3750 pr_err("Failed to allocate thread masks\n"); 3751 return -ENOMEM; 3752 } 3753 3754 for (t = 0; t < nr_threads; t++) { 3755 ret = record__thread_mask_alloc(&rec->thread_masks[t], nr_bits); 3756 if (ret) { 3757 pr_err("Failed to allocate thread masks[%d]\n", t); 3758 goto out_free; 3759 } 3760 } 3761 3762 return 0; 3763 3764 out_free: 3765 record__free_thread_masks(rec, nr_threads); 3766 3767 return ret; 3768 } 3769 3770 static int record__init_thread_cpu_masks(struct record *rec, struct perf_cpu_map *cpus) 3771 { 3772 int t, ret, nr_cpus = perf_cpu_map__nr(cpus); 3773 3774 ret = record__alloc_thread_masks(rec, nr_cpus, cpu__max_cpu().cpu); 3775 if (ret) 3776 return ret; 3777 3778 rec->nr_threads = nr_cpus; 3779 pr_debug("nr_threads: %d\n", rec->nr_threads); 3780 3781 for (t = 0; t < rec->nr_threads; t++) { 3782 __set_bit(perf_cpu_map__cpu(cpus, t).cpu, rec->thread_masks[t].maps.bits); 3783 __set_bit(perf_cpu_map__cpu(cpus, t).cpu, rec->thread_masks[t].affinity.bits); 3784 if (verbose > 0) { 3785 pr_debug("thread_masks[%d]: ", t); 3786 mmap_cpu_mask__scnprintf(&rec->thread_masks[t].maps, "maps"); 3787 pr_debug("thread_masks[%d]: ", t); 3788 mmap_cpu_mask__scnprintf(&rec->thread_masks[t].affinity, "affinity"); 3789 } 3790 } 3791 3792 return 0; 3793 } 3794 3795 static int record__init_thread_masks_spec(struct record *rec, struct perf_cpu_map *cpus, 3796 const char **maps_spec, const char **affinity_spec, 3797 u32 nr_spec) 3798 { 3799 u32 s; 3800 int ret = 0, t = 0; 3801 struct mmap_cpu_mask cpus_mask; 3802 struct thread_mask thread_mask, full_mask, *thread_masks; 3803 3804 ret = record__mmap_cpu_mask_alloc(&cpus_mask, cpu__max_cpu().cpu); 3805 if (ret) { 3806 pr_err("Failed to allocate CPUs mask\n"); 3807 return ret; 3808 } 3809 3810 ret = record__mmap_cpu_mask_init(&cpus_mask, cpus); 3811 if (ret) { 3812 pr_err("Failed to init cpu mask\n"); 3813 goto out_free_cpu_mask; 3814 } 3815 3816 ret = record__thread_mask_alloc(&full_mask, cpu__max_cpu().cpu); 3817 if (ret) { 3818 pr_err("Failed to allocate full mask\n"); 3819 goto out_free_cpu_mask; 3820 } 3821 3822 ret = record__thread_mask_alloc(&thread_mask, cpu__max_cpu().cpu); 3823 if (ret) { 3824 pr_err("Failed to allocate thread mask\n"); 3825 goto out_free_full_and_cpu_masks; 3826 } 3827 3828 for (s = 0; s < nr_spec; s++) { 3829 ret = record__mmap_cpu_mask_init_spec(&thread_mask.maps, maps_spec[s]); 3830 if (ret) { 3831 pr_err("Failed to initialize maps thread mask\n"); 3832 goto out_free; 3833 } 3834 ret = record__mmap_cpu_mask_init_spec(&thread_mask.affinity, affinity_spec[s]); 3835 if (ret) { 3836 pr_err("Failed to initialize affinity thread mask\n"); 3837 goto out_free; 3838 } 3839 3840 /* ignore invalid CPUs but do not allow empty masks */ 3841 if (!bitmap_and(thread_mask.maps.bits, thread_mask.maps.bits, 3842 cpus_mask.bits, thread_mask.maps.nbits)) { 3843 pr_err("Empty maps mask: %s\n", maps_spec[s]); 3844 ret = -EINVAL; 3845 goto out_free; 3846 } 3847 if (!bitmap_and(thread_mask.affinity.bits, thread_mask.affinity.bits, 3848 cpus_mask.bits, thread_mask.affinity.nbits)) { 3849 pr_err("Empty affinity mask: %s\n", affinity_spec[s]); 3850 ret = -EINVAL; 3851 goto out_free; 3852 } 3853 3854 /* do not allow intersection with other masks (full_mask) */ 3855 if (bitmap_intersects(thread_mask.maps.bits, full_mask.maps.bits, 3856 thread_mask.maps.nbits)) { 3857 pr_err("Intersecting maps mask: %s\n", maps_spec[s]); 3858 ret = -EINVAL; 3859 goto out_free; 3860 } 3861 if (bitmap_intersects(thread_mask.affinity.bits, full_mask.affinity.bits, 3862 thread_mask.affinity.nbits)) { 3863 pr_err("Intersecting affinity mask: %s\n", affinity_spec[s]); 3864 ret = -EINVAL; 3865 goto out_free; 3866 } 3867 3868 bitmap_or(full_mask.maps.bits, full_mask.maps.bits, 3869 thread_mask.maps.bits, full_mask.maps.nbits); 3870 bitmap_or(full_mask.affinity.bits, full_mask.affinity.bits, 3871 thread_mask.affinity.bits, full_mask.maps.nbits); 3872 3873 thread_masks = realloc(rec->thread_masks, (t + 1) * sizeof(struct thread_mask)); 3874 if (!thread_masks) { 3875 pr_err("Failed to reallocate thread masks\n"); 3876 ret = -ENOMEM; 3877 goto out_free; 3878 } 3879 rec->thread_masks = thread_masks; 3880 rec->thread_masks[t] = thread_mask; 3881 if (verbose > 0) { 3882 pr_debug("thread_masks[%d]: ", t); 3883 mmap_cpu_mask__scnprintf(&rec->thread_masks[t].maps, "maps"); 3884 pr_debug("thread_masks[%d]: ", t); 3885 mmap_cpu_mask__scnprintf(&rec->thread_masks[t].affinity, "affinity"); 3886 } 3887 t++; 3888 ret = record__thread_mask_alloc(&thread_mask, cpu__max_cpu().cpu); 3889 if (ret) { 3890 pr_err("Failed to allocate thread mask\n"); 3891 goto out_free_full_and_cpu_masks; 3892 } 3893 } 3894 rec->nr_threads = t; 3895 pr_debug("nr_threads: %d\n", rec->nr_threads); 3896 if (!rec->nr_threads) 3897 ret = -EINVAL; 3898 3899 out_free: 3900 record__thread_mask_free(&thread_mask); 3901 out_free_full_and_cpu_masks: 3902 record__thread_mask_free(&full_mask); 3903 out_free_cpu_mask: 3904 record__mmap_cpu_mask_free(&cpus_mask); 3905 3906 return ret; 3907 } 3908 3909 static int record__init_thread_core_masks(struct record *rec, struct perf_cpu_map *cpus) 3910 { 3911 int ret; 3912 struct cpu_topology *topo; 3913 3914 topo = cpu_topology__new(); 3915 if (!topo) { 3916 pr_err("Failed to allocate CPU topology\n"); 3917 return -ENOMEM; 3918 } 3919 3920 ret = record__init_thread_masks_spec(rec, cpus, topo->core_cpus_list, 3921 topo->core_cpus_list, topo->core_cpus_lists); 3922 cpu_topology__delete(topo); 3923 3924 return ret; 3925 } 3926 3927 static int record__init_thread_package_masks(struct record *rec, struct perf_cpu_map *cpus) 3928 { 3929 int ret; 3930 struct cpu_topology *topo; 3931 3932 topo = cpu_topology__new(); 3933 if (!topo) { 3934 pr_err("Failed to allocate CPU topology\n"); 3935 return -ENOMEM; 3936 } 3937 3938 ret = record__init_thread_masks_spec(rec, cpus, topo->package_cpus_list, 3939 topo->package_cpus_list, topo->package_cpus_lists); 3940 cpu_topology__delete(topo); 3941 3942 return ret; 3943 } 3944 3945 static int record__init_thread_numa_masks(struct record *rec, struct perf_cpu_map *cpus) 3946 { 3947 u32 s; 3948 int ret; 3949 const char **spec; 3950 struct numa_topology *topo; 3951 3952 topo = numa_topology__new(); 3953 if (!topo) { 3954 pr_err("Failed to allocate NUMA topology\n"); 3955 return -ENOMEM; 3956 } 3957 3958 spec = calloc(topo->nr, sizeof(char *)); 3959 if (!spec) { 3960 pr_err("Failed to allocate NUMA spec\n"); 3961 ret = -ENOMEM; 3962 goto out_delete_topo; 3963 } 3964 for (s = 0; s < topo->nr; s++) 3965 spec[s] = topo->nodes[s].cpus; 3966 3967 ret = record__init_thread_masks_spec(rec, cpus, spec, spec, topo->nr); 3968 3969 zfree(&spec); 3970 3971 out_delete_topo: 3972 numa_topology__delete(topo); 3973 3974 return ret; 3975 } 3976 3977 static int record__init_thread_user_masks(struct record *rec, struct perf_cpu_map *cpus) 3978 { 3979 int t, ret; 3980 u32 s, nr_spec = 0; 3981 char **maps_spec = NULL, **affinity_spec = NULL, **tmp_spec; 3982 char *user_spec, *spec, *spec_ptr, *mask, *mask_ptr, *dup_mask = NULL; 3983 3984 for (t = 0, user_spec = (char *)rec->opts.threads_user_spec; ; t++, user_spec = NULL) { 3985 spec = strtok_r(user_spec, ":", &spec_ptr); 3986 if (spec == NULL) 3987 break; 3988 pr_debug2("threads_spec[%d]: %s\n", t, spec); 3989 mask = strtok_r(spec, "/", &mask_ptr); 3990 if (mask == NULL) 3991 break; 3992 pr_debug2(" maps mask: %s\n", mask); 3993 tmp_spec = realloc(maps_spec, (nr_spec + 1) * sizeof(char *)); 3994 if (!tmp_spec) { 3995 pr_err("Failed to reallocate maps spec\n"); 3996 ret = -ENOMEM; 3997 goto out_free; 3998 } 3999 maps_spec = tmp_spec; 4000 maps_spec[nr_spec] = dup_mask = strdup(mask); 4001 if (!maps_spec[nr_spec]) { 4002 pr_err("Failed to allocate maps spec[%d]\n", nr_spec); 4003 ret = -ENOMEM; 4004 goto out_free; 4005 } 4006 mask = strtok_r(NULL, "/", &mask_ptr); 4007 if (mask == NULL) { 4008 pr_err("Invalid thread maps or affinity specs\n"); 4009 ret = -EINVAL; 4010 goto out_free; 4011 } 4012 pr_debug2(" affinity mask: %s\n", mask); 4013 tmp_spec = realloc(affinity_spec, (nr_spec + 1) * sizeof(char *)); 4014 if (!tmp_spec) { 4015 pr_err("Failed to reallocate affinity spec\n"); 4016 ret = -ENOMEM; 4017 goto out_free; 4018 } 4019 affinity_spec = tmp_spec; 4020 affinity_spec[nr_spec] = strdup(mask); 4021 if (!affinity_spec[nr_spec]) { 4022 pr_err("Failed to allocate affinity spec[%d]\n", nr_spec); 4023 ret = -ENOMEM; 4024 goto out_free; 4025 } 4026 dup_mask = NULL; 4027 nr_spec++; 4028 } 4029 4030 ret = record__init_thread_masks_spec(rec, cpus, (const char **)maps_spec, 4031 (const char **)affinity_spec, nr_spec); 4032 4033 out_free: 4034 free(dup_mask); 4035 for (s = 0; s < nr_spec; s++) { 4036 if (maps_spec) 4037 free(maps_spec[s]); 4038 if (affinity_spec) 4039 free(affinity_spec[s]); 4040 } 4041 free(affinity_spec); 4042 free(maps_spec); 4043 4044 return ret; 4045 } 4046 4047 static int record__init_thread_default_masks(struct record *rec, struct perf_cpu_map *cpus) 4048 { 4049 int ret; 4050 4051 ret = record__alloc_thread_masks(rec, 1, cpu__max_cpu().cpu); 4052 if (ret) 4053 return ret; 4054 4055 if (record__mmap_cpu_mask_init(&rec->thread_masks->maps, cpus)) 4056 return -ENODEV; 4057 4058 rec->nr_threads = 1; 4059 4060 return 0; 4061 } 4062 4063 static int record__init_thread_masks(struct record *rec) 4064 { 4065 int ret = 0; 4066 struct perf_cpu_map *cpus = evlist__core(rec->evlist)->all_cpus; 4067 4068 if (!record__threads_enabled(rec)) 4069 return record__init_thread_default_masks(rec, cpus); 4070 4071 if (evlist__per_thread(rec->evlist)) { 4072 pr_err("--per-thread option is mutually exclusive to parallel streaming mode.\n"); 4073 return -EINVAL; 4074 } 4075 4076 switch (rec->opts.threads_spec) { 4077 case THREAD_SPEC__CPU: 4078 ret = record__init_thread_cpu_masks(rec, cpus); 4079 break; 4080 case THREAD_SPEC__CORE: 4081 ret = record__init_thread_core_masks(rec, cpus); 4082 break; 4083 case THREAD_SPEC__PACKAGE: 4084 ret = record__init_thread_package_masks(rec, cpus); 4085 break; 4086 case THREAD_SPEC__NUMA: 4087 ret = record__init_thread_numa_masks(rec, cpus); 4088 break; 4089 case THREAD_SPEC__USER: 4090 ret = record__init_thread_user_masks(rec, cpus); 4091 break; 4092 default: 4093 break; 4094 } 4095 4096 return ret; 4097 } 4098 4099 int cmd_record(int argc, const char **argv) 4100 { 4101 int err; 4102 struct record *rec = &record; 4103 char errbuf[BUFSIZ]; 4104 4105 setlocale(LC_ALL, ""); 4106 4107 #ifndef HAVE_BPF_SKEL 4108 # define set_nobuild(s, l, m, c) set_option_nobuild(record_options, s, l, m, c) 4109 set_nobuild('\0', "off-cpu", "no BUILD_BPF_SKEL=1", true); 4110 # undef set_nobuild 4111 #endif 4112 4113 /* Disable eager loading of kernel symbols that adds overhead to perf record. */ 4114 symbol_conf.lazy_load_kernel_maps = true; 4115 rec->opts.affinity = PERF_AFFINITY_SYS; 4116 4117 rec->evlist = evlist__new(); 4118 if (rec->evlist == NULL) 4119 return -ENOMEM; 4120 4121 err = perf_config(perf_record_config, rec); 4122 if (err) 4123 return err; 4124 4125 argc = parse_options(argc, argv, record_options, record_usage, 4126 PARSE_OPT_STOP_AT_NON_OPTION); 4127 if (quiet) 4128 perf_quiet_option(); 4129 4130 err = symbol__validate_sym_arguments(); 4131 if (err) 4132 return err; 4133 4134 perf_debuginfod_setup(&record.debuginfod); 4135 4136 /* 4137 * Use system wide (-a) for the default target (ie. when no 4138 * workload). User ID filtering also implies system-wide. 4139 */ 4140 if ((!argc && target__none(&rec->opts.target)) || rec->uid_str) 4141 rec->opts.target.system_wide = true; 4142 4143 if (nr_cgroups && !rec->opts.target.system_wide) { 4144 usage_with_options_msg(record_usage, record_options, 4145 "cgroup monitoring only available in system-wide mode"); 4146 4147 } 4148 4149 if (record.latency) { 4150 /* 4151 * There is no fundamental reason why latency profiling 4152 * can't work for system-wide mode, but exact semantics 4153 * and details are to be defined. 4154 * See the following thread for details: 4155 * https://lore.kernel.org/all/Z4XDJyvjiie3howF@google.com/ 4156 */ 4157 if (record.opts.target.system_wide) { 4158 pr_err("Failed: latency profiling is not supported with system-wide collection.\n"); 4159 err = -EINVAL; 4160 goto out_opts; 4161 } 4162 record.opts.record_switch_events = true; 4163 } 4164 4165 if (rec->buildid_mmap && !perf_can_record_build_id()) { 4166 pr_warning("Missing support for build id in kernel mmap events.\n" 4167 "Disable this warning with --no-buildid-mmap\n"); 4168 rec->buildid_mmap = false; 4169 } 4170 4171 if (rec->buildid_mmap) { 4172 /* Enable perf_event_attr::build_id bit. */ 4173 rec->opts.build_id = true; 4174 /* Disable build-ID table in the header. */ 4175 rec->no_buildid = true; 4176 } else { 4177 pr_debug("Disabling build id in synthesized mmap2 events.\n"); 4178 symbol_conf.no_buildid_mmap2 = true; 4179 } 4180 4181 if (rec->no_buildid_set && rec->no_buildid) { 4182 /* -B implies -N for historic reasons. */ 4183 rec->no_buildid_cache = true; 4184 } 4185 4186 if (rec->opts.record_cgroup && !perf_can_record_cgroup()) { 4187 pr_err("Kernel has no cgroup sampling support.\n"); 4188 err = -EINVAL; 4189 goto out_opts; 4190 } 4191 4192 if (rec->opts.kcore) 4193 rec->opts.text_poke = true; 4194 4195 if (rec->opts.kcore || record__threads_enabled(rec)) 4196 rec->data.is_dir = true; 4197 4198 if (record__threads_enabled(rec)) { 4199 if (rec->opts.affinity != PERF_AFFINITY_SYS) { 4200 pr_err("--affinity option is mutually exclusive to parallel streaming mode.\n"); 4201 goto out_opts; 4202 } 4203 if (record__aio_enabled(rec)) { 4204 pr_err("Asynchronous streaming mode (--aio) is mutually exclusive to parallel streaming mode.\n"); 4205 goto out_opts; 4206 } 4207 } 4208 4209 if (rec->opts.comp_level != 0) { 4210 pr_debug("Compression enabled, disabling build id collection at the end of the session.\n"); 4211 rec->no_buildid = true; 4212 } 4213 4214 if (rec->opts.record_switch_events && 4215 !perf_can_record_switch_events()) { 4216 ui__error("kernel does not support recording context switch events\n"); 4217 parse_options_usage(record_usage, record_options, "switch-events", 0); 4218 err = -EINVAL; 4219 goto out_opts; 4220 } 4221 4222 if (switch_output_setup(rec)) { 4223 parse_options_usage(record_usage, record_options, "switch-output", 0); 4224 err = -EINVAL; 4225 goto out_opts; 4226 } 4227 4228 if (rec->switch_output.time) { 4229 signal(SIGALRM, alarm_sig_handler); 4230 alarm(rec->switch_output.time); 4231 } 4232 4233 if (rec->switch_output.num_files) { 4234 rec->switch_output.filenames = calloc(rec->switch_output.num_files, 4235 sizeof(char *)); 4236 if (!rec->switch_output.filenames) { 4237 err = -EINVAL; 4238 goto out_opts; 4239 } 4240 } 4241 4242 if (rec->timestamp_filename && record__threads_enabled(rec)) { 4243 rec->timestamp_filename = false; 4244 pr_warning("WARNING: --timestamp-filename option is not available in parallel streaming mode.\n"); 4245 } 4246 4247 if (rec->filter_action) { 4248 if (!strcmp(rec->filter_action, "pin")) 4249 err = perf_bpf_filter__pin(); 4250 else if (!strcmp(rec->filter_action, "unpin")) 4251 err = perf_bpf_filter__unpin(); 4252 else { 4253 pr_warning("Unknown BPF filter action: %s\n", rec->filter_action); 4254 err = -EINVAL; 4255 } 4256 goto out_opts; 4257 } 4258 4259 /* For backward compatibility, -d implies --mem-info and --data-mmap */ 4260 if (rec->opts.sample_address) { 4261 rec->opts.sample_data_src = true; 4262 if (!rec->opts.record_data_mmap_set) 4263 rec->opts.record_data_mmap = true; 4264 } 4265 4266 /* 4267 * Allow aliases to facilitate the lookup of symbols for address 4268 * filters. Refer to auxtrace_parse_filters(). 4269 */ 4270 symbol_conf.allow_aliases = true; 4271 4272 symbol__init(NULL); 4273 4274 err = record__auxtrace_init(rec); 4275 if (err) 4276 goto out; 4277 4278 if (dry_run) 4279 goto out; 4280 4281 err = -ENOMEM; 4282 4283 if (rec->no_buildid_cache) { 4284 disable_buildid_cache(); 4285 } else if (rec->switch_output.enabled) { 4286 /* 4287 * In 'perf record --switch-output', disable buildid 4288 * generation by default to reduce data file switching 4289 * overhead. Still generate buildid if they are required 4290 * explicitly using 4291 * 4292 * perf record --switch-output --no-no-buildid \ 4293 * --no-no-buildid-cache 4294 * 4295 * Following code equals to: 4296 * 4297 * if ((rec->no_buildid || !rec->no_buildid_set) && 4298 * (rec->no_buildid_cache || !rec->no_buildid_cache_set)) 4299 * disable_buildid_cache(); 4300 */ 4301 bool disable = true; 4302 4303 if (rec->no_buildid_set && !rec->no_buildid) 4304 disable = false; 4305 if (rec->no_buildid_cache_set && !rec->no_buildid_cache) 4306 disable = false; 4307 if (disable) { 4308 rec->no_buildid = true; 4309 rec->no_buildid_cache = true; 4310 disable_buildid_cache(); 4311 } 4312 } 4313 4314 if (record.opts.overwrite) 4315 record.opts.tail_synthesize = true; 4316 4317 if (evlist__nr_entries(rec->evlist) == 0) { 4318 struct evlist *def_evlist = evlist__new_default(&rec->opts.target, 4319 callchain_param.enabled); 4320 4321 if (!def_evlist) 4322 goto out; 4323 4324 evlist__splice_list_tail(rec->evlist, &evlist__core(def_evlist)->entries); 4325 evlist__put(def_evlist); 4326 } 4327 4328 if (rec->opts.target.tid && !rec->opts.no_inherit_set) 4329 rec->opts.no_inherit = true; 4330 4331 err = target__validate(&rec->opts.target); 4332 if (err) { 4333 target__strerror(&rec->opts.target, err, errbuf, BUFSIZ); 4334 ui__warning("%s\n", errbuf); 4335 } 4336 4337 if (rec->uid_str) { 4338 uid_t uid = parse_uid(rec->uid_str); 4339 4340 if (uid == UINT_MAX) { 4341 ui__error("Invalid User: %s", rec->uid_str); 4342 err = -EINVAL; 4343 goto out; 4344 } 4345 err = parse_uid_filter(rec->evlist, uid); 4346 if (err) 4347 goto out; 4348 } 4349 4350 /* Enable ignoring missing threads when -p option is defined. */ 4351 rec->opts.ignore_missing_thread = rec->opts.target.pid; 4352 4353 evlist__warn_user_requested_cpus(rec->evlist, rec->opts.target.cpu_list); 4354 4355 if (callchain_param.enabled && callchain_param.record_mode == CALLCHAIN_FP) { 4356 if (EM_HOST == EM_AARCH64) 4357 add_leaf_frame_caller_opts_aarch64(&rec->opts); 4358 } 4359 4360 err = -ENOMEM; 4361 if (evlist__create_maps(rec->evlist, &rec->opts.target) < 0) { 4362 if (rec->opts.target.pid != NULL) { 4363 pr_err("Couldn't create thread/CPU maps: %s\n", 4364 errno == ENOENT ? "No such process" : str_error_r(errno, errbuf, sizeof(errbuf))); 4365 goto out; 4366 } 4367 else 4368 usage_with_options(record_usage, record_options); 4369 } 4370 4371 err = auxtrace_record__options(rec->itr, rec->evlist, &rec->opts); 4372 if (err) 4373 goto out; 4374 4375 /* 4376 * We take all buildids when the file contains 4377 * AUX area tracing data because we do not decode the 4378 * trace because it would take too long. 4379 */ 4380 if (rec->opts.full_auxtrace) 4381 rec->buildid_all = true; 4382 4383 if (rec->opts.text_poke) { 4384 err = record__config_text_poke(rec->evlist); 4385 if (err) { 4386 pr_err("record__config_text_poke failed, error %d\n", err); 4387 goto out; 4388 } 4389 } 4390 4391 if (rec->off_cpu) { 4392 err = record__config_off_cpu(rec); 4393 if (err) { 4394 pr_err("record__config_off_cpu failed, error %d\n", err); 4395 goto out; 4396 } 4397 } 4398 4399 if (record_opts__config(&rec->opts)) { 4400 err = -EINVAL; 4401 goto out; 4402 } 4403 4404 err = record__config_tracking_events(rec); 4405 if (err) { 4406 pr_err("record__config_tracking_events failed, error %d\n", err); 4407 goto out; 4408 } 4409 4410 err = record__init_thread_masks(rec); 4411 if (err) { 4412 pr_err("Failed to initialize parallel data streaming masks\n"); 4413 goto out; 4414 } 4415 4416 if (rec->opts.nr_cblocks > nr_cblocks_max) 4417 rec->opts.nr_cblocks = nr_cblocks_max; 4418 pr_debug("nr_cblocks: %d\n", rec->opts.nr_cblocks); 4419 4420 pr_debug("affinity: %s\n", affinity_tags[rec->opts.affinity]); 4421 pr_debug("mmap flush: %d\n", rec->opts.mmap_flush); 4422 4423 if (rec->opts.comp_level > comp_level_max) 4424 rec->opts.comp_level = comp_level_max; 4425 pr_debug("comp level: %d\n", rec->opts.comp_level); 4426 4427 err = __cmd_record(&record, argc, argv); 4428 out: 4429 record__free_thread_masks(rec, rec->nr_threads); 4430 rec->nr_threads = 0; 4431 symbol__exit(); 4432 auxtrace_record__free(rec->itr); 4433 out_opts: 4434 evlist__close_control(rec->opts.ctl_fd, rec->opts.ctl_fd_ack, &rec->opts.ctl_fd_close); 4435 evlist__put(rec->evlist); 4436 return err; 4437 } 4438 4439 static void snapshot_sig_handler(int sig __maybe_unused) 4440 { 4441 struct record *rec = &record; 4442 4443 hit_auxtrace_snapshot_trigger(rec); 4444 4445 if (switch_output_signal(rec)) 4446 trigger_hit(&switch_output_trigger); 4447 } 4448 4449 static void alarm_sig_handler(int sig __maybe_unused) 4450 { 4451 struct record *rec = &record; 4452 4453 if (switch_output_time(rec)) 4454 trigger_hit(&switch_output_trigger); 4455 } 4456