Merge tag 'perf-core-for-mingo-20160615' of git://git.kernel.org/pub/scm/linux/kernel...
[deliverable/linux.git] / tools / perf / util / util.c
CommitLineData
1aed2671 1#include "../perf.h"
4cf40131 2#include "util.h"
84f5d36f 3#include "debug.h"
cd0cfad7 4#include <api/fs/fs.h>
69e3f52d 5#include <sys/mman.h>
07bc5c69 6#include <sys/utsname.h>
89fe808a 7#ifdef HAVE_BACKTRACE_SUPPORT
dc4552bf 8#include <execinfo.h>
c9f08bee 9#endif
dc4552bf
ACM
10#include <stdio.h>
11#include <stdlib.h>
cef82c9f
JO
12#include <string.h>
13#include <errno.h>
1a47245d 14#include <limits.h>
71db07b1 15#include <byteswap.h>
838d1452 16#include <linux/kernel.h>
c339b1a9 17#include <linux/log2.h>
9398c484 18#include <unistd.h>
23aadb1f 19#include "callchain.h"
14cbfbeb 20#include "strlist.h"
23aadb1f
JO
21
22struct callchain_param callchain_param = {
def02db0 23 .mode = CHAIN_GRAPH_ABS,
23aadb1f 24 .min_percent = 0.5,
792aeafa 25 .order = ORDER_CALLEE,
f2af0086
NK
26 .key = CCKEY_FUNCTION,
27 .value = CCVAL_PERCENT,
23aadb1f 28};
4cf40131 29
1aed2671
JR
30/*
31 * XXX We need to find a better place for these things...
32 */
0c1fe6b2 33unsigned int page_size;
2b1b7100 34int cacheline_size;
0c1fe6b2 35
a29d5c9b
ACM
36int sysctl_perf_event_max_stack = PERF_MAX_STACK_DEPTH;
37int sysctl_perf_event_max_contexts_per_stack = PERF_MAX_CONTEXTS_PER_STACK;
4cb93446 38
0c6332e9
ACM
39bool test_attr__enabled;
40
1aed2671 41bool perf_host = true;
c4a7dca9 42bool perf_guest = false;
1aed2671
JR
43
44void event_attr_init(struct perf_event_attr *attr)
45{
46 if (!perf_host)
47 attr->exclude_host = 1;
48 if (!perf_guest)
49 attr->exclude_guest = 1;
7e1ccd38
SE
50 /* to capture ABI version */
51 attr->size = sizeof(*attr);
1aed2671
JR
52}
53
4cf40131
ACM
54int mkdir_p(char *path, mode_t mode)
55{
56 struct stat st;
57 int err;
58 char *d = path;
59
60 if (*d != '/')
61 return -1;
62
63 if (stat(path, &st) == 0)
64 return 0;
65
66 while (*++d == '/');
67
68 while ((d = strchr(d, '/'))) {
69 *d = '\0';
70 err = stat(path, &st) && mkdir(path, mode);
71 *d++ = '/';
72 if (err)
73 return -1;
74 while (*d == '/')
75 ++d;
76 }
77 return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
78}
79
0b1de0be
NK
80int rm_rf(char *path)
81{
82 DIR *dir;
83 int ret = 0;
84 struct dirent *d;
85 char namebuf[PATH_MAX];
86
87 dir = opendir(path);
88 if (dir == NULL)
89 return 0;
90
91 while ((d = readdir(dir)) != NULL && !ret) {
92 struct stat statbuf;
93
94 if (!strcmp(d->d_name, ".") || !strcmp(d->d_name, ".."))
95 continue;
96
97 scnprintf(namebuf, sizeof(namebuf), "%s/%s",
98 path, d->d_name);
99
2a1ef032
MH
100 /* We have to check symbolic link itself */
101 ret = lstat(namebuf, &statbuf);
0b1de0be
NK
102 if (ret < 0) {
103 pr_debug("stat failed: %s\n", namebuf);
104 break;
105 }
106
2a1ef032 107 if (S_ISDIR(statbuf.st_mode))
0b1de0be 108 ret = rm_rf(namebuf);
2a1ef032
MH
109 else
110 ret = unlink(namebuf);
0b1de0be
NK
111 }
112 closedir(dir);
113
114 if (ret < 0)
115 return ret;
116
117 return rmdir(path);
118}
119
e1ce726e
MH
120/* A filter which removes dot files */
121bool lsdir_no_dot_filter(const char *name __maybe_unused, struct dirent *d)
122{
123 return d->d_name[0] != '.';
124}
125
126/* lsdir reads a directory and store it in strlist */
127struct strlist *lsdir(const char *name,
128 bool (*filter)(const char *, struct dirent *))
129{
130 struct strlist *list = NULL;
131 DIR *dir;
132 struct dirent *d;
133
134 dir = opendir(name);
135 if (!dir)
136 return NULL;
137
138 list = strlist__new(NULL, NULL);
139 if (!list) {
357a54f3 140 errno = ENOMEM;
e1ce726e
MH
141 goto out;
142 }
143
144 while ((d = readdir(dir)) != NULL) {
145 if (!filter || filter(name, d))
146 strlist__add(list, d->d_name);
147 }
148
149out:
150 closedir(dir);
151 return list;
152}
153
d7c72606 154static int slow_copyfile(const char *from, const char *to)
9e201442 155{
9a17d726 156 int err = -1;
9e201442
ACM
157 char *line = NULL;
158 size_t n;
159 FILE *from_fp = fopen(from, "r"), *to_fp;
160
161 if (from_fp == NULL)
162 goto out;
163
164 to_fp = fopen(to, "w");
165 if (to_fp == NULL)
166 goto out_fclose_from;
167
168 while (getline(&line, &n, from_fp) > 0)
169 if (fputs(line, to_fp) == EOF)
170 goto out_fclose_to;
171 err = 0;
172out_fclose_to:
173 fclose(to_fp);
174 free(line);
175out_fclose_from:
176 fclose(from_fp);
177out:
178 return err;
179}
180
9c9f5a2f
NK
181int copyfile_offset(int ifd, loff_t off_in, int ofd, loff_t off_out, u64 size)
182{
183 void *ptr;
184 loff_t pgoff;
185
186 pgoff = off_in & ~(page_size - 1);
187 off_in -= pgoff;
188
189 ptr = mmap(NULL, off_in + size, PROT_READ, MAP_PRIVATE, ifd, pgoff);
190 if (ptr == MAP_FAILED)
191 return -1;
192
193 while (size) {
194 ssize_t ret = pwrite(ofd, ptr + off_in, size, off_out);
195 if (ret < 0 && errno == EINTR)
196 continue;
197 if (ret <= 0)
198 break;
199
200 size -= ret;
201 off_in += ret;
202 off_out -= ret;
203 }
204 munmap(ptr, off_in + size);
205
206 return size ? -1 : 0;
207}
208
9a17d726 209int copyfile_mode(const char *from, const char *to, mode_t mode)
4cf40131
ACM
210{
211 int fromfd, tofd;
212 struct stat st;
4cf40131 213 int err = -1;
d7c72606 214 char *tmp = NULL, *ptr = NULL;
4cf40131
ACM
215
216 if (stat(from, &st))
217 goto out;
218
d7c72606
MV
219 /* extra 'x' at the end is to reserve space for '.' */
220 if (asprintf(&tmp, "%s.XXXXXXx", to) < 0) {
221 tmp = NULL;
4cf40131 222 goto out;
d7c72606
MV
223 }
224 ptr = strrchr(tmp, '/');
225 if (!ptr)
226 goto out;
227 ptr = memmove(ptr + 1, ptr, strlen(ptr) - 1);
228 *ptr = '.';
4cf40131 229
d7c72606 230 tofd = mkstemp(tmp);
4cf40131 231 if (tofd < 0)
d7c72606
MV
232 goto out;
233
234 if (fchmod(tofd, mode))
235 goto out_close_to;
236
237 if (st.st_size == 0) { /* /proc? do it slowly... */
238 err = slow_copyfile(from, tmp);
239 goto out_close_to;
240 }
241
242 fromfd = open(from, O_RDONLY);
243 if (fromfd < 0)
244 goto out_close_to;
4cf40131 245
9c9f5a2f 246 err = copyfile_offset(fromfd, 0, tofd, 0, st.st_size);
4cf40131 247
4cf40131 248 close(fromfd);
d7c72606
MV
249out_close_to:
250 close(tofd);
251 if (!err)
252 err = link(tmp, to);
253 unlink(tmp);
4cf40131 254out:
d7c72606 255 free(tmp);
4cf40131
ACM
256 return err;
257}
c82ee828 258
9a17d726
AH
259int copyfile(const char *from, const char *to)
260{
261 return copyfile_mode(from, to, 0755);
262}
263
c82ee828
ACM
264unsigned long convert_unit(unsigned long value, char *unit)
265{
266 *unit = ' ';
267
268 if (value > 1000) {
269 value /= 1000;
270 *unit = 'K';
271 }
272
273 if (value > 1000) {
274 value /= 1000;
275 *unit = 'M';
276 }
277
278 if (value > 1000) {
279 value /= 1000;
280 *unit = 'G';
281 }
282
283 return value;
284}
1e7972cc 285
bc3a502b 286static ssize_t ion(bool is_read, int fd, void *buf, size_t n)
1e7972cc
ACM
287{
288 void *buf_start = buf;
838d1452 289 size_t left = n;
1e7972cc 290
838d1452 291 while (left) {
bc3a502b
JO
292 ssize_t ret = is_read ? read(fd, buf, left) :
293 write(fd, buf, left);
1e7972cc 294
e148c760
NK
295 if (ret < 0 && errno == EINTR)
296 continue;
1e7972cc
ACM
297 if (ret <= 0)
298 return ret;
299
838d1452
JO
300 left -= ret;
301 buf += ret;
1e7972cc
ACM
302 }
303
838d1452
JO
304 BUG_ON((size_t)(buf - buf_start) != n);
305 return n;
1e7972cc 306}
61e04b33 307
bc3a502b
JO
308/*
309 * Read exactly 'n' bytes or return an error.
310 */
311ssize_t readn(int fd, void *buf, size_t n)
312{
313 return ion(true, fd, buf, n);
314}
315
316/*
317 * Write exactly 'n' bytes or return an error.
318 */
319ssize_t writen(int fd, void *buf, size_t n)
320{
321 return ion(false, fd, buf, n);
322}
323
61e04b33
ACM
324size_t hex_width(u64 v)
325{
326 size_t n = 1;
327
328 while ((v >>= 4))
329 ++n;
330
331 return n;
332}
dc4552bf 333
b2aff5f6
JO
334static int hex(char ch)
335{
336 if ((ch >= '0') && (ch <= '9'))
337 return ch - '0';
338 if ((ch >= 'a') && (ch <= 'f'))
339 return ch - 'a' + 10;
340 if ((ch >= 'A') && (ch <= 'F'))
341 return ch - 'A' + 10;
342 return -1;
343}
344
345/*
346 * While we find nice hex chars, build a long_val.
347 * Return number of chars processed.
348 */
349int hex2u64(const char *ptr, u64 *long_val)
350{
351 const char *p = ptr;
352 *long_val = 0;
353
354 while (*p) {
355 const int hex_val = hex(*p);
356
357 if (hex_val < 0)
358 break;
359
360 *long_val = (*long_val << 4) | hex_val;
361 p++;
362 }
363
364 return p - ptr;
365}
366
dc4552bf 367/* Obtain a backtrace and print it to stdout. */
89fe808a 368#ifdef HAVE_BACKTRACE_SUPPORT
dc4552bf
ACM
369void dump_stack(void)
370{
371 void *array[16];
372 size_t size = backtrace(array, ARRAY_SIZE(array));
373 char **strings = backtrace_symbols(array, size);
374 size_t i;
375
376 printf("Obtained %zd stack frames.\n", size);
377
378 for (i = 0; i < size; i++)
379 printf("%s\n", strings[i]);
380
381 free(strings);
382}
c9f08bee
IT
383#else
384void dump_stack(void) {}
385#endif
2c803e52 386
07c1a0da
ACM
387void sighandler_dump_stack(int sig)
388{
389 psignal(sig, "perf");
390 dump_stack();
9daddf66
ACM
391 signal(sig, SIG_DFL);
392 raise(sig);
07c1a0da
ACM
393}
394
3b47abe1
NK
395int parse_nsec_time(const char *str, u64 *ptime)
396{
397 u64 time_sec, time_nsec;
398 char *end;
399
400 time_sec = strtoul(str, &end, 10);
401 if (*end != '.' && *end != '\0')
402 return -1;
403
404 if (*end == '.') {
405 int i;
406 char nsec_buf[10];
407
408 if (strlen(++end) > 9)
409 return -1;
410
411 strncpy(nsec_buf, end, 9);
412 nsec_buf[9] = '\0';
413
414 /* make it nsec precision */
415 for (i = strlen(nsec_buf); i < 9; i++)
416 nsec_buf[i] = '0';
417
418 time_nsec = strtoul(nsec_buf, &end, 10);
419 if (*end != '\0')
420 return -1;
421 } else
422 time_nsec = 0;
423
424 *ptime = time_sec * NSEC_PER_SEC + time_nsec;
425 return 0;
426}
27050f53
JO
427
428unsigned long parse_tag_value(const char *str, struct parse_tag *tags)
429{
430 struct parse_tag *i = tags;
431
432 while (i->tag) {
433 char *s;
434
435 s = strchr(str, i->tag);
436 if (s) {
437 unsigned long int value;
438 char *endptr;
439
440 value = strtoul(str, &endptr, 10);
441 if (s != endptr)
442 break;
443
56921bec
AH
444 if (value > ULONG_MAX / i->mult)
445 break;
27050f53
JO
446 value *= i->mult;
447 return value;
448 }
449 i++;
450 }
451
452 return (unsigned long) -1;
453}
97a07f10 454
076a30c4
KL
455int get_stack_size(const char *str, unsigned long *_size)
456{
457 char *endptr;
458 unsigned long size;
459 unsigned long max_size = round_down(USHRT_MAX, sizeof(u64));
460
461 size = strtoul(str, &endptr, 0);
462
463 do {
464 if (*endptr)
465 break;
466
467 size = round_up(size, sizeof(u64));
468 if (!size || size > max_size)
469 break;
470
471 *_size = size;
472 return 0;
473
474 } while (0);
475
476 pr_err("callchain: Incorrect stack dump size (max %ld): %s\n",
477 max_size, str);
478 return -1;
479}
480
481int parse_callchain_record(const char *arg, struct callchain_param *param)
482{
483 char *tok, *name, *saveptr = NULL;
484 char *buf;
485 int ret = -1;
486
487 /* We need buffer that we know we can write to. */
488 buf = malloc(strlen(arg) + 1);
489 if (!buf)
490 return -ENOMEM;
491
492 strcpy(buf, arg);
493
494 tok = strtok_r((char *)buf, ",", &saveptr);
495 name = tok ? : (char *)buf;
496
497 do {
498 /* Framepointer style */
499 if (!strncmp(name, "fp", sizeof("fp"))) {
500 if (!strtok_r(NULL, ",", &saveptr)) {
501 param->record_mode = CALLCHAIN_FP;
502 ret = 0;
503 } else
504 pr_err("callchain: No more arguments "
505 "needed for --call-graph fp\n");
506 break;
507
076a30c4
KL
508 /* Dwarf style */
509 } else if (!strncmp(name, "dwarf", sizeof("dwarf"))) {
510 const unsigned long default_stack_dump_size = 8192;
511
512 ret = 0;
513 param->record_mode = CALLCHAIN_DWARF;
514 param->dump_size = default_stack_dump_size;
515
516 tok = strtok_r(NULL, ",", &saveptr);
517 if (tok) {
518 unsigned long size = 0;
519
520 ret = get_stack_size(tok, &size);
521 param->dump_size = size;
522 }
076a30c4
KL
523 } else if (!strncmp(name, "lbr", sizeof("lbr"))) {
524 if (!strtok_r(NULL, ",", &saveptr)) {
525 param->record_mode = CALLCHAIN_LBR;
526 ret = 0;
527 } else
528 pr_err("callchain: No more arguments "
529 "needed for --call-graph lbr\n");
530 break;
531 } else {
532 pr_err("callchain: Unknown --call-graph option "
533 "value: %s\n", arg);
534 break;
535 }
536
537 } while (0);
538
539 free(buf);
540 return ret;
541}
542
e1a2b174
DY
543const char *get_filename_for_perf_kvm(void)
544{
545 const char *filename;
546
547 if (perf_host && !perf_guest)
548 filename = strdup("perf.data.host");
549 else if (!perf_host && perf_guest)
550 filename = strdup("perf.data.guest");
551 else
552 filename = strdup("perf.data.kvm");
553
554 return filename;
555}
1a47245d
AH
556
557int perf_event_paranoid(void)
558{
1a47245d
AH
559 int value;
560
ce27309f 561 if (sysctl__read_int("kernel/perf_event_paranoid", &value))
1a47245d
AH
562 return INT_MAX;
563
564 return value;
565}
71db07b1
AH
566
567void mem_bswap_32(void *src, int byte_size)
568{
569 u32 *m = src;
570 while (byte_size > 0) {
571 *m = bswap_32(*m);
572 byte_size -= sizeof(u32);
573 ++m;
574 }
575}
576
577void mem_bswap_64(void *src, int byte_size)
578{
579 u64 *m = src;
580
581 while (byte_size > 0) {
582 *m = bswap_64(*m);
583 byte_size -= sizeof(u64);
584 ++m;
585 }
586}
63914aca
JO
587
588bool find_process(const char *name)
589{
590 size_t len = strlen(name);
591 DIR *dir;
592 struct dirent *d;
593 int ret = -1;
594
595 dir = opendir(procfs__mountpoint());
596 if (!dir)
bf644563 597 return false;
63914aca
JO
598
599 /* Walk through the directory. */
600 while (ret && (d = readdir(dir)) != NULL) {
601 char path[PATH_MAX];
602 char *data;
603 size_t size;
604
605 if ((d->d_type != DT_DIR) ||
606 !strcmp(".", d->d_name) ||
607 !strcmp("..", d->d_name))
608 continue;
609
610 scnprintf(path, sizeof(path), "%s/%s/comm",
611 procfs__mountpoint(), d->d_name);
612
613 if (filename__read_str(path, &data, &size))
614 continue;
615
616 ret = strncmp(name, data, len);
617 free(data);
618 }
619
620 closedir(dir);
621 return ret ? false : true;
622}
07bc5c69
WN
623
624int
625fetch_kernel_version(unsigned int *puint, char *str,
626 size_t str_size)
627{
628 struct utsname utsname;
629 int version, patchlevel, sublevel, err;
630
631 if (uname(&utsname))
632 return -1;
633
634 if (str && str_size) {
635 strncpy(str, utsname.release, str_size);
636 str[str_size - 1] = '\0';
637 }
638
639 err = sscanf(utsname.release, "%d.%d.%d",
640 &version, &patchlevel, &sublevel);
641
642 if (err != 3) {
643 pr_debug("Unablt to get kernel version from uname '%s'\n",
644 utsname.release);
645 return -1;
646 }
647
648 if (puint)
649 *puint = (version << 16) + (patchlevel << 8) + sublevel;
650 return 0;
651}
14cbfbeb
NK
652
653const char *perf_tip(const char *dirpath)
654{
655 struct strlist *tips;
656 struct str_node *node;
657 char *tip = NULL;
658 struct strlist_config conf = {
34b7b0f9
NK
659 .dirname = dirpath,
660 .file_only = true,
14cbfbeb
NK
661 };
662
663 tips = strlist__new("tips.txt", &conf);
34b7b0f9
NK
664 if (tips == NULL)
665 return errno == ENOENT ? NULL : "Tip: get more memory! ;-p";
666
667 if (strlist__nr_entries(tips) == 0)
14cbfbeb 668 goto out;
14cbfbeb
NK
669
670 node = strlist__entry(tips, random() % strlist__nr_entries(tips));
671 if (asprintf(&tip, "Tip: %s", node->s) < 0)
672 tip = (char *)"Tip: get more memory! ;-)";
673
674out:
675 strlist__delete(tips);
676
677 return tip;
678}
40356721
JO
679
680bool is_regular_file(const char *file)
681{
682 struct stat st;
683
684 if (stat(file, &st))
685 return false;
686
687 return S_ISREG(st.st_mode);
688}
37b20151
WN
689
690int fetch_current_timestamp(char *buf, size_t sz)
691{
692 struct timeval tv;
693 struct tm tm;
694 char dt[32];
695
696 if (gettimeofday(&tv, NULL) || !localtime_r(&tv.tv_sec, &tm))
697 return -1;
698
699 if (!strftime(dt, sizeof(dt), "%Y%m%d%H%M%S", &tm))
700 return -1;
701
702 scnprintf(buf, sz, "%s%02u", dt, (unsigned)tv.tv_usec / 10000);
703
704 return 0;
705}
c339b1a9
WN
706
707void print_binary(unsigned char *data, size_t len,
708 size_t bytes_per_line, print_binary_t printer,
709 void *extra)
710{
711 size_t i, j, mask;
712
713 if (!printer)
714 return;
715
716 bytes_per_line = roundup_pow_of_two(bytes_per_line);
717 mask = bytes_per_line - 1;
718
719 printer(BINARY_PRINT_DATA_BEGIN, 0, extra);
720 for (i = 0; i < len; i++) {
721 if ((i & mask) == 0) {
722 printer(BINARY_PRINT_LINE_BEGIN, -1, extra);
723 printer(BINARY_PRINT_ADDR, i, extra);
724 }
725
726 printer(BINARY_PRINT_NUM_DATA, data[i], extra);
727
728 if (((i & mask) == mask) || i == len - 1) {
729 for (j = 0; j < mask-(i & mask); j++)
730 printer(BINARY_PRINT_NUM_PAD, -1, extra);
731
732 printer(BINARY_PRINT_SEP, i, extra);
733 for (j = i & ~mask; j <= i; j++)
734 printer(BINARY_PRINT_CHAR_DATA, data[j], extra);
735 for (j = 0; j < mask-(i & mask); j++)
736 printer(BINARY_PRINT_CHAR_PAD, i, extra);
737 printer(BINARY_PRINT_LINE_END, -1, extra);
738 }
739 }
740 printer(BINARY_PRINT_DATA_END, -1, extra);
741}
This page took 0.258682 seconds and 5 git commands to generate.