xref: /netbsd-src/usr.sbin/tprof/tprof.c (revision 7d62b00eb9ad855ffcd7da46b41e23feb5476fac)
1 /*	$NetBSD: tprof.c,v 1.20 2022/12/26 08:00:13 ryo Exp $	*/
2 
3 /*
4  * Copyright (c) 2018 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Maxime Villard.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Copyright (c)2008 YAMAMOTO Takashi,
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  *
45  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
46  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
47  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
48  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
49  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
50  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
51  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
52  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
53  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
54  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
55  * SUCH DAMAGE.
56  */
57 
58 #include <sys/cdefs.h>
59 #ifndef lint
60 __RCSID("$NetBSD: tprof.c,v 1.20 2022/12/26 08:00:13 ryo Exp $");
61 #endif /* not lint */
62 
63 #include <sys/atomic.h>
64 #include <sys/ioctl.h>
65 #include <sys/sysctl.h>
66 #include <sys/wait.h>
67 
68 #include <dev/tprof/tprof_ioctl.h>
69 
70 #include <err.h>
71 #include <errno.h>
72 #include <fcntl.h>
73 #include <inttypes.h>
74 #include <math.h>
75 #include <pthread.h>
76 #include <signal.h>
77 #include <stdbool.h>
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <string.h>
81 #include <time.h>
82 #include <unistd.h>
83 #include <util.h>
84 #include "tprof.h"
85 
86 #define	_PATH_TPROF	"/dev/tprof"
87 
88 struct tprof_info tprof_info;
89 u_int ncounters;
90 int devfd;
91 int outfd;
92 int ncpu;
93 u_int nevent;
94 double interval = 0xffffffff;	/* XXX */
95 const char *eventname[TPROF_MAXCOUNTERS];
96 u_int eventnamewidth[TPROF_MAXCOUNTERS];
97 #define	COUNTER_COLUMNS_WIDTH	11
98 
99 static void tprof_list(int, char **);
100 static void tprof_monitor_common(bool, int, char **) __dead;
101 static void tprof_monitor(int, char **) __dead;
102 static void tprof_count(int, char **) __dead;
103 
104 static struct cmdtab {
105 	const char *label;
106 	bool takesargs;
107 	bool argsoptional;
108 	void (*func)(int, char **);
109 } const tprof_cmdtab[] = {
110 	{ "list",	false, false, tprof_list },
111 	{ "monitor",	true,  false, tprof_monitor },
112 	{ "count",	true,  false, tprof_count },
113 	{ "analyze",	true,  true,  tprof_analyze },
114 	{ "top",	true,  true,  tprof_top },
115 	{ NULL,		false, false, NULL },
116 };
117 
118 __dead static void
119 usage(void)
120 {
121 
122 	fprintf(stderr, "%s op [arguments]\n", getprogname());
123 	fprintf(stderr, "\n");
124 	fprintf(stderr, "\tlist\n");
125 	fprintf(stderr, "\t\tList the available events.\n");
126 	fprintf(stderr, "\tmonitor -e name[:option] [-e ...] [-o outfile]"
127 	    " command\n");
128 	fprintf(stderr, "\t\tMonitor the event 'name' with option 'option'\n"
129 	    "\t\tcounted during the execution of 'command'.\n");
130 	fprintf(stderr, "\tcount -e name[:option] [-e ...] [-i interval]"
131 	    " command\n");
132 	fprintf(stderr, "\t\tSame as monitor, but does not profile,"
133 	    " only outputs a counter.\n");
134 	fprintf(stderr, "\tanalyze [-CkLPs] [-p pid] file\n");
135 	fprintf(stderr, "\t\tAnalyze the samples of the file 'file'.\n");
136 	fprintf(stderr, "\ttop [-e name [-e ...]] [-i interval] [-acu]\n");
137 	fprintf(stderr, "\t\tDisplay profiling results in real-time.\n");
138 	exit(EXIT_FAILURE);
139 }
140 
141 static int
142 getncpu(void)
143 {
144 	size_t size;
145 	int mib[2];
146 
147 	mib[0] = CTL_HW;
148 	mib[1] = HW_NCPU;
149 	size = sizeof(ncpu);
150 	if (sysctl(mib, 2, &ncpu, &size, NULL, 0) == -1)
151 		ncpu = 1;
152 	return ncpu;
153 }
154 
155 static void *
156 process_samples(void *dummy)
157 {
158 
159 	for (;;) {
160 		char buf[4096];
161 		const char *cp;
162 		ssize_t ssz;
163 
164 		ssz = read(devfd, buf, sizeof(buf));
165 		if (ssz == -1) {
166 			err(EXIT_FAILURE, "read");
167 		}
168 		if (ssz == 0) {
169 			break;
170 		}
171 		cp = buf;
172 		while (ssz) {
173 			ssize_t wsz;
174 
175 			wsz = write(outfd, cp, ssz);
176 			if (wsz == -1) {
177 				err(EXIT_FAILURE, "write");
178 			}
179 			ssz -= wsz;
180 			cp += wsz;
181 		}
182 	}
183 	return NULL;
184 }
185 
186 static void
187 show_counters(void)
188 {
189 	unsigned int i;
190 	int n, ret;
191 
192 	fprintf(stderr, "      ");
193 	for (i = 0; i < nevent; i++)
194 		fprintf(stderr, " %*s", eventnamewidth[i], eventname[i]);
195 	fprintf(stderr, "\n");
196 
197 	for (n = 0; n < ncpu; n++) {
198 		tprof_counts_t counts;
199 
200 		memset(&counts, 0, sizeof(counts));
201 		counts.c_cpu = n;
202 		ret = ioctl(devfd, TPROF_IOC_GETCOUNTS, &counts);
203 		if (ret == -1)
204 			err(EXIT_FAILURE, "TPROF_IOC_GETCOUNTS");
205 
206 		fprintf(stderr, "CPU%-3d", n);
207 		for (i = 0; i < nevent; i++) {
208 			fprintf(stderr, " %*"PRIu64,
209 			    eventnamewidth[i], counts.c_count[i]);
210 		}
211 		fprintf(stderr, "\n");
212 	}
213 }
214 
215 /* XXX: avoid mixing with the output of the child process SIGINFO handler... */
216 static void
217 output_delay(void)
218 {
219 	struct timespec delay_ts;
220 
221 	delay_ts.tv_sec = 0;
222 	delay_ts.tv_nsec = 100000000;
223 	nanosleep(&delay_ts, NULL);
224 }
225 
226 static void
227 siginfo_nothing(int signo)
228 {
229 	__nothing;
230 }
231 
232 static void
233 siginfo_showcount(int signo)
234 {
235 	output_delay();
236 	show_counters();
237 }
238 
239 static void *
240 process_stat(void *arg)
241 {
242 	unsigned int *done = arg;
243 	double ival, fval;
244 	struct timespec ts;
245 
246 	ival = floor(interval);
247 	fval = (1000000000 * (interval - ival));
248 	ts.tv_sec = ival;
249 	ts.tv_nsec = fval;
250 
251 	while (atomic_add_int_nv(done, 0) == 0) {
252 		show_counters();
253 		nanosleep(&ts, NULL);
254 		if (errno == EINTR)	/* interrupted by SIGINFO? */
255 			output_delay();
256 	}
257 	return NULL;
258 }
259 
260 static void
261 tprof_list(int argc, char **argv)
262 {
263 	printf("%u events can be counted at the same time\n", ncounters);
264 	tprof_event_list();
265 }
266 
267 int
268 tprof_parse_event(tprof_param_t *param, const char *str, uint32_t flags,
269     const char **eventnamep, char **errmsgp)
270 {
271 	double d;
272 	uint64_t n;
273 	int error = 0;
274 	char *p, *event = NULL, *opt = NULL, *scale = NULL;
275 	bool allow_option, allow_scale;
276 	static char errmsgbuf[128];
277 
278 	allow_option = flags & TPROF_PARSE_EVENT_F_ALLOWOPTION;
279 	allow_scale = flags & TPROF_PARSE_EVENT_F_ALLOWSCALE;
280 
281 	p = estrdup(str);
282 	event = p;
283 	if (allow_option) {
284 		opt = strchr(p, ':');
285 		if (opt != NULL) {
286 			*opt++ = '\0';
287 			p = opt;
288 		}
289 	}
290 	if (allow_scale) {
291 		scale = strchr(p, ',');
292 		if (scale != NULL)
293 			*scale++ = '\0';
294 	}
295 
296 	tprof_event_lookup(event, param);
297 
298 	if (opt != NULL) {
299 		while (*opt != '\0') {
300 			switch (*opt) {
301 			case 'u':
302 				param->p_flags |= TPROF_PARAM_USER;
303 				break;
304 			case 'k':
305 				param->p_flags |= TPROF_PARAM_KERN;
306 				break;
307 			default:
308 				error = -1;
309 				snprintf(errmsgbuf, sizeof(errmsgbuf),
310 				    "invalid option: '%c'", *opt);
311 				goto done;
312 			}
313 			opt++;
314 		}
315 	} else if (allow_option) {
316 		param->p_flags |= TPROF_PARAM_USER;
317 		param->p_flags |= TPROF_PARAM_KERN;
318 	}
319 
320 	if (scale != NULL) {
321 		if (*scale == '=') {
322 			scale++;
323 			n = strtoull(scale, &p, 0);
324 			if (*p != '\0') {
325 				error = -1;
326 			} else {
327 				param->p_value2 = n;
328 				param->p_flags |=
329 				    TPROF_PARAM_VALUE2_TRIGGERCOUNT;
330 			}
331 		} else {
332 			if (strncasecmp("0x", scale, 2) == 0)
333 				d = strtol(scale, &p, 0);
334 			else
335 				d = strtod(scale, &p);
336 			if (*p != '\0' || d <= 0) {
337 				error = -1;
338 			} else {
339 				param->p_value2 = 0x100000000ULL / d;
340 				param->p_flags |= TPROF_PARAM_VALUE2_SCALE;
341 			}
342 		}
343 
344 		if (error != 0) {
345 			snprintf(errmsgbuf, sizeof(errmsgbuf),
346 			    "invalid scale: %s", scale);
347 			goto done;
348 		}
349 	}
350 
351  done:
352 	if (eventnamep != NULL)
353 		*eventnamep = event;
354 	if (error != 0 && errmsgp != NULL)
355 		*errmsgp = errmsgbuf;
356 	return error;
357 }
358 
359 static void
360 tprof_monitor_common(bool do_profile, int argc, char **argv)
361 {
362 	const char *outfile = "tprof.out";
363 	struct tprof_stat ts;
364 	tprof_param_t params[TPROF_MAXCOUNTERS];
365 	pid_t pid;
366 	pthread_t pt;
367 	int ret, ch, i;
368 	char *p, *errmsg;
369 	tprof_countermask_t mask = TPROF_COUNTERMASK_ALL;
370 
371 	memset(params, 0, sizeof(params));
372 
373 	while ((ch = getopt(argc, argv, do_profile ? "o:e:" : "e:i:")) != -1) {
374 		switch (ch) {
375 		case 'o':
376 			outfile = optarg;
377 			break;
378 		case 'i':
379 			interval = strtod(optarg, &p);
380 			if (*p != '\0' || interval <= 0)
381 				errx(EXIT_FAILURE, "Bad/invalid interval: %s",
382 				    optarg);
383 			break;
384 		case 'e':
385 			if (tprof_parse_event(&params[nevent], optarg,
386 			    TPROF_PARSE_EVENT_F_ALLOWOPTION |
387 			    (do_profile ? TPROF_PARSE_EVENT_F_ALLOWSCALE : 0),
388 			    &eventname[nevent], &errmsg) != 0) {
389 				errx(EXIT_FAILURE, "%s", errmsg);
390 			}
391 			eventnamewidth[nevent] = strlen(eventname[nevent]);
392 			if (eventnamewidth[nevent] < COUNTER_COLUMNS_WIDTH)
393 				eventnamewidth[nevent] = COUNTER_COLUMNS_WIDTH;
394 			nevent++;
395 			if (nevent > __arraycount(params) ||
396 			    nevent > ncounters)
397 				errx(EXIT_FAILURE, "Too many events. Only a"
398 				    " maximum of %d counters can be used.",
399 				    ncounters);
400 			break;
401 		default:
402 			usage();
403 		}
404 	}
405 	argc -= optind;
406 	argv += optind;
407 	if (argc == 0 || nevent == 0) {
408 		usage();
409 	}
410 
411 	if (do_profile) {
412 		outfd = open(outfile, O_WRONLY | O_CREAT | O_TRUNC, 0666);
413 		if (outfd == -1) {
414 			err(EXIT_FAILURE, "%s", outfile);
415 		}
416 	}
417 
418 	for (i = 0; i < (int)nevent; i++) {
419 		params[i].p_counter = i;
420 		if (do_profile)
421 			params[i].p_flags |= TPROF_PARAM_PROFILE;
422 		ret = ioctl(devfd, TPROF_IOC_CONFIGURE_EVENT, &params[i]);
423 		if (ret == -1) {
424 			err(EXIT_FAILURE, "TPROF_IOC_CONFIGURE_EVENT: %s",
425 			    eventname[i]);
426 		}
427 	}
428 
429 	ret = ioctl(devfd, TPROF_IOC_START, &mask);
430 	if (ret == -1) {
431 		err(EXIT_FAILURE, "TPROF_IOC_START");
432 	}
433 
434 	pid = fork();
435 	switch (pid) {
436 	case -1:
437 		err(EXIT_FAILURE, "fork");
438 	case 0:
439 		close(devfd);
440 		execvp(argv[0], argv);
441 		_Exit(EXIT_FAILURE);
442 	}
443 
444 	signal(SIGINT, SIG_IGN);
445 	if (do_profile)
446 		signal(SIGINFO, siginfo_showcount);
447 	else
448 		signal(SIGINFO, siginfo_nothing);
449 
450 	unsigned int done = 0;
451 	if (do_profile)
452 		ret = pthread_create(&pt, NULL, process_samples, NULL);
453 	else
454 		ret = pthread_create(&pt, NULL, process_stat, &done);
455 	if (ret != 0)
456 		errx(1, "pthread_create: %s", strerror(ret));
457 
458 	for (;;) {
459 		int status;
460 
461 		pid = wait4(-1, &status, 0, NULL);
462 		if (pid == -1) {
463 			if (errno == ECHILD) {
464 				break;
465 			}
466 			err(EXIT_FAILURE, "wait4");
467 		}
468 		if (pid != 0 && WIFEXITED(status)) {
469 			break;
470 		}
471 	}
472 
473 	ret = ioctl(devfd, TPROF_IOC_STOP, &mask);
474 	if (ret == -1) {
475 		err(EXIT_FAILURE, "TPROF_IOC_STOP");
476 	}
477 
478 	if (!do_profile) {
479 		atomic_add_int(&done, 1);	/* terminate thread */
480 		kill(0, SIGINFO);
481 	}
482 
483 	pthread_join(pt, NULL);
484 
485 	if (do_profile) {
486 		ret = ioctl(devfd, TPROF_IOC_GETSTAT, &ts);
487 		if (ret == -1)
488 			err(EXIT_FAILURE, "TPROF_IOC_GETSTAT");
489 
490 		fprintf(stderr, "\n%s statistics:\n", getprogname());
491 		fprintf(stderr, "\tsample %" PRIu64 "\n", ts.ts_sample);
492 		fprintf(stderr, "\toverflow %" PRIu64 "\n", ts.ts_overflow);
493 		fprintf(stderr, "\tbuf %" PRIu64 "\n", ts.ts_buf);
494 		fprintf(stderr, "\temptybuf %" PRIu64 "\n", ts.ts_emptybuf);
495 		fprintf(stderr, "\tdropbuf %" PRIu64 "\n", ts.ts_dropbuf);
496 		fprintf(stderr, "\tdropbuf_sample %" PRIu64 "\n",
497 		    ts.ts_dropbuf_sample);
498 
499 		fprintf(stderr, "\n");
500 	}
501 	show_counters();
502 
503 	exit(EXIT_SUCCESS);
504 }
505 
506 static void
507 tprof_monitor(int argc, char **argv)
508 {
509 	tprof_monitor_common(true, argc, argv);
510 }
511 
512 static void
513 tprof_count(int argc, char **argv)
514 {
515 	tprof_monitor_common(false, argc, argv);
516 }
517 
518 int
519 main(int argc, char *argv[])
520 {
521 	const struct cmdtab *ct;
522 	int ret;
523 
524 	getncpu();
525 	setprogname(argv[0]);
526 	argv += 1, argc -= 1;
527 
528 	devfd = open(_PATH_TPROF, O_RDWR);
529 	if (devfd == -1) {
530 		err(EXIT_FAILURE, "%s", _PATH_TPROF);
531 	}
532 
533 	ret = ioctl(devfd, TPROF_IOC_GETINFO, &tprof_info);
534 	if (ret == -1) {
535 		err(EXIT_FAILURE, "TPROF_IOC_GETINFO");
536 	}
537 	if (tprof_info.ti_version != TPROF_VERSION) {
538 		errx(EXIT_FAILURE, "version mismatch: version=%d, expected=%d",
539 		    tprof_info.ti_version, TPROF_VERSION);
540 	}
541 	if (tprof_event_init(tprof_info.ti_ident) == -1) {
542 		errx(EXIT_FAILURE, "cpu not supported");
543 	}
544 
545 	ret = ioctl(devfd, TPROF_IOC_GETNCOUNTERS, &ncounters);
546 	if (ret == -1) {
547 		err(EXIT_FAILURE, "TPROF_IOC_GETNCOUNTERS");
548 	}
549 	if (ncounters == 0) {
550 		errx(EXIT_FAILURE, "no available counters");
551 	}
552 
553 	if (argc == 0)
554 		usage();
555 
556 	for (ct = tprof_cmdtab; ct->label != NULL; ct++) {
557 		if (strcmp(argv[0], ct->label) == 0) {
558 			if (!ct->argsoptional &&
559 			    ((ct->takesargs == 0) ^ (argv[1] == NULL)))
560 			{
561 				usage();
562 			}
563 			(*ct->func)(argc, argv);
564 			break;
565 		}
566 	}
567 	if (ct->label == NULL) {
568 		usage();
569 	}
570 }
571