]> git.karo-electronics.de Git - karo-tx-linux.git/blob - tools/perf/builtin-record.c
9f98b86e747c67142875bc7c6901ed35ac34f495
[karo-tx-linux.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                 perf_header__add_attr(header, h_attr);
224         }
225
226         return h_attr;
227 }
228
229 static void create_counter(int counter, int cpu, pid_t pid)
230 {
231         char *filter = filters[counter];
232         struct perf_event_attr *attr = attrs + counter;
233         struct perf_header_attr *h_attr;
234         int track = !counter; /* only the first counter needs these */
235         int ret;
236         struct {
237                 u64 count;
238                 u64 time_enabled;
239                 u64 time_running;
240                 u64 id;
241         } read_data;
242
243         attr->read_format       = PERF_FORMAT_TOTAL_TIME_ENABLED |
244                                   PERF_FORMAT_TOTAL_TIME_RUNNING |
245                                   PERF_FORMAT_ID;
246
247         attr->sample_type       |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
248
249         if (freq) {
250                 attr->sample_type       |= PERF_SAMPLE_PERIOD;
251                 attr->freq              = 1;
252                 attr->sample_freq       = freq;
253         }
254
255         if (no_samples)
256                 attr->sample_freq = 0;
257
258         if (inherit_stat)
259                 attr->inherit_stat = 1;
260
261         if (sample_address)
262                 attr->sample_type       |= PERF_SAMPLE_ADDR;
263
264         if (call_graph)
265                 attr->sample_type       |= PERF_SAMPLE_CALLCHAIN;
266
267         if (raw_samples) {
268                 attr->sample_type       |= PERF_SAMPLE_TIME;
269                 attr->sample_type       |= PERF_SAMPLE_RAW;
270                 attr->sample_type       |= PERF_SAMPLE_CPU;
271         }
272
273         attr->mmap              = track;
274         attr->comm              = track;
275         attr->inherit           = (cpu < 0) && inherit;
276         attr->disabled          = 1;
277
278 try_again:
279         fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
280
281         if (fd[nr_cpu][counter] < 0) {
282                 int err = errno;
283
284                 if (err == EPERM)
285                         die("Permission error - are you root?\n");
286                 else if (err ==  ENODEV && profile_cpu != -1)
287                         die("No such device - did you specify an out-of-range profile CPU?\n");
288
289                 /*
290                  * If it's cycles then fall back to hrtimer
291                  * based cpu-clock-tick sw counter, which
292                  * is always available even if no PMU support:
293                  */
294                 if (attr->type == PERF_TYPE_HARDWARE
295                         && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
296
297                         if (verbose)
298                                 warning(" ... trying to fall back to cpu-clock-ticks\n");
299                         attr->type = PERF_TYPE_SOFTWARE;
300                         attr->config = PERF_COUNT_SW_CPU_CLOCK;
301                         goto try_again;
302                 }
303                 printf("\n");
304                 error("perfcounter syscall returned with %d (%s)\n",
305                         fd[nr_cpu][counter], strerror(err));
306                 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
307                 exit(-1);
308         }
309
310         h_attr = get_header_attr(attr, counter);
311
312         if (!file_new) {
313                 if (memcmp(&h_attr->attr, attr, sizeof(*attr))) {
314                         fprintf(stderr, "incompatible append\n");
315                         exit(-1);
316                 }
317         }
318
319         if (read(fd[nr_cpu][counter], &read_data, sizeof(read_data)) == -1) {
320                 perror("Unable to read perf file descriptor\n");
321                 exit(-1);
322         }
323
324         perf_header_attr__add_id(h_attr, read_data.id);
325
326         assert(fd[nr_cpu][counter] >= 0);
327         fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
328
329         /*
330          * First counter acts as the group leader:
331          */
332         if (group && group_fd == -1)
333                 group_fd = fd[nr_cpu][counter];
334         if (multiplex && multiplex_fd == -1)
335                 multiplex_fd = fd[nr_cpu][counter];
336
337         if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
338
339                 ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
340                 assert(ret != -1);
341         } else {
342                 event_array[nr_poll].fd = fd[nr_cpu][counter];
343                 event_array[nr_poll].events = POLLIN;
344                 nr_poll++;
345
346                 mmap_array[nr_cpu][counter].counter = counter;
347                 mmap_array[nr_cpu][counter].prev = 0;
348                 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
349                 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
350                                 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
351                 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
352                         error("failed to mmap with %d (%s)\n", errno, strerror(errno));
353                         exit(-1);
354                 }
355         }
356
357         if (filter != NULL) {
358                 ret = ioctl(fd[nr_cpu][counter],
359                             PERF_EVENT_IOC_SET_FILTER, filter);
360                 if (ret) {
361                         error("failed to set filter with %d (%s)\n", errno,
362                               strerror(errno));
363                         exit(-1);
364                 }
365         }
366
367         ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
368 }
369
370 static void open_counters(int cpu, pid_t pid)
371 {
372         int counter;
373
374         group_fd = -1;
375         for (counter = 0; counter < nr_counters; counter++)
376                 create_counter(counter, cpu, pid);
377
378         nr_cpu++;
379 }
380
381 static bool write_buildid_table(void)
382 {
383         struct dso *pos;
384         bool have_buildid = false;
385
386         list_for_each_entry(pos, &dsos, node) {
387                 struct build_id_event b;
388                 size_t len;
389
390                 if (filename__read_build_id(pos->long_name,
391                                             &b.build_id,
392                                             sizeof(b.build_id)) < 0)
393                         continue;
394                 have_buildid = true;
395                 memset(&b.header, 0, sizeof(b.header));
396                 len = strlen(pos->long_name) + 1;
397                 len = ALIGN(len, 64);
398                 b.header.size = sizeof(b) + len;
399                 write_output(&b, sizeof(b));
400                 write_output(pos->long_name, len);
401         }
402
403         return have_buildid;
404 }
405
406 static void atexit_header(void)
407 {
408         header->data_size += bytes_written;
409
410         if (write_buildid_table())
411                 perf_header__set_feat(header, HEADER_BUILD_ID);
412
413         perf_header__write(header, output);
414 }
415
416 static int __cmd_record(int argc, const char **argv)
417 {
418         int i, counter;
419         struct stat st;
420         pid_t pid = 0;
421         int flags;
422         int ret;
423         unsigned long waking = 0;
424
425         page_size = sysconf(_SC_PAGE_SIZE);
426         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
427         assert(nr_cpus <= MAX_NR_CPUS);
428         assert(nr_cpus >= 0);
429
430         atexit(sig_atexit);
431         signal(SIGCHLD, sig_handler);
432         signal(SIGINT, sig_handler);
433
434         if (!stat(output_name, &st) && st.st_size) {
435                 if (!force && !append_file) {
436                         fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
437                                         output_name);
438                         exit(-1);
439                 }
440         } else {
441                 append_file = 0;
442         }
443
444         flags = O_CREAT|O_RDWR;
445         if (append_file)
446                 file_new = 0;
447         else
448                 flags |= O_TRUNC;
449
450         output = open(output_name, flags, S_IRUSR|S_IWUSR);
451         if (output < 0) {
452                 perror("failed to create output file");
453                 exit(-1);
454         }
455
456         if (!file_new)
457                 header = perf_header__read(output);
458         else
459                 header = perf_header__new();
460
461         if (raw_samples) {
462                 perf_header__feat_trace_info(header);
463         } else {
464                 for (i = 0; i < nr_counters; i++) {
465                         if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
466                                 perf_header__feat_trace_info(header);
467                                 break;
468                         }
469                 }
470         }
471
472         atexit(atexit_header);
473
474         if (!system_wide) {
475                 pid = target_pid;
476                 if (pid == -1)
477                         pid = getpid();
478
479                 open_counters(profile_cpu, pid);
480         } else {
481                 if (profile_cpu != -1) {
482                         open_counters(profile_cpu, target_pid);
483                 } else {
484                         for (i = 0; i < nr_cpus; i++)
485                                 open_counters(i, target_pid);
486                 }
487         }
488
489         if (file_new)
490                 perf_header__write(header, output);
491
492         if (!system_wide)
493                 event__synthesize_thread(pid, process_synthesized_event);
494         else
495                 event__synthesize_threads(process_synthesized_event);
496
497         if (target_pid == -1 && argc) {
498                 pid = fork();
499                 if (pid < 0)
500                         die("failed to fork");
501
502                 if (!pid) {
503                         if (execvp(argv[0], (char **)argv)) {
504                                 perror(argv[0]);
505                                 exit(-1);
506                         }
507                 } else {
508                         /*
509                          * Wait a bit for the execv'ed child to appear
510                          * and be updated in /proc
511                          * FIXME: Do you know a less heuristical solution?
512                          */
513                         usleep(1000);
514                         event__synthesize_thread(pid,
515                                                  process_synthesized_event);
516                 }
517
518                 child_pid = pid;
519         }
520
521         if (realtime_prio) {
522                 struct sched_param param;
523
524                 param.sched_priority = realtime_prio;
525                 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
526                         pr_err("Could not set realtime priority.\n");
527                         exit(-1);
528                 }
529         }
530
531         for (;;) {
532                 int hits = samples;
533
534                 for (i = 0; i < nr_cpu; i++) {
535                         for (counter = 0; counter < nr_counters; counter++) {
536                                 if (mmap_array[i][counter].base)
537                                         mmap_read(&mmap_array[i][counter]);
538                         }
539                 }
540
541                 if (hits == samples) {
542                         if (done)
543                                 break;
544                         ret = poll(event_array, nr_poll, -1);
545                         waking++;
546                 }
547
548                 if (done) {
549                         for (i = 0; i < nr_cpu; i++) {
550                                 for (counter = 0; counter < nr_counters; counter++)
551                                         ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
552                         }
553                 }
554         }
555
556         fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
557
558         /*
559          * Approximate RIP event size: 24 bytes.
560          */
561         fprintf(stderr,
562                 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
563                 (double)bytes_written / 1024.0 / 1024.0,
564                 output_name,
565                 bytes_written / 24);
566
567         return 0;
568 }
569
570 static const char * const record_usage[] = {
571         "perf record [<options>] [<command>]",
572         "perf record [<options>] -- <command> [<options>]",
573         NULL
574 };
575
576 static const struct option options[] = {
577         OPT_CALLBACK('e', "event", NULL, "event",
578                      "event selector. use 'perf list' to list available events",
579                      parse_events),
580         OPT_CALLBACK(0, "filter", NULL, "filter",
581                      "event filter", parse_filter),
582         OPT_INTEGER('p', "pid", &target_pid,
583                     "record events on existing pid"),
584         OPT_INTEGER('r', "realtime", &realtime_prio,
585                     "collect data with this RT SCHED_FIFO priority"),
586         OPT_BOOLEAN('R', "raw-samples", &raw_samples,
587                     "collect raw sample records from all opened counters"),
588         OPT_BOOLEAN('a', "all-cpus", &system_wide,
589                             "system-wide collection from all CPUs"),
590         OPT_BOOLEAN('A', "append", &append_file,
591                             "append to the output file to do incremental profiling"),
592         OPT_INTEGER('C', "profile_cpu", &profile_cpu,
593                             "CPU to profile on"),
594         OPT_BOOLEAN('f', "force", &force,
595                         "overwrite existing data file"),
596         OPT_LONG('c', "count", &default_interval,
597                     "event period to sample"),
598         OPT_STRING('o', "output", &output_name, "file",
599                     "output file name"),
600         OPT_BOOLEAN('i', "inherit", &inherit,
601                     "child tasks inherit counters"),
602         OPT_INTEGER('F', "freq", &freq,
603                     "profile at this frequency"),
604         OPT_INTEGER('m', "mmap-pages", &mmap_pages,
605                     "number of mmap data pages"),
606         OPT_BOOLEAN('g', "call-graph", &call_graph,
607                     "do call-graph (stack chain/backtrace) recording"),
608         OPT_BOOLEAN('v', "verbose", &verbose,
609                     "be more verbose (show counter open errors, etc)"),
610         OPT_BOOLEAN('s', "stat", &inherit_stat,
611                     "per thread counts"),
612         OPT_BOOLEAN('d', "data", &sample_address,
613                     "Sample addresses"),
614         OPT_BOOLEAN('n', "no-samples", &no_samples,
615                     "don't sample"),
616         OPT_BOOLEAN('M', "multiplex", &multiplex,
617                     "multiplex counter output in a single channel"),
618         OPT_END()
619 };
620
621 int cmd_record(int argc, const char **argv, const char *prefix __used)
622 {
623         int counter;
624
625         symbol__init(0);
626
627         argc = parse_options(argc, argv, options, record_usage,
628                 PARSE_OPT_STOP_AT_NON_OPTION);
629         if (!argc && target_pid == -1 && !system_wide)
630                 usage_with_options(record_usage, options);
631
632         if (!nr_counters) {
633                 nr_counters     = 1;
634                 attrs[0].type   = PERF_TYPE_HARDWARE;
635                 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
636         }
637
638         /*
639          * User specified count overrides default frequency.
640          */
641         if (default_interval)
642                 freq = 0;
643         else if (freq) {
644                 default_interval = freq;
645         } else {
646                 fprintf(stderr, "frequency and count are zero, aborting\n");
647                 exit(EXIT_FAILURE);
648         }
649
650         for (counter = 0; counter < nr_counters; counter++) {
651                 if (attrs[counter].sample_period)
652                         continue;
653
654                 attrs[counter].sample_period = default_interval;
655         }
656
657         return __cmd_record(argc, argv);
658 }