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