xref: /openbmc/linux/tools/perf/util/util.c (revision c819e2cf)
1 #include "../perf.h"
2 #include "util.h"
3 #include "debug.h"
4 #include <api/fs/fs.h>
5 #include <sys/mman.h>
6 #ifdef HAVE_BACKTRACE_SUPPORT
7 #include <execinfo.h>
8 #endif
9 #include <stdio.h>
10 #include <stdlib.h>
11 #include <string.h>
12 #include <errno.h>
13 #include <limits.h>
14 #include <byteswap.h>
15 #include <linux/kernel.h>
16 #include <unistd.h>
17 #include "callchain.h"
18 
19 struct callchain_param	callchain_param = {
20 	.mode	= CHAIN_GRAPH_REL,
21 	.min_percent = 0.5,
22 	.order  = ORDER_CALLEE,
23 	.key	= CCKEY_FUNCTION
24 };
25 
26 /*
27  * XXX We need to find a better place for these things...
28  */
29 unsigned int page_size;
30 int cacheline_size;
31 
32 bool test_attr__enabled;
33 
34 bool perf_host  = true;
35 bool perf_guest = false;
36 
37 char tracing_events_path[PATH_MAX + 1] = "/sys/kernel/debug/tracing/events";
38 
39 void event_attr_init(struct perf_event_attr *attr)
40 {
41 	if (!perf_host)
42 		attr->exclude_host  = 1;
43 	if (!perf_guest)
44 		attr->exclude_guest = 1;
45 	/* to capture ABI version */
46 	attr->size = sizeof(*attr);
47 }
48 
49 int mkdir_p(char *path, mode_t mode)
50 {
51 	struct stat st;
52 	int err;
53 	char *d = path;
54 
55 	if (*d != '/')
56 		return -1;
57 
58 	if (stat(path, &st) == 0)
59 		return 0;
60 
61 	while (*++d == '/');
62 
63 	while ((d = strchr(d, '/'))) {
64 		*d = '\0';
65 		err = stat(path, &st) && mkdir(path, mode);
66 		*d++ = '/';
67 		if (err)
68 			return -1;
69 		while (*d == '/')
70 			++d;
71 	}
72 	return (stat(path, &st) && mkdir(path, mode)) ? -1 : 0;
73 }
74 
75 static int slow_copyfile(const char *from, const char *to, mode_t mode)
76 {
77 	int err = -1;
78 	char *line = NULL;
79 	size_t n;
80 	FILE *from_fp = fopen(from, "r"), *to_fp;
81 	mode_t old_umask;
82 
83 	if (from_fp == NULL)
84 		goto out;
85 
86 	old_umask = umask(mode ^ 0777);
87 	to_fp = fopen(to, "w");
88 	umask(old_umask);
89 	if (to_fp == NULL)
90 		goto out_fclose_from;
91 
92 	while (getline(&line, &n, from_fp) > 0)
93 		if (fputs(line, to_fp) == EOF)
94 			goto out_fclose_to;
95 	err = 0;
96 out_fclose_to:
97 	fclose(to_fp);
98 	free(line);
99 out_fclose_from:
100 	fclose(from_fp);
101 out:
102 	return err;
103 }
104 
105 int copyfile_mode(const char *from, const char *to, mode_t mode)
106 {
107 	int fromfd, tofd;
108 	struct stat st;
109 	void *addr;
110 	int err = -1;
111 
112 	if (stat(from, &st))
113 		goto out;
114 
115 	if (st.st_size == 0) /* /proc? do it slowly... */
116 		return slow_copyfile(from, to, mode);
117 
118 	fromfd = open(from, O_RDONLY);
119 	if (fromfd < 0)
120 		goto out;
121 
122 	tofd = creat(to, mode);
123 	if (tofd < 0)
124 		goto out_close_from;
125 
126 	addr = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fromfd, 0);
127 	if (addr == MAP_FAILED)
128 		goto out_close_to;
129 
130 	if (write(tofd, addr, st.st_size) == st.st_size)
131 		err = 0;
132 
133 	munmap(addr, st.st_size);
134 out_close_to:
135 	close(tofd);
136 	if (err)
137 		unlink(to);
138 out_close_from:
139 	close(fromfd);
140 out:
141 	return err;
142 }
143 
144 int copyfile(const char *from, const char *to)
145 {
146 	return copyfile_mode(from, to, 0755);
147 }
148 
149 unsigned long convert_unit(unsigned long value, char *unit)
150 {
151 	*unit = ' ';
152 
153 	if (value > 1000) {
154 		value /= 1000;
155 		*unit = 'K';
156 	}
157 
158 	if (value > 1000) {
159 		value /= 1000;
160 		*unit = 'M';
161 	}
162 
163 	if (value > 1000) {
164 		value /= 1000;
165 		*unit = 'G';
166 	}
167 
168 	return value;
169 }
170 
171 static ssize_t ion(bool is_read, int fd, void *buf, size_t n)
172 {
173 	void *buf_start = buf;
174 	size_t left = n;
175 
176 	while (left) {
177 		ssize_t ret = is_read ? read(fd, buf, left) :
178 					write(fd, buf, left);
179 
180 		if (ret < 0 && errno == EINTR)
181 			continue;
182 		if (ret <= 0)
183 			return ret;
184 
185 		left -= ret;
186 		buf  += ret;
187 	}
188 
189 	BUG_ON((size_t)(buf - buf_start) != n);
190 	return n;
191 }
192 
193 /*
194  * Read exactly 'n' bytes or return an error.
195  */
196 ssize_t readn(int fd, void *buf, size_t n)
197 {
198 	return ion(true, fd, buf, n);
199 }
200 
201 /*
202  * Write exactly 'n' bytes or return an error.
203  */
204 ssize_t writen(int fd, void *buf, size_t n)
205 {
206 	return ion(false, fd, buf, n);
207 }
208 
209 size_t hex_width(u64 v)
210 {
211 	size_t n = 1;
212 
213 	while ((v >>= 4))
214 		++n;
215 
216 	return n;
217 }
218 
219 static int hex(char ch)
220 {
221 	if ((ch >= '0') && (ch <= '9'))
222 		return ch - '0';
223 	if ((ch >= 'a') && (ch <= 'f'))
224 		return ch - 'a' + 10;
225 	if ((ch >= 'A') && (ch <= 'F'))
226 		return ch - 'A' + 10;
227 	return -1;
228 }
229 
230 /*
231  * While we find nice hex chars, build a long_val.
232  * Return number of chars processed.
233  */
234 int hex2u64(const char *ptr, u64 *long_val)
235 {
236 	const char *p = ptr;
237 	*long_val = 0;
238 
239 	while (*p) {
240 		const int hex_val = hex(*p);
241 
242 		if (hex_val < 0)
243 			break;
244 
245 		*long_val = (*long_val << 4) | hex_val;
246 		p++;
247 	}
248 
249 	return p - ptr;
250 }
251 
252 /* Obtain a backtrace and print it to stdout. */
253 #ifdef HAVE_BACKTRACE_SUPPORT
254 void dump_stack(void)
255 {
256 	void *array[16];
257 	size_t size = backtrace(array, ARRAY_SIZE(array));
258 	char **strings = backtrace_symbols(array, size);
259 	size_t i;
260 
261 	printf("Obtained %zd stack frames.\n", size);
262 
263 	for (i = 0; i < size; i++)
264 		printf("%s\n", strings[i]);
265 
266 	free(strings);
267 }
268 #else
269 void dump_stack(void) {}
270 #endif
271 
272 void get_term_dimensions(struct winsize *ws)
273 {
274 	char *s = getenv("LINES");
275 
276 	if (s != NULL) {
277 		ws->ws_row = atoi(s);
278 		s = getenv("COLUMNS");
279 		if (s != NULL) {
280 			ws->ws_col = atoi(s);
281 			if (ws->ws_row && ws->ws_col)
282 				return;
283 		}
284 	}
285 #ifdef TIOCGWINSZ
286 	if (ioctl(1, TIOCGWINSZ, ws) == 0 &&
287 	    ws->ws_row && ws->ws_col)
288 		return;
289 #endif
290 	ws->ws_row = 25;
291 	ws->ws_col = 80;
292 }
293 
294 void set_term_quiet_input(struct termios *old)
295 {
296 	struct termios tc;
297 
298 	tcgetattr(0, old);
299 	tc = *old;
300 	tc.c_lflag &= ~(ICANON | ECHO);
301 	tc.c_cc[VMIN] = 0;
302 	tc.c_cc[VTIME] = 0;
303 	tcsetattr(0, TCSANOW, &tc);
304 }
305 
306 static void set_tracing_events_path(const char *tracing, const char *mountpoint)
307 {
308 	snprintf(tracing_events_path, sizeof(tracing_events_path), "%s/%s%s",
309 		 mountpoint, tracing, "events");
310 }
311 
312 static const char *__perf_tracefs_mount(const char *mountpoint)
313 {
314 	const char *mnt;
315 
316 	mnt = tracefs_mount(mountpoint);
317 	if (!mnt)
318 		return NULL;
319 
320 	set_tracing_events_path("", mnt);
321 
322 	return mnt;
323 }
324 
325 static const char *__perf_debugfs_mount(const char *mountpoint)
326 {
327 	const char *mnt;
328 
329 	mnt = debugfs_mount(mountpoint);
330 	if (!mnt)
331 		return NULL;
332 
333 	set_tracing_events_path("tracing/", mnt);
334 
335 	return mnt;
336 }
337 
338 const char *perf_debugfs_mount(const char *mountpoint)
339 {
340 	const char *mnt;
341 
342 	mnt = __perf_tracefs_mount(mountpoint);
343 	if (mnt)
344 		return mnt;
345 
346 	mnt = __perf_debugfs_mount(mountpoint);
347 
348 	return mnt;
349 }
350 
351 void perf_debugfs_set_path(const char *mntpt)
352 {
353 	snprintf(debugfs_mountpoint, strlen(debugfs_mountpoint), "%s", mntpt);
354 	set_tracing_events_path("tracing/", mntpt);
355 }
356 
357 static const char *find_tracefs(void)
358 {
359 	const char *path = __perf_tracefs_mount(NULL);
360 
361 	return path;
362 }
363 
364 static const char *find_debugfs(void)
365 {
366 	const char *path = __perf_debugfs_mount(NULL);
367 
368 	if (!path)
369 		fprintf(stderr, "Your kernel does not support the debugfs filesystem");
370 
371 	return path;
372 }
373 
374 /*
375  * Finds the path to the debugfs/tracing
376  * Allocates the string and stores it.
377  */
378 const char *find_tracing_dir(void)
379 {
380 	const char *tracing_dir = "";
381 	static char *tracing;
382 	static int tracing_found;
383 	const char *debugfs;
384 
385 	if (tracing_found)
386 		return tracing;
387 
388 	debugfs = find_tracefs();
389 	if (!debugfs) {
390 		tracing_dir = "/tracing";
391 		debugfs = find_debugfs();
392 		if (!debugfs)
393 			return NULL;
394 	}
395 
396 	if (asprintf(&tracing, "%s%s", debugfs, tracing_dir) < 0)
397 		return NULL;
398 
399 	tracing_found = 1;
400 	return tracing;
401 }
402 
403 char *get_tracing_file(const char *name)
404 {
405 	const char *tracing;
406 	char *file;
407 
408 	tracing = find_tracing_dir();
409 	if (!tracing)
410 		return NULL;
411 
412 	if (asprintf(&file, "%s/%s", tracing, name) < 0)
413 		return NULL;
414 
415 	return file;
416 }
417 
418 void put_tracing_file(char *file)
419 {
420 	free(file);
421 }
422 
423 int parse_nsec_time(const char *str, u64 *ptime)
424 {
425 	u64 time_sec, time_nsec;
426 	char *end;
427 
428 	time_sec = strtoul(str, &end, 10);
429 	if (*end != '.' && *end != '\0')
430 		return -1;
431 
432 	if (*end == '.') {
433 		int i;
434 		char nsec_buf[10];
435 
436 		if (strlen(++end) > 9)
437 			return -1;
438 
439 		strncpy(nsec_buf, end, 9);
440 		nsec_buf[9] = '\0';
441 
442 		/* make it nsec precision */
443 		for (i = strlen(nsec_buf); i < 9; i++)
444 			nsec_buf[i] = '0';
445 
446 		time_nsec = strtoul(nsec_buf, &end, 10);
447 		if (*end != '\0')
448 			return -1;
449 	} else
450 		time_nsec = 0;
451 
452 	*ptime = time_sec * NSEC_PER_SEC + time_nsec;
453 	return 0;
454 }
455 
456 unsigned long parse_tag_value(const char *str, struct parse_tag *tags)
457 {
458 	struct parse_tag *i = tags;
459 
460 	while (i->tag) {
461 		char *s;
462 
463 		s = strchr(str, i->tag);
464 		if (s) {
465 			unsigned long int value;
466 			char *endptr;
467 
468 			value = strtoul(str, &endptr, 10);
469 			if (s != endptr)
470 				break;
471 
472 			if (value > ULONG_MAX / i->mult)
473 				break;
474 			value *= i->mult;
475 			return value;
476 		}
477 		i++;
478 	}
479 
480 	return (unsigned long) -1;
481 }
482 
483 int filename__read_str(const char *filename, char **buf, size_t *sizep)
484 {
485 	size_t size = 0, alloc_size = 0;
486 	void *bf = NULL, *nbf;
487 	int fd, n, err = 0;
488 	char sbuf[STRERR_BUFSIZE];
489 
490 	fd = open(filename, O_RDONLY);
491 	if (fd < 0)
492 		return -errno;
493 
494 	do {
495 		if (size == alloc_size) {
496 			alloc_size += BUFSIZ;
497 			nbf = realloc(bf, alloc_size);
498 			if (!nbf) {
499 				err = -ENOMEM;
500 				break;
501 			}
502 
503 			bf = nbf;
504 		}
505 
506 		n = read(fd, bf + size, alloc_size - size);
507 		if (n < 0) {
508 			if (size) {
509 				pr_warning("read failed %d: %s\n", errno,
510 					 strerror_r(errno, sbuf, sizeof(sbuf)));
511 				err = 0;
512 			} else
513 				err = -errno;
514 
515 			break;
516 		}
517 
518 		size += n;
519 	} while (n > 0);
520 
521 	if (!err) {
522 		*sizep = size;
523 		*buf   = bf;
524 	} else
525 		free(bf);
526 
527 	close(fd);
528 	return err;
529 }
530 
531 const char *get_filename_for_perf_kvm(void)
532 {
533 	const char *filename;
534 
535 	if (perf_host && !perf_guest)
536 		filename = strdup("perf.data.host");
537 	else if (!perf_host && perf_guest)
538 		filename = strdup("perf.data.guest");
539 	else
540 		filename = strdup("perf.data.kvm");
541 
542 	return filename;
543 }
544 
545 int perf_event_paranoid(void)
546 {
547 	int value;
548 
549 	if (sysctl__read_int("kernel/perf_event_paranoid", &value))
550 		return INT_MAX;
551 
552 	return value;
553 }
554 
555 void mem_bswap_32(void *src, int byte_size)
556 {
557 	u32 *m = src;
558 	while (byte_size > 0) {
559 		*m = bswap_32(*m);
560 		byte_size -= sizeof(u32);
561 		++m;
562 	}
563 }
564 
565 void mem_bswap_64(void *src, int byte_size)
566 {
567 	u64 *m = src;
568 
569 	while (byte_size > 0) {
570 		*m = bswap_64(*m);
571 		byte_size -= sizeof(u64);
572 		++m;
573 	}
574 }
575 
576 bool find_process(const char *name)
577 {
578 	size_t len = strlen(name);
579 	DIR *dir;
580 	struct dirent *d;
581 	int ret = -1;
582 
583 	dir = opendir(procfs__mountpoint());
584 	if (!dir)
585 		return -1;
586 
587 	/* Walk through the directory. */
588 	while (ret && (d = readdir(dir)) != NULL) {
589 		char path[PATH_MAX];
590 		char *data;
591 		size_t size;
592 
593 		if ((d->d_type != DT_DIR) ||
594 		     !strcmp(".", d->d_name) ||
595 		     !strcmp("..", d->d_name))
596 			continue;
597 
598 		scnprintf(path, sizeof(path), "%s/%s/comm",
599 			  procfs__mountpoint(), d->d_name);
600 
601 		if (filename__read_str(path, &data, &size))
602 			continue;
603 
604 		ret = strncmp(name, data, len);
605 		free(data);
606 	}
607 
608 	closedir(dir);
609 	return ret ? false : true;
610 }
611