]> git.karo-electronics.de Git - mv-sheeva.git/blob - Documentation/perf_counter/builtin-record.c
perf record: Add --append option
[mv-sheeva.git] / Documentation / perf_counter / builtin-record.c
1 /*
2  * perf record: Record the profile of a workload (or a CPU, or a PID) into
3  * the perf.data output file - for later analysis via perf report.
4  */
5 #include "perf.h"
6 #include "builtin.h"
7 #include "util/util.h"
8 #include "util/parse-options.h"
9 #include "util/parse-events.h"
10 #include "util/string.h"
11
12 #include <unistd.h>
13 #include <sched.h>
14
15 #define ALIGN(x, a)             __ALIGN_MASK(x, (typeof(x))(a)-1)
16 #define __ALIGN_MASK(x, mask)   (((x)+(mask))&~(mask))
17
18 static int                      default_interval = 100000;
19 static int                      event_count[MAX_COUNTERS];
20
21 static int                      fd[MAX_NR_CPUS][MAX_COUNTERS];
22 static int                      nr_cpus                         =  0;
23 static unsigned int             page_size;
24 static unsigned int             mmap_pages                      = 16;
25 static int                      output;
26 static const char               *output_name                    = "perf.data";
27 static int                      group                           = 0;
28 static unsigned int             realtime_prio                   = 0;
29 static int                      system_wide                     = 0;
30 static pid_t                    target_pid                      = -1;
31 static int                      inherit                         = 1;
32 static int                      force                           = 0;
33 static int                      append_file                     = 0;
34
35 const unsigned int default_count[] = {
36         1000000,
37         1000000,
38           10000,
39           10000,
40         1000000,
41           10000,
42 };
43
44 struct mmap_data {
45         int counter;
46         void *base;
47         unsigned int mask;
48         unsigned int prev;
49 };
50
51 static unsigned int mmap_read_head(struct mmap_data *md)
52 {
53         struct perf_counter_mmap_page *pc = md->base;
54         int head;
55
56         head = pc->data_head;
57         rmb();
58
59         return head;
60 }
61
62 static long events;
63 static struct timeval last_read, this_read;
64
65 static void mmap_read(struct mmap_data *md)
66 {
67         unsigned int head = mmap_read_head(md);
68         unsigned int old = md->prev;
69         unsigned char *data = md->base + page_size;
70         unsigned long size;
71         void *buf;
72         int diff;
73
74         gettimeofday(&this_read, NULL);
75
76         /*
77          * If we're further behind than half the buffer, there's a chance
78          * the writer will bite our tail and screw up the events under us.
79          *
80          * If we somehow ended up ahead of the head, we got messed up.
81          *
82          * In either case, truncate and restart at head.
83          */
84         diff = head - old;
85         if (diff > md->mask / 2 || diff < 0) {
86                 struct timeval iv;
87                 unsigned long msecs;
88
89                 timersub(&this_read, &last_read, &iv);
90                 msecs = iv.tv_sec*1000 + iv.tv_usec/1000;
91
92                 fprintf(stderr, "WARNING: failed to keep up with mmap data."
93                                 "  Last read %lu msecs ago.\n", msecs);
94
95                 /*
96                  * head points to a known good entry, start there.
97                  */
98                 old = head;
99         }
100
101         last_read = this_read;
102
103         if (old != head)
104                 events++;
105
106         size = head - old;
107
108         if ((old & md->mask) + size != (head & md->mask)) {
109                 buf = &data[old & md->mask];
110                 size = md->mask + 1 - (old & md->mask);
111                 old += size;
112                 while (size) {
113                         int ret = write(output, buf, size);
114                         if (ret < 0) {
115                                 perror("failed to write");
116                                 exit(-1);
117                         }
118                         size -= ret;
119                         buf += ret;
120                 }
121         }
122
123         buf = &data[old & md->mask];
124         size = head - old;
125         old += size;
126         while (size) {
127                 int ret = write(output, buf, size);
128                 if (ret < 0) {
129                         perror("failed to write");
130                         exit(-1);
131                 }
132                 size -= ret;
133                 buf += ret;
134         }
135
136         md->prev = old;
137 }
138
139 static volatile int done = 0;
140
141 static void sig_handler(int sig)
142 {
143         done = 1;
144 }
145
146 static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
147 static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
148
149 static int nr_poll;
150 static int nr_cpu;
151
152 struct mmap_event {
153         struct perf_event_header        header;
154         __u32                           pid;
155         __u32                           tid;
156         __u64                           start;
157         __u64                           len;
158         __u64                           pgoff;
159         char                            filename[PATH_MAX];
160 };
161
162 struct comm_event {
163         struct perf_event_header        header;
164         __u32                           pid;
165         __u32                           tid;
166         char                            comm[16];
167 };
168
169 static void pid_synthesize_comm_event(pid_t pid, int full)
170 {
171         struct comm_event comm_ev;
172         char filename[PATH_MAX];
173         char bf[BUFSIZ];
174         int fd, ret;
175         size_t size;
176         char *field, *sep;
177         DIR *tasks;
178         struct dirent dirent, *next;
179
180         snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
181
182         fd = open(filename, O_RDONLY);
183         if (fd < 0) {
184                 fprintf(stderr, "couldn't open %s\n", filename);
185                 exit(EXIT_FAILURE);
186         }
187         if (read(fd, bf, sizeof(bf)) < 0) {
188                 fprintf(stderr, "couldn't read %s\n", filename);
189                 exit(EXIT_FAILURE);
190         }
191         close(fd);
192
193         /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
194         memset(&comm_ev, 0, sizeof(comm_ev));
195         field = strchr(bf, '(');
196         if (field == NULL)
197                 goto out_failure;
198         sep = strchr(++field, ')');
199         if (sep == NULL)
200                 goto out_failure;
201         size = sep - field;
202         memcpy(comm_ev.comm, field, size++);
203
204         comm_ev.pid = pid;
205         comm_ev.header.type = PERF_EVENT_COMM;
206         size = ALIGN(size, sizeof(uint64_t));
207         comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
208
209         if (!full) {
210                 comm_ev.tid = pid;
211
212                 ret = write(output, &comm_ev, comm_ev.header.size);
213                 if (ret < 0) {
214                         perror("failed to write");
215                         exit(-1);
216                 }
217                 return;
218         }
219
220         snprintf(filename, sizeof(filename), "/proc/%d/task", pid);
221
222         tasks = opendir(filename);
223         while (!readdir_r(tasks, &dirent, &next) && next) {
224                 char *end;
225                 pid = strtol(dirent.d_name, &end, 10);
226                 if (*end)
227                         continue;
228
229                 comm_ev.tid = pid;
230
231                 ret = write(output, &comm_ev, comm_ev.header.size);
232                 if (ret < 0) {
233                         perror("failed to write");
234                         exit(-1);
235                 }
236         }
237         closedir(tasks);
238         return;
239
240 out_failure:
241         fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
242                 filename);
243         exit(EXIT_FAILURE);
244 }
245
246 static void pid_synthesize_mmap_events(pid_t pid)
247 {
248         char filename[PATH_MAX];
249         FILE *fp;
250
251         snprintf(filename, sizeof(filename), "/proc/%d/maps", pid);
252
253         fp = fopen(filename, "r");
254         if (fp == NULL) {
255                 fprintf(stderr, "couldn't open %s\n", filename);
256                 exit(EXIT_FAILURE);
257         }
258         while (1) {
259                 char bf[BUFSIZ], *pbf = bf;
260                 struct mmap_event mmap_ev = {
261                         .header.type = PERF_EVENT_MMAP,
262                 };
263                 int n;
264                 size_t size;
265                 if (fgets(bf, sizeof(bf), fp) == NULL)
266                         break;
267
268                 /* 00400000-0040c000 r-xp 00000000 fd:01 41038  /bin/cat */
269                 n = hex2u64(pbf, &mmap_ev.start);
270                 if (n < 0)
271                         continue;
272                 pbf += n + 1;
273                 n = hex2u64(pbf, &mmap_ev.len);
274                 if (n < 0)
275                         continue;
276                 pbf += n + 3;
277                 if (*pbf == 'x') { /* vm_exec */
278                         char *execname = strrchr(bf, ' ');
279
280                         if (execname == NULL || execname[1] != '/')
281                                 continue;
282
283                         execname += 1;
284                         size = strlen(execname);
285                         execname[size - 1] = '\0'; /* Remove \n */
286                         memcpy(mmap_ev.filename, execname, size);
287                         size = ALIGN(size, sizeof(uint64_t));
288                         mmap_ev.len -= mmap_ev.start;
289                         mmap_ev.header.size = (sizeof(mmap_ev) -
290                                                (sizeof(mmap_ev.filename) - size));
291                         mmap_ev.pid = pid;
292                         mmap_ev.tid = pid;
293
294                         if (write(output, &mmap_ev, mmap_ev.header.size) < 0) {
295                                 perror("failed to write");
296                                 exit(-1);
297                         }
298                 }
299         }
300
301         fclose(fp);
302 }
303
304 static void synthesize_events(void)
305 {
306         DIR *proc;
307         struct dirent dirent, *next;
308
309         proc = opendir("/proc");
310
311         while (!readdir_r(proc, &dirent, &next) && next) {
312                 char *end;
313                 pid_t pid;
314
315                 pid = strtol(dirent.d_name, &end, 10);
316                 if (*end) /* only interested in proper numerical dirents */
317                         continue;
318
319                 pid_synthesize_comm_event(pid, 1);
320                 pid_synthesize_mmap_events(pid);
321         }
322
323         closedir(proc);
324 }
325
326 static void open_counters(int cpu, pid_t pid)
327 {
328         struct perf_counter_attr attr;
329         int counter, group_fd;
330         int track = 1;
331
332         if (pid > 0) {
333                 pid_synthesize_comm_event(pid, 0);
334                 pid_synthesize_mmap_events(pid);
335         }
336
337         group_fd = -1;
338         for (counter = 0; counter < nr_counters; counter++) {
339
340                 memset(&attr, 0, sizeof(attr));
341                 attr.config             = event_id[counter];
342                 attr.sample_period      = event_count[counter];
343                 attr.sample_type        = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
344                 attr.mmap               = track;
345                 attr.comm               = track;
346                 attr.inherit    = (cpu < 0) && inherit;
347
348                 track = 0; // only the first counter needs these
349
350                 fd[nr_cpu][counter] =
351                         sys_perf_counter_open(&attr, pid, cpu, group_fd, 0);
352
353                 if (fd[nr_cpu][counter] < 0) {
354                         int err = errno;
355                         printf("kerneltop error: syscall returned with %d (%s)\n",
356                                         fd[nr_cpu][counter], strerror(err));
357                         if (err == EPERM)
358                                 printf("Are you root?\n");
359                         exit(-1);
360                 }
361                 assert(fd[nr_cpu][counter] >= 0);
362                 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
363
364                 /*
365                  * First counter acts as the group leader:
366                  */
367                 if (group && group_fd == -1)
368                         group_fd = fd[nr_cpu][counter];
369
370                 event_array[nr_poll].fd = fd[nr_cpu][counter];
371                 event_array[nr_poll].events = POLLIN;
372                 nr_poll++;
373
374                 mmap_array[nr_cpu][counter].counter = counter;
375                 mmap_array[nr_cpu][counter].prev = 0;
376                 mmap_array[nr_cpu][counter].mask = mmap_pages*page_size - 1;
377                 mmap_array[nr_cpu][counter].base = mmap(NULL, (mmap_pages+1)*page_size,
378                                 PROT_READ, MAP_SHARED, fd[nr_cpu][counter], 0);
379                 if (mmap_array[nr_cpu][counter].base == MAP_FAILED) {
380                         printf("kerneltop error: failed to mmap with %d (%s)\n",
381                                         errno, strerror(errno));
382                         exit(-1);
383                 }
384         }
385         nr_cpu++;
386 }
387
388 static int __cmd_record(int argc, const char **argv)
389 {
390         int i, counter;
391         struct stat st;
392         pid_t pid;
393         int flags;
394         int ret;
395
396         page_size = sysconf(_SC_PAGE_SIZE);
397         nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
398         assert(nr_cpus <= MAX_NR_CPUS);
399         assert(nr_cpus >= 0);
400
401         if (!stat(output_name, &st) && !force && !append_file) {
402                 fprintf(stderr, "Error, output file %s exists, use -A to append or -f to overwrite.\n",
403                                 output_name);
404                 exit(-1);
405         }
406
407         flags = O_CREAT|O_RDWR;
408         if (append_file)
409                 flags |= O_APPEND;
410         else
411                 flags |= O_TRUNC;
412
413         output = open(output_name, flags, S_IRUSR|S_IWUSR);
414         if (output < 0) {
415                 perror("failed to create output file");
416                 exit(-1);
417         }
418
419         if (!system_wide) {
420                 open_counters(-1, target_pid != -1 ? target_pid : 0);
421         } else for (i = 0; i < nr_cpus; i++)
422                 open_counters(i, target_pid);
423
424         signal(SIGCHLD, sig_handler);
425         signal(SIGINT, sig_handler);
426
427         if (target_pid == -1 && argc) {
428                 pid = fork();
429                 if (pid < 0)
430                         perror("failed to fork");
431
432                 if (!pid) {
433                         if (execvp(argv[0], (char **)argv)) {
434                                 perror(argv[0]);
435                                 exit(-1);
436                         }
437                 }
438         }
439
440         if (realtime_prio) {
441                 struct sched_param param;
442
443                 param.sched_priority = realtime_prio;
444                 if (sched_setscheduler(0, SCHED_FIFO, &param)) {
445                         printf("Could not set realtime priority.\n");
446                         exit(-1);
447                 }
448         }
449
450         if (system_wide)
451                 synthesize_events();
452
453         while (!done) {
454                 int hits = events;
455
456                 for (i = 0; i < nr_cpu; i++) {
457                         for (counter = 0; counter < nr_counters; counter++)
458                                 mmap_read(&mmap_array[i][counter]);
459                 }
460
461                 if (hits == events)
462                         ret = poll(event_array, nr_poll, 100);
463         }
464
465         return 0;
466 }
467
468 static const char * const record_usage[] = {
469         "perf record [<options>] [<command>]",
470         "perf record [<options>] -- <command> [<options>]",
471         NULL
472 };
473
474 static char events_help_msg[EVENTS_HELP_MAX];
475
476 static const struct option options[] = {
477         OPT_CALLBACK('e', "event", NULL, "event",
478                      events_help_msg, parse_events),
479         OPT_INTEGER('p', "pid", &target_pid,
480                     "record events on existing pid"),
481         OPT_INTEGER('r', "realtime", &realtime_prio,
482                     "collect data with this RT SCHED_FIFO priority"),
483         OPT_BOOLEAN('a', "all-cpus", &system_wide,
484                             "system-wide collection from all CPUs"),
485         OPT_BOOLEAN('A', "append", &append_file,
486                             "append to the output file to do incremental profiling"),
487         OPT_BOOLEAN('f', "force", &force,
488                         "overwrite existing data file"),
489         OPT_INTEGER('c', "count", &default_interval,
490                     "event period to sample"),
491         OPT_STRING('o', "output", &output_name, "file",
492                     "output file name"),
493         OPT_BOOLEAN('i', "inherit", &inherit,
494                     "child tasks inherit counters"),
495         OPT_INTEGER('m', "mmap-pages", &mmap_pages,
496                     "number of mmap data pages"),
497         OPT_END()
498 };
499
500 int cmd_record(int argc, const char **argv, const char *prefix)
501 {
502         int counter;
503
504         create_events_help(events_help_msg);
505
506         argc = parse_options(argc, argv, options, record_usage, 0);
507         if (!argc && target_pid == -1 && !system_wide)
508                 usage_with_options(record_usage, options);
509
510         if (!nr_counters) {
511                 nr_counters = 1;
512                 event_id[0] = 0;
513         }
514
515         for (counter = 0; counter < nr_counters; counter++) {
516                 if (event_count[counter])
517                         continue;
518
519                 event_count[counter] = default_interval;
520         }
521
522         return __cmd_record(argc, argv);
523 }