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