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