1 /* 2 * builtin-record.c 3 * 4 * Builtin record command: Record the profile of a workload 5 * (or a CPU, or a PID) into the perf.data output file - for 6 * later analysis via perf report. 7 */ 8 #include "builtin.h" 9 10 #include "perf.h" 11 12 #include "util/util.h" 13 #include "util/parse-options.h" 14 #include "util/parse-events.h" 15 #include "util/string.h" 16 17 #include "util/header.h" 18 #include "util/event.h" 19 #include "util/debug.h" 20 #include "util/session.h" 21 #include "util/symbol.h" 22 23 #include <unistd.h> 24 #include <sched.h> 25 26 static int fd[MAX_NR_CPUS][MAX_COUNTERS]; 27 28 static long default_interval = 0; 29 30 static int nr_cpus = 0; 31 static unsigned int page_size; 32 static unsigned int mmap_pages = 128; 33 static int freq = 1000; 34 static int output; 35 static const char *output_name = "perf.data"; 36 static int group = 0; 37 static unsigned int realtime_prio = 0; 38 static int raw_samples = 0; 39 static int system_wide = 0; 40 static int profile_cpu = -1; 41 static pid_t target_pid = -1; 42 static pid_t child_pid = -1; 43 static int inherit = 1; 44 static int force = 0; 45 static int append_file = 0; 46 static int call_graph = 0; 47 static int inherit_stat = 0; 48 static int no_samples = 0; 49 static int sample_address = 0; 50 static int multiplex = 0; 51 static int multiplex_fd = -1; 52 53 static long samples = 0; 54 static struct timeval last_read; 55 static struct timeval this_read; 56 57 static u64 bytes_written = 0; 58 59 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS]; 60 61 static int nr_poll = 0; 62 static int nr_cpu = 0; 63 64 static int file_new = 1; 65 66 static struct perf_session *session; 67 68 struct mmap_data { 69 int counter; 70 void *base; 71 unsigned int mask; 72 unsigned int prev; 73 }; 74 75 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS]; 76 77 static unsigned long mmap_read_head(struct mmap_data *md) 78 { 79 struct perf_event_mmap_page *pc = md->base; 80 long head; 81 82 head = pc->data_head; 83 rmb(); 84 85 return head; 86 } 87 88 static void mmap_write_tail(struct mmap_data *md, unsigned long tail) 89 { 90 struct perf_event_mmap_page *pc = md->base; 91 92 /* 93 * ensure all reads are done before we write the tail out. 94 */ 95 /* mb(); */ 96 pc->data_tail = tail; 97 } 98 99 static void write_output(void *buf, size_t size) 100 { 101 while (size) { 102 int ret = write(output, buf, size); 103 104 if (ret < 0) 105 die("failed to write"); 106 107 size -= ret; 108 buf += ret; 109 110 bytes_written += ret; 111 } 112 } 113 114 static void write_event(event_t *buf, size_t size) 115 { 116 /* 117 * Add it to the list of DSOs, so that when we finish this 118 * record session we can pick the available build-ids. 119 */ 120 if (buf->header.type == PERF_RECORD_MMAP) 121 dsos__findnew(buf->mmap.filename); 122 123 write_output(buf, size); 124 } 125 126 static int process_synthesized_event(event_t *event, 127 struct perf_session *self __used) 128 { 129 write_event(event, event->header.size); 130 return 0; 131 } 132 133 static void mmap_read(struct mmap_data *md) 134 { 135 unsigned int head = mmap_read_head(md); 136 unsigned int old = md->prev; 137 unsigned char *data = md->base + page_size; 138 unsigned long size; 139 void *buf; 140 int diff; 141 142 gettimeofday(&this_read, NULL); 143 144 /* 145 * If we're further behind than half the buffer, there's a chance 146 * the writer will bite our tail and mess up the samples under us. 147 * 148 * If we somehow ended up ahead of the head, we got messed up. 149 * 150 * In either case, truncate and restart at head. 151 */ 152 diff = head - old; 153 if (diff < 0) { 154 struct timeval iv; 155 unsigned long msecs; 156 157 timersub(&this_read, &last_read, &iv); 158 msecs = iv.tv_sec*1000 + iv.tv_usec/1000; 159 160 fprintf(stderr, "WARNING: failed to keep up with mmap data." 161 " Last read %lu msecs ago.\n", msecs); 162 163 /* 164 * head points to a known good entry, start there. 165 */ 166 old = head; 167 } 168 169 last_read = this_read; 170 171 if (old != head) 172 samples++; 173 174 size = head - old; 175 176 if ((old & md->mask) + size != (head & md->mask)) { 177 buf = &data[old & md->mask]; 178 size = md->mask + 1 - (old & md->mask); 179 old += size; 180 181 write_event(buf, size); 182 } 183 184 buf = &data[old & md->mask]; 185 size = head - old; 186 old += size; 187 188 write_event(buf, size); 189 190 md->prev = old; 191 mmap_write_tail(md, old); 192 } 193 194 static volatile int done = 0; 195 static volatile int signr = -1; 196 197 static void sig_handler(int sig) 198 { 199 done = 1; 200 signr = sig; 201 } 202 203 static void sig_atexit(void) 204 { 205 if (child_pid != -1) 206 kill(child_pid, SIGTERM); 207 208 if (signr == -1) 209 return; 210 211 signal(signr, SIG_DFL); 212 kill(getpid(), signr); 213 } 214 215 static int group_fd; 216 217 static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr) 218 { 219 struct perf_header_attr *h_attr; 220 221 if (nr < session->header.attrs) { 222 h_attr = session->header.attr[nr]; 223 } else { 224 h_attr = perf_header_attr__new(a); 225 if (h_attr != NULL) 226 if (perf_header__add_attr(&session->header, h_attr) < 0) { 227 perf_header_attr__delete(h_attr); 228 h_attr = NULL; 229 } 230 } 231 232 return h_attr; 233 } 234 235 static void create_counter(int counter, int cpu, pid_t pid) 236 { 237 char *filter = filters[counter]; 238 struct perf_event_attr *attr = attrs + counter; 239 struct perf_header_attr *h_attr; 240 int track = !counter; /* only the first counter needs these */ 241 int ret; 242 struct { 243 u64 count; 244 u64 time_enabled; 245 u64 time_running; 246 u64 id; 247 } read_data; 248 249 attr->read_format = PERF_FORMAT_TOTAL_TIME_ENABLED | 250 PERF_FORMAT_TOTAL_TIME_RUNNING | 251 PERF_FORMAT_ID; 252 253 attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID; 254 255 if (freq) { 256 attr->sample_type |= PERF_SAMPLE_PERIOD; 257 attr->freq = 1; 258 attr->sample_freq = freq; 259 } 260 261 if (no_samples) 262 attr->sample_freq = 0; 263 264 if (inherit_stat) 265 attr->inherit_stat = 1; 266 267 if (sample_address) 268 attr->sample_type |= PERF_SAMPLE_ADDR; 269 270 if (call_graph) 271 attr->sample_type |= PERF_SAMPLE_CALLCHAIN; 272 273 if (raw_samples) { 274 attr->sample_type |= PERF_SAMPLE_TIME; 275 attr->sample_type |= PERF_SAMPLE_RAW; 276 attr->sample_type |= PERF_SAMPLE_CPU; 277 } 278 279 attr->mmap = track; 280 attr->comm = track; 281 attr->inherit = inherit; 282 attr->disabled = 1; 283 284 try_again: 285 fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0); 286 287 if (fd[nr_cpu][counter] < 0) { 288 int err = errno; 289 290 if (err == EPERM || err == EACCES) 291 die("Permission error - are you root?\n"); 292 else if (err == ENODEV && profile_cpu != -1) 293 die("No such device - did you specify an out-of-range profile CPU?\n"); 294 295 /* 296 * If it's cycles then fall back to hrtimer 297 * based cpu-clock-tick sw counter, which 298 * is always available even if no PMU support: 299 */ 300 if (attr->type == PERF_TYPE_HARDWARE 301 && attr->config == PERF_COUNT_HW_CPU_CYCLES) { 302 303 if (verbose) 304 warning(" ... trying to fall back to cpu-clock-ticks\n"); 305 attr->type = PERF_TYPE_SOFTWARE; 306 attr->config = PERF_COUNT_SW_CPU_CLOCK; 307 goto try_again; 308 } 309 printf("\n"); 310 error("perfcounter syscall returned with %d (%s)\n", 311 fd[nr_cpu][counter], strerror(err)); 312 313 #if defined(__i386__) || defined(__x86_64__) 314 if (attr->type == PERF_TYPE_HARDWARE && err == EOPNOTSUPP) 315 die("No hardware sampling interrupt available. No APIC? If so then you can boot the kernel with the \"lapic\" boot parameter to force-enable it.\n"); 316 #endif 317 318 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n"); 319 exit(-1); 320 } 321 322 h_attr = get_header_attr(attr, counter); 323 if (h_attr == NULL) 324 die("nomem\n"); 325 326 if (!file_new) { 327 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) { 328 fprintf(stderr, "incompatible append\n"); 329 exit(-1); 330 } 331 } 332 333 if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) { 334 perror("Unable to read perf file descriptor\n"); 335 exit(-1); 336 } 337 338 if (perf_header_attr__add_id(h_attr, read_data.id) < 0) { 339 pr_warning("Not enough memory to add id\n"); 340 exit(-1); 341 } 342 343 assert(fd[nr_cpu][counter] >= 0); 344 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK); 345 346 /* 347 * First counter acts as the group leader: 348 */ 349 if (group && group_fd == -1) 350 group_fd = fd[nr_cpu][counter]; 351 if (multiplex && multiplex_fd == -1) 352 multiplex_fd = fd[nr_cpu][counter]; 353 354 if (multiplex && fd[nr_cpu][counter] != multiplex_fd) { 355 356 ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd); 357 assert(ret != -1); 358 } else { 359 event_array[nr_poll].fd = fd[nr_cpu][counter]; 360 event_array[nr_poll].events = POLLIN; 361 nr_poll++; 362 363 mmap_array[nr_cpu][counter].counter = counter; 364 mmap_array[nr_cpu][counter].prev = 0; 365 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1; 366 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size, 367 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0); 368 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) { 369 error("failed to mmap with %d (%s)\n", errno, strerror(errno)); 370 exit(-1); 371 } 372 } 373 374 if (filter != NULL) { 375 ret = ioctl(fd[nr_cpu][counter], 376 PERF_EVENT_IOC_SET_FILTER, filter); 377 if (ret) { 378 error("failed to set filter with %d (%s)\n", errno, 379 strerror(errno)); 380 exit(-1); 381 } 382 } 383 384 ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE); 385 } 386 387 static void open_counters(int cpu, pid_t pid) 388 { 389 int counter; 390 391 group_fd = -1; 392 for (counter = 0; counter < nr_counters; counter++) 393 create_counter(counter, cpu, pid); 394 395 nr_cpu++; 396 } 397 398 static void atexit_header(void) 399 { 400 session->header.data_size += bytes_written; 401 402 perf_header__write(&session->header, output, true); 403 } 404 405 static int __cmd_record(int argc __used, const char **argv) 406 { 407 int i, counter; 408 struct stat st; 409 pid_t pid = 0; 410 int flags; 411 int err; 412 unsigned long waking = 0; 413 int child_ready_pipe[2], go_pipe[2]; 414 char buf; 415 416 page_size = sysconf(_SC_PAGE_SIZE); 417 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN); 418 assert(nr_cpus <= MAX_NR_CPUS); 419 assert(nr_cpus >= 0); 420 421 atexit(sig_atexit); 422 signal(SIGCHLD, sig_handler); 423 signal(SIGINT, sig_handler); 424 425 if (pipe(child_ready_pipe) < 0 || pipe(go_pipe) < 0) { 426 perror("failed to create pipes"); 427 exit(-1); 428 } 429 430 if (!stat(output_name, &st) && st.st_size) { 431 if (!force) { 432 if (!append_file) { 433 pr_err("Error, output file %s exists, use -A " 434 "to append or -f to overwrite.\n", 435 output_name); 436 exit(-1); 437 } 438 } else { 439 char oldname[PATH_MAX]; 440 snprintf(oldname, sizeof(oldname), "%s.old", 441 output_name); 442 unlink(oldname); 443 rename(output_name, oldname); 444 } 445 } else { 446 append_file = 0; 447 } 448 449 flags = O_CREAT|O_RDWR; 450 if (append_file) 451 file_new = 0; 452 else 453 flags |= O_TRUNC; 454 455 output = open(output_name, flags, S_IRUSR|S_IWUSR); 456 if (output < 0) { 457 perror("failed to create output file"); 458 exit(-1); 459 } 460 461 session = perf_session__new(output_name, O_WRONLY, force); 462 if (session == NULL) { 463 pr_err("Not enough memory for reading perf file header\n"); 464 return -1; 465 } 466 467 if (!file_new) { 468 err = perf_header__read(&session->header, output); 469 if (err < 0) 470 return err; 471 } 472 473 if (raw_samples) { 474 perf_header__set_feat(&session->header, HEADER_TRACE_INFO); 475 } else { 476 for (i = 0; i < nr_counters; i++) { 477 if (attrs[i].sample_type & PERF_SAMPLE_RAW) { 478 perf_header__set_feat(&session->header, HEADER_TRACE_INFO); 479 break; 480 } 481 } 482 } 483 484 atexit(atexit_header); 485 486 if (target_pid == -1) { 487 pid = fork(); 488 if (pid < 0) { 489 perror("failed to fork"); 490 exit(-1); 491 } 492 493 if (!pid) { 494 close(child_ready_pipe[0]); 495 close(go_pipe[1]); 496 fcntl(go_pipe[0], F_SETFD, FD_CLOEXEC); 497 498 /* 499 * Do a dummy execvp to get the PLT entry resolved, 500 * so we avoid the resolver overhead on the real 501 * execvp call. 502 */ 503 execvp("", (char **)argv); 504 505 /* 506 * Tell the parent we're ready to go 507 */ 508 close(child_ready_pipe[1]); 509 510 /* 511 * Wait until the parent tells us to go. 512 */ 513 if (read(go_pipe[0], &buf, 1) == -1) 514 perror("unable to read pipe"); 515 516 execvp(argv[0], (char **)argv); 517 518 perror(argv[0]); 519 exit(-1); 520 } 521 522 child_pid = pid; 523 524 if (!system_wide) 525 target_pid = pid; 526 527 close(child_ready_pipe[1]); 528 close(go_pipe[0]); 529 /* 530 * wait for child to settle 531 */ 532 if (read(child_ready_pipe[0], &buf, 1) == -1) { 533 perror("unable to read pipe"); 534 exit(-1); 535 } 536 close(child_ready_pipe[0]); 537 } 538 539 540 if ((!system_wide && !inherit) || profile_cpu != -1) { 541 open_counters(profile_cpu, target_pid); 542 } else { 543 for (i = 0; i < nr_cpus; i++) 544 open_counters(i, target_pid); 545 } 546 547 if (file_new) { 548 err = perf_header__write(&session->header, output, false); 549 if (err < 0) 550 return err; 551 } 552 553 if (!system_wide) 554 event__synthesize_thread(pid, process_synthesized_event, 555 session); 556 else 557 event__synthesize_threads(process_synthesized_event, session); 558 559 if (realtime_prio) { 560 struct sched_param param; 561 562 param.sched_priority = realtime_prio; 563 if (sched_setscheduler(0, SCHED_FIFO, ¶m)) { 564 pr_err("Could not set realtime priority.\n"); 565 exit(-1); 566 } 567 } 568 569 /* 570 * Let the child rip 571 */ 572 close(go_pipe[1]); 573 574 for (;;) { 575 int hits = samples; 576 577 for (i = 0; i < nr_cpu; i++) { 578 for (counter = 0; counter < nr_counters; counter++) { 579 if (mmap_array[i][counter].base) 580 mmap_read(&mmap_array[i][counter]); 581 } 582 } 583 584 if (hits == samples) { 585 if (done) 586 break; 587 err = poll(event_array, nr_poll, -1); 588 waking++; 589 } 590 591 if (done) { 592 for (i = 0; i < nr_cpu; i++) { 593 for (counter = 0; counter < nr_counters; counter++) 594 ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE); 595 } 596 } 597 } 598 599 fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking); 600 601 /* 602 * Approximate RIP event size: 24 bytes. 603 */ 604 fprintf(stderr, 605 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n", 606 (double)bytes_written / 1024.0 / 1024.0, 607 output_name, 608 bytes_written / 24); 609 610 return 0; 611 } 612 613 static const char * const record_usage[] = { 614 "perf record [<options>] [<command>]", 615 "perf record [<options>] -- <command> [<options>]", 616 NULL 617 }; 618 619 static const struct option options[] = { 620 OPT_CALLBACK('e', "event", NULL, "event", 621 "event selector. use 'perf list' to list available events", 622 parse_events), 623 OPT_CALLBACK(0, "filter", NULL, "filter", 624 "event filter", parse_filter), 625 OPT_INTEGER('p', "pid", &target_pid, 626 "record events on existing pid"), 627 OPT_INTEGER('r', "realtime", &realtime_prio, 628 "collect data with this RT SCHED_FIFO priority"), 629 OPT_BOOLEAN('R', "raw-samples", &raw_samples, 630 "collect raw sample records from all opened counters"), 631 OPT_BOOLEAN('a', "all-cpus", &system_wide, 632 "system-wide collection from all CPUs"), 633 OPT_BOOLEAN('A', "append", &append_file, 634 "append to the output file to do incremental profiling"), 635 OPT_INTEGER('C', "profile_cpu", &profile_cpu, 636 "CPU to profile on"), 637 OPT_BOOLEAN('f', "force", &force, 638 "overwrite existing data file"), 639 OPT_LONG('c', "count", &default_interval, 640 "event period to sample"), 641 OPT_STRING('o', "output", &output_name, "file", 642 "output file name"), 643 OPT_BOOLEAN('i', "inherit", &inherit, 644 "child tasks inherit counters"), 645 OPT_INTEGER('F', "freq", &freq, 646 "profile at this frequency"), 647 OPT_INTEGER('m', "mmap-pages", &mmap_pages, 648 "number of mmap data pages"), 649 OPT_BOOLEAN('g', "call-graph", &call_graph, 650 "do call-graph (stack chain/backtrace) recording"), 651 OPT_BOOLEAN('v', "verbose", &verbose, 652 "be more verbose (show counter open errors, etc)"), 653 OPT_BOOLEAN('s', "stat", &inherit_stat, 654 "per thread counts"), 655 OPT_BOOLEAN('d', "data", &sample_address, 656 "Sample addresses"), 657 OPT_BOOLEAN('n', "no-samples", &no_samples, 658 "don't sample"), 659 OPT_BOOLEAN('M', "multiplex", &multiplex, 660 "multiplex counter output in a single channel"), 661 OPT_END() 662 }; 663 664 int cmd_record(int argc, const char **argv, const char *prefix __used) 665 { 666 int counter; 667 668 argc = parse_options(argc, argv, options, record_usage, 669 PARSE_OPT_STOP_AT_NON_OPTION); 670 if (!argc && target_pid == -1 && (!system_wide || profile_cpu == -1)) 671 usage_with_options(record_usage, options); 672 673 symbol__init(); 674 675 if (!nr_counters) { 676 nr_counters = 1; 677 attrs[0].type = PERF_TYPE_HARDWARE; 678 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES; 679 } 680 681 /* 682 * User specified count overrides default frequency. 683 */ 684 if (default_interval) 685 freq = 0; 686 else if (freq) { 687 default_interval = freq; 688 } else { 689 fprintf(stderr, "frequency and count are zero, aborting\n"); 690 exit(EXIT_FAILURE); 691 } 692 693 for (counter = 0; counter < nr_counters; counter++) { 694 if (attrs[counter].sample_period) 695 continue; 696 697 attrs[counter].sample_period = default_interval; 698 } 699 700 return __cmd_record(argc, argv); 701 } 702