perf_counter tools: Handle lost events
[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 <unistd.h>
18 #include <sched.h>
19
20 #define ALIGN(x, a)             __ALIGN_MASK(x, (typeof(x))(a)-1)
21 #define __ALIGN_MASK(x, mask)   (((x)+(mask))&~(mask))
22
23 static int                      fd[MAX_NR_CPUS][MAX_COUNTERS];
24
25 static long                     default_interval                = 100000;
26
27 static int                      nr_cpus                         = 0;
28 static unsigned int             page_size;
29 static unsigned int             mmap_pages                      = 128;
30 static int                      freq                            = 0;
31 static int                      output;
32 static const char               *output_name                    = "perf.data";
33 static int                      group                           = 0;
34 static unsigned int             realtime_prio                   = 0;
35 static int                      system_wide                     = 0;
36 static pid_t                    target_pid                      = -1;
37 static int                      inherit                         = 1;
38 static int                      force                           = 0;
39 static int                      append_file                     = 0;
40 static int                      call_graph                      = 0;
41 static int                      verbose                         = 0;
42
43 static long                     samples;
44 static struct timeval           last_read;
45 static struct timeval           this_read;
46
47 static __u64                    bytes_written;
48
49 static struct pollfd            event_array[MAX_NR_CPUS * MAX_COUNTERS];
50
51 static int                      nr_poll;
52 static int                      nr_cpu;
53
54 struct mmap_event {
55         struct perf_event_header        header;
56         __u32                           pid;
57         __u32                           tid;
58         __u64                           start;
59         __u64                           len;
60         __u64                           pgoff;
61         char                            filename[PATH_MAX];
62 };
63
64 struct comm_event {
65         struct perf_event_header        header;
66         __u32                           pid;
67         __u32                           tid;
68         char                            comm[16];
69 };
70
71
72 struct mmap_data {
73         int                     counter;
74         void                    *base;
75         unsigned int            mask;
76         unsigned int            prev;
77 };
78
79 static struct mmap_data         mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
80
81 static unsigned long mmap_read_head(struct mmap_data *md)
82 {
83         struct perf_counter_mmap_page *pc = md->base;
84         long head;
85
86         head = pc->data_head;
87         rmb();
88
89         return head;
90 }
91
92 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
93 {
94         struct perf_counter_mmap_page *pc = md->base;
95
96         /*
97          * ensure all reads are done before we write the tail out.
98          */
99         /* mb(); */
100         pc->data_tail = tail;
101 }
102
103 static void mmap_read(struct mmap_data *md)
104 {
105         unsigned int head = mmap_read_head(md);
106         unsigned int old = md->prev;
107         unsigned char *data = md->base + page_size;
108         unsigned long size;
109         void *buf;
110         int diff;
111
112         gettimeofday(&this_read, NULL);
113
114         /*
115          * If we're further behind than half the buffer, there's a chance
116          * the writer will bite our tail and mess up the samples under us.
117          *
118          * If we somehow ended up ahead of the head, we got messed up.
119          *
120          * In either case, truncate and restart at head.
121          */
122         diff = head - old;
123         if (diff < 0) {
124                 struct timeval iv;
125                 unsigned long msecs;
126
127                 timersub(&this_read, &last_read, &iv);
128                 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
129
130                 fprintf(stderr, "WARNING: failed to keep up with mmap data."
131                                 "  Last read %lu msecs ago.\n", msecs);
132
133                 /*
134                  * head points to a known good entry, start there.
135                  */
136                 old = head;
137         }
138
139         last_read = this_read;
140
141         if (old != head)
142                 samples++;
143
144         size = head - old;
145
146         if ((old & md->mask) + size != (head & md->mask)) {
147                 buf = &data[old & md->mask];
148                 size = md->mask + 1 - (old & md->mask);
149                 old += size;
150
151                 while (size) {
152                         int ret = write(output, buf, size);
153
154                         if (ret < 0)
155                                 die("failed to write");
156
157                         size -= ret;
158                         buf += ret;
159
160                         bytes_written += ret;
161                 }
162         }
163
164         buf = &data[old & md->mask];
165         size = head - old;
166         old += size;
167
168         while (size) {
169                 int ret = write(output, buf, size);
170
171                 if (ret < 0)
172                         die("failed to write");
173
174                 size -= ret;
175                 buf += ret;
176
177                 bytes_written += ret;
178         }
179
180         md->prev = old;
181         mmap_write_tail(md, old);
182 }
183
184 static volatile int done = 0;
185 static volatile int signr = -1;
186
187 static void sig_handler(int sig)
188 {
189         done = 1;
190         signr = sig;
191 }
192
193 static void sig_atexit(void)
194 {
195         if (signr == -1)
196                 return;
197
198         signal(signr, SIG_DFL);
199         kill(getpid(), signr);
200 }
201
202 static void pid_synthesize_comm_event(pid_t pid, int full)
203 {
204         struct comm_event comm_ev;
205         char filename[PATH_MAX];
206         char bf[BUFSIZ];
207         int fd, ret;
208         size_t size;
209         char *field, *sep;
210         DIR *tasks;
211         struct dirent dirent, *next;
212
213         snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
214
215         fd = open(filename, O_RDONLY);
216         if (fd < 0) {
217                 /*
218                  * We raced with a task exiting - just return:
219                  */
220                 if (verbose)
221                         fprintf(stderr, "couldn't open %s\n", filename);
222                 return;
223         }
224         if (read(fd, bf, sizeof(bf)) < 0) {
225                 fprintf(stderr, "couldn't read %s\n", filename);
226                 exit(EXIT_FAILURE);
227         }
228         close(fd);
229
230         /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
231         memset(&comm_ev, 0, sizeof(comm_ev));
232         field = strchr(bf, '(');
233         if (field == NULL)
234                 goto out_failure;
235         sep = strchr(++field, ')');
236         if (sep == NULL)
237                 goto out_failure;
238         size = sep - field;
239         memcpy(comm_ev.comm, field, size++);
240
241         comm_ev.pid = pid;
242         comm_ev.header.type = PERF_EVENT_COMM;
243         size = ALIGN(size, sizeof(__u64));
244         comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
245
246         if (!full) {
247                 comm_ev.tid = pid;
248
249                 ret = write(output, &comm_ev, comm_ev.header.size);
250                 if (ret < 0) {
251                         perror("failed to write");
252                         exit(-1);
253                 }
254                 return;
255         }
256
257         snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
258
259         tasks = opendir(filename);
260         while (!readdir_r(tasks, &dirent, &next) && next) {
261                 char *end;
262                 pid = strtol(dirent.d_name, &end, 10);
263                 if (*end)
264                         continue;
265
266                 comm_ev.tid = pid;
267
268                 ret = write(output, &comm_ev, comm_ev.header.size);
269                 if (ret < 0) {
270                         perror("failed to write");
271                         exit(-1);
272                 }
273         }
274         closedir(tasks);
275         return;
276
277 out_failure:
278         fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
279                 filename);
280         exit(EXIT_FAILURE);
281 }
282
283 static void pid_synthesize_mmap_samples(pid_t pid)
284 {
285         char filename[PATH_MAX];
286         FILE *fp;
287
288         snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
289
290         fp = fopen(filename, "r");
291         if (fp == NULL) {
292                 /*
293                  * We raced with a task exiting - just return:
294                  */
295                 if (verbose)
296                         fprintf(stderr, "couldn't open %s\n", filename);
297                 return;
298         }
299         while (1) {
300                 char bf[BUFSIZ], *pbf = bf;
301                 struct mmap_event mmap_ev = {
302                         .header.type = PERF_EVENT_MMAP,
303                 };
304                 int n;
305                 size_t size;
306                 if (fgets(bf, sizeof(bf), fp) == NULL)
307                         break;
308
309                 /* 00400000-0040c000 r-xp 00000000 fd:01 41038  /bin/cat */
310                 n = hex2u64(pbf, &mmap_ev.start);
311                 if (n < 0)
312                         continue;
313                 pbf += n + 1;
314                 n = hex2u64(pbf, &mmap_ev.len);
315                 if (n < 0)
316                         continue;
317                 pbf += n + 3;
318                 if (*pbf == 'x') { /* vm_exec */
319                         char *execname = strrchr(bf, ' ');
320
321                         if (execname == NULL || execname[1] != '/')
322                                 continue;
323
324                         execname += 1;
325                         size = strlen(execname);
326                         execname[size - 1] = '\0'; /* Remove \n */
327                         memcpy(mmap_ev.filename, execname, size);
328                         size = ALIGN(size, sizeof(__u64));
329                         mmap_ev.len -= mmap_ev.start;
330                         mmap_ev.header.size = (sizeof(mmap_ev) -
331                                                (sizeof(mmap_ev.filename) - size));
332                         mmap_ev.pid = pid;
333                         mmap_ev.tid = pid;
334
335                         if (write(output, &mmap_ev, mmap_ev.header.size) < 0) {
336                                 perror("failed to write");
337                                 exit(-1);
338                         }
339                 }
340         }
341
342         fclose(fp);
343 }
344
345 static void synthesize_samples(void)
346 {
347         DIR *proc;
348         struct dirent dirent, *next;
349
350         proc = opendir("/proc");
351
352         while (!readdir_r(proc, &dirent, &next) && next) {
353                 char *end;
354                 pid_t pid;
355
356                 pid = strtol(dirent.d_name, &end, 10);
357                 if (*end) /* only interested in proper numerical dirents */
358                         continue;
359
360                 pid_synthesize_comm_event(pid, 1);
361                 pid_synthesize_mmap_samples(pid);
362         }
363
364         closedir(proc);
365 }
366
367 static int group_fd;
368
369 static void create_counter(int counter, int cpu, pid_t pid)
370 {
371         struct perf_counter_attr *attr = attrs + counter;
372         int track = 1;
373
374         attr->sample_type       = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
375
376         if (freq) {
377                 attr->sample_type       |= PERF_SAMPLE_PERIOD;
378                 attr->freq              = 1;
379                 attr->sample_freq       = freq;
380         }
381
382         if (call_graph)
383                 attr->sample_type       |= PERF_SAMPLE_CALLCHAIN;
384
385         attr->mmap              = track;
386         attr->comm              = track;
387         attr->inherit           = (cpu < 0) && inherit;
388         attr->disabled          = 1;
389
390         track = 0; /* only the first counter needs these */
391
392 try_again:
393         fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
394
395         if (fd[nr_cpu][counter] < 0) {
396                 int err = errno;
397
398                 if (err == EPERM)
399                         die("Permission error - are you root?\n");
400
401                 /*
402                  * If it's cycles then fall back to hrtimer
403                  * based cpu-clock-tick sw counter, which
404                  * is always available even if no PMU support:
405                  */
406                 if (attr->type == PERF_TYPE_HARDWARE
407                         && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
408
409                         if (verbose)
410                                 warning(" ... trying to fall back to cpu-clock-ticks\n");
411                         attr->type = PERF_TYPE_SOFTWARE;
412                         attr->config = PERF_COUNT_SW_CPU_CLOCK;
413                         goto try_again;
414                 }
415                 printf("\n");
416                 error("perfcounter syscall returned with %d (%s)\n",
417                         fd[nr_cpu][counter], strerror(err));
418                 die("No CONFIG_PERF_COUNTERS=y kernel support configured?\n");
419                 exit(-1);
420         }
421
422         assert(fd[nr_cpu][counter] >= 0);
423         fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
424
425         /*
426          * First counter acts as the group leader:
427          */
428         if (group && group_fd == -1)
429                 group_fd = fd[nr_cpu][counter];
430
431         event_array[nr_poll].fd = fd[nr_cpu][counter];
432         event_array[nr_poll].events = POLLIN;
433         nr_poll++;
434
435         mmap_array[nr_cpu][counter].counter = counter;
436         mmap_array[nr_cpu][counter].prev = 0;
437         mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
438         mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
439                         PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
440         if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
441                 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
442                 exit(-1);
443         }
444
445         ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
446 }
447
448 static void open_counters(int cpu, pid_t pid)
449 {
450         int counter;
451
452         if (pid > 0) {
453                 pid_synthesize_comm_event(pid, 0);
454                 pid_synthesize_mmap_samples(pid);
455         }
456
457         group_fd = -1;
458         for (counter = 0; counter < nr_counters; counter++)
459                 create_counter(counter, cpu, pid);
460
461         nr_cpu++;
462 }
463
464 static int __cmd_record(int argc, const char **argv)
465 {
466         int i, counter;
467         struct stat st;
468         pid_t pid;
469         int flags;
470         int ret;
471
472         page_size = sysconf(_SC_PAGE_SIZE);
473         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
474         assert(nr_cpus <= MAX_NR_CPUS);
475         assert(nr_cpus >= 0);
476
477         if (!stat(output_name, &st) && !force && !append_file) {
478                 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
479                                 output_name);
480                 exit(-1);
481         }
482
483         flags = O_CREAT|O_RDWR;
484         if (append_file)
485                 flags |= O_APPEND;
486         else
487                 flags |= O_TRUNC;
488
489         output = open(output_name, flags, S_IRUSR|S_IWUSR);
490         if (output < 0) {
491                 perror("failed to create output file");
492                 exit(-1);
493         }
494
495         if (!system_wide) {
496                 open_counters(-1, target_pid != -1 ? target_pid : getpid());
497         } else for (i = 0; i < nr_cpus; i++)
498                 open_counters(i, target_pid);
499
500         atexit(sig_atexit);
501         signal(SIGCHLD, sig_handler);
502         signal(SIGINT, sig_handler);
503
504         if (target_pid == -1 && argc) {
505                 pid = fork();
506                 if (pid < 0)
507                         perror("failed to fork");
508
509                 if (!pid) {
510                         if (execvp(argv[0], (char **)argv)) {
511                                 perror(argv[0]);
512                                 exit(-1);
513                         }
514                 }
515         }
516
517         if (realtime_prio) {
518                 struct sched_param param;
519
520                 param.sched_priority = realtime_prio;
521                 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
522                         printf("Could not set realtime priority.\n");
523                         exit(-1);
524                 }
525         }
526
527         if (system_wide)
528                 synthesize_samples();
529
530         while (!done) {
531                 int hits = samples;
532
533                 for (i = 0; i < nr_cpu; i++) {
534                         for (counter = 0; counter < nr_counters; counter++)
535                                 mmap_read(&mmap_array[i][counter]);
536                 }
537
538                 if (hits == samples)
539                         ret = poll(event_array, nr_poll, 100);
540         }
541
542         /*
543          * Approximate RIP event size: 24 bytes.
544          */
545         fprintf(stderr,
546                 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
547                 (double)bytes_written / 1024.0 / 1024.0,
548                 output_name,
549                 bytes_written / 24);
550
551         return 0;
552 }
553
554 static const char * const record_usage[] = {
555         "perf record [<options>] [<command>]",
556         "perf record [<options>] -- <command> [<options>]",
557         NULL
558 };
559
560 static const struct option options[] = {
561         OPT_CALLBACK('e', "event", NULL, "event",
562                      "event selector. use 'perf list' to list available events",
563                      parse_events),
564         OPT_INTEGER('p', "pid", &target_pid,
565                     "record events on existing pid"),
566         OPT_INTEGER('r', "realtime", &realtime_prio,
567                     "collect data with this RT SCHED_FIFO priority"),
568         OPT_BOOLEAN('a', "all-cpus", &system_wide,
569                             "system-wide collection from all CPUs"),
570         OPT_BOOLEAN('A', "append", &append_file,
571                             "append to the output file to do incremental profiling"),
572         OPT_BOOLEAN('f', "force", &force,
573                         "overwrite existing data file"),
574         OPT_LONG('c', "count", &default_interval,
575                     "event period to sample"),
576         OPT_STRING('o', "output", &output_name, "file",
577                     "output file name"),
578         OPT_BOOLEAN('i', "inherit", &inherit,
579                     "child tasks inherit counters"),
580         OPT_INTEGER('F', "freq", &freq,
581                     "profile at this frequency"),
582         OPT_INTEGER('m', "mmap-pages", &mmap_pages,
583                     "number of mmap data pages"),
584         OPT_BOOLEAN('g', "call-graph", &call_graph,
585                     "do call-graph (stack chain/backtrace) recording"),
586         OPT_BOOLEAN('v', "verbose", &verbose,
587                     "be more verbose (show counter open errors, etc)"),
588         OPT_END()
589 };
590
591 int cmd_record(int argc, const char **argv, const char *prefix)
592 {
593         int counter;
594
595         argc = parse_options(argc, argv, options, record_usage, 0);
596         if (!argc && target_pid == -1 && !system_wide)
597                 usage_with_options(record_usage, options);
598
599         if (!nr_counters) {
600                 nr_counters     = 1;
601                 attrs[0].type   = PERF_TYPE_HARDWARE;
602                 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
603         }
604
605         for (counter = 0; counter < nr_counters; counter++) {
606                 if (attrs[counter].sample_period)
607                         continue;
608
609                 attrs[counter].sample_period = default_interval;
610         }
611
612         return __cmd_record(argc, argv);
613 }