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