tprof.c revision 1.18 1 /* $NetBSD: tprof.c,v 1.18 2022/12/16 08:02:04 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.18 2022/12/16 08:02:04 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] [-u]\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 }
314 } else if (allow_option) {
315 param->p_flags |= TPROF_PARAM_USER;
316 param->p_flags |= TPROF_PARAM_KERN;
317 }
318
319 if (scale != NULL) {
320 if (*scale == '=') {
321 scale++;
322 n = strtoull(scale, &p, 0);
323 if (*p != '\0') {
324 error = -1;
325 } else {
326 param->p_value2 = n;
327 param->p_flags |=
328 TPROF_PARAM_VALUE2_TRIGGERCOUNT;
329 }
330 } else {
331 if (strncasecmp("0x", scale, 2) == 0)
332 d = strtol(scale, &p, 0);
333 else
334 d = strtod(scale, &p);
335 if (*p != '\0' || d <= 0) {
336 error = -1;
337 } else {
338 param->p_value2 = 0x100000000ULL / d;
339 param->p_flags |= TPROF_PARAM_VALUE2_SCALE;
340 }
341 }
342
343 if (error != 0) {
344 snprintf(errmsgbuf, sizeof(errmsgbuf),
345 "invalid scale: %s", scale);
346 goto done;
347 }
348 }
349
350 done:
351 if (eventnamep != NULL)
352 *eventnamep = event;
353 if (error != 0 && errmsgp != NULL)
354 *errmsgp = errmsgbuf;
355 return error;
356 }
357
358 static void
359 tprof_monitor_common(bool do_profile, int argc, char **argv)
360 {
361 const char *outfile = "tprof.out";
362 struct tprof_stat ts;
363 tprof_param_t params[TPROF_MAXCOUNTERS];
364 pid_t pid;
365 pthread_t pt;
366 int ret, ch, i;
367 char *p, *errmsg;
368 tprof_countermask_t mask = TPROF_COUNTERMASK_ALL;
369
370 memset(params, 0, sizeof(params));
371
372 while ((ch = getopt(argc, argv, do_profile ? "o:e:" : "e:i:")) != -1) {
373 switch (ch) {
374 case 'o':
375 outfile = optarg;
376 break;
377 case 'i':
378 interval = strtod(optarg, &p);
379 if (*p != '\0' || interval <= 0)
380 errx(EXIT_FAILURE, "Bad/invalid interval: %s",
381 optarg);
382 break;
383 case 'e':
384 if (tprof_parse_event(¶ms[nevent], optarg,
385 TPROF_PARSE_EVENT_F_ALLOWOPTION |
386 (do_profile ? TPROF_PARSE_EVENT_F_ALLOWSCALE : 0),
387 &eventname[nevent], &errmsg) != 0) {
388 errx(EXIT_FAILURE, "%s", errmsg);
389 }
390 eventnamewidth[nevent] = strlen(eventname[nevent]);
391 if (eventnamewidth[nevent] < COUNTER_COLUMNS_WIDTH)
392 eventnamewidth[nevent] = COUNTER_COLUMNS_WIDTH;
393 nevent++;
394 if (nevent > __arraycount(params) ||
395 nevent > ncounters)
396 errx(EXIT_FAILURE, "Too many events. Only a"
397 " maximum of %d counters can be used.",
398 ncounters);
399 break;
400 default:
401 usage();
402 }
403 }
404 argc -= optind;
405 argv += optind;
406 if (argc == 0 || nevent == 0) {
407 usage();
408 }
409
410 if (do_profile) {
411 outfd = open(outfile, O_WRONLY | O_CREAT | O_TRUNC, 0666);
412 if (outfd == -1) {
413 err(EXIT_FAILURE, "%s", outfile);
414 }
415 }
416
417 for (i = 0; i < (int)nevent; i++) {
418 params[i].p_counter = i;
419 if (do_profile)
420 params[i].p_flags |= TPROF_PARAM_PROFILE;
421 ret = ioctl(devfd, TPROF_IOC_CONFIGURE_EVENT, ¶ms[i]);
422 if (ret == -1) {
423 err(EXIT_FAILURE, "TPROF_IOC_CONFIGURE_EVENT: %s",
424 eventname[i]);
425 }
426 }
427
428 ret = ioctl(devfd, TPROF_IOC_START, &mask);
429 if (ret == -1) {
430 err(EXIT_FAILURE, "TPROF_IOC_START");
431 }
432
433 pid = fork();
434 switch (pid) {
435 case -1:
436 err(EXIT_FAILURE, "fork");
437 case 0:
438 close(devfd);
439 execvp(argv[0], argv);
440 _Exit(EXIT_FAILURE);
441 }
442
443 signal(SIGINT, SIG_IGN);
444 if (do_profile)
445 signal(SIGINFO, siginfo_showcount);
446 else
447 signal(SIGINFO, siginfo_nothing);
448
449 unsigned int done = 0;
450 if (do_profile)
451 ret = pthread_create(&pt, NULL, process_samples, NULL);
452 else
453 ret = pthread_create(&pt, NULL, process_stat, &done);
454 if (ret != 0)
455 errx(1, "pthread_create: %s", strerror(ret));
456
457 for (;;) {
458 int status;
459
460 pid = wait4(-1, &status, 0, NULL);
461 if (pid == -1) {
462 if (errno == ECHILD) {
463 break;
464 }
465 err(EXIT_FAILURE, "wait4");
466 }
467 if (pid != 0 && WIFEXITED(status)) {
468 break;
469 }
470 }
471
472 ret = ioctl(devfd, TPROF_IOC_STOP, &mask);
473 if (ret == -1) {
474 err(EXIT_FAILURE, "TPROF_IOC_STOP");
475 }
476
477 if (!do_profile) {
478 atomic_add_int(&done, 1); /* terminate thread */
479 kill(0, SIGINFO);
480 }
481
482 pthread_join(pt, NULL);
483
484 if (do_profile) {
485 ret = ioctl(devfd, TPROF_IOC_GETSTAT, &ts);
486 if (ret == -1)
487 err(EXIT_FAILURE, "TPROF_IOC_GETSTAT");
488
489 fprintf(stderr, "\n%s statistics:\n", getprogname());
490 fprintf(stderr, "\tsample %" PRIu64 "\n", ts.ts_sample);
491 fprintf(stderr, "\toverflow %" PRIu64 "\n", ts.ts_overflow);
492 fprintf(stderr, "\tbuf %" PRIu64 "\n", ts.ts_buf);
493 fprintf(stderr, "\temptybuf %" PRIu64 "\n", ts.ts_emptybuf);
494 fprintf(stderr, "\tdropbuf %" PRIu64 "\n", ts.ts_dropbuf);
495 fprintf(stderr, "\tdropbuf_sample %" PRIu64 "\n",
496 ts.ts_dropbuf_sample);
497
498 fprintf(stderr, "\n");
499 }
500 show_counters();
501
502 exit(EXIT_SUCCESS);
503 }
504
505 static void
506 tprof_monitor(int argc, char **argv)
507 {
508 tprof_monitor_common(true, argc, argv);
509 }
510
511 static void
512 tprof_count(int argc, char **argv)
513 {
514 tprof_monitor_common(false, argc, argv);
515 }
516
517 int
518 main(int argc, char *argv[])
519 {
520 const struct cmdtab *ct;
521 int ret;
522
523 getncpu();
524 setprogname(argv[0]);
525 argv += 1, argc -= 1;
526
527 devfd = open(_PATH_TPROF, O_RDWR);
528 if (devfd == -1) {
529 err(EXIT_FAILURE, "%s", _PATH_TPROF);
530 }
531
532 ret = ioctl(devfd, TPROF_IOC_GETINFO, &tprof_info);
533 if (ret == -1) {
534 err(EXIT_FAILURE, "TPROF_IOC_GETINFO");
535 }
536 if (tprof_info.ti_version != TPROF_VERSION) {
537 errx(EXIT_FAILURE, "version mismatch: version=%d, expected=%d",
538 tprof_info.ti_version, TPROF_VERSION);
539 }
540 if (tprof_event_init(tprof_info.ti_ident) == -1) {
541 errx(EXIT_FAILURE, "cpu not supported");
542 }
543
544 ret = ioctl(devfd, TPROF_IOC_GETNCOUNTERS, &ncounters);
545 if (ret == -1) {
546 err(EXIT_FAILURE, "TPROF_IOC_GETNCOUNTERS");
547 }
548 if (ncounters == 0) {
549 errx(EXIT_FAILURE, "no available counters");
550 }
551
552 if (argc == 0)
553 usage();
554
555 for (ct = tprof_cmdtab; ct->label != NULL; ct++) {
556 if (strcmp(argv[0], ct->label) == 0) {
557 if (!ct->argsoptional &&
558 ((ct->takesargs == 0) ^ (argv[1] == NULL)))
559 {
560 usage();
561 }
562 (*ct->func)(argc, argv);
563 break;
564 }
565 }
566 if (ct->label == NULL) {
567 usage();
568 }
569 }
570