main.c revision 1.2 1 /* $NetBSD: main.c,v 1.2 2006/09/07 01:23:59 ad Exp $ */
2
3 /*-
4 * Copyright (c) 2006 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Andrew Doran.
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 * 3. All advertising materials mentioning features or use of this software
19 * must display the following acknowledgement:
20 * This product includes software developed by the NetBSD
21 * Foundation, Inc. and its contributors.
22 * 4. Neither the name of The NetBSD Foundation nor the names of its
23 * contributors may be used to endorse or promote products derived
24 * from this software without specific prior written permission.
25 *
26 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
27 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
28 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
29 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
30 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
31 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
32 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
33 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
34 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
35 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
36 * POSSIBILITY OF SUCH DAMAGE.
37 */
38
39 /*
40 * TODO:
41 *
42 * - Need better analysis and tracking of events.
43 * - Should be binary format agnostic, but given that we're likely to be using
44 * ELF for quite a while that's not a big problem.
45 * - Shouldn't have to parse the namelist here. We should use something like
46 * FreeBSD's libelf.
47 * - The way the namelist is searched sucks, is it worth doing something
48 * better?
49 */
50
51 #include <sys/cdefs.h>
52 #ifndef lint
53 __RCSID("$NetBSD: main.c,v 1.2 2006/09/07 01:23:59 ad Exp $");
54 #endif /* not lint */
55
56 #include <sys/types.h>
57 #include <sys/param.h>
58 #include <sys/time.h>
59 #include <sys/fcntl.h>
60 #include <sys/ioctl.h>
61 #include <sys/wait.h>
62 #include <sys/signal.h>
63 #include <sys/sysctl.h>
64
65 #include <dev/lockstat.h>
66
67 #include <stdio.h>
68 #include <stdlib.h>
69 #include <string.h>
70 #include <limits.h>
71 #include <unistd.h>
72 #include <err.h>
73 #include <paths.h>
74 #include <util.h>
75 #include <ctype.h>
76 #include <errno.h>
77
78 #include "extern.h"
79
80 #define _PATH_DEV_LOCKSTAT "/dev/lockstat"
81
82 #define MILLI 1000.0
83 #define MICRO 1000000.0
84 #define NANO 1000000000.0
85 #define PICO 1000000000000.0
86
87 TAILQ_HEAD(lock_head, lockstruct);
88 typedef struct lock_head locklist_t;
89 TAILQ_HEAD(buf_head, lsbuf);
90 typedef struct buf_head buflist_t;
91
92 typedef struct lockstruct {
93 TAILQ_ENTRY(lockstruct) chain;
94 buflist_t bufs;
95 uintptr_t lock;
96 double times[LB_NEVENT];
97 uint32_t counts[LB_NEVENT];
98 u_int flags;
99 } lock_t;
100
101 typedef struct name {
102 const char *name;
103 int mask;
104 } name_t;
105
106 const name_t locknames[] = {
107 { "adaptive_mutex", LB_ADAPTIVE_MUTEX },
108 { "adaptive_rwlock", LB_ADAPTIVE_RWLOCK },
109 { "spin_mutex", LB_SPIN_MUTEX },
110 { "spin_rwlock", LB_SPIN_RWLOCK },
111 { "lockmgr", LB_LOCKMGR },
112 { NULL, 0 }
113 };
114
115 const name_t eventnames[] = {
116 { "spin", LB_SPIN },
117 { "sleep", LB_SLEEP },
118 { NULL, 0 },
119 };
120
121 const name_t alltypes[] = {
122 { "Adaptive mutex spin", LB_ADAPTIVE_MUTEX | LB_SPIN },
123 { "Adaptive mutex sleep", LB_ADAPTIVE_MUTEX | LB_SLEEP },
124 { "Adaptive RW lock spin", LB_ADAPTIVE_RWLOCK | LB_SPIN },
125 { "Adaptive RW lock sleep", LB_ADAPTIVE_RWLOCK | LB_SPIN },
126 { "Spin mutex spin", LB_SPIN_MUTEX | LB_SPIN },
127 { "Spin RW lock spin", LB_SPIN_RWLOCK | LB_SPIN },
128 { "lockmgr sleep", LB_LOCKMGR | LB_SLEEP },
129 { NULL, 0 }
130 };
131
132 locklist_t locklist[LB_NLOCK];
133
134 lsbuf_t *bufs;
135 lsdisable_t ld;
136 int lflag;
137 int nbufs;
138 int cflag;
139 int lsfd;
140 int displayed;
141 int bin64;
142 double tscale;
143 double cscale;
144 double cpuscale[sizeof(ld.ld_freq) / sizeof(ld.ld_freq[0])];
145 FILE *outfp;
146
147 void findsym(findsym_t, char *, uintptr_t *, uintptr_t *);
148 void spawn(int, char **);
149 void display(int, const char *name);
150 void listnames(const name_t *);
151 int matchname(const name_t *, const char *);
152 void makelists(void);
153 void nullsig(int);
154 void usage(void);
155 void resort(int, int);
156 int ncpu(void);
157
158 int
159 main(int argc, char **argv)
160 {
161 int eventtype, locktype, ch, nlfd, sflag, fd, i, pflag;
162 const char *nlistf, *outf;
163 char *lockname, *funcname;
164 const name_t *name;
165 lsenable_t le;
166 double ms;
167 char *p;
168
169 nlistf = NULL;
170 outf = NULL;
171 lockname = NULL;
172 funcname = NULL;
173 eventtype = -1;
174 locktype = -1;
175 nbufs = 0;
176 sflag = 0;
177 pflag = 0;
178
179 while ((ch = getopt(argc, argv, "E:F:L:M:N:T:b:ceflo:pst")) != -1)
180 switch (ch) {
181 case 'E':
182 eventtype = matchname(eventnames, optarg);
183 break;
184 case 'F':
185 funcname = optarg;
186 break;
187 case 'L':
188 lockname = optarg;
189 break;
190 case 'N':
191 nlistf = optarg;
192 break;
193 case 'T':
194 locktype = matchname(locknames, optarg);
195 break;
196 case 'b':
197 nbufs = (int)strtol(optarg, &p, 0);
198 if (!isdigit((u_int)*optarg) || *p != '\0')
199 usage();
200 break;
201 case 'c':
202 cflag = 1;
203 break;
204 case 'e':
205 listnames(eventnames);
206 break;
207 case 'l':
208 lflag = 1;
209 break;
210 case 'o':
211 outf = optarg;
212 break;
213 case 'p':
214 pflag = 1;
215 break;
216 case 's':
217 sflag = 1;
218 break;
219 case 't':
220 listnames(locknames);
221 break;
222 default:
223 usage();
224 }
225 argc -= optind;
226 argv += optind;
227
228 if (*argv == NULL)
229 usage();
230
231 if (outf) {
232 if ((fd = open(outf, O_WRONLY | O_CREAT, 0600)) == -1)
233 err(EXIT_FAILURE, "opening %s", outf);
234 outfp = fdopen(fd, "w");
235 } else
236 outfp = stdout;
237
238 /*
239 * Find the name list for resolving symbol names, and load it into
240 * memory.
241 */
242 if (nlistf == NULL) {
243 nlfd = open(_PATH_KSYMS, O_RDONLY);
244 nlistf = getbootfile();
245 } else
246 nlfd = -1;
247 if (nlfd == -1) {
248 if ((nlfd = open(nlistf, O_RDONLY)) < 0)
249 err(EXIT_FAILURE, "cannot open " _PATH_KSYMS " or %s",
250 nlistf);
251 }
252 if (loadsym32(nlfd) != 0) {
253 if (loadsym64(nlfd) != 0)
254 errx(EXIT_FAILURE, "unable to load symbol table");
255 bin64 = 1;
256 }
257 close(nlfd);
258
259 memset(&le, 0, sizeof(le));
260 le.le_nbufs = nbufs;
261
262 /*
263 * Set up initial filtering.
264 */
265 if (lockname != NULL) {
266 findsym(LOCK_BYNAME, lockname, &le.le_lock, NULL);
267 le.le_flags |= LE_ONE_LOCK;
268 }
269 if (!lflag)
270 le.le_flags |= LE_CALLSITE;
271 if (funcname != NULL) {
272 if (lflag)
273 usage();
274 findsym(FUNC_BYNAME, funcname, &le.le_csstart, &le.le_csend);
275 le.le_flags |= LE_ONE_CALLSITE;
276 }
277 le.le_mask = (eventtype & LB_EVENT_MASK) | (locktype & LB_LOCK_MASK);
278
279 /*
280 * Start tracing.
281 */
282 if ((lsfd = open(_PATH_DEV_LOCKSTAT, O_RDONLY)) < 0)
283 err(EXIT_FAILURE, "cannot open " _PATH_DEV_LOCKSTAT);
284 if (ioctl(lsfd, IOC_LOCKSTAT_GVERSION, &ch) < 0)
285 err(EXIT_FAILURE, "ioctl");
286 if (ch != LS_VERSION)
287 errx(EXIT_FAILURE, "incompatible lockstat interface version");
288 if (ioctl(lsfd, IOC_LOCKSTAT_ENABLE, &le))
289 err(EXIT_FAILURE, "cannot enable tracing");
290
291 /*
292 * Execute the traced program.
293 */
294 spawn(argc, argv);
295
296 /*
297 * Stop tracing, and read the trace buffers from the kernel.
298 */
299 if (ioctl(lsfd, IOC_LOCKSTAT_DISABLE, &ld) == -1) {
300 if (errno == EOVERFLOW) {
301 warnx("overflowed available kernel trace buffers");
302 exit(EXIT_FAILURE);
303 }
304 err(EXIT_FAILURE, "cannot disable tracing");
305 }
306 if ((bufs = malloc(ld.ld_size)) == NULL)
307 err(EXIT_FAILURE, "cannot allocate memory for user buffers");
308 if (read(lsfd, bufs, ld.ld_size) != ld.ld_size)
309 err(EXIT_FAILURE, "reading from " _PATH_DEV_LOCKSTAT);
310 if (close(lsfd))
311 err(EXIT_FAILURE, "close(" _PATH_DEV_LOCKSTAT ")");
312
313 /*
314 * Figure out how to scale the results, and build the lists. For
315 * internal use we convert all times from CPU frequency based to
316 * picoseconds, and values are eventually displayed in ms.
317 */
318 for (i = 0; i < sizeof(ld.ld_freq) / sizeof(ld.ld_freq[0]); i++)
319 if (ld.ld_freq[i] != 0)
320 cpuscale[i] = PICO / ld.ld_freq[i];
321 ms = ld.ld_time.tv_sec * MILLI + ld.ld_time.tv_nsec / MICRO;
322 if (pflag)
323 cscale = 1.0 / ncpu();
324 else
325 cscale = 1.0;
326 cscale *= (sflag ? MILLI / ms : 1.0);
327 tscale = cscale / NANO;
328 nbufs = (int)(ld.ld_size / sizeof(lsbuf_t));
329 makelists();
330
331 /*
332 * Display the results.
333 */
334 fprintf(outfp, "Elapsed time: %.2f seconds.", ms / MILLI);
335 if (sflag || pflag) {
336 fprintf(outfp, " Displaying ");
337 if (pflag)
338 fprintf(outfp, "per-CPU ");
339 if (sflag)
340 fprintf(outfp, "per-second ");
341 fprintf(outfp, "averages.");
342 }
343 putc('\n', outfp);
344
345 for (name = alltypes; name->name != NULL; name++) {
346 if (eventtype != -1 &&
347 (name->mask & LB_EVENT_MASK) != eventtype)
348 continue;
349 if (locktype != -1 &&
350 (name->mask & LB_LOCK_MASK) != locktype)
351 continue;
352
353 display(name->mask, name->name);
354 }
355
356 if (displayed == 0)
357 fprintf(outfp, "None of the selected events were recorded.\n");
358 exit(EXIT_SUCCESS);
359 }
360
361 void
362 usage(void)
363 {
364
365 fprintf(stderr,
366 "%s: usage:\n"
367 "%s [options] <command>\n\n"
368 "-F func\t\tlimit trace to one function\n"
369 "-E evt\t\tdisplay only one type of event\n"
370 "-L lock\t\tlimit trace to one lock (name, or address)\n"
371 "-N nlist\tspecify name list file\n"
372 "-T type\t\tdisplay only one type of lock\n"
373 "-b nbuf\t\tset number of event buffers to allocate\n"
374 "-c\t\treport percentage of total events by count, not time\n"
375 "-e\t\tlist event types\n"
376 "-l\t\ttrace only by lock\n"
377 "-o file\t\tsend output to named file, not stdout\n"
378 "-p\t\tshow average count/time per CPU, not total\n"
379 "-s\t\tshow average count/time per second, not total\n"
380 "-t\t\tlist lock types\n",
381 getprogname(), getprogname());
382
383 exit(EXIT_FAILURE);
384 }
385
386 void
387 nullsig(int junk)
388 {
389
390 (void)junk;
391 }
392
393 void
394 listnames(const name_t *name)
395 {
396
397 for (; name->name != NULL; name++)
398 printf("%s\n", name->name);
399
400 exit(EXIT_SUCCESS);
401 }
402
403 int
404 matchname(const name_t *name, const char *string)
405 {
406
407 for (; name->name != NULL; name++)
408 if (strcasecmp(name->name, string) == 0)
409 return name->mask;
410
411 warnx("unknown type `%s'", string);
412 usage();
413 return 0;
414 }
415
416 /*
417 * Return the number of CPUs in the running system.
418 */
419 int
420 ncpu(void)
421 {
422 int rv, mib[2];
423 size_t varlen;
424
425 mib[0] = CTL_HW;
426 mib[1] = HW_NCPU;
427 varlen = sizeof(rv);
428 if (sysctl(mib, 2, &rv, &varlen, NULL, (size_t)0) < 0)
429 rv = 1;
430
431 return (rv);
432 }
433
434 /*
435 * Call into the ELF parser and look up a symbol by name or by address.
436 */
437 void
438 findsym(findsym_t find, char *name, uintptr_t *start, uintptr_t *end)
439 {
440 uintptr_t tend;
441 char *p;
442 int rv;
443
444 if (end == NULL)
445 end = &tend;
446
447 if (find == LOCK_BYNAME) {
448 if (isdigit((u_int)name[0])) {
449 *start = (uintptr_t)strtoul(name, &p, 0);
450 if (*p == '\0')
451 return;
452 }
453 }
454
455 if (bin64)
456 rv = findsym64(find, name, start, end);
457 else
458 rv = findsym32(find, name, start, end);
459
460 if (find == FUNC_BYNAME || find == LOCK_BYNAME) {
461 if (rv == -1)
462 errx(EXIT_FAILURE, "unable to find symbol `%s'", name);
463 return;
464 }
465
466 if (rv == -1)
467 sprintf(name, "0x%016lx", (long)*start);
468 }
469
470 /*
471 * Fork off the child process and wait for it to complete. We trap SIGINT
472 * so that the caller can use Ctrl-C to stop tracing early and still get
473 * useful results.
474 */
475 void
476 spawn(int argc, char **argv)
477 {
478 pid_t pid;
479
480 switch (pid = fork()) {
481 case 0:
482 close(lsfd);
483 if (execvp(argv[0], argv) == -1)
484 err(EXIT_FAILURE, "cannot exec");
485 break;
486 case -1:
487 err(EXIT_FAILURE, "cannot fork to exec");
488 break;
489 default:
490 signal(SIGINT, nullsig);
491 wait(NULL);
492 signal(SIGINT, SIG_DFL);
493 break;
494 }
495 }
496
497 /*
498 * From the kernel supplied data, construct two dimensional lists of locks
499 * and event buffers, indexed by lock type.
500 */
501 void
502 makelists(void)
503 {
504 lsbuf_t *lb, *lb2, *max;
505 int i, type;
506 lock_t *l;
507
508 for (i = 0; i < LB_NLOCK; i++)
509 TAILQ_INIT(&locklist[i]);
510
511 for (lb = bufs, max = bufs + nbufs; lb < max; lb++) {
512 if (lb->lb_flags == 0)
513 continue;
514
515 /*
516 * Look for a record descibing this lock, and allocate a
517 * new one if needed.
518 */
519 type = ((lb->lb_flags & LB_LOCK_MASK) >> LB_LOCK_SHIFT) - 1;
520 TAILQ_FOREACH(l, &locklist[type], chain) {
521 if (l->lock == lb->lb_lock)
522 break;
523 }
524 if (l == NULL) {
525 l = (lock_t *)malloc(sizeof(*l));
526 l->flags = lb->lb_flags;
527 l->lock = lb->lb_lock;
528 memset(&l->counts, 0, sizeof(l->counts));
529 memset(&l->times, 0, sizeof(l->times));
530 TAILQ_INIT(&l->bufs);
531 TAILQ_INSERT_TAIL(&locklist[type], l, chain);
532 }
533
534 /*
535 * Scale the time values per buffer and summarise
536 * times+counts per lock.
537 */
538 for (i = 0; i < LB_NEVENT; i++) {
539 lb->lb_times[i] *= cpuscale[lb->lb_cpu];
540 l->counts[i] += lb->lb_counts[i];
541 l->times[i] += lb->lb_times[i];
542 }
543
544 /*
545 * Merge same lock+callsite pairs from multiple CPUs
546 * together.
547 */
548 TAILQ_FOREACH(lb2, &l->bufs, lb_chain.tailq) {
549 if (lb->lb_callsite == lb2->lb_callsite)
550 break;
551 }
552 if (lb2 != NULL) {
553 for (i = 0; i < LB_NEVENT; i++) {
554 lb2->lb_counts[i] += lb->lb_counts[i];
555 lb2->lb_times[i] += lb->lb_times[i];
556 }
557 } else
558 TAILQ_INSERT_HEAD(&l->bufs, lb, lb_chain.tailq);
559 }
560 }
561
562 /*
563 * Re-sort one list of locks / lock buffers by event type.
564 */
565 void
566 resort(int type, int event)
567 {
568 lsbuf_t *lb, *lb2;
569 locklist_t llist;
570 buflist_t blist;
571 lock_t *l, *l2;
572
573 TAILQ_INIT(&llist);
574 while ((l = TAILQ_FIRST(&locklist[type])) != NULL) {
575 TAILQ_REMOVE(&locklist[type], l, chain);
576
577 /*
578 * Sort the buffers into the per-lock list.
579 */
580 TAILQ_INIT(&blist);
581 while ((lb = TAILQ_FIRST(&l->bufs)) != NULL) {
582 TAILQ_REMOVE(&l->bufs, lb, lb_chain.tailq);
583
584 lb2 = TAILQ_FIRST(&blist);
585 while (lb2 != NULL) {
586 if (cflag) {
587 if (lb->lb_counts[event] >
588 lb2->lb_counts[event])
589 break;
590 } else if (lb->lb_times[event] >
591 lb2->lb_times[event])
592 break;
593 lb2 = TAILQ_NEXT(lb2, lb_chain.tailq);
594 }
595 if (lb2 == NULL)
596 TAILQ_INSERT_TAIL(&blist, lb, lb_chain.tailq);
597 else
598 TAILQ_INSERT_BEFORE(lb2, lb, lb_chain.tailq);
599 }
600 l->bufs = blist;
601
602 /*
603 * Sort this lock into the per-type list, based on the
604 * totals per lock.
605 */
606 l2 = TAILQ_FIRST(&llist);
607 while (l2 != NULL) {
608 if (cflag) {
609 if (l->counts[event] > l2->counts[event])
610 break;
611 } else if (l->times[event] > l2->times[event])
612 break;
613 l2 = TAILQ_NEXT(l2, chain);
614 }
615 if (l2 == NULL)
616 TAILQ_INSERT_TAIL(&llist, l, chain);
617 else
618 TAILQ_INSERT_BEFORE(l2, l, chain);
619 }
620 locklist[type] = llist;
621 }
622
623 /*
624 * Display a summary table for one lock type / event type pair.
625 */
626 void
627 display(int mask, const char *name)
628 {
629 lock_t *l;
630 lsbuf_t *lb;
631 int event, type;
632 double pcscale, metric;
633 char lname[256], fname[256];
634
635 type = ((mask & LB_LOCK_MASK) >> LB_LOCK_SHIFT) - 1;
636 if (TAILQ_FIRST(&locklist[type]) == NULL)
637 return;
638
639 event = (mask & LB_EVENT_MASK) - 1;
640 resort(type, event);
641
642 fprintf(outfp, "\n-- %s\n\n"
643 "Total%% Count Time/ms Lock Caller\n"
644 "------ ------- --------- ------------------ ----------------------------------\n",
645 name);
646
647 /*
648 * Sum up all events for this type of lock + event.
649 */
650 pcscale = 0;
651 TAILQ_FOREACH(l, &locklist[type], chain) {
652 if (cflag)
653 pcscale += l->counts[event];
654 else
655 pcscale += l->times[event];
656 displayed++;
657 }
658 if (pcscale == 0)
659 pcscale = 100;
660 else
661 pcscale = (100.0 / pcscale);
662
663 /*
664 * For each lock, print a summary total, followed by a breakdown by
665 * caller.
666 */
667 TAILQ_FOREACH(l, &locklist[type], chain) {
668 if (cflag)
669 metric = l->counts[event];
670 else
671 metric = l->times[event];
672 metric *= pcscale;
673
674 findsym(LOCK_BYADDR, lname, &l->lock, NULL);
675
676 fprintf(outfp, "%6.2f %7d %9.2f %-18s <all>\n", metric,
677 (int)(l->counts[event] * cscale),
678 l->times[event] * tscale, lname);
679
680 if (lflag)
681 continue;
682
683 TAILQ_FOREACH(lb, &l->bufs, lb_chain.tailq) {
684 if (cflag)
685 metric = lb->lb_counts[event];
686 else
687 metric = lb->lb_times[event];
688 metric *= pcscale;
689
690 findsym(LOCK_BYADDR, lname, &lb->lb_lock, NULL);
691 findsym(FUNC_BYADDR, fname, &lb->lb_callsite, NULL);
692 fprintf(outfp, "%6.2f %7d %9.2f %-18s %s\n", metric,
693 (int)(lb->lb_counts[event] * cscale),
694 lb->lb_times[event] * tscale,
695 lname, fname);
696 }
697 }
698 }
699