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