perf record: Set frequency correctly
[linux-2.6/linux-acpi-2.6/ibm-acpi-2.6.git] / Documentation / perf_counter / builtin-record.c
blobc22ea0c7472a32ca6485882af6ba7526bd612a45
1 /*
2 * builtin-record.c
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"
10 #include "perf.h"
12 #include "util/util.h"
13 #include "util/parse-options.h"
14 #include "util/parse-events.h"
15 #include "util/string.h"
17 #include <unistd.h>
18 #include <sched.h>
20 #define ALIGN(x, a) __ALIGN_MASK(x, (typeof(x))(a)-1)
21 #define __ALIGN_MASK(x, mask) (((x)+(mask))&~(mask))
23 static long default_interval = 100000;
24 static long event_count[MAX_COUNTERS];
26 static int fd[MAX_NR_CPUS][MAX_COUNTERS];
27 static int nr_cpus = 0;
28 static unsigned int page_size;
29 static unsigned int mmap_pages = 128;
30 static int freq = 0;
31 static int output;
32 static const char *output_name = "perf.data";
33 static int group = 0;
34 static unsigned int realtime_prio = 0;
35 static int system_wide = 0;
36 static pid_t target_pid = -1;
37 static int inherit = 1;
38 static int force = 0;
39 static int append_file = 0;
41 const unsigned int default_count[] = {
42 1000000,
43 1000000,
44 10000,
45 10000,
46 1000000,
47 10000,
50 struct mmap_data {
51 int counter;
52 void *base;
53 unsigned int mask;
54 unsigned int prev;
57 static unsigned int mmap_read_head(struct mmap_data *md)
59 struct perf_counter_mmap_page *pc = md->base;
60 int head;
62 head = pc->data_head;
63 rmb();
65 return head;
68 static long samples;
69 static struct timeval last_read, this_read;
71 static __u64 bytes_written;
73 static void mmap_read(struct mmap_data *md)
75 unsigned int head = mmap_read_head(md);
76 unsigned int old = md->prev;
77 unsigned char *data = md->base + page_size;
78 unsigned long size;
79 void *buf;
80 int diff;
82 gettimeofday(&this_read, NULL);
85 * If we're further behind than half the buffer, there's a chance
86 * the writer will bite our tail and mess up the samples under us.
88 * If we somehow ended up ahead of the head, we got messed up.
90 * In either case, truncate and restart at head.
92 diff = head - old;
93 if (diff > md->mask / 2 || diff < 0) {
94 struct timeval iv;
95 unsigned long msecs;
97 timersub(&this_read, &last_read, &iv);
98 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
100 fprintf(stderr, "WARNING: failed to keep up with mmap data."
101 " Last read %lu msecs ago.\n", msecs);
104 * head points to a known good entry, start there.
106 old = head;
109 last_read = this_read;
111 if (old != head)
112 samples++;
114 size = head - old;
116 if ((old & md->mask) + size != (head & md->mask)) {
117 buf = &data[old & md->mask];
118 size = md->mask + 1 - (old & md->mask);
119 old += size;
121 while (size) {
122 int ret = write(output, buf, size);
124 if (ret < 0)
125 die("failed to write");
127 size -= ret;
128 buf += ret;
130 bytes_written += ret;
134 buf = &data[old & md->mask];
135 size = head - old;
136 old += size;
138 while (size) {
139 int ret = write(output, buf, size);
141 if (ret < 0)
142 die("failed to write");
144 size -= ret;
145 buf += ret;
147 bytes_written += ret;
150 md->prev = old;
153 static volatile int done = 0;
155 static void sig_handler(int sig)
157 done = 1;
160 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
161 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
163 static int nr_poll;
164 static int nr_cpu;
166 struct mmap_event {
167 struct perf_event_header header;
168 __u32 pid;
169 __u32 tid;
170 __u64 start;
171 __u64 len;
172 __u64 pgoff;
173 char filename[PATH_MAX];
176 struct comm_event {
177 struct perf_event_header header;
178 __u32 pid;
179 __u32 tid;
180 char comm[16];
183 static void pid_synthesize_comm_event(pid_t pid, int full)
185 struct comm_event comm_ev;
186 char filename[PATH_MAX];
187 char bf[BUFSIZ];
188 int fd, ret;
189 size_t size;
190 char *field, *sep;
191 DIR *tasks;
192 struct dirent dirent, *next;
194 snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
196 fd = open(filename, O_RDONLY);
197 if (fd < 0) {
198 fprintf(stderr, "couldn't open %s\n", filename);
199 exit(EXIT_FAILURE);
201 if (read(fd, bf, sizeof(bf)) < 0) {
202 fprintf(stderr, "couldn't read %s\n", filename);
203 exit(EXIT_FAILURE);
205 close(fd);
207 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
208 memset(&comm_ev, 0, sizeof(comm_ev));
209 field = strchr(bf, '(');
210 if (field == NULL)
211 goto out_failure;
212 sep = strchr(++field, ')');
213 if (sep == NULL)
214 goto out_failure;
215 size = sep - field;
216 memcpy(comm_ev.comm, field, size++);
218 comm_ev.pid = pid;
219 comm_ev.header.type = PERF_EVENT_COMM;
220 size = ALIGN(size, sizeof(uint64_t));
221 comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
223 if (!full) {
224 comm_ev.tid = pid;
226 ret = write(output, &comm_ev, comm_ev.header.size);
227 if (ret < 0) {
228 perror("failed to write");
229 exit(-1);
231 return;
234 snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
236 tasks = opendir(filename);
237 while (!readdir_r(tasks, &dirent, &next) && next) {
238 char *end;
239 pid = strtol(dirent.d_name, &end, 10);
240 if (*end)
241 continue;
243 comm_ev.tid = pid;
245 ret = write(output, &comm_ev, comm_ev.header.size);
246 if (ret < 0) {
247 perror("failed to write");
248 exit(-1);
251 closedir(tasks);
252 return;
254 out_failure:
255 fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
256 filename);
257 exit(EXIT_FAILURE);
260 static void pid_synthesize_mmap_samples(pid_t pid)
262 char filename[PATH_MAX];
263 FILE *fp;
265 snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
267 fp = fopen(filename, "r");
268 if (fp == NULL) {
269 fprintf(stderr, "couldn't open %s\n", filename);
270 exit(EXIT_FAILURE);
272 while (1) {
273 char bf[BUFSIZ], *pbf = bf;
274 struct mmap_event mmap_ev = {
275 .header.type = PERF_EVENT_MMAP,
277 int n;
278 size_t size;
279 if (fgets(bf, sizeof(bf), fp) == NULL)
280 break;
282 /* 00400000-0040c000 r-xp 00000000 fd:01 41038 /bin/cat */
283 n = hex2u64(pbf, &mmap_ev.start);
284 if (n < 0)
285 continue;
286 pbf += n + 1;
287 n = hex2u64(pbf, &mmap_ev.len);
288 if (n < 0)
289 continue;
290 pbf += n + 3;
291 if (*pbf == 'x') { /* vm_exec */
292 char *execname = strrchr(bf, ' ');
294 if (execname == NULL || execname[1] != '/')
295 continue;
297 execname += 1;
298 size = strlen(execname);
299 execname[size - 1] = '\0'; /* Remove \n */
300 memcpy(mmap_ev.filename, execname, size);
301 size = ALIGN(size, sizeof(uint64_t));
302 mmap_ev.len -= mmap_ev.start;
303 mmap_ev.header.size = (sizeof(mmap_ev) -
304 (sizeof(mmap_ev.filename) - size));
305 mmap_ev.pid = pid;
306 mmap_ev.tid = pid;
308 if (write(output, &mmap_ev, mmap_ev.header.size) < 0) {
309 perror("failed to write");
310 exit(-1);
315 fclose(fp);
318 static void synthesize_samples(void)
320 DIR *proc;
321 struct dirent dirent, *next;
323 proc = opendir("/proc");
325 while (!readdir_r(proc, &dirent, &next) && next) {
326 char *end;
327 pid_t pid;
329 pid = strtol(dirent.d_name, &end, 10);
330 if (*end) /* only interested in proper numerical dirents */
331 continue;
333 pid_synthesize_comm_event(pid, 1);
334 pid_synthesize_mmap_samples(pid);
337 closedir(proc);
340 static int group_fd;
342 static void create_counter(int counter, int cpu, pid_t pid)
344 struct perf_counter_attr attr;
345 int track = 1;
347 memset(&attr, 0, sizeof(attr));
348 attr.config = event_id[counter];
349 attr.sample_period = event_count[counter];
350 attr.sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID | PERF_SAMPLE_PERIOD;
351 if (freq) {
352 attr.freq = 1;
353 attr.sample_freq = freq;
355 attr.mmap = track;
356 attr.comm = track;
357 attr.inherit = (cpu < 0) && inherit;
359 track = 0; /* only the first counter needs these */
361 fd[nr_cpu][counter] = sys_perf_counter_open(&attr, pid, cpu, group_fd, 0);
363 if (fd[nr_cpu][counter] < 0) {
364 int err = errno;
366 error("syscall returned with %d (%s)\n",
367 fd[nr_cpu][counter], strerror(err));
368 if (err == EPERM)
369 printf("Are you root?\n");
370 exit(-1);
372 assert(fd[nr_cpu][counter] >= 0);
373 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
376 * First counter acts as the group leader:
378 if (group && group_fd == -1)
379 group_fd = fd[nr_cpu][counter];
381 event_array[nr_poll].fd = fd[nr_cpu][counter];
382 event_array[nr_poll].events = POLLIN;
383 nr_poll++;
385 mmap_array[nr_cpu][counter].counter = counter;
386 mmap_array[nr_cpu][counter].prev = 0;
387 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
388 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
389 PROT_READ, MAP_SHARED, fd[nr_cpu][counter], 0);
390 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
391 error("failed to mmap with %d (%s)\n", errno, strerror(errno));
392 exit(-1);
396 static void open_counters(int cpu, pid_t pid)
398 int counter;
400 if (pid > 0) {
401 pid_synthesize_comm_event(pid, 0);
402 pid_synthesize_mmap_samples(pid);
405 group_fd = -1;
406 for (counter = 0; counter < nr_counters; counter++)
407 create_counter(counter, cpu, pid);
409 nr_cpu++;
412 static int __cmd_record(int argc, const char **argv)
414 int i, counter;
415 struct stat st;
416 pid_t pid;
417 int flags;
418 int ret;
420 page_size = sysconf(_SC_PAGE_SIZE);
421 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
422 assert(nr_cpus <= MAX_NR_CPUS);
423 assert(nr_cpus >= 0);
425 if (!stat(output_name, &st) && !force && !append_file) {
426 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
427 output_name);
428 exit(-1);
431 flags = O_CREAT|O_RDWR;
432 if (append_file)
433 flags |= O_APPEND;
434 else
435 flags |= O_TRUNC;
437 output = open(output_name, flags, S_IRUSR|S_IWUSR);
438 if (output < 0) {
439 perror("failed to create output file");
440 exit(-1);
443 if (!system_wide) {
444 open_counters(-1, target_pid != -1 ? target_pid : getpid());
445 } else for (i = 0; i < nr_cpus; i++)
446 open_counters(i, target_pid);
448 signal(SIGCHLD, sig_handler);
449 signal(SIGINT, sig_handler);
451 if (target_pid == -1 && argc) {
452 pid = fork();
453 if (pid < 0)
454 perror("failed to fork");
456 if (!pid) {
457 if (execvp(argv[0], (char **)argv)) {
458 perror(argv[0]);
459 exit(-1);
464 if (realtime_prio) {
465 struct sched_param param;
467 param.sched_priority = realtime_prio;
468 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
469 printf("Could not set realtime priority.\n");
470 exit(-1);
474 if (system_wide)
475 synthesize_samples();
477 while (!done) {
478 int hits = samples;
480 for (i = 0; i < nr_cpu; i++) {
481 for (counter = 0; counter < nr_counters; counter++)
482 mmap_read(&mmap_array[i][counter]);
485 if (hits == samples)
486 ret = poll(event_array, nr_poll, 100);
490 * Approximate RIP event size: 24 bytes.
492 fprintf(stderr,
493 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
494 (double)bytes_written / 1024.0 / 1024.0,
495 output_name,
496 bytes_written / 24);
498 return 0;
501 static const char * const record_usage[] = {
502 "perf record [<options>] [<command>]",
503 "perf record [<options>] -- <command> [<options>]",
504 NULL
507 static char events_help_msg[EVENTS_HELP_MAX];
509 static const struct option options[] = {
510 OPT_CALLBACK('e', "event", NULL, "event",
511 events_help_msg, parse_events),
512 OPT_INTEGER('p', "pid", &target_pid,
513 "record events on existing pid"),
514 OPT_INTEGER('r', "realtime", &realtime_prio,
515 "collect data with this RT SCHED_FIFO priority"),
516 OPT_BOOLEAN('a', "all-cpus", &system_wide,
517 "system-wide collection from all CPUs"),
518 OPT_BOOLEAN('A', "append", &append_file,
519 "append to the output file to do incremental profiling"),
520 OPT_BOOLEAN('f', "force", &force,
521 "overwrite existing data file"),
522 OPT_LONG('c', "count", &default_interval,
523 "event period to sample"),
524 OPT_STRING('o', "output", &output_name, "file",
525 "output file name"),
526 OPT_BOOLEAN('i', "inherit", &inherit,
527 "child tasks inherit counters"),
528 OPT_INTEGER('F', "freq", &freq,
529 "profile at this frequency"),
530 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
531 "number of mmap data pages"),
532 OPT_END()
535 int cmd_record(int argc, const char **argv, const char *prefix)
537 int counter;
539 create_events_help(events_help_msg);
541 argc = parse_options(argc, argv, options, record_usage, 0);
542 if (!argc && target_pid == -1 && !system_wide)
543 usage_with_options(record_usage, options);
545 if (!nr_counters) {
546 nr_counters = 1;
547 event_id[0] = 0;
550 for (counter = 0; counter < nr_counters; counter++) {
551 if (event_count[counter])
552 continue;
554 event_count[counter] = default_interval;
557 return __cmd_record(argc, argv);