]> git.karo-electronics.de Git - mv-sheeva.git/blob - tools/perf/builtin-record.c
perf tools: Don't die() in perf_header__add_attr()
[mv-sheeva.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 "util/header.h"
18 #include "util/event.h"
19 #include "util/debug.h"
20 #include "util/symbol.h"
21
22 #include <unistd.h>
23 #include <sched.h>
24
25 static int                      fd[MAX_NR_CPUS][MAX_COUNTERS];
26
27 static long                     default_interval                =      0;
28
29 static int                      nr_cpus                         =      0;
30 static unsigned int             page_size;
31 static unsigned int             mmap_pages                      =    128;
32 static int                      freq                            =   1000;
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                      raw_samples                     =      0;
38 static int                      system_wide                     =      0;
39 static int                      profile_cpu                     =     -1;
40 static pid_t                    target_pid                      =     -1;
41 static pid_t                    child_pid                       =     -1;
42 static int                      inherit                         =      1;
43 static int                      force                           =      0;
44 static int                      append_file                     =      0;
45 static int                      call_graph                      =      0;
46 static int                      inherit_stat                    =      0;
47 static int                      no_samples                      =      0;
48 static int                      sample_address                  =      0;
49 static int                      multiplex                       =      0;
50 static int                      multiplex_fd                    =     -1;
51
52 static long                     samples                         =      0;
53 static struct timeval           last_read;
54 static struct timeval           this_read;
55
56 static u64                      bytes_written                   =      0;
57
58 static struct pollfd            event_array[MAX_NR_CPUS * MAX_COUNTERS];
59
60 static int                      nr_poll                         =      0;
61 static int                      nr_cpu                          =      0;
62
63 static int                      file_new                        =      1;
64
65 struct perf_header              *header                         =   NULL;
66
67 struct mmap_data {
68         int                     counter;
69         void                    *base;
70         unsigned int            mask;
71         unsigned int            prev;
72 };
73
74 static struct mmap_data         mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
75
76 static unsigned long mmap_read_head(struct mmap_data *md)
77 {
78         struct perf_event_mmap_page *pc = md->base;
79         long head;
80
81         head = pc->data_head;
82         rmb();
83
84         return head;
85 }
86
87 static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
88 {
89         struct perf_event_mmap_page *pc = md->base;
90
91         /*
92          * ensure all reads are done before we write the tail out.
93          */
94         /* mb(); */
95         pc->data_tail = tail;
96 }
97
98 static void write_output(void *buf, size_t size)
99 {
100         while (size) {
101                 int ret = write(output, buf, size);
102
103                 if (ret < 0)
104                         die("failed to write");
105
106                 size -= ret;
107                 buf += ret;
108
109                 bytes_written += ret;
110         }
111 }
112
113 static void write_event(event_t *buf, size_t size)
114 {
115         /*
116         * Add it to the list of DSOs, so that when we finish this
117          * record session we can pick the available build-ids.
118          */
119         if (buf->header.type == PERF_RECORD_MMAP)
120                 dsos__findnew(buf->mmap.filename);
121
122         write_output(buf, size);
123 }
124
125 static int process_synthesized_event(event_t *event)
126 {
127         write_event(event, event->header.size);
128         return 0;
129 }
130
131 static void mmap_read(struct mmap_data *md)
132 {
133         unsigned int head = mmap_read_head(md);
134         unsigned int old = md->prev;
135         unsigned char *data = md->base + page_size;
136         unsigned long size;
137         void *buf;
138         int diff;
139
140         gettimeofday(&this_read, NULL);
141
142         /*
143          * If we're further behind than half the buffer, there's a chance
144          * the writer will bite our tail and mess up the samples under us.
145          *
146          * If we somehow ended up ahead of the head, we got messed up.
147          *
148          * In either case, truncate and restart at head.
149          */
150         diff = head - old;
151         if (diff < 0) {
152                 struct timeval iv;
153                 unsigned long msecs;
154
155                 timersub(&this_read, &last_read, &iv);
156                 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
157
158                 fprintf(stderr, "WARNING: failed to keep up with mmap data."
159                                 "  Last read %lu msecs ago.\n", msecs);
160
161                 /*
162                  * head points to a known good entry, start there.
163                  */
164                 old = head;
165         }
166
167         last_read = this_read;
168
169         if (old != head)
170                 samples++;
171
172         size = head - old;
173
174         if ((old & md->mask) + size != (head & md->mask)) {
175                 buf = &data[old & md->mask];
176                 size = md->mask + 1 - (old & md->mask);
177                 old += size;
178
179                 write_event(buf, size);
180         }
181
182         buf = &data[old & md->mask];
183         size = head - old;
184         old += size;
185
186         write_event(buf, size);
187
188         md->prev = old;
189         mmap_write_tail(md, old);
190 }
191
192 static volatile int done = 0;
193 static volatile int signr = -1;
194
195 static void sig_handler(int sig)
196 {
197         done = 1;
198         signr = sig;
199 }
200
201 static void sig_atexit(void)
202 {
203         if (child_pid != -1)
204                 kill(child_pid, SIGTERM);
205
206         if (signr == -1)
207                 return;
208
209         signal(signr, SIG_DFL);
210         kill(getpid(), signr);
211 }
212
213 static int group_fd;
214
215 static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
216 {
217         struct perf_header_attr *h_attr;
218
219         if (nr < header->attrs) {
220                 h_attr = header->attr[nr];
221         } else {
222                 h_attr = perf_header_attr__new(a);
223                 if (h_attr != NULL)
224                         if (perf_header__add_attr(header, h_attr) < 0) {
225                                 perf_header_attr__delete(h_attr);
226                                 h_attr = NULL;
227                         }
228         }
229
230         return h_attr;
231 }
232
233 static void create_counter(int counter, int cpu, pid_t pid)
234 {
235         char *filter = filters[counter];
236         struct perf_event_attr *attr = attrs + counter;
237         struct perf_header_attr *h_attr;
238         int track = !counter; /* only the first counter needs these */
239         int ret;
240         struct {
241                 u64 count;
242                 u64 time_enabled;
243                 u64 time_running;
244                 u64 id;
245         } read_data;
246
247         attr->read_format       = PERF_FORMAT_TOTAL_TIME_ENABLED |
248                                   PERF_FORMAT_TOTAL_TIME_RUNNING |
249                                   PERF_FORMAT_ID;
250
251         attr->sample_type       |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
252
253         if (freq) {
254                 attr->sample_type       |= PERF_SAMPLE_PERIOD;
255                 attr->freq              = 1;
256                 attr->sample_freq       = freq;
257         }
258
259         if (no_samples)
260                 attr->sample_freq = 0;
261
262         if (inherit_stat)
263                 attr->inherit_stat = 1;
264
265         if (sample_address)
266                 attr->sample_type       |= PERF_SAMPLE_ADDR;
267
268         if (call_graph)
269                 attr->sample_type       |= PERF_SAMPLE_CALLCHAIN;
270
271         if (raw_samples) {
272                 attr->sample_type       |= PERF_SAMPLE_TIME;
273                 attr->sample_type       |= PERF_SAMPLE_RAW;
274                 attr->sample_type       |= PERF_SAMPLE_CPU;
275         }
276
277         attr->mmap              = track;
278         attr->comm              = track;
279         attr->inherit           = (cpu < 0) && inherit;
280         attr->disabled          = 1;
281
282 try_again:
283         fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
284
285         if (fd[nr_cpu][counter] < 0) {
286                 int err = errno;
287
288                 if (err == EPERM || err == EACCES)
289                         die("Permission error - are you root?\n");
290                 else if (err ==  ENODEV && profile_cpu != -1)
291                         die("No such device - did you specify an out-of-range profile CPU?\n");
292
293                 /*
294                  * If it's cycles then fall back to hrtimer
295                  * based cpu-clock-tick sw counter, which
296                  * is always available even if no PMU support:
297                  */
298                 if (attr->type == PERF_TYPE_HARDWARE
299                         && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
300
301                         if (verbose)
302                                 warning(" ... trying to fall back to cpu-clock-ticks\n");
303                         attr->type = PERF_TYPE_SOFTWARE;
304                         attr->config = PERF_COUNT_SW_CPU_CLOCK;
305                         goto try_again;
306                 }
307                 printf("\n");
308                 error("perfcounter syscall returned with %d (%s)\n",
309                         fd[nr_cpu][counter], strerror(err));
310                 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
311                 exit(-1);
312         }
313
314         h_attr = get_header_attr(attr, counter);
315         if (h_attr == NULL)
316                 die("nomem\n");
317
318         if (!file_new) {
319                 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
320                         fprintf(stderr, "incompatible append\n");
321                         exit(-1);
322                 }
323         }
324
325         if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
326                 perror("Unable to read perf file descriptor\n");
327                 exit(-1);
328         }
329
330         perf_header_attr__add_id(h_attr, read_data.id);
331
332         assert(fd[nr_cpu][counter] >= 0);
333         fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
334
335         /*
336          * First counter acts as the group leader:
337          */
338         if (group && group_fd == -1)
339                 group_fd = fd[nr_cpu][counter];
340         if (multiplex && multiplex_fd == -1)
341                 multiplex_fd = fd[nr_cpu][counter];
342
343         if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
344
345                 ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
346                 assert(ret != -1);
347         } else {
348                 event_array[nr_poll].fd = fd[nr_cpu][counter];
349                 event_array[nr_poll].events = POLLIN;
350                 nr_poll++;
351
352                 mmap_array[nr_cpu][counter].counter = counter;
353                 mmap_array[nr_cpu][counter].prev = 0;
354                 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
355                 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
356                                 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
357                 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
358                         error("failed to mmap with %d (%s)\n", errno, strerror(errno));
359                         exit(-1);
360                 }
361         }
362
363         if (filter != NULL) {
364                 ret = ioctl(fd[nr_cpu][counter],
365                             PERF_EVENT_IOC_SET_FILTER, filter);
366                 if (ret) {
367                         error("failed to set filter with %d (%s)\n", errno,
368                               strerror(errno));
369                         exit(-1);
370                 }
371         }
372
373         ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
374 }
375
376 static void open_counters(int cpu, pid_t pid)
377 {
378         int counter;
379
380         group_fd = -1;
381         for (counter = 0; counter < nr_counters; counter++)
382                 create_counter(counter, cpu, pid);
383
384         nr_cpu++;
385 }
386
387 static void atexit_header(void)
388 {
389         header->data_size += bytes_written;
390
391         perf_header__write(header, output, true);
392 }
393
394 static int __cmd_record(int argc, const char **argv)
395 {
396         int i, counter;
397         struct stat st;
398         pid_t pid = 0;
399         int flags;
400         int ret;
401         unsigned long waking = 0;
402
403         page_size = sysconf(_SC_PAGE_SIZE);
404         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
405         assert(nr_cpus <= MAX_NR_CPUS);
406         assert(nr_cpus >= 0);
407
408         atexit(sig_atexit);
409         signal(SIGCHLD, sig_handler);
410         signal(SIGINT, sig_handler);
411
412         if (!stat(output_name, &st) && st.st_size) {
413                 if (!force && !append_file) {
414                         fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
415                                         output_name);
416                         exit(-1);
417                 }
418         } else {
419                 append_file = 0;
420         }
421
422         flags = O_CREAT|O_RDWR;
423         if (append_file)
424                 file_new = 0;
425         else
426                 flags |= O_TRUNC;
427
428         output = open(output_name, flags, S_IRUSR|S_IWUSR);
429         if (output < 0) {
430                 perror("failed to create output file");
431                 exit(-1);
432         }
433
434         if (!file_new)
435                 header = perf_header__read(output);
436         else
437                 header = perf_header__new();
438
439         if (raw_samples) {
440                 perf_header__set_feat(header, HEADER_TRACE_INFO);
441         } else {
442                 for (i = 0; i < nr_counters; i++) {
443                         if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
444                                 perf_header__set_feat(header, HEADER_TRACE_INFO);
445                                 break;
446                         }
447                 }
448         }
449
450         atexit(atexit_header);
451
452         if (!system_wide) {
453                 pid = target_pid;
454                 if (pid == -1)
455                         pid = getpid();
456
457                 open_counters(profile_cpu, pid);
458         } else {
459                 if (profile_cpu != -1) {
460                         open_counters(profile_cpu, target_pid);
461                 } else {
462                         for (i = 0; i < nr_cpus; i++)
463                                 open_counters(i, target_pid);
464                 }
465         }
466
467         if (file_new)
468                 perf_header__write(header, output, false);
469
470         if (!system_wide)
471                 event__synthesize_thread(pid, process_synthesized_event);
472         else
473                 event__synthesize_threads(process_synthesized_event);
474
475         if (target_pid == -1 && argc) {
476                 pid = fork();
477                 if (pid < 0)
478                         die("failed to fork");
479
480                 if (!pid) {
481                         if (execvp(argv[0], (char **)argv)) {
482                                 perror(argv[0]);
483                                 exit(-1);
484                         }
485                 } else {
486                         /*
487                          * Wait a bit for the execv'ed child to appear
488                          * and be updated in /proc
489                          * FIXME: Do you know a less heuristical solution?
490                          */
491                         usleep(1000);
492                         event__synthesize_thread(pid,
493                                                  process_synthesized_event);
494                 }
495
496                 child_pid = pid;
497         }
498
499         if (realtime_prio) {
500                 struct sched_param param;
501
502                 param.sched_priority = realtime_prio;
503                 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
504                         pr_err("Could not set realtime priority.\n");
505                         exit(-1);
506                 }
507         }
508
509         for (;;) {
510                 int hits = samples;
511
512                 for (i = 0; i < nr_cpu; i++) {
513                         for (counter = 0; counter < nr_counters; counter++) {
514                                 if (mmap_array[i][counter].base)
515                                         mmap_read(&mmap_array[i][counter]);
516                         }
517                 }
518
519                 if (hits == samples) {
520                         if (done)
521                                 break;
522                         ret = poll(event_array, nr_poll, -1);
523                         waking++;
524                 }
525
526                 if (done) {
527                         for (i = 0; i < nr_cpu; i++) {
528                                 for (counter = 0; counter < nr_counters; counter++)
529                                         ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
530                         }
531                 }
532         }
533
534         fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
535
536         /*
537          * Approximate RIP event size: 24 bytes.
538          */
539         fprintf(stderr,
540                 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
541                 (double)bytes_written / 1024.0 / 1024.0,
542                 output_name,
543                 bytes_written / 24);
544
545         return 0;
546 }
547
548 static const char * const record_usage[] = {
549         "perf record [<options>] [<command>]",
550         "perf record [<options>] -- <command> [<options>]",
551         NULL
552 };
553
554 static const struct option options[] = {
555         OPT_CALLBACK('e', "event", NULL, "event",
556                      "event selector. use 'perf list' to list available events",
557                      parse_events),
558         OPT_CALLBACK(0, "filter", NULL, "filter",
559                      "event filter", parse_filter),
560         OPT_INTEGER('p', "pid", &target_pid,
561                     "record events on existing pid"),
562         OPT_INTEGER('r', "realtime", &realtime_prio,
563                     "collect data with this RT SCHED_FIFO priority"),
564         OPT_BOOLEAN('R', "raw-samples", &raw_samples,
565                     "collect raw sample records from all opened counters"),
566         OPT_BOOLEAN('a', "all-cpus", &system_wide,
567                             "system-wide collection from all CPUs"),
568         OPT_BOOLEAN('A', "append", &append_file,
569                             "append to the output file to do incremental profiling"),
570         OPT_INTEGER('C', "profile_cpu", &profile_cpu,
571                             "CPU to profile on"),
572         OPT_BOOLEAN('f', "force", &force,
573                         "overwrite existing data file"),
574         OPT_LONG('c', "count", &default_interval,
575                     "event period to sample"),
576         OPT_STRING('o', "output", &output_name, "file",
577                     "output file name"),
578         OPT_BOOLEAN('i', "inherit", &inherit,
579                     "child tasks inherit counters"),
580         OPT_INTEGER('F', "freq", &freq,
581                     "profile at this frequency"),
582         OPT_INTEGER('m', "mmap-pages", &mmap_pages,
583                     "number of mmap data pages"),
584         OPT_BOOLEAN('g', "call-graph", &call_graph,
585                     "do call-graph (stack chain/backtrace) recording"),
586         OPT_BOOLEAN('v', "verbose", &verbose,
587                     "be more verbose (show counter open errors, etc)"),
588         OPT_BOOLEAN('s', "stat", &inherit_stat,
589                     "per thread counts"),
590         OPT_BOOLEAN('d', "data", &sample_address,
591                     "Sample addresses"),
592         OPT_BOOLEAN('n', "no-samples", &no_samples,
593                     "don't sample"),
594         OPT_BOOLEAN('M', "multiplex", &multiplex,
595                     "multiplex counter output in a single channel"),
596         OPT_END()
597 };
598
599 int cmd_record(int argc, const char **argv, const char *prefix __used)
600 {
601         int counter;
602
603         symbol__init(0);
604
605         argc = parse_options(argc, argv, options, record_usage,
606                 PARSE_OPT_STOP_AT_NON_OPTION);
607         if (!argc && target_pid == -1 && !system_wide)
608                 usage_with_options(record_usage, options);
609
610         if (!nr_counters) {
611                 nr_counters     = 1;
612                 attrs[0].type   = PERF_TYPE_HARDWARE;
613                 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
614         }
615
616         /*
617          * User specified count overrides default frequency.
618          */
619         if (default_interval)
620                 freq = 0;
621         else if (freq) {
622                 default_interval = freq;
623         } else {
624                 fprintf(stderr, "frequency and count are zero, aborting\n");
625                 exit(EXIT_FAILURE);
626         }
627
628         for (counter = 0; counter < nr_counters; counter++) {
629                 if (attrs[counter].sample_period)
630                         continue;
631
632                 attrs[counter].sample_period = default_interval;
633         }
634
635         return __cmd_record(argc, argv);
636 }