79f99dba5be0ce493d37c48a0fb765aca6b355b3
[safe/jmp/linux-2.6] / tools / perf / builtin-record.c
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/trace-event.h"
21
22 #include <unistd.h>
23 #include <sched.h>
24
25 #define ALIGN(x, a)             __ALIGN_MASK(x, (typeof(x))(a)-1)
26 #define __ALIGN_MASK(x, mask)   (((x)+(mask))&~(mask))
27
28 static int                      fd[MAX_NR_CPUS][MAX_COUNTERS];
29
30 static long                     default_interval                = 100000;
31
32 static int                      nr_cpus                         = 0;
33 static unsigned int             page_size;
34 static unsigned int             mmap_pages                      = 128;
35 static int                      freq                            = 0;
36 static int                      output;
37 static const char               *output_name                    = "perf.data";
38 static int                      group                           = 0;
39 static unsigned int             realtime_prio                   = 0;
40 static int                      raw_samples                     = 0;
41 static int                      system_wide                     = 0;
42 static int                      profile_cpu                     = -1;
43 static pid_t                    target_pid                      = -1;
44 static int                      inherit                         = 1;
45 static int                      force                           = 0;
46 static int                      append_file                     = 0;
47 static int                      call_graph                      = 0;
48 static int                      inherit_stat                    = 0;
49 static int                      no_samples                      = 0;
50 static int                      sample_address                  = 0;
51 static int                      multiplex                       = 0;
52
53 static long                     samples;
54 static struct timeval           last_read;
55 static struct timeval           this_read;
56
57 static u64                      bytes_written;
58
59 static struct pollfd            event_array[MAX_NR_CPUS * MAX_COUNTERS];
60
61 static int                      nr_poll;
62 static int                      nr_cpu;
63
64 static int                      file_new = 1;
65
66 struct perf_header              *header;
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_counter_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_counter_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 mmap_read(struct mmap_data *md)
115 {
116         unsigned int head = mmap_read_head(md);
117         unsigned int old = md->prev;
118         unsigned char *data = md->base + page_size;
119         unsigned long size;
120         void *buf;
121         int diff;
122
123         gettimeofday(&this_read, NULL);
124
125         /*
126          * If we're further behind than half the buffer, there's a chance
127          * the writer will bite our tail and mess up the samples under us.
128          *
129          * If we somehow ended up ahead of the head, we got messed up.
130          *
131          * In either case, truncate and restart at head.
132          */
133         diff = head - old;
134         if (diff < 0) {
135                 struct timeval iv;
136                 unsigned long msecs;
137
138                 timersub(&this_read, &last_read, &iv);
139                 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
140
141                 fprintf(stderr, "WARNING: failed to keep up with mmap data."
142                                 "  Last read %lu msecs ago.\n", msecs);
143
144                 /*
145                  * head points to a known good entry, start there.
146                  */
147                 old = head;
148         }
149
150         last_read = this_read;
151
152         if (old != head)
153                 samples++;
154
155         size = head - old;
156
157         if ((old & md->mask) + size != (head & md->mask)) {
158                 buf = &data[old & md->mask];
159                 size = md->mask + 1 - (old & md->mask);
160                 old += size;
161
162                 write_output(buf, size);
163         }
164
165         buf = &data[old & md->mask];
166         size = head - old;
167         old += size;
168
169         write_output(buf, size);
170
171         md->prev = old;
172         mmap_write_tail(md, old);
173 }
174
175 static volatile int done = 0;
176 static volatile int signr = -1;
177
178 static void sig_handler(int sig)
179 {
180         done = 1;
181         signr = sig;
182 }
183
184 static void sig_atexit(void)
185 {
186         if (signr == -1)
187                 return;
188
189         signal(signr, SIG_DFL);
190         kill(getpid(), signr);
191 }
192
193 static pid_t pid_synthesize_comm_event(pid_t pid, int full)
194 {
195         struct comm_event comm_ev;
196         char filename[PATH_MAX];
197         char bf[BUFSIZ];
198         FILE *fp;
199         size_t size = 0;
200         DIR *tasks;
201         struct dirent dirent, *next;
202         pid_t tgid = 0;
203
204         snprintf(filename, sizeof(filename), "/proc/%d/status", pid);
205
206         fp = fopen(filename, "r");
207         if (fp == NULL) {
208                 /*
209                  * We raced with a task exiting - just return:
210                  */
211                 if (verbose)
212                         fprintf(stderr, "couldn't open %s\n", filename);
213                 return 0;
214         }
215
216         memset(&comm_ev, 0, sizeof(comm_ev));
217         while (!comm_ev.comm[0] || !comm_ev.pid) {
218                 if (fgets(bf, sizeof(bf), fp) == NULL)
219                         goto out_failure;
220
221                 if (memcmp(bf, "Name:", 5) == 0) {
222                         char *name = bf + 5;
223                         while (*name && isspace(*name))
224                                 ++name;
225                         size = strlen(name) - 1;
226                         memcpy(comm_ev.comm, name, size++);
227                 } else if (memcmp(bf, "Tgid:", 5) == 0) {
228                         char *tgids = bf + 5;
229                         while (*tgids && isspace(*tgids))
230                                 ++tgids;
231                         tgid = comm_ev.pid = atoi(tgids);
232                 }
233         }
234
235         comm_ev.header.type = PERF_EVENT_COMM;
236         size = ALIGN(size, sizeof(u64));
237         comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
238
239         if (!full) {
240                 comm_ev.tid = pid;
241
242                 write_output(&comm_ev, comm_ev.header.size);
243                 goto out_fclose;
244         }
245
246         snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
247
248         tasks = opendir(filename);
249         while (!readdir_r(tasks, &dirent, &next) && next) {
250                 char *end;
251                 pid = strtol(dirent.d_name, &end, 10);
252                 if (*end)
253                         continue;
254
255                 comm_ev.tid = pid;
256
257                 write_output(&comm_ev, comm_ev.header.size);
258         }
259         closedir(tasks);
260
261 out_fclose:
262         fclose(fp);
263         return tgid;
264
265 out_failure:
266         fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
267                 filename);
268         exit(EXIT_FAILURE);
269 }
270
271 static void pid_synthesize_mmap_samples(pid_t pid, pid_t tgid)
272 {
273         char filename[PATH_MAX];
274         FILE *fp;
275
276         snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
277
278         fp = fopen(filename, "r");
279         if (fp == NULL) {
280                 /*
281                  * We raced with a task exiting - just return:
282                  */
283                 if (verbose)
284                         fprintf(stderr, "couldn't open %s\n", filename);
285                 return;
286         }
287         while (1) {
288                 char bf[BUFSIZ], *pbf = bf;
289                 struct mmap_event mmap_ev = {
290                         .header = { .type = PERF_EVENT_MMAP },
291                 };
292                 int n;
293                 size_t size;
294                 if (fgets(bf, sizeof(bf), fp) == NULL)
295                         break;
296
297                 /* 00400000-0040c000 r-xp 00000000 fd:01 41038  /bin/cat */
298                 n = hex2u64(pbf, &mmap_ev.start);
299                 if (n < 0)
300                         continue;
301                 pbf += n + 1;
302                 n = hex2u64(pbf, &mmap_ev.len);
303                 if (n < 0)
304                         continue;
305                 pbf += n + 3;
306                 if (*pbf == 'x') { /* vm_exec */
307                         char *execname = strchr(bf, '/');
308
309                         /* Catch VDSO */
310                         if (execname == NULL)
311                                 execname = strstr(bf, "[vdso]");
312
313                         if (execname == NULL)
314                                 continue;
315
316                         size = strlen(execname);
317                         execname[size - 1] = '\0'; /* Remove \n */
318                         memcpy(mmap_ev.filename, execname, size);
319                         size = ALIGN(size, sizeof(u64));
320                         mmap_ev.len -= mmap_ev.start;
321                         mmap_ev.header.size = (sizeof(mmap_ev) -
322                                                (sizeof(mmap_ev.filename) - size));
323                         mmap_ev.pid = tgid;
324                         mmap_ev.tid = pid;
325
326                         write_output(&mmap_ev, mmap_ev.header.size);
327                 }
328         }
329
330         fclose(fp);
331 }
332
333 static void synthesize_all(void)
334 {
335         DIR *proc;
336         struct dirent dirent, *next;
337
338         proc = opendir("/proc");
339
340         while (!readdir_r(proc, &dirent, &next) && next) {
341                 char *end;
342                 pid_t pid, tgid;
343
344                 pid = strtol(dirent.d_name, &end, 10);
345                 if (*end) /* only interested in proper numerical dirents */
346                         continue;
347
348                 tgid = pid_synthesize_comm_event(pid, 1);
349                 pid_synthesize_mmap_samples(pid, tgid);
350         }
351
352         closedir(proc);
353 }
354
355 static int group_fd;
356
357 static struct perf_header_attr *get_header_attr(struct perf_counter_attr *a, int nr)
358 {
359         struct perf_header_attr *h_attr;
360
361         if (nr < header->attrs) {
362                 h_attr = header->attr[nr];
363         } else {
364                 h_attr = perf_header_attr__new(a);
365                 perf_header__add_attr(header, h_attr);
366         }
367
368         return h_attr;
369 }
370
371 static void create_counter(int counter, int cpu, pid_t pid)
372 {
373         struct perf_counter_attr *attr = attrs + counter;
374         struct perf_header_attr *h_attr;
375         int track = !counter; /* only the first counter needs these */
376         struct {
377                 u64 count;
378                 u64 time_enabled;
379                 u64 time_running;
380                 u64 id;
381         } read_data;
382
383         attr->read_format       = PERF_FORMAT_TOTAL_TIME_ENABLED |
384                                   PERF_FORMAT_TOTAL_TIME_RUNNING |
385                                   PERF_FORMAT_ID;
386
387         attr->sample_type       |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
388
389         if (freq) {
390                 attr->sample_type       |= PERF_SAMPLE_PERIOD;
391                 attr->freq              = 1;
392                 attr->sample_freq       = freq;
393         }
394
395         if (no_samples)
396                 attr->sample_freq = 0;
397
398         if (inherit_stat)
399                 attr->inherit_stat = 1;
400
401         if (sample_address)
402                 attr->sample_type       |= PERF_SAMPLE_ADDR;
403
404         if (call_graph)
405                 attr->sample_type       |= PERF_SAMPLE_CALLCHAIN;
406
407         if (raw_samples) {
408                 attr->sample_type       |= PERF_SAMPLE_TIME;
409                 attr->sample_type       |= PERF_SAMPLE_RAW;
410                 attr->sample_type       |= PERF_SAMPLE_CPU;
411         }
412
413         attr->mmap              = track;
414         attr->comm              = track;
415         attr->inherit           = (cpu < 0) && inherit;
416         attr->disabled          = 1;
417
418 try_again:
419         fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
420
421         if (fd[nr_cpu][counter] < 0) {
422                 int err = errno;
423
424                 if (err == EPERM)
425                         die("Permission error - are you root?\n");
426                 else if (err ==  ENODEV && profile_cpu != -1)
427                         die("No such device - did you specify an out-of-range profile CPU?\n");
428
429                 /*
430                  * If it's cycles then fall back to hrtimer
431                  * based cpu-clock-tick sw counter, which
432                  * is always available even if no PMU support:
433                  */
434                 if (attr->type == PERF_TYPE_HARDWARE
435                         && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
436
437                         if (verbose)
438                                 warning(" ... trying to fall back to cpu-clock-ticks\n");
439                         attr->type = PERF_TYPE_SOFTWARE;
440                         attr->config = PERF_COUNT_SW_CPU_CLOCK;
441                         goto try_again;
442                 }
443                 printf("\n");
444                 error("perfcounter syscall returned with %d (%s)\n",
445                         fd[nr_cpu][counter], strerror(err));
446                 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
447                 exit(-1);
448         }
449
450         h_attr = get_header_attr(attr, counter);
451
452         if (!file_new) {
453                 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
454                         fprintf(stderr, "incompatible append\n");
455                         exit(-1);
456                 }
457         }
458
459         if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
460                 perror("Unable to read perf file descriptor\n");
461                 exit(-1);
462         }
463
464         perf_header_attr__add_id(h_attr, read_data.id);
465
466         assert(fd[nr_cpu][counter] >= 0);
467         fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
468
469         /*
470          * First counter acts as the group leader:
471          */
472         if (group && group_fd == -1)
473                 group_fd = fd[nr_cpu][counter];
474
475         event_array[nr_poll].fd = fd[nr_cpu][counter];
476         event_array[nr_poll].events = POLLIN;
477         nr_poll++;
478
479         mmap_array[nr_cpu][counter].counter = counter;
480         mmap_array[nr_cpu][counter].prev = 0;
481         mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
482         mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
483                         PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
484         if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
485                 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
486                 exit(-1);
487         }
488
489         if (multiplex && fd[nr_cpu][counter] != group_fd)
490                 ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_SET_OUTPUT, group_fd);
491
492         ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
493 }
494
495 static void open_counters(int cpu, pid_t pid)
496 {
497         int counter;
498
499         group_fd = -1;
500         for (counter = 0; counter < nr_counters; counter++)
501                 create_counter(counter, cpu, pid);
502
503         nr_cpu++;
504 }
505
506 static void atexit_header(void)
507 {
508         header->data_size += bytes_written;
509
510         perf_header__write(header, output);
511 }
512
513 static int __cmd_record(int argc, const char **argv)
514 {
515         int i, counter;
516         struct stat st;
517         pid_t pid = 0;
518         int flags;
519         int ret;
520
521         page_size = sysconf(_SC_PAGE_SIZE);
522         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
523         assert(nr_cpus <= MAX_NR_CPUS);
524         assert(nr_cpus >= 0);
525
526         atexit(sig_atexit);
527         signal(SIGCHLD, sig_handler);
528         signal(SIGINT, sig_handler);
529
530         if (!stat(output_name, &st) && st.st_size) {
531                 if (!force && !append_file) {
532                         fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
533                                         output_name);
534                         exit(-1);
535                 }
536         } else {
537                 append_file = 0;
538         }
539
540         flags = O_CREAT|O_RDWR;
541         if (append_file)
542                 file_new = 0;
543         else
544                 flags |= O_TRUNC;
545
546         output = open(output_name, flags, S_IRUSR|S_IWUSR);
547         if (output < 0) {
548                 perror("failed to create output file");
549                 exit(-1);
550         }
551
552         if (!file_new)
553                 header = perf_header__read(output);
554         else
555                 header = perf_header__new();
556
557
558         if (raw_samples) {
559                 read_tracing_data(attrs, nr_counters);
560         } else {
561                 for (i = 0; i < nr_counters; i++) {
562                         if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
563                                 read_tracing_data(attrs, nr_counters);
564                                 break;
565                         }
566                 }
567         }
568         atexit(atexit_header);
569
570         if (!system_wide) {
571                 pid = target_pid;
572                 if (pid == -1)
573                         pid = getpid();
574
575                 open_counters(profile_cpu, pid);
576         } else {
577                 if (profile_cpu != -1) {
578                         open_counters(profile_cpu, target_pid);
579                 } else {
580                         for (i = 0; i < nr_cpus; i++)
581                                 open_counters(i, target_pid);
582                 }
583         }
584
585         if (file_new)
586                 perf_header__write(header, output);
587
588         if (!system_wide) {
589                 pid_t tgid = pid_synthesize_comm_event(pid, 0);
590                 pid_synthesize_mmap_samples(pid, tgid);
591         } else
592                 synthesize_all();
593
594         if (target_pid == -1 && argc) {
595                 pid = fork();
596                 if (pid < 0)
597                         perror("failed to fork");
598
599                 if (!pid) {
600                         if (execvp(argv[0], (char **)argv)) {
601                                 perror(argv[0]);
602                                 exit(-1);
603                         }
604                 }
605         }
606
607         if (realtime_prio) {
608                 struct sched_param param;
609
610                 param.sched_priority = realtime_prio;
611                 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
612                         printf("Could not set realtime priority.\n");
613                         exit(-1);
614                 }
615         }
616
617         for (;;) {
618                 int hits = samples;
619
620                 for (i = 0; i < nr_cpu; i++) {
621                         for (counter = 0; counter < nr_counters; counter++)
622                                 mmap_read(&mmap_array[i][counter]);
623                 }
624
625                 if (hits == samples) {
626                         if (done)
627                                 break;
628                         ret = poll(event_array, nr_poll, 100);
629                 }
630         }
631
632         /*
633          * Approximate RIP event size: 24 bytes.
634          */
635         fprintf(stderr,
636                 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
637                 (double)bytes_written / 1024.0 / 1024.0,
638                 output_name,
639                 bytes_written / 24);
640
641         return 0;
642 }
643
644 static const char * const record_usage[] = {
645         "perf record [<options>] [<command>]",
646         "perf record [<options>] -- <command> [<options>]",
647         NULL
648 };
649
650 static const struct option options[] = {
651         OPT_CALLBACK('e', "event", NULL, "event",
652                      "event selector. use 'perf list' to list available events",
653                      parse_events),
654         OPT_INTEGER('p', "pid", &target_pid,
655                     "record events on existing pid"),
656         OPT_INTEGER('r', "realtime", &realtime_prio,
657                     "collect data with this RT SCHED_FIFO priority"),
658         OPT_BOOLEAN('R', "raw-samples", &raw_samples,
659                     "collect raw sample records from all opened counters"),
660         OPT_BOOLEAN('a', "all-cpus", &system_wide,
661                             "system-wide collection from all CPUs"),
662         OPT_BOOLEAN('A', "append", &append_file,
663                             "append to the output file to do incremental profiling"),
664         OPT_INTEGER('C', "profile_cpu", &profile_cpu,
665                             "CPU to profile on"),
666         OPT_BOOLEAN('f', "force", &force,
667                         "overwrite existing data file"),
668         OPT_LONG('c', "count", &default_interval,
669                     "event period to sample"),
670         OPT_STRING('o', "output", &output_name, "file",
671                     "output file name"),
672         OPT_BOOLEAN('i', "inherit", &inherit,
673                     "child tasks inherit counters"),
674         OPT_INTEGER('F', "freq", &freq,
675                     "profile at this frequency"),
676         OPT_INTEGER('m', "mmap-pages", &mmap_pages,
677                     "number of mmap data pages"),
678         OPT_BOOLEAN('g', "call-graph", &call_graph,
679                     "do call-graph (stack chain/backtrace) recording"),
680         OPT_BOOLEAN('v', "verbose", &verbose,
681                     "be more verbose (show counter open errors, etc)"),
682         OPT_BOOLEAN('s', "stat", &inherit_stat,
683                     "per thread counts"),
684         OPT_BOOLEAN('d', "data", &sample_address,
685                     "Sample addresses"),
686         OPT_BOOLEAN('n', "no-samples", &no_samples,
687                     "don't sample"),
688         OPT_BOOLEAN('M', "multiplex", &multiplex,
689                     "multiplex counter output in a single channel"),
690         OPT_END()
691 };
692
693 int cmd_record(int argc, const char **argv, const char *prefix __used)
694 {
695         int counter;
696
697         argc = parse_options(argc, argv, options, record_usage,
698                 PARSE_OPT_STOP_AT_NON_OPTION);
699         if (!argc && target_pid == -1 && !system_wide)
700                 usage_with_options(record_usage, options);
701
702         if (!nr_counters) {
703                 nr_counters     = 1;
704                 attrs[0].type   = PERF_TYPE_HARDWARE;
705                 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
706         }
707
708         for (counter = 0; counter < nr_counters; counter++) {
709                 if (attrs[counter].sample_period)
710                         continue;
711
712                 attrs[counter].sample_period = default_interval;
713         }
714
715         return __cmd_record(argc, argv);
716 }