perf tools: Don't die() in perf_header_attr__add_id()
[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
7c6a1c65 17#include "util/header.h"
66e274f3 18#include "util/event.h"
8f28827a 19#include "util/debug.h"
8d06367f 20#include "util/symbol.h"
7c6a1c65 21
97124d5e 22#include <unistd.h>
de9ac07b 23#include <sched.h>
de9ac07b 24
de9ac07b 25static int fd[MAX_NR_CPUS][MAX_COUNTERS];
a21ca2ca 26
7e4ff9e3 27static long default_interval = 0;
a21ca2ca 28
42e59d7d 29static int nr_cpus = 0;
de9ac07b 30static unsigned int page_size;
42e59d7d
IM
31static unsigned int mmap_pages = 128;
32static int freq = 1000;
de9ac07b 33static int output;
23ac9cbe 34static const char *output_name = "perf.data";
42e59d7d
IM
35static int group = 0;
36static unsigned int realtime_prio = 0;
37static int raw_samples = 0;
38static int system_wide = 0;
39static int profile_cpu = -1;
40static pid_t target_pid = -1;
41static pid_t child_pid = -1;
42static int inherit = 1;
43static int force = 0;
44static int append_file = 0;
45static int call_graph = 0;
46static int inherit_stat = 0;
47static int no_samples = 0;
48static int sample_address = 0;
49static int multiplex = 0;
50static int multiplex_fd = -1;
51
52static long samples = 0;
a21ca2ca
IM
53static struct timeval last_read;
54static struct timeval this_read;
55
42e59d7d 56static u64 bytes_written = 0;
a21ca2ca
IM
57
58static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
59
42e59d7d
IM
60static int nr_poll = 0;
61static int nr_cpu = 0;
a21ca2ca 62
42e59d7d 63static int file_new = 1;
7c6a1c65 64
42e59d7d 65struct perf_header *header = NULL;
f5970550 66
de9ac07b 67struct mmap_data {
a21ca2ca
IM
68 int counter;
69 void *base;
70 unsigned int mask;
71 unsigned int prev;
de9ac07b
PZ
72};
73
a21ca2ca
IM
74static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
75
9d91a6f7 76static unsigned long mmap_read_head(struct mmap_data *md)
de9ac07b 77{
cdd6c482 78 struct perf_event_mmap_page *pc = md->base;
9d91a6f7 79 long head;
de9ac07b
PZ
80
81 head = pc->data_head;
82 rmb();
83
84 return head;
85}
86
9d91a6f7
PZ
87static void mmap_write_tail(struct mmap_data *md, unsigned long tail)
88{
cdd6c482 89 struct perf_event_mmap_page *pc = md->base;
9d91a6f7
PZ
90
91 /*
92 * ensure all reads are done before we write the tail out.
93 */
94 /* mb(); */
95 pc->data_tail = tail;
96}
97
f5970550
PZ
98static 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
8d06367f
ACM
113static 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
234fbbf5
ACM
125static int process_synthesized_event(event_t *event)
126{
8d06367f 127 write_event(event, event->header.size);
234fbbf5
ACM
128 return 0;
129}
130
de9ac07b
PZ
131static 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
2debbc83 144 * the writer will bite our tail and mess up the samples under us.
de9ac07b
PZ
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;
9d91a6f7 151 if (diff < 0) {
de9ac07b
PZ
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)
2debbc83 170 samples++;
de9ac07b
PZ
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;
021e9f47 178
8d06367f 179 write_event(buf, size);
de9ac07b
PZ
180 }
181
182 buf = &data[old & md->mask];
183 size = head - old;
184 old += size;
021e9f47 185
8d06367f 186 write_event(buf, size);
de9ac07b
PZ
187
188 md->prev = old;
9d91a6f7 189 mmap_write_tail(md, old);
de9ac07b
PZ
190}
191
192static volatile int done = 0;
f7b7c26e 193static volatile int signr = -1;
de9ac07b 194
16c8a109 195static void sig_handler(int sig)
de9ac07b 196{
16c8a109 197 done = 1;
f7b7c26e
PZ
198 signr = sig;
199}
200
201static void sig_atexit(void)
202{
933da83a
CW
203 if (child_pid != -1)
204 kill(child_pid, SIGTERM);
205
f7b7c26e
PZ
206 if (signr == -1)
207 return;
208
209 signal(signr, SIG_DFL);
210 kill(getpid(), signr);
de9ac07b
PZ
211}
212
f250c030
IM
213static int group_fd;
214
cdd6c482 215static struct perf_header_attr *get_header_attr(struct perf_event_attr *a, int nr)
7c6a1c65
PZ
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);
dc79c0fc 223 if (h_attr != NULL)
11deb1f9
ACM
224 if (perf_header__add_attr(header, h_attr) < 0) {
225 perf_header_attr__delete(h_attr);
226 h_attr = NULL;
227 }
7c6a1c65
PZ
228 }
229
230 return h_attr;
231}
232
f250c030 233static void create_counter(int counter, int cpu, pid_t pid)
de9ac07b 234{
c171b552 235 char *filter = filters[counter];
cdd6c482 236 struct perf_event_attr *attr = attrs + counter;
7c6a1c65
PZ
237 struct perf_header_attr *h_attr;
238 int track = !counter; /* only the first counter needs these */
c171b552 239 int ret;
7c6a1c65
PZ
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;
16c8a109 250
3a9f131f 251 attr->sample_type |= PERF_SAMPLE_IP | PERF_SAMPLE_TID;
3efa1cc9 252
1dba15e7 253 if (freq) {
ea1900e5 254 attr->sample_type |= PERF_SAMPLE_PERIOD;
a21ca2ca
IM
255 attr->freq = 1;
256 attr->sample_freq = freq;
1dba15e7 257 }
3efa1cc9 258
649c48a9
PZ
259 if (no_samples)
260 attr->sample_freq = 0;
261
262 if (inherit_stat)
263 attr->inherit_stat = 1;
264
4bba828d
AB
265 if (sample_address)
266 attr->sample_type |= PERF_SAMPLE_ADDR;
267
3efa1cc9
IM
268 if (call_graph)
269 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
270
cd6feeea 271 if (raw_samples) {
6ddf259d 272 attr->sample_type |= PERF_SAMPLE_TIME;
daac07b2 273 attr->sample_type |= PERF_SAMPLE_RAW;
cd6feeea
IM
274 attr->sample_type |= PERF_SAMPLE_CPU;
275 }
f413cdb8 276
a21ca2ca
IM
277 attr->mmap = track;
278 attr->comm = track;
279 attr->inherit = (cpu < 0) && inherit;
4502d77c 280 attr->disabled = 1;
16c8a109 281
3da297a6 282try_again:
cdd6c482 283 fd[nr_cpu][counter] = sys_perf_event_open(attr, pid, cpu, group_fd, 0);
16c8a109 284
f250c030
IM
285 if (fd[nr_cpu][counter] < 0) {
286 int err = errno;
16c8a109 287
c10edee2 288 if (err == EPERM || err == EACCES)
3da297a6 289 die("Permission error - are you root?\n");
0a5ac846
JA
290 else if (err == ENODEV && profile_cpu != -1)
291 die("No such device - did you specify an out-of-range profile CPU?\n");
3da297a6
IM
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
f4dbfa8f 299 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
3da297a6
IM
300
301 if (verbose)
302 warning(" ... trying to fall back to cpu-clock-ticks\n");
303 attr->type = PERF_TYPE_SOFTWARE;
f4dbfa8f 304 attr->config = PERF_COUNT_SW_CPU_CLOCK;
3da297a6
IM
305 goto try_again;
306 }
30c806a0
IM
307 printf("\n");
308 error("perfcounter syscall returned with %d (%s)\n",
309 fd[nr_cpu][counter], strerror(err));
cdd6c482 310 die("No CONFIG_PERF_EVENTS=y kernel support configured?\n");
f250c030
IM
311 exit(-1);
312 }
3da297a6 313
7c6a1c65 314 h_attr = get_header_attr(attr, counter);
dc79c0fc
ACM
315 if (h_attr == NULL)
316 die("nomem\n");
7c6a1c65
PZ
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
3928ddbe
FW
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 }
7c6a1c65 329
58754121
ACM
330 if (perf_header_attr__add_id(h_attr, read_data.id) < 0) {
331 pr_warning("Not enough memory to add id\n");
332 exit(-1);
333 }
7c6a1c65 334
f250c030
IM
335 assert(fd[nr_cpu][counter] >= 0);
336 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
16c8a109 337
f250c030
IM
338 /*
339 * First counter acts as the group leader:
340 */
341 if (group && group_fd == -1)
342 group_fd = fd[nr_cpu][counter];
ea57c4f5
IM
343 if (multiplex && multiplex_fd == -1)
344 multiplex_fd = fd[nr_cpu][counter];
f250c030 345
ea57c4f5 346 if (multiplex && fd[nr_cpu][counter] != multiplex_fd) {
4502d77c 347
cdd6c482 348 ret = ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_SET_OUTPUT, multiplex_fd);
ea57c4f5
IM
349 assert(ret != -1);
350 } else {
351 event_array[nr_poll].fd = fd[nr_cpu][counter];
352 event_array[nr_poll].events = POLLIN;
353 nr_poll++;
354
355 mmap_array[nr_cpu][counter].counter = counter;
356 mmap_array[nr_cpu][counter].prev = 0;
357 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
358 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
359 PROT_READ|PROT_WRITE, MAP_SHARED, fd[nr_cpu][counter], 0);
360 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
361 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
362 exit(-1);
363 }
364 }
d1302522 365
c171b552
LZ
366 if (filter != NULL) {
367 ret = ioctl(fd[nr_cpu][counter],
368 PERF_EVENT_IOC_SET_FILTER, filter);
369 if (ret) {
370 error("failed to set filter with %d (%s)\n", errno,
371 strerror(errno));
372 exit(-1);
373 }
374 }
375
cdd6c482 376 ioctl(fd[nr_cpu][counter], PERF_EVENT_IOC_ENABLE);
f250c030 377}
f2521b6e 378
f250c030
IM
379static void open_counters(int cpu, pid_t pid)
380{
381 int counter;
16c8a109 382
f250c030
IM
383 group_fd = -1;
384 for (counter = 0; counter < nr_counters; counter++)
385 create_counter(counter, cpu, pid);
386
16c8a109
PZ
387 nr_cpu++;
388}
389
f5970550
PZ
390static void atexit_header(void)
391{
7c6a1c65 392 header->data_size += bytes_written;
f5970550 393
8671dab9 394 perf_header__write(header, output, true);
f5970550
PZ
395}
396
0e9b20b8 397static int __cmd_record(int argc, const char **argv)
16c8a109
PZ
398{
399 int i, counter;
abaff32a 400 struct stat st;
7c6a1c65 401 pid_t pid = 0;
abaff32a 402 int flags;
de9ac07b 403 int ret;
8b412664 404 unsigned long waking = 0;
de9ac07b
PZ
405
406 page_size = sysconf(_SC_PAGE_SIZE);
de9ac07b
PZ
407 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
408 assert(nr_cpus <= MAX_NR_CPUS);
409 assert(nr_cpus >= 0);
410
f5970550
PZ
411 atexit(sig_atexit);
412 signal(SIGCHLD, sig_handler);
413 signal(SIGINT, sig_handler);
414
266e0e21
PH
415 if (!stat(output_name, &st) && st.st_size) {
416 if (!force && !append_file) {
417 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
418 output_name);
419 exit(-1);
420 }
421 } else {
422 append_file = 0;
97124d5e
PZ
423 }
424
abaff32a
IM
425 flags = O_CREAT|O_RDWR;
426 if (append_file)
f5970550 427 file_new = 0;
abaff32a
IM
428 else
429 flags |= O_TRUNC;
430
431 output = open(output_name, flags, S_IRUSR|S_IWUSR);
de9ac07b
PZ
432 if (output < 0) {
433 perror("failed to create output file");
434 exit(-1);
435 }
436
7c6a1c65
PZ
437 if (!file_new)
438 header = perf_header__read(output);
439 else
440 header = perf_header__new();
f5970550 441
9df37ddd 442 if (raw_samples) {
3e13ab2d 443 perf_header__set_feat(header, HEADER_TRACE_INFO);
9df37ddd
FW
444 } else {
445 for (i = 0; i < nr_counters; i++) {
446 if (attrs[i].sample_type & PERF_SAMPLE_RAW) {
3e13ab2d 447 perf_header__set_feat(header, HEADER_TRACE_INFO);
9df37ddd
FW
448 break;
449 }
450 }
451 }
03456a15 452
f5970550
PZ
453 atexit(atexit_header);
454
1a853e36 455 if (!system_wide) {
7c6a1c65
PZ
456 pid = target_pid;
457 if (pid == -1)
458 pid = getpid();
459
0a5ac846
JA
460 open_counters(profile_cpu, pid);
461 } else {
462 if (profile_cpu != -1) {
463 open_counters(profile_cpu, target_pid);
464 } else {
465 for (i = 0; i < nr_cpus; i++)
466 open_counters(i, target_pid);
467 }
468 }
de9ac07b 469
7c6a1c65 470 if (file_new)
8671dab9 471 perf_header__write(header, output, false);
7c6a1c65 472
234fbbf5
ACM
473 if (!system_wide)
474 event__synthesize_thread(pid, process_synthesized_event);
475 else
476 event__synthesize_threads(process_synthesized_event);
7c6a1c65 477
ef65b2a0 478 if (target_pid == -1 && argc) {
1a853e36
ACM
479 pid = fork();
480 if (pid < 0)
de896721 481 die("failed to fork");
de9ac07b 482
1a853e36 483 if (!pid) {
0e9b20b8 484 if (execvp(argv[0], (char **)argv)) {
1a853e36
ACM
485 perror(argv[0]);
486 exit(-1);
487 }
de896721
FW
488 } else {
489 /*
490 * Wait a bit for the execv'ed child to appear
491 * and be updated in /proc
492 * FIXME: Do you know a less heuristical solution?
493 */
494 usleep(1000);
495 event__synthesize_thread(pid,
496 process_synthesized_event);
de9ac07b 497 }
933da83a
CW
498
499 child_pid = pid;
de9ac07b
PZ
500 }
501
502 if (realtime_prio) {
503 struct sched_param param;
504
505 param.sched_priority = realtime_prio;
506 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
6beba7ad 507 pr_err("Could not set realtime priority.\n");
de9ac07b
PZ
508 exit(-1);
509 }
510 }
511
649c48a9 512 for (;;) {
2debbc83 513 int hits = samples;
de9ac07b 514
16c8a109 515 for (i = 0; i < nr_cpu; i++) {
ea57c4f5
IM
516 for (counter = 0; counter < nr_counters; counter++) {
517 if (mmap_array[i][counter].base)
518 mmap_read(&mmap_array[i][counter]);
519 }
de9ac07b
PZ
520 }
521
649c48a9
PZ
522 if (hits == samples) {
523 if (done)
524 break;
8b412664
PZ
525 ret = poll(event_array, nr_poll, -1);
526 waking++;
527 }
528
529 if (done) {
530 for (i = 0; i < nr_cpu; i++) {
531 for (counter = 0; counter < nr_counters; counter++)
cdd6c482 532 ioctl(fd[i][counter], PERF_EVENT_IOC_DISABLE);
8b412664 533 }
649c48a9 534 }
de9ac07b
PZ
535 }
536
8b412664
PZ
537 fprintf(stderr, "[ perf record: Woken up %ld times to write data ]\n", waking);
538
021e9f47
IM
539 /*
540 * Approximate RIP event size: 24 bytes.
541 */
542 fprintf(stderr,
2debbc83 543 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
021e9f47
IM
544 (double)bytes_written / 1024.0 / 1024.0,
545 output_name,
546 bytes_written / 24);
addc2785 547
de9ac07b
PZ
548 return 0;
549}
0e9b20b8 550
0e9b20b8 551static const char * const record_usage[] = {
9e096753
MG
552 "perf record [<options>] [<command>]",
553 "perf record [<options>] -- <command> [<options>]",
0e9b20b8
IM
554 NULL
555};
556
5242519b 557static const struct option options[] = {
0e9b20b8 558 OPT_CALLBACK('e', "event", NULL, "event",
86847b62
TG
559 "event selector. use 'perf list' to list available events",
560 parse_events),
c171b552
LZ
561 OPT_CALLBACK(0, "filter", NULL, "filter",
562 "event filter", parse_filter),
0e9b20b8
IM
563 OPT_INTEGER('p', "pid", &target_pid,
564 "record events on existing pid"),
565 OPT_INTEGER('r', "realtime", &realtime_prio,
566 "collect data with this RT SCHED_FIFO priority"),
daac07b2
FW
567 OPT_BOOLEAN('R', "raw-samples", &raw_samples,
568 "collect raw sample records from all opened counters"),
0e9b20b8
IM
569 OPT_BOOLEAN('a', "all-cpus", &system_wide,
570 "system-wide collection from all CPUs"),
abaff32a
IM
571 OPT_BOOLEAN('A', "append", &append_file,
572 "append to the output file to do incremental profiling"),
0a5ac846
JA
573 OPT_INTEGER('C', "profile_cpu", &profile_cpu,
574 "CPU to profile on"),
97124d5e
PZ
575 OPT_BOOLEAN('f', "force", &force,
576 "overwrite existing data file"),
e61078a0 577 OPT_LONG('c', "count", &default_interval,
abaff32a
IM
578 "event period to sample"),
579 OPT_STRING('o', "output", &output_name, "file",
580 "output file name"),
581 OPT_BOOLEAN('i', "inherit", &inherit,
582 "child tasks inherit counters"),
cf1f4574
IM
583 OPT_INTEGER('F', "freq", &freq,
584 "profile at this frequency"),
abaff32a
IM
585 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
586 "number of mmap data pages"),
3efa1cc9
IM
587 OPT_BOOLEAN('g', "call-graph", &call_graph,
588 "do call-graph (stack chain/backtrace) recording"),
3da297a6
IM
589 OPT_BOOLEAN('v', "verbose", &verbose,
590 "be more verbose (show counter open errors, etc)"),
649c48a9
PZ
591 OPT_BOOLEAN('s', "stat", &inherit_stat,
592 "per thread counts"),
4bba828d
AB
593 OPT_BOOLEAN('d', "data", &sample_address,
594 "Sample addresses"),
649c48a9
PZ
595 OPT_BOOLEAN('n', "no-samples", &no_samples,
596 "don't sample"),
d1302522
FW
597 OPT_BOOLEAN('M', "multiplex", &multiplex,
598 "multiplex counter output in a single channel"),
0e9b20b8
IM
599 OPT_END()
600};
601
f37a291c 602int cmd_record(int argc, const char **argv, const char *prefix __used)
0e9b20b8
IM
603{
604 int counter;
605
8d06367f
ACM
606 symbol__init(0);
607
a0541234
AB
608 argc = parse_options(argc, argv, options, record_usage,
609 PARSE_OPT_STOP_AT_NON_OPTION);
ef65b2a0 610 if (!argc && target_pid == -1 && !system_wide)
0e9b20b8
IM
611 usage_with_options(record_usage, options);
612
bbd36e5e
PZ
613 if (!nr_counters) {
614 nr_counters = 1;
615 attrs[0].type = PERF_TYPE_HARDWARE;
616 attrs[0].config = PERF_COUNT_HW_CPU_CYCLES;
617 }
0e9b20b8 618
7e4ff9e3
MG
619 /*
620 * User specified count overrides default frequency.
621 */
622 if (default_interval)
623 freq = 0;
624 else if (freq) {
625 default_interval = freq;
626 } else {
627 fprintf(stderr, "frequency and count are zero, aborting\n");
628 exit(EXIT_FAILURE);
629 }
630
0e9b20b8 631 for (counter = 0; counter < nr_counters; counter++) {
a21ca2ca 632 if (attrs[counter].sample_period)
0e9b20b8
IM
633 continue;
634
a21ca2ca 635 attrs[counter].sample_period = default_interval;
0e9b20b8
IM
636 }
637
638 return __cmd_record(argc, argv);
639}