]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - tools/perf/builtin-record.c
perf record: Fix fast task-exit race
[mirror_ubuntu-bionic-kernel.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;
3efa1cc9 40static int call_graph = 0;
3da297a6 41static int verbose = 0;
de9ac07b 42
a21ca2ca
IM
43static long samples;
44static struct timeval last_read;
45static struct timeval this_read;
46
47static __u64 bytes_written;
48
49static struct pollfd event_array[MAX_NR_CPUS * MAX_COUNTERS];
50
51static int nr_poll;
52static int nr_cpu;
53
54struct 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
64struct comm_event {
65 struct perf_event_header header;
66 __u32 pid;
67 __u32 tid;
68 char comm[16];
de9ac07b
PZ
69};
70
a21ca2ca 71
de9ac07b 72struct mmap_data {
a21ca2ca
IM
73 int counter;
74 void *base;
75 unsigned int mask;
76 unsigned int prev;
de9ac07b
PZ
77};
78
a21ca2ca
IM
79static struct mmap_data mmap_array[MAX_NR_CPUS][MAX_COUNTERS];
80
de9ac07b
PZ
81static 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
de9ac07b
PZ
92static 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
2debbc83 105 * the writer will bite our tail and mess up the samples under us.
de9ac07b
PZ
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)
2debbc83 131 samples++;
de9ac07b
PZ
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;
021e9f47 139
de9ac07b
PZ
140 while (size) {
141 int ret = write(output, buf, size);
021e9f47
IM
142
143 if (ret < 0)
144 die("failed to write");
145
de9ac07b
PZ
146 size -= ret;
147 buf += ret;
021e9f47
IM
148
149 bytes_written += ret;
de9ac07b
PZ
150 }
151 }
152
153 buf = &data[old & md->mask];
154 size = head - old;
155 old += size;
021e9f47 156
de9ac07b
PZ
157 while (size) {
158 int ret = write(output, buf, size);
021e9f47
IM
159
160 if (ret < 0)
161 die("failed to write");
162
de9ac07b
PZ
163 size -= ret;
164 buf += ret;
021e9f47
IM
165
166 bytes_written += ret;
de9ac07b
PZ
167 }
168
169 md->prev = old;
170}
171
172static volatile int done = 0;
f7b7c26e 173static volatile int signr = -1;
de9ac07b 174
16c8a109 175static void sig_handler(int sig)
de9ac07b 176{
16c8a109 177 done = 1;
f7b7c26e
PZ
178 signr = sig;
179}
180
181static void sig_atexit(void)
182{
183 if (signr == -1)
184 return;
185
186 signal(signr, SIG_DFL);
187 kill(getpid(), signr);
de9ac07b
PZ
188}
189
f70e87d7 190static void pid_synthesize_comm_event(pid_t pid, int full)
1a853e36 191{
16f762a2 192 struct comm_event comm_ev;
1a853e36
ACM
193 char filename[PATH_MAX];
194 char bf[BUFSIZ];
a0055ae2 195 int fd, ret;
1a853e36 196 size_t size;
a0055ae2 197 char *field, *sep;
f70e87d7
PZ
198 DIR *tasks;
199 struct dirent dirent, *next;
1a853e36
ACM
200
201 snprintf(filename, sizeof(filename), "/proc/%d/stat", pid);
202
203 fd = open(filename, O_RDONLY);
204 if (fd < 0) {
613d8602
IM
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;
1a853e36
ACM
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
a0055ae2 218 /* 9027 (cat) R 6747 9027 6747 34816 9027 ... */
1a853e36 219 memset(&comm_ev, 0, sizeof(comm_ev));
a0055ae2
ACM
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++);
f70e87d7
PZ
228
229 comm_ev.pid = pid;
1a853e36 230 comm_ev.header.type = PERF_EVENT_COMM;
729ff5e2 231 size = ALIGN(size, sizeof(__u64));
1a853e36 232 comm_ev.header.size = sizeof(comm_ev) - (sizeof(comm_ev.comm) - size);
16f762a2 233
f70e87d7
PZ
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 }
1a853e36 261 }
f70e87d7
PZ
262 closedir(tasks);
263 return;
264
a0055ae2
ACM
265out_failure:
266 fprintf(stderr, "couldn't get COMM and pgid, malformed %s\n",
267 filename);
268 exit(EXIT_FAILURE);
1a853e36
ACM
269}
270
2debbc83 271static void pid_synthesize_mmap_samples(pid_t pid)
1a853e36
ACM
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) {
613d8602
IM
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;
1a853e36
ACM
286 }
287 while (1) {
a0055ae2 288 char bf[BUFSIZ], *pbf = bf;
1a853e36
ACM
289 struct mmap_event mmap_ev = {
290 .header.type = PERF_EVENT_MMAP,
291 };
a0055ae2 292 int n;
1a853e36
ACM
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 */
a0055ae2
ACM
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 */
1a853e36
ACM
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);
729ff5e2 316 size = ALIGN(size, sizeof(__u64));
1a853e36
ACM
317 mmap_ev.len -= mmap_ev.start;
318 mmap_ev.header.size = (sizeof(mmap_ev) -
319 (sizeof(mmap_ev.filename) - size));
f70e87d7 320 mmap_ev.pid = pid;
1a853e36
ACM
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
2debbc83 333static void synthesize_samples(void)
f70e87d7
PZ
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);
2debbc83 349 pid_synthesize_mmap_samples(pid);
f70e87d7
PZ
350 }
351
352 closedir(proc);
353}
354
f250c030
IM
355static int group_fd;
356
357static void create_counter(int counter, int cpu, pid_t pid)
de9ac07b 358{
a21ca2ca 359 struct perf_counter_attr *attr = attrs + counter;
16c8a109 360 int track = 1;
16c8a109 361
ea1900e5 362 attr->sample_type = PERF_SAMPLE_IP | PERF_SAMPLE_TID;
3efa1cc9 363
1dba15e7 364 if (freq) {
ea1900e5 365 attr->sample_type |= PERF_SAMPLE_PERIOD;
a21ca2ca
IM
366 attr->freq = 1;
367 attr->sample_freq = freq;
1dba15e7 368 }
3efa1cc9
IM
369
370 if (call_graph)
371 attr->sample_type |= PERF_SAMPLE_CALLCHAIN;
372
a21ca2ca
IM
373 attr->mmap = track;
374 attr->comm = track;
375 attr->inherit = (cpu < 0) && inherit;
4502d77c 376 attr->disabled = 1;
16c8a109 377
f250c030 378 track = 0; /* only the first counter needs these */
16c8a109 379
3da297a6 380try_again:
a21ca2ca 381 fd[nr_cpu][counter] = sys_perf_counter_open(attr, pid, cpu, group_fd, 0);
16c8a109 382
f250c030
IM
383 if (fd[nr_cpu][counter] < 0) {
384 int err = errno;
16c8a109 385
f250c030 386 if (err == EPERM)
3da297a6
IM
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
f4dbfa8f 395 && attr->config == PERF_COUNT_HW_CPU_CYCLES) {
3da297a6
IM
396
397 if (verbose)
398 warning(" ... trying to fall back to cpu-clock-ticks\n");
399 attr->type = PERF_TYPE_SOFTWARE;
f4dbfa8f 400 attr->config = PERF_COUNT_SW_CPU_CLOCK;
3da297a6
IM
401 goto try_again;
402 }
30c806a0
IM
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");
f250c030
IM
407 exit(-1);
408 }
3da297a6 409
f250c030
IM
410 assert(fd[nr_cpu][counter] >= 0);
411 fcntl(fd[nr_cpu][counter], F_SETFL, O_NONBLOCK);
16c8a109 412
f250c030
IM
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 }
4502d77c
PZ
432
433 ioctl(fd[nr_cpu][counter], PERF_COUNTER_IOC_ENABLE);
f250c030 434}
f2521b6e 435
f250c030
IM
436static void open_counters(int cpu, pid_t pid)
437{
438 int counter;
16c8a109 439
f250c030
IM
440 if (pid > 0) {
441 pid_synthesize_comm_event(pid, 0);
2debbc83 442 pid_synthesize_mmap_samples(pid);
16c8a109 443 }
f250c030
IM
444
445 group_fd = -1;
446 for (counter = 0; counter < nr_counters; counter++)
447 create_counter(counter, cpu, pid);
448
16c8a109
PZ
449 nr_cpu++;
450}
451
0e9b20b8 452static int __cmd_record(int argc, const char **argv)
16c8a109
PZ
453{
454 int i, counter;
abaff32a 455 struct stat st;
de9ac07b 456 pid_t pid;
abaff32a 457 int flags;
de9ac07b
PZ
458 int ret;
459
460 page_size = sysconf(_SC_PAGE_SIZE);
de9ac07b
PZ
461 nr_cpus = sysconf(_SC_NPROCESSORS_ONLN);
462 assert(nr_cpus <= MAX_NR_CPUS);
463 assert(nr_cpus >= 0);
464
abaff32a
IM
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",
97124d5e
PZ
467 output_name);
468 exit(-1);
469 }
470
abaff32a
IM
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);
de9ac07b
PZ
478 if (output < 0) {
479 perror("failed to create output file");
480 exit(-1);
481 }
482
1a853e36 483 if (!system_wide) {
df97992c 484 open_counters(-1, target_pid != -1 ? target_pid : getpid());
1a853e36
ACM
485 } else for (i = 0; i < nr_cpus; i++)
486 open_counters(i, target_pid);
de9ac07b 487
f7b7c26e 488 atexit(sig_atexit);
16c8a109
PZ
489 signal(SIGCHLD, sig_handler);
490 signal(SIGINT, sig_handler);
de9ac07b 491
ef65b2a0 492 if (target_pid == -1 && argc) {
1a853e36
ACM
493 pid = fork();
494 if (pid < 0)
495 perror("failed to fork");
de9ac07b 496
1a853e36 497 if (!pid) {
0e9b20b8 498 if (execvp(argv[0], (char **)argv)) {
1a853e36
ACM
499 perror(argv[0]);
500 exit(-1);
501 }
de9ac07b
PZ
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
f70e87d7 515 if (system_wide)
2debbc83 516 synthesize_samples();
de9ac07b
PZ
517
518 while (!done) {
2debbc83 519 int hits = samples;
de9ac07b 520
16c8a109 521 for (i = 0; i < nr_cpu; i++) {
de9ac07b
PZ
522 for (counter = 0; counter < nr_counters; counter++)
523 mmap_read(&mmap_array[i][counter]);
524 }
525
2debbc83 526 if (hits == samples)
de9ac07b
PZ
527 ret = poll(event_array, nr_poll, 100);
528 }
529
021e9f47
IM
530 /*
531 * Approximate RIP event size: 24 bytes.
532 */
533 fprintf(stderr,
2debbc83 534 "[ perf record: Captured and wrote %.3f MB %s (~%lld samples) ]\n",
021e9f47
IM
535 (double)bytes_written / 1024.0 / 1024.0,
536 output_name,
537 bytes_written / 24);
addc2785 538
de9ac07b
PZ
539 return 0;
540}
0e9b20b8 541
0e9b20b8 542static const char * const record_usage[] = {
9e096753
MG
543 "perf record [<options>] [<command>]",
544 "perf record [<options>] -- <command> [<options>]",
0e9b20b8
IM
545 NULL
546};
547
5242519b 548static const struct option options[] = {
0e9b20b8 549 OPT_CALLBACK('e', "event", NULL, "event",
86847b62
TG
550 "event selector. use 'perf list' to list available events",
551 parse_events),
0e9b20b8
IM
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"),
abaff32a
IM
558 OPT_BOOLEAN('A', "append", &append_file,
559 "append to the output file to do incremental profiling"),
97124d5e
PZ
560 OPT_BOOLEAN('f', "force", &force,
561 "overwrite existing data file"),
e61078a0 562 OPT_LONG('c', "count", &default_interval,
abaff32a
IM
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"),
cf1f4574
IM
568 OPT_INTEGER('F', "freq", &freq,
569 "profile at this frequency"),
abaff32a
IM
570 OPT_INTEGER('m', "mmap-pages", &mmap_pages,
571 "number of mmap data pages"),
3efa1cc9
IM
572 OPT_BOOLEAN('g', "call-graph", &call_graph,
573 "do call-graph (stack chain/backtrace) recording"),
3da297a6
IM
574 OPT_BOOLEAN('v', "verbose", &verbose,
575 "be more verbose (show counter open errors, etc)"),
0e9b20b8
IM
576 OPT_END()
577};
578
579int cmd_record(int argc, const char **argv, const char *prefix)
580{
581 int counter;
582
0e9b20b8 583 argc = parse_options(argc, argv, options, record_usage, 0);
ef65b2a0 584 if (!argc && target_pid == -1 && !system_wide)
0e9b20b8
IM
585 usage_with_options(record_usage, options);
586
bbd36e5e
PZ
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 }
0e9b20b8
IM
592
593 for (counter = 0; counter < nr_counters; counter++) {
a21ca2ca 594 if (attrs[counter].sample_period)
0e9b20b8
IM
595 continue;
596
a21ca2ca 597 attrs[counter].sample_period = default_interval;
0e9b20b8
IM
598 }
599
600 return __cmd_record(argc, argv);
601}