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