tprof.c revision 1.17
1/*	$NetBSD: tprof.c,v 1.17 2022/12/05 05:02:45 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.17 2022/12/05 05:02:45 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 **) __dead;
102static void tprof_count(int, char **) __dead;
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	{ "top",	true,  true,  tprof_top },
115	{ NULL,		false, false, NULL },
116};
117
118__dead static void
119usage(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] [-u]\n");
137	fprintf(stderr, "\t\tDisplay profiling results in real-time.\n");
138	exit(EXIT_FAILURE);
139}
140
141static int
142getncpu(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
155static void *
156process_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
186static void
187show_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... */
216static void
217output_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
226static void
227siginfo_nothing(int signo)
228{
229	__nothing;
230}
231
232static void
233siginfo_showcount(int signo)
234{
235	output_delay();
236	show_counters();
237}
238
239static void *
240process_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
260static void
261tprof_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
267static void
268tprof_monitor_common(bool do_profile, int argc, char **argv)
269{
270	const char *outfile = "tprof.out";
271	struct tprof_stat ts;
272	tprof_param_t params[TPROF_MAXCOUNTERS];
273	pid_t pid;
274	pthread_t pt;
275	int ret, ch, i;
276	char *tokens[2], *p;
277	tprof_countermask_t mask = TPROF_COUNTERMASK_ALL;
278
279	memset(params, 0, sizeof(params));
280
281	while ((ch = getopt(argc, argv, do_profile ? "o:e:" : "e:i:")) != -1) {
282		switch (ch) {
283		case 'o':
284			outfile = optarg;
285			break;
286		case 'i':
287			interval = strtod(optarg, &p);
288			if (*p != '\0' || interval <= 0)
289				errx(EXIT_FAILURE, "Bad/invalid interval: %s",
290				    optarg);
291			break;
292		case 'e':
293			p = estrdup(optarg);
294			tokens[0] = strtok(p, ":");
295			tokens[1] = strtok(NULL, ":");
296			tprof_event_lookup(tokens[0], &params[nevent]);
297
298			if (tokens[1] == NULL) {
299				params[nevent].p_flags |=
300				    (TPROF_PARAM_USER | TPROF_PARAM_KERN);
301			} else {
302				if (strchr(tokens[1], 'u'))
303					params[nevent].p_flags |=
304					    TPROF_PARAM_USER;
305				if (strchr(tokens[1], 'k'))
306					params[nevent].p_flags |=
307					    TPROF_PARAM_KERN;
308			}
309			eventname[nevent] = tokens[0];
310			eventnamewidth[nevent] = strlen(eventname[nevent]);
311			if (eventnamewidth[nevent] < COUNTER_COLUMNS_WIDTH)
312				eventnamewidth[nevent] = COUNTER_COLUMNS_WIDTH;
313			nevent++;
314			if (nevent > __arraycount(params) ||
315			    nevent > ncounters)
316				errx(EXIT_FAILURE, "Too many events. Only a"
317				    " maximum of %d counters can be used.",
318				    ncounters);
319			break;
320		default:
321			usage();
322		}
323	}
324	argc -= optind;
325	argv += optind;
326	if (argc == 0 || nevent == 0) {
327		usage();
328	}
329
330	if (do_profile) {
331		outfd = open(outfile, O_WRONLY | O_CREAT | O_TRUNC, 0666);
332		if (outfd == -1) {
333			err(EXIT_FAILURE, "%s", outfile);
334		}
335	}
336
337	for (i = 0; i < (int)nevent; i++) {
338		params[i].p_counter = i;
339		if (do_profile)
340			params[i].p_flags |= TPROF_PARAM_PROFILE;
341		ret = ioctl(devfd, TPROF_IOC_CONFIGURE_EVENT, &params[i]);
342		if (ret == -1) {
343			err(EXIT_FAILURE, "TPROF_IOC_CONFIGURE_EVENT: %s",
344			    eventname[i]);
345		}
346	}
347
348	ret = ioctl(devfd, TPROF_IOC_START, &mask);
349	if (ret == -1) {
350		err(EXIT_FAILURE, "TPROF_IOC_START");
351	}
352
353	pid = fork();
354	switch (pid) {
355	case -1:
356		err(EXIT_FAILURE, "fork");
357	case 0:
358		close(devfd);
359		execvp(argv[0], argv);
360		_Exit(EXIT_FAILURE);
361	}
362
363	signal(SIGINT, SIG_IGN);
364	if (do_profile)
365		signal(SIGINFO, siginfo_showcount);
366	else
367		signal(SIGINFO, siginfo_nothing);
368
369	unsigned int done = 0;
370	if (do_profile)
371		ret = pthread_create(&pt, NULL, process_samples, NULL);
372	else
373		ret = pthread_create(&pt, NULL, process_stat, &done);
374	if (ret != 0)
375		errx(1, "pthread_create: %s", strerror(ret));
376
377	for (;;) {
378		int status;
379
380		pid = wait4(-1, &status, 0, NULL);
381		if (pid == -1) {
382			if (errno == ECHILD) {
383				break;
384			}
385			err(EXIT_FAILURE, "wait4");
386		}
387		if (pid != 0 && WIFEXITED(status)) {
388			break;
389		}
390	}
391
392	ret = ioctl(devfd, TPROF_IOC_STOP, &mask);
393	if (ret == -1) {
394		err(EXIT_FAILURE, "TPROF_IOC_STOP");
395	}
396
397	if (!do_profile) {
398		atomic_add_int(&done, 1);	/* terminate thread */
399		kill(0, SIGINFO);
400	}
401
402	pthread_join(pt, NULL);
403
404	if (do_profile) {
405		ret = ioctl(devfd, TPROF_IOC_GETSTAT, &ts);
406		if (ret == -1)
407			err(EXIT_FAILURE, "TPROF_IOC_GETSTAT");
408
409		fprintf(stderr, "\n%s statistics:\n", getprogname());
410		fprintf(stderr, "\tsample %" PRIu64 "\n", ts.ts_sample);
411		fprintf(stderr, "\toverflow %" PRIu64 "\n", ts.ts_overflow);
412		fprintf(stderr, "\tbuf %" PRIu64 "\n", ts.ts_buf);
413		fprintf(stderr, "\temptybuf %" PRIu64 "\n", ts.ts_emptybuf);
414		fprintf(stderr, "\tdropbuf %" PRIu64 "\n", ts.ts_dropbuf);
415		fprintf(stderr, "\tdropbuf_sample %" PRIu64 "\n",
416		    ts.ts_dropbuf_sample);
417
418		fprintf(stderr, "\n");
419	}
420	show_counters();
421
422	exit(EXIT_SUCCESS);
423}
424
425static void
426tprof_monitor(int argc, char **argv)
427{
428	tprof_monitor_common(true, argc, argv);
429}
430
431static void
432tprof_count(int argc, char **argv)
433{
434	tprof_monitor_common(false, argc, argv);
435}
436
437int
438main(int argc, char *argv[])
439{
440	const struct cmdtab *ct;
441	int ret;
442
443	getncpu();
444	setprogname(argv[0]);
445	argv += 1, argc -= 1;
446
447	devfd = open(_PATH_TPROF, O_RDWR);
448	if (devfd == -1) {
449		err(EXIT_FAILURE, "%s", _PATH_TPROF);
450	}
451
452	ret = ioctl(devfd, TPROF_IOC_GETINFO, &tprof_info);
453	if (ret == -1) {
454		err(EXIT_FAILURE, "TPROF_IOC_GETINFO");
455	}
456	if (tprof_info.ti_version != TPROF_VERSION) {
457		errx(EXIT_FAILURE, "version mismatch: version=%d, expected=%d",
458		    tprof_info.ti_version, TPROF_VERSION);
459	}
460	if (tprof_event_init(tprof_info.ti_ident) == -1) {
461		errx(EXIT_FAILURE, "cpu not supported");
462	}
463
464	ret = ioctl(devfd, TPROF_IOC_GETNCOUNTERS, &ncounters);
465	if (ret == -1) {
466		err(EXIT_FAILURE, "TPROF_IOC_GETNCOUNTERS");
467	}
468	if (ncounters == 0) {
469		errx(EXIT_FAILURE, "no available counters");
470	}
471
472	if (argc == 0)
473		usage();
474
475	for (ct = tprof_cmdtab; ct->label != NULL; ct++) {
476		if (strcmp(argv[0], ct->label) == 0) {
477			if (!ct->argsoptional &&
478			    ((ct->takesargs == 0) ^ (argv[1] == NULL)))
479			{
480				usage();
481			}
482			(*ct->func)(argc, argv);
483			break;
484		}
485	}
486	if (ct->label == NULL) {
487		usage();
488	}
489}
490