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