tprof.c revision 1.15
1/*	$NetBSD: tprof.c,v 1.15 2022/12/01 00:40:05 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.15 2022/12/01 00:40:05 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
88struct tprof_info tprof_info;
89u_int ncounters;
90int devfd;
91int outfd;
92int ncpu;
93u_int nevent;
94double interval = 0xffffffff;	/* XXX */
95const char *eventname[TPROF_MAXCOUNTERS];
96u_int eventnamewidth[TPROF_MAXCOUNTERS];
97#define	COUNTER_COLUMNS_WIDTH	11
98
99static void tprof_list(int, char **);
100static void tprof_monitor_common(bool, int, char **) __dead;
101static void tprof_monitor(int, char **);
102static void tprof_count(int, char **);
103
104static 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	{ NULL,		false, false, NULL },
115};
116
117__dead static void
118usage(void)
119{
120
121	fprintf(stderr, "%s op [arguments]\n", getprogname());
122	fprintf(stderr, "\n");
123	fprintf(stderr, "\tlist\n");
124	fprintf(stderr, "\t\tList the available events.\n");
125	fprintf(stderr, "\tmonitor -e name[:option] [-e ...] [-o outfile] command\n");
126	fprintf(stderr, "\t\tMonitor the event 'name' with option 'option'\n"
127	    "\t\tcounted during the execution of 'command'.\n");
128	fprintf(stderr, "\tcount -e name[:option] [-e ...] [-i interval]"
129	    " command\n");
130	fprintf(stderr, "\t\tSame as monitor, but does not profile,"
131	    " only outputs a counter.\n");
132	fprintf(stderr, "\tanalyze [-CkLPs] [-p pid] file\n");
133	fprintf(stderr, "\t\tAnalyze the samples of the file 'file'.\n");
134
135	exit(EXIT_FAILURE);
136}
137
138static int
139getncpu(void)
140{
141	size_t size;
142	int mib[2];
143
144	mib[0] = CTL_HW;
145	mib[1] = HW_NCPU;
146	size = sizeof(ncpu);
147	if (sysctl(mib, 2, &ncpu, &size, NULL, 0) == -1)
148		ncpu = 1;
149	return ncpu;
150}
151
152static void *
153process_samples(void *dummy)
154{
155
156	for (;;) {
157		char buf[4096];
158		const char *cp;
159		ssize_t ssz;
160
161		ssz = read(devfd, buf, sizeof(buf));
162		if (ssz == -1) {
163			err(EXIT_FAILURE, "read");
164		}
165		if (ssz == 0) {
166			break;
167		}
168		cp = buf;
169		while (ssz) {
170			ssize_t wsz;
171
172			wsz = write(outfd, cp, ssz);
173			if (wsz == -1) {
174				err(EXIT_FAILURE, "write");
175			}
176			ssz -= wsz;
177			cp += wsz;
178		}
179	}
180	return NULL;
181}
182
183static void
184show_counters(void)
185{
186	unsigned int i;
187	int n, ret;
188
189	fprintf(stderr, "      ");
190	for (i = 0; i < nevent; i++)
191		fprintf(stderr, " %*s", eventnamewidth[i], eventname[i]);
192	fprintf(stderr, "\n");
193
194	for (n = 0; n < ncpu; n++) {
195		tprof_counts_t counts;
196
197		memset(&counts, 0, sizeof(counts));
198		counts.c_cpu = n;
199		ret = ioctl(devfd, TPROF_IOC_GETCOUNTS, &counts);
200		if (ret == -1)
201			err(EXIT_FAILURE, "TPROF_IOC_GETCOUNTS");
202
203		fprintf(stderr, "CPU%-3d", n);
204		for (i = 0; i < nevent; i++) {
205			fprintf(stderr, " %*"PRIu64,
206			    eventnamewidth[i], counts.c_count[i]);
207		}
208		fprintf(stderr, "\n");
209	}
210}
211
212/* XXX: avoid mixing with the output of the child process SIGINFO handler... */
213static void
214output_delay(void)
215{
216	struct timespec delay_ts;
217
218	delay_ts.tv_sec = 0;
219	delay_ts.tv_nsec = 100000000;
220	nanosleep(&delay_ts, NULL);
221}
222
223static void
224siginfo_nothing(int signo)
225{
226	__nothing;
227}
228
229static void
230siginfo_showcount(int signo)
231{
232	output_delay();
233	show_counters();
234}
235
236static void *
237process_stat(void *arg)
238{
239	unsigned int *done = arg;
240	double ival, fval;
241	struct timespec ts;
242
243	ival = floor(interval);
244	fval = (1000000000 * (interval - ival));
245	ts.tv_sec = ival;
246	ts.tv_nsec = fval;
247
248	while (atomic_add_int_nv(done, 0) == 0) {
249		show_counters();
250		nanosleep(&ts, NULL);
251		if (errno == EINTR)	/* interrupted by SIGINFO? */
252			output_delay();
253	}
254	return NULL;
255}
256
257static void
258tprof_list(int argc, char **argv)
259{
260	tprof_event_list();
261}
262
263static void
264tprof_monitor_common(bool do_profile, int argc, char **argv)
265{
266	const char *outfile = "tprof.out";
267	struct tprof_stat ts;
268	tprof_param_t params[TPROF_MAXCOUNTERS];
269	pid_t pid;
270	pthread_t pt;
271	int ret, ch, i;
272	char *tokens[2], *p;
273	tprof_countermask_t mask = TPROF_COUNTERMASK_ALL;
274
275	memset(params, 0, sizeof(params));
276
277	while ((ch = getopt(argc, argv, do_profile ? "o:e:" : "e:i:")) != -1) {
278		switch (ch) {
279		case 'o':
280			outfile = optarg;
281			break;
282		case 'i':
283			interval = strtod(optarg, &p);
284			if (*p != '\0' || interval <= 0)
285				errx(EXIT_FAILURE, "Bad/invalid interval: %s",
286				    optarg);
287			break;
288		case 'e':
289			p = estrdup(optarg);
290			tokens[0] = strtok(p, ":");
291			tokens[1] = strtok(NULL, ":");
292			tprof_event_lookup(tokens[0], &params[nevent]);
293
294			if (tokens[1] == NULL) {
295				params[nevent].p_flags |=
296				    (TPROF_PARAM_USER | TPROF_PARAM_KERN);
297			} else {
298				if (strchr(tokens[1], 'u'))
299					params[nevent].p_flags |=
300					    TPROF_PARAM_USER;
301				if (strchr(tokens[1], 'k'))
302					params[nevent].p_flags |=
303					    TPROF_PARAM_KERN;
304			}
305			eventname[nevent] = tokens[0];
306			eventnamewidth[nevent] = strlen(eventname[nevent]);
307			if (eventnamewidth[nevent] < COUNTER_COLUMNS_WIDTH)
308				eventnamewidth[nevent] = COUNTER_COLUMNS_WIDTH;
309			nevent++;
310			if (nevent > __arraycount(params) ||
311			    nevent > ncounters)
312				errx(EXIT_FAILURE, "Too many events");
313			break;
314		default:
315			usage();
316		}
317	}
318	argc -= optind;
319	argv += optind;
320	if (argc == 0 || nevent == 0) {
321		usage();
322	}
323
324	if (do_profile) {
325		outfd = open(outfile, O_WRONLY | O_CREAT | O_TRUNC, 0666);
326		if (outfd == -1) {
327			err(EXIT_FAILURE, "%s", outfile);
328		}
329	}
330
331	for (i = 0; i < (int)nevent; i++) {
332		params[i].p_counter = i;
333		if (do_profile)
334			params[i].p_flags |= TPROF_PARAM_PROFILE;
335		ret = ioctl(devfd, TPROF_IOC_CONFIGURE_EVENT, &params[i]);
336		if (ret == -1)
337			err(EXIT_FAILURE, "TPROF_IOC_CONFIGURE_EVENT");
338	}
339
340	ret = ioctl(devfd, TPROF_IOC_START, &mask);
341	if (ret == -1) {
342		err(EXIT_FAILURE, "TPROF_IOC_START");
343	}
344
345	pid = fork();
346	switch (pid) {
347	case -1:
348		err(EXIT_FAILURE, "fork");
349	case 0:
350		close(devfd);
351		execvp(argv[0], argv);
352		_Exit(EXIT_FAILURE);
353	}
354
355	signal(SIGINT, SIG_IGN);
356	if (do_profile)
357		signal(SIGINFO, siginfo_showcount);
358	else
359		signal(SIGINFO, siginfo_nothing);
360
361	unsigned int done = 0;
362	if (do_profile)
363		ret = pthread_create(&pt, NULL, process_samples, NULL);
364	else
365		ret = pthread_create(&pt, NULL, process_stat, &done);
366	if (ret != 0)
367		errx(1, "pthread_create: %s", strerror(ret));
368
369	for (;;) {
370		int status;
371
372		pid = wait4(-1, &status, 0, NULL);
373		if (pid == -1) {
374			if (errno == ECHILD) {
375				break;
376			}
377			err(EXIT_FAILURE, "wait4");
378		}
379		if (pid != 0 && WIFEXITED(status)) {
380			break;
381		}
382	}
383
384	ret = ioctl(devfd, TPROF_IOC_STOP, &mask);
385	if (ret == -1) {
386		err(EXIT_FAILURE, "TPROF_IOC_STOP");
387	}
388
389	if (!do_profile) {
390		atomic_add_int(&done, 1);	/* terminate thread */
391		kill(0, SIGINFO);
392	}
393
394	pthread_join(pt, NULL);
395
396	if (do_profile) {
397		ret = ioctl(devfd, TPROF_IOC_GETSTAT, &ts);
398		if (ret == -1)
399			err(EXIT_FAILURE, "TPROF_IOC_GETSTAT");
400
401		fprintf(stderr, "\n%s statistics:\n", getprogname());
402		fprintf(stderr, "\tsample %" PRIu64 "\n", ts.ts_sample);
403		fprintf(stderr, "\toverflow %" PRIu64 "\n", ts.ts_overflow);
404		fprintf(stderr, "\tbuf %" PRIu64 "\n", ts.ts_buf);
405		fprintf(stderr, "\temptybuf %" PRIu64 "\n", ts.ts_emptybuf);
406		fprintf(stderr, "\tdropbuf %" PRIu64 "\n", ts.ts_dropbuf);
407		fprintf(stderr, "\tdropbuf_sample %" PRIu64 "\n", ts.ts_dropbuf_sample);
408
409		fprintf(stderr, "\n");
410	}
411	show_counters();
412
413	exit(EXIT_SUCCESS);
414}
415
416static void
417tprof_monitor(int argc, char **argv)
418{
419	tprof_monitor_common(true, argc, argv);
420}
421
422static void
423tprof_count(int argc, char **argv)
424{
425	tprof_monitor_common(false, argc, argv);
426}
427
428int
429main(int argc, char *argv[])
430{
431	const struct cmdtab *ct;
432	int ret;
433
434	getncpu();
435	setprogname(argv[0]);
436	argv += 1, argc -= 1;
437
438	devfd = open(_PATH_TPROF, O_RDWR);
439	if (devfd == -1) {
440		err(EXIT_FAILURE, "%s", _PATH_TPROF);
441	}
442
443	ret = ioctl(devfd, TPROF_IOC_GETINFO, &tprof_info);
444	if (ret == -1) {
445		err(EXIT_FAILURE, "TPROF_IOC_GETINFO");
446	}
447	if (tprof_info.ti_version != TPROF_VERSION) {
448		errx(EXIT_FAILURE, "version mismatch: version=%d, expected=%d",
449		    tprof_info.ti_version, TPROF_VERSION);
450	}
451	if (tprof_event_init(tprof_info.ti_ident) == -1) {
452		errx(EXIT_FAILURE, "cpu not supported");
453	}
454
455	ret = ioctl(devfd, TPROF_IOC_GETNCOUNTERS, &ncounters);
456	if (ret == -1) {
457		err(EXIT_FAILURE, "TPROF_IOC_GETNCOUNTERS");
458	}
459	if (ncounters == 0) {
460		errx(EXIT_FAILURE, "no available counters");
461	}
462
463	if (argc == 0)
464		usage();
465
466	for (ct = tprof_cmdtab; ct->label != NULL; ct++) {
467		if (strcmp(argv[0], ct->label) == 0) {
468			if (!ct->argsoptional &&
469			    ((ct->takesargs == 0) ^ (argv[1] == NULL)))
470			{
471				usage();
472			}
473			(*ct->func)(argc, argv);
474			break;
475		}
476	}
477	if (ct->label == NULL) {
478		usage();
479	}
480}
481