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