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