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