vmstat.c revision 1.194 1 /* $NetBSD: vmstat.c,v 1.194 2014/06/03 21:16:15 joerg Exp $ */
2
3 /*-
4 * Copyright (c) 1998, 2000, 2001, 2007 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation by:
8 * - Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center.
10 * - Simon Burge and Luke Mewburn of Wasabi Systems, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 * POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 /*
35 * Copyright (c) 1980, 1986, 1991, 1993
36 * The Regents of the University of California. All rights reserved.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * SUCH DAMAGE.
61 */
62
63 #include <sys/cdefs.h>
64 #ifndef lint
65 __COPYRIGHT("@(#) Copyright (c) 1980, 1986, 1991, 1993\
66 The Regents of the University of California. All rights reserved.");
67 #endif /* not lint */
68
69 #ifndef lint
70 #if 0
71 static char sccsid[] = "@(#)vmstat.c 8.2 (Berkeley) 3/1/95";
72 #else
73 __RCSID("$NetBSD: vmstat.c,v 1.194 2014/06/03 21:16:15 joerg Exp $");
74 #endif
75 #endif /* not lint */
76
77 #define __POOL_EXPOSE
78
79 #include <sys/param.h>
80 #include <sys/types.h>
81 #include <sys/mount.h>
82 #include <sys/uio.h>
83
84 #include <sys/buf.h>
85 #include <sys/evcnt.h>
86 #include <sys/ioctl.h>
87 #include <sys/malloc.h>
88 #include <sys/mallocvar.h>
89 #include <sys/namei.h>
90 #include <sys/pool.h>
91 #include <sys/proc.h>
92 #include <sys/sched.h>
93 #include <sys/socket.h>
94 #include <sys/sysctl.h>
95 #include <sys/time.h>
96 #include <sys/queue.h>
97 #include <sys/kernhist.h>
98
99 #include <uvm/uvm_extern.h>
100 #include <uvm/uvm_stat.h>
101
102 #include <net/if.h>
103 #include <netinet/in.h>
104 #include <netinet/in_var.h>
105
106 #include <ufs/ufs/inode.h>
107
108 #include <nfs/rpcv2.h>
109 #include <nfs/nfsproto.h>
110 #include <nfs/nfsnode.h>
111
112 #include <ctype.h>
113 #include <err.h>
114 #include <errno.h>
115 #include <fcntl.h>
116 #include <kvm.h>
117 #include <limits.h>
118 #include <nlist.h>
119 #undef n_hash
120 #include <paths.h>
121 #include <signal.h>
122 #include <stdio.h>
123 #include <stddef.h>
124 #include <stdlib.h>
125 #include <string.h>
126 #include <time.h>
127 #include <unistd.h>
128 #include <util.h>
129
130 #include "drvstats.h"
131
132 /*
133 * All this mess will go away once everything is converted.
134 */
135 #ifdef __HAVE_CPU_DATA_FIRST
136
137 # include <sys/cpu_data.h>
138 struct cpu_info {
139 struct cpu_data ci_data;
140 };
141 #else
142 # include <sys/cpu.h>
143 #endif
144
145 struct cpu_info **cpu_infos;
146
147 /*
148 * General namelist
149 */
150 struct nlist namelist[] =
151 {
152 #define X_BOOTTIME 0
153 { .n_name = "_boottime" },
154 #define X_HZ 1
155 { .n_name = "_hz" },
156 #define X_STATHZ 2
157 { .n_name = "_stathz" },
158 #define X_NCHSTATS 3
159 { .n_name = "_nchstats" },
160 #define X_ALLEVENTS 4
161 { .n_name = "_allevents" },
162 #define X_POOLHEAD 5
163 { .n_name = "_pool_head" },
164 #define X_UVMEXP 6
165 { .n_name = "_uvmexp" },
166 #define X_TIME_SECOND 7
167 { .n_name = "_time_second" },
168 #define X_TIME 8
169 { .n_name = "_time" },
170 #define X_CPU_INFOS 9
171 { .n_name = "_cpu_infos" },
172 #define X_NL_SIZE 10
173 { .n_name = NULL },
174 };
175
176 /*
177 * Namelist for pre-evcnt interrupt counters.
178 */
179 struct nlist intrnl[] =
180 {
181 #define X_INTRNAMES 0
182 { .n_name = "_intrnames" },
183 #define X_EINTRNAMES 1
184 { .n_name = "_eintrnames" },
185 #define X_INTRCNT 2
186 { .n_name = "_intrcnt" },
187 #define X_EINTRCNT 3
188 { .n_name = "_eintrcnt" },
189 #define X_INTRNL_SIZE 4
190 { .n_name = NULL },
191 };
192
193
194 /*
195 * Namelist for hash statistics
196 */
197 struct nlist hashnl[] =
198 {
199 #define X_NFSNODE 0
200 { .n_name = "_nfsnodehash" },
201 #define X_NFSNODETBL 1
202 { .n_name = "_nfsnodehashtbl" },
203 #define X_IHASH 2
204 { .n_name = "_ihash" },
205 #define X_IHASHTBL 3
206 { .n_name = "_ihashtbl" },
207 #define X_BUFHASH 4
208 { .n_name = "_bufhash" },
209 #define X_BUFHASHTBL 5
210 { .n_name = "_bufhashtbl" },
211 #define X_UIHASH 6
212 { .n_name = "_uihash" },
213 #define X_UIHASHTBL 7
214 { .n_name = "_uihashtbl" },
215 #define X_IFADDRHASH 8
216 { .n_name = "_in_ifaddrhash" },
217 #define X_IFADDRHASHTBL 9
218 { .n_name = "_in_ifaddrhashtbl" },
219 #define X_NCHASH 10
220 { .n_name = "_nchash" },
221 #define X_NCHASHTBL 11
222 { .n_name = "_nchashtbl" },
223 #define X_NCVHASH 12
224 { .n_name = "_ncvhash" },
225 #define X_NCVHASHTBL 13
226 { .n_name = "_ncvhashtbl" },
227 #define X_HASHNL_SIZE 14 /* must be last */
228 { .n_name = NULL },
229 };
230
231 /*
232 * Namelist for kernel histories
233 */
234 struct nlist histnl[] =
235 {
236 { .n_name = "_kern_histories" },
237 #define X_KERN_HISTORIES 0
238 { .n_name = NULL },
239 };
240
241
242 #define KILO 1024
243
244 struct cpu_counter {
245 uint64_t nintr;
246 uint64_t nsyscall;
247 uint64_t nswtch;
248 uint64_t nfault;
249 uint64_t ntrap;
250 uint64_t nsoft;
251 } cpucounter, ocpucounter;
252
253 struct uvmexp uvmexp, ouvmexp;
254 int ndrives;
255
256 int winlines = 20;
257
258 kvm_t *kd;
259
260
261 #define FORKSTAT 0x001
262 #define INTRSTAT 0x002
263 #define MEMSTAT 0x004
264 #define SUMSTAT 0x008
265 #define EVCNTSTAT 0x010
266 #define VMSTAT 0x020
267 #define HISTLIST 0x040
268 #define HISTDUMP 0x080
269 #define HASHSTAT 0x100
270 #define HASHLIST 0x200
271 #define VMTOTAL 0x400
272 #define POOLCACHESTAT 0x800
273
274 /*
275 * Print single word. `ovflow' is number of characters didn't fit
276 * on the last word. `fmt' is a format string to print this word.
277 * It must contain asterisk for field width. `width' is a width
278 * occupied by this word. `fixed' is a number of constant chars in
279 * `fmt'. `val' is a value to be printed using format string `fmt'.
280 */
281 #define PRWORD(ovflw, fmt, width, fixed, val) do { \
282 (ovflw) += printf((fmt), \
283 (width) - (fixed) - (ovflw) > 0 ? \
284 (width) - (fixed) - (ovflw) : 0, \
285 (val)) - (width); \
286 if ((ovflw) < 0) \
287 (ovflw) = 0; \
288 } while (/* CONSTCOND */0)
289
290 void cpustats(int *);
291 void cpucounters(struct cpu_counter *);
292 void deref_kptr(const void *, void *, size_t, const char *);
293 void drvstats(int *);
294 void doevcnt(int verbose, int type);
295 void dohashstat(int, int, const char *);
296 void dointr(int verbose);
297 void dopool(int, int);
298 void dopoolcache(int);
299 void dosum(void);
300 void dovmstat(struct timespec *, int);
301 void print_total_hdr(void);
302 void dovmtotal(struct timespec *, int);
303 void kread(struct nlist *, int, void *, size_t);
304 int kreadc(struct nlist *, int, void *, size_t);
305 void needhdr(int);
306 void getnlist(int);
307 long getuptime(void);
308 void printhdr(void);
309 long pct(long, long);
310 __dead static void usage(void);
311 void doforkst(void);
312
313 void hist_traverse(int, const char *);
314 void hist_dodump(struct kern_history *);
315
316 int main(int, char **);
317 char **choosedrives(char **);
318
319 /* Namelist and memory file names. */
320 char *nlistf, *memf;
321
322 /* allow old usage [vmstat 1] */
323 #define BACKWARD_COMPATIBILITY
324
325 static const int vmmeter_mib[] = { CTL_VM, VM_METER };
326 static const int uvmexp2_mib[] = { CTL_VM, VM_UVMEXP2 };
327 static const int boottime_mib[] = { CTL_KERN, KERN_BOOTTIME };
328 static char kvm_errbuf[_POSIX2_LINE_MAX];
329
330 int
331 main(int argc, char *argv[])
332 {
333 int c, todo, verbose, wide;
334 struct timespec interval;
335 int reps;
336 gid_t egid = getegid();
337 const char *histname, *hashname;
338
339 histname = hashname = NULL;
340 (void)setegid(getgid());
341 memf = nlistf = NULL;
342 reps = todo = verbose = wide = 0;
343 interval.tv_sec = 0;
344 interval.tv_nsec = 0;
345 while ((c = getopt(argc, argv, "Cc:efh:HilLM:mN:stu:UvWw:")) != -1) {
346 switch (c) {
347 case 'c':
348 reps = atoi(optarg);
349 break;
350 case 'C':
351 todo |= POOLCACHESTAT;
352 break;
353 case 'e':
354 todo |= EVCNTSTAT;
355 break;
356 case 'f':
357 todo |= FORKSTAT;
358 break;
359 case 'h':
360 hashname = optarg;
361 /* FALLTHROUGH */
362 case 'H':
363 todo |= HASHSTAT;
364 break;
365 case 'i':
366 todo |= INTRSTAT;
367 break;
368 case 'l':
369 todo |= HISTLIST;
370 break;
371 case 'L':
372 todo |= HASHLIST;
373 break;
374 case 'M':
375 memf = optarg;
376 break;
377 case 'm':
378 todo |= MEMSTAT;
379 break;
380 case 'N':
381 nlistf = optarg;
382 break;
383 case 's':
384 todo |= SUMSTAT;
385 break;
386 case 't':
387 todo |= VMTOTAL;
388 break;
389 case 'u':
390 histname = optarg;
391 /* FALLTHROUGH */
392 case 'U':
393 todo |= HISTDUMP;
394 break;
395 case 'v':
396 verbose++;
397 break;
398 case 'W':
399 wide++;
400 break;
401 case 'w':
402 interval.tv_sec = atol(optarg);
403 break;
404 case '?':
405 default:
406 usage();
407 }
408 }
409 argc -= optind;
410 argv += optind;
411
412 if (todo == 0)
413 todo = VMSTAT;
414
415 /*
416 * Discard setgid privileges. If not the running kernel, we toss
417 * them away totally so that bad guys can't print interesting stuff
418 * from kernel memory, otherwise switch back to kmem for the
419 * duration of the kvm_openfiles() call.
420 */
421 if (nlistf != NULL || memf != NULL)
422 (void)setgid(getgid());
423 else
424 (void)setegid(egid);
425
426 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, kvm_errbuf);
427 if (kd == NULL) {
428 if (nlistf != NULL || memf != NULL) {
429 errx(1, "kvm_openfiles: %s", kvm_errbuf);
430 }
431 }
432
433 if (nlistf == NULL && memf == NULL)
434 (void)setgid(getgid());
435
436
437 if (todo & VMSTAT) {
438 struct winsize winsize;
439
440 (void)drvinit(0);/* Initialize disk stats, no disks selected. */
441
442 (void)setgid(getgid()); /* don't need privs anymore */
443
444 argv = choosedrives(argv); /* Select disks. */
445 winsize.ws_row = 0;
446 (void)ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
447 if (winsize.ws_row > 0)
448 winlines = winsize.ws_row;
449
450 }
451
452 #ifdef BACKWARD_COMPATIBILITY
453 if (*argv) {
454 interval.tv_sec = atol(*argv);
455 if (*++argv)
456 reps = atoi(*argv);
457 }
458 #endif
459
460 if (interval.tv_sec) {
461 if (!reps)
462 reps = -1;
463 } else if (reps)
464 interval.tv_sec = 1;
465
466
467 getnlist(todo);
468 /*
469 * Statistics dumping is incompatible with the default
470 * VMSTAT/dovmstat() output. So perform the interval/reps handling
471 * for it here.
472 */
473 if ((todo & (VMSTAT|VMTOTAL)) == 0) {
474 for (;;) {
475 if (todo & (HISTLIST|HISTDUMP)) {
476 if ((todo & (HISTLIST|HISTDUMP)) ==
477 (HISTLIST|HISTDUMP))
478 errx(1, "you may list or dump,"
479 " but not both!");
480 hist_traverse(todo, histname);
481 (void)putchar('\n');
482 }
483 if (todo & FORKSTAT) {
484 doforkst();
485 (void)putchar('\n');
486 }
487 if (todo & MEMSTAT) {
488 dopool(verbose, wide);
489 (void)putchar('\n');
490 }
491 if (todo & POOLCACHESTAT) {
492 dopoolcache(verbose);
493 (void)putchar('\n');
494 }
495 if (todo & SUMSTAT) {
496 dosum();
497 (void)putchar('\n');
498 }
499 if (todo & INTRSTAT) {
500 dointr(verbose);
501 (void)putchar('\n');
502 }
503 if (todo & EVCNTSTAT) {
504 doevcnt(verbose, EVCNT_TYPE_ANY);
505 (void)putchar('\n');
506 }
507 if (todo & (HASHLIST|HASHSTAT)) {
508 if ((todo & (HASHLIST|HASHSTAT)) ==
509 (HASHLIST|HASHSTAT))
510 errx(1, "you may list or display,"
511 " but not both!");
512 dohashstat(verbose, todo, hashname);
513 (void)putchar('\n');
514 }
515
516 fflush(stdout);
517 if (reps >= 0 && --reps <=0)
518 break;
519 (void)nanosleep(&interval, NULL);
520 }
521 } else {
522 if ((todo & (VMSTAT|VMTOTAL)) == (VMSTAT|VMTOTAL)) {
523 errx(1, "you may not both do vmstat and vmtotal");
524 }
525 if (todo & VMSTAT)
526 dovmstat(&interval, reps);
527 if (todo & VMTOTAL)
528 dovmtotal(&interval, reps);
529 }
530 return 0;
531 }
532
533 void
534 getnlist(int todo)
535 {
536 static int namelist_done = 0;
537 static int done = 0;
538 int c;
539 size_t i;
540
541 if (kd == NULL)
542 errx(1, "kvm_openfiles: %s", kvm_errbuf);
543
544 if (!namelist_done) {
545 namelist_done = 1;
546 if ((c = kvm_nlist(kd, namelist)) != 0) {
547 int doexit = 0;
548 if (c == -1)
549 errx(1, "kvm_nlist: %s %s",
550 "namelist", kvm_geterr(kd));
551 for (i = 0; i < __arraycount(namelist)-1; i++)
552 if (namelist[i].n_type == 0 &&
553 i != X_TIME_SECOND &&
554 i != X_TIME) {
555 if (doexit++ == 0)
556 (void)fprintf(stderr,
557 "%s: undefined symbols:",
558 getprogname());
559 (void)fprintf(stderr, " %s",
560 namelist[i].n_name);
561 }
562 if (doexit) {
563 (void)fputc('\n', stderr);
564 exit(1);
565 }
566 }
567 }
568 if ((todo & (SUMSTAT|INTRSTAT)) && !(done & (SUMSTAT|INTRSTAT))) {
569 done |= SUMSTAT|INTRSTAT;
570 (void) kvm_nlist(kd, intrnl);
571 }
572 if ((todo & (HASHLIST|HASHSTAT)) && !(done & (HASHLIST|HASHSTAT))) {
573 done |= HASHLIST|HASHSTAT;
574 if ((c = kvm_nlist(kd, hashnl)) == -1 || c == X_HASHNL_SIZE)
575 errx(1, "kvm_nlist: %s %s", "hashnl", kvm_geterr(kd));
576 }
577 if ((todo & (HISTLIST|HISTDUMP)) && !(done & (HISTLIST|HISTDUMP))) {
578 done |= HISTLIST|HISTDUMP;
579 if (kvm_nlist(kd, histnl) == -1)
580 errx(1, "kvm_nlist: %s %s", "histnl", kvm_geterr(kd));
581 }
582 }
583
584 char **
585 choosedrives(char **argv)
586 {
587 size_t i;
588
589 /*
590 * Choose drives to be displayed. Priority goes to (in order) drives
591 * supplied as arguments, default drives. If everything isn't filled
592 * in and there are drives not taken care of, display the first few
593 * that fit.
594 */
595 #define BACKWARD_COMPATIBILITY
596 for (ndrives = 0; *argv; ++argv) {
597 #ifdef BACKWARD_COMPATIBILITY
598 if (isdigit((unsigned char)**argv))
599 break;
600 #endif
601 for (i = 0; i < ndrive; i++) {
602 if (strcmp(dr_name[i], *argv))
603 continue;
604 drv_select[i] = 1;
605 ++ndrives;
606 break;
607 }
608 }
609 for (i = 0; i < ndrive && ndrives < 2; i++) {
610 if (drv_select[i])
611 continue;
612 drv_select[i] = 1;
613 ++ndrives;
614 }
615
616 return (argv);
617 }
618
619 long
620 getuptime(void)
621 {
622 static struct timespec boottime;
623 struct timespec now;
624 time_t uptime, nowsec;
625
626 if (memf == NULL) {
627 if (boottime.tv_sec == 0) {
628 size_t buflen = sizeof(boottime);
629 if (sysctl(boottime_mib, __arraycount(boottime_mib),
630 &boottime, &buflen, NULL, 0) == -1)
631 warn("Can't get boottime");
632 }
633 clock_gettime(CLOCK_REALTIME, &now);
634 } else {
635 if (boottime.tv_sec == 0)
636 kread(namelist, X_BOOTTIME, &boottime,
637 sizeof(boottime));
638 if (kreadc(namelist, X_TIME_SECOND, &nowsec, sizeof(nowsec))) {
639 /*
640 * XXX this assignment dance can be removed once
641 * timeval tv_sec is SUS mandated time_t
642 */
643 now.tv_sec = nowsec;
644 now.tv_nsec = 0;
645 } else {
646 kread(namelist, X_TIME, &now, sizeof(now));
647 }
648 }
649 uptime = now.tv_sec - boottime.tv_sec;
650 if (uptime <= 0 || uptime > 60*60*24*365*10)
651 errx(1, "time makes no sense; namelist must be wrong.");
652 return (uptime);
653 }
654
655 int hz, hdrcnt;
656
657 void
658 print_total_hdr(void)
659 {
660
661 (void)printf("procs memory\n");
662 (void)printf("ru dw pw sl");
663 (void)printf(" total-v active-v active-r");
664 (void)printf(" vm-sh avm-sh rm-sh arm-sh free\n");
665 hdrcnt = winlines - 2;
666 }
667
668 void
669 dovmtotal(struct timespec *interval, int reps)
670 {
671 struct vmtotal total;
672 size_t size;
673
674 (void)signal(SIGCONT, needhdr);
675
676 for (hdrcnt = 1;;) {
677 if (!--hdrcnt)
678 print_total_hdr();
679 if (memf != NULL) {
680 warnx("Unable to get vmtotals from crash dump.");
681 (void)memset(&total, 0, sizeof(total));
682 } else {
683 size = sizeof(total);
684 if (sysctl(vmmeter_mib, __arraycount(vmmeter_mib),
685 &total, &size, NULL, 0) == -1) {
686 warn("Can't get vmtotals");
687 (void)memset(&total, 0, sizeof(total));
688 }
689 }
690 (void)printf("%2d ", total.t_rq);
691 (void)printf("%2d ", total.t_dw);
692 (void)printf("%2d ", total.t_pw);
693 (void)printf("%2d ", total.t_sl);
694
695 (void)printf("%9d ", total.t_vm);
696 (void)printf("%9d ", total.t_avm);
697 (void)printf("%9d ", total.t_arm);
698 (void)printf("%5d ", total.t_vmshr);
699 (void)printf("%6d ", total.t_avmshr);
700 (void)printf("%5d ", total.t_rmshr);
701 (void)printf("%6d ", total.t_armshr);
702 (void)printf("%5d", total.t_free);
703
704 (void)putchar('\n');
705
706 (void)fflush(stdout);
707 if (reps >= 0 && --reps <= 0)
708 break;
709
710 (void)nanosleep(interval, NULL);
711 }
712 }
713
714 void
715 dovmstat(struct timespec *interval, int reps)
716 {
717 struct vmtotal total;
718 time_t uptime, halfuptime;
719 size_t size;
720 int pagesize = getpagesize();
721 int ovflw;
722
723 uptime = getuptime();
724 halfuptime = uptime / 2;
725 (void)signal(SIGCONT, needhdr);
726
727 if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
728 kread(namelist, X_STATHZ, &hz, sizeof(hz));
729 if (!hz)
730 kread(namelist, X_HZ, &hz, sizeof(hz));
731
732 kread(namelist, X_CPU_INFOS, &cpu_infos, sizeof(cpu_infos));
733
734 for (hdrcnt = 1;;) {
735 if (!--hdrcnt)
736 printhdr();
737 /* Read new disk statistics */
738 cpureadstats();
739 drvreadstats();
740 tkreadstats();
741 kread(namelist, X_UVMEXP, &uvmexp, sizeof(uvmexp));
742 if (memf != NULL) {
743 /*
744 * XXX Can't do this if we're reading a crash
745 * XXX dump because they're lazily-calculated.
746 */
747 warnx("Unable to get vmtotals from crash dump.");
748 (void)memset(&total, 0, sizeof(total));
749 } else {
750 size = sizeof(total);
751 if (sysctl(vmmeter_mib, __arraycount(vmmeter_mib),
752 &total, &size, NULL, 0) == -1) {
753 warn("Can't get vmtotals");
754 (void)memset(&total, 0, sizeof(total));
755 }
756 }
757 cpucounters(&cpucounter);
758 ovflw = 0;
759 PRWORD(ovflw, " %*d", 2, 1, total.t_rq - 1);
760 PRWORD(ovflw, " %*d", 2, 1, total.t_dw + total.t_pw);
761 #define pgtok(a) (long)((a) * ((uint32_t)pagesize >> 10))
762 #define rate(x) (u_long)(((x) + halfuptime) / uptime) /* round */
763 PRWORD(ovflw, " %*ld", 9, 1, pgtok(total.t_avm));
764 PRWORD(ovflw, " %*ld", 7, 1, pgtok(total.t_free));
765 PRWORD(ovflw, " %*ld", 5, 1,
766 rate(cpucounter.nfault - ocpucounter.nfault));
767 PRWORD(ovflw, " %*ld", 4, 1,
768 rate(uvmexp.pdreact - ouvmexp.pdreact));
769 PRWORD(ovflw, " %*ld", 4, 1,
770 rate(uvmexp.pageins - ouvmexp.pageins));
771 PRWORD(ovflw, " %*ld", 5, 1,
772 rate(uvmexp.pgswapout - ouvmexp.pgswapout));
773 PRWORD(ovflw, " %*ld", 5, 1,
774 rate(uvmexp.pdfreed - ouvmexp.pdfreed));
775 PRWORD(ovflw, " %*ld", 6, 2,
776 rate(uvmexp.pdscans - ouvmexp.pdscans));
777 drvstats(&ovflw);
778 PRWORD(ovflw, " %*ld", 5, 1,
779 rate(cpucounter.nintr - ocpucounter.nintr));
780 PRWORD(ovflw, " %*ld", 5, 1,
781 rate(cpucounter.nsyscall - ocpucounter.nsyscall));
782 PRWORD(ovflw, " %*ld", 4, 1,
783 rate(cpucounter.nswtch - ocpucounter.nswtch));
784 cpustats(&ovflw);
785 (void)putchar('\n');
786 (void)fflush(stdout);
787 if (reps >= 0 && --reps <= 0)
788 break;
789 ouvmexp = uvmexp;
790 ocpucounter = cpucounter;
791 uptime = interval->tv_sec;
792 /*
793 * We round upward to avoid losing low-frequency events
794 * (i.e., >= 1 per interval but < 1 per second).
795 */
796 halfuptime = uptime == 1 ? 0 : (uptime + 1) / 2;
797 (void)nanosleep(interval, NULL);
798 }
799 }
800
801 void
802 printhdr(void)
803 {
804 size_t i;
805
806 (void)printf(" procs memory page%*s", 23, "");
807 if (ndrives > 0)
808 (void)printf("%s %*sfaults cpu\n",
809 ((ndrives > 1) ? "disks" : "disk"),
810 ((ndrives > 1) ? ndrives * 3 - 4 : 0), "");
811 else
812 (void)printf("%*s faults cpu\n",
813 ndrives * 3, "");
814
815 (void)printf(" r b avm fre flt re pi po fr sr ");
816 for (i = 0; i < ndrive; i++)
817 if (drv_select[i])
818 (void)printf("%c%c ", dr_name[i][0],
819 dr_name[i][strlen(dr_name[i]) - 1]);
820 (void)printf(" in sy cs us sy id\n");
821 hdrcnt = winlines - 2;
822 }
823
824 /*
825 * Force a header to be prepended to the next output.
826 */
827 void
828 /*ARGSUSED*/
829 needhdr(int dummy)
830 {
831
832 hdrcnt = 1;
833 }
834
835 long
836 pct(long top, long bot)
837 {
838 long ans;
839
840 if (bot == 0)
841 return (0);
842 ans = (long)((quad_t)top * 100 / bot);
843 return (ans);
844 }
845
846 #define PCT(top, bot) (int)pct((long)(top), (long)(bot))
847
848 void
849 dosum(void)
850 {
851 struct nchstats_sysctl nch_stats;
852 uint64_t nchtotal;
853 struct uvmexp_sysctl uvmexp2;
854 size_t ssize;
855 int active_kernel;
856 struct cpu_counter cc;
857
858 /*
859 * The "active" and "inactive" variables
860 * are now estimated by the kernel and sadly
861 * can not easily be dug out of a crash dump.
862 */
863 ssize = sizeof(uvmexp2);
864 memset(&uvmexp2, 0, ssize);
865 active_kernel = (memf == NULL);
866 if (active_kernel) {
867 /* only on active kernel */
868 if (sysctl(uvmexp2_mib, __arraycount(uvmexp2_mib), &uvmexp2,
869 &ssize, NULL, 0) == -1)
870 warn("sysctl vm.uvmexp2 failed");
871 }
872
873 kread(namelist, X_UVMEXP, &uvmexp, sizeof(uvmexp));
874
875 (void)printf("%9u bytes per page\n", uvmexp.pagesize);
876
877 (void)printf("%9u page color%s\n",
878 uvmexp.ncolors, uvmexp.ncolors == 1 ? "" : "s");
879
880 (void)printf("%9u pages managed\n", uvmexp.npages);
881 (void)printf("%9u pages free\n", uvmexp.free);
882 if (active_kernel) {
883 (void)printf("%9" PRIu64 " pages active\n", uvmexp2.active);
884 (void)printf("%9" PRIu64 " pages inactive\n", uvmexp2.inactive);
885 }
886 (void)printf("%9u pages paging\n", uvmexp.paging);
887 (void)printf("%9u pages wired\n", uvmexp.wired);
888 (void)printf("%9u zero pages\n", uvmexp.zeropages);
889 (void)printf("%9u reserve pagedaemon pages\n",
890 uvmexp.reserve_pagedaemon);
891 (void)printf("%9u reserve kernel pages\n", uvmexp.reserve_kernel);
892 (void)printf("%9u anonymous pages\n", uvmexp.anonpages);
893 (void)printf("%9u cached file pages\n", uvmexp.filepages);
894 (void)printf("%9u cached executable pages\n", uvmexp.execpages);
895
896 (void)printf("%9u minimum free pages\n", uvmexp.freemin);
897 (void)printf("%9u target free pages\n", uvmexp.freetarg);
898 (void)printf("%9u maximum wired pages\n", uvmexp.wiredmax);
899
900 (void)printf("%9u swap devices\n", uvmexp.nswapdev);
901 (void)printf("%9u swap pages\n", uvmexp.swpages);
902 (void)printf("%9u swap pages in use\n", uvmexp.swpginuse);
903 (void)printf("%9u swap allocations\n", uvmexp.nswget);
904
905 kread(namelist, X_CPU_INFOS, &cpu_infos, sizeof(cpu_infos));
906 cpucounters(&cc);
907
908 (void)printf("%9" PRIu64 " total faults taken\n", cc.nfault);
909 (void)printf("%9" PRIu64 " traps\n", cc.ntrap);
910 (void)printf("%9" PRIu64 " device interrupts\n", cc.nintr);
911 (void)printf("%9" PRIu64 " CPU context switches\n", cc.nswtch);
912 (void)printf("%9" PRIu64 " software interrupts\n", cc.nsoft);
913 (void)printf("%9" PRIu64 " system calls\n", cc.nsyscall);
914 (void)printf("%9u pagein requests\n", uvmexp.pageins);
915 (void)printf("%9u pageout requests\n", uvmexp.pdpageouts);
916 (void)printf("%9u pages swapped in\n", uvmexp.pgswapin);
917 (void)printf("%9u pages swapped out\n", uvmexp.pgswapout);
918 (void)printf("%9u forks total\n", uvmexp.forks);
919 (void)printf("%9u forks blocked parent\n", uvmexp.forks_ppwait);
920 (void)printf("%9u forks shared address space with parent\n",
921 uvmexp.forks_sharevm);
922 (void)printf("%9u pagealloc zero wanted and avail\n",
923 uvmexp.pga_zerohit);
924 (void)printf("%9u pagealloc zero wanted and not avail\n",
925 uvmexp.pga_zeromiss);
926 (void)printf("%9u aborts of idle page zeroing\n",
927 uvmexp.zeroaborts);
928 (void)printf("%9u pagealloc desired color avail\n",
929 uvmexp.colorhit);
930 (void)printf("%9u pagealloc desired color not avail\n",
931 uvmexp.colormiss);
932 (void)printf("%9u pagealloc local cpu avail\n",
933 uvmexp.cpuhit);
934 (void)printf("%9u pagealloc local cpu not avail\n",
935 uvmexp.cpumiss);
936
937 (void)printf("%9u faults with no memory\n", uvmexp.fltnoram);
938 (void)printf("%9u faults with no anons\n", uvmexp.fltnoanon);
939 (void)printf("%9u faults had to wait on pages\n", uvmexp.fltpgwait);
940 (void)printf("%9u faults found released page\n", uvmexp.fltpgrele);
941 (void)printf("%9u faults relock (%u ok)\n", uvmexp.fltrelck,
942 uvmexp.fltrelckok);
943 (void)printf("%9u anon page faults\n", uvmexp.fltanget);
944 (void)printf("%9u anon retry faults\n", uvmexp.fltanretry);
945 (void)printf("%9u amap copy faults\n", uvmexp.fltamcopy);
946 (void)printf("%9u neighbour anon page faults\n", uvmexp.fltnamap);
947 (void)printf("%9u neighbour object page faults\n", uvmexp.fltnomap);
948 (void)printf("%9u locked pager get faults\n", uvmexp.fltlget);
949 (void)printf("%9u unlocked pager get faults\n", uvmexp.fltget);
950 (void)printf("%9u anon faults\n", uvmexp.flt_anon);
951 (void)printf("%9u anon copy on write faults\n", uvmexp.flt_acow);
952 (void)printf("%9u object faults\n", uvmexp.flt_obj);
953 (void)printf("%9u promote copy faults\n", uvmexp.flt_prcopy);
954 (void)printf("%9u promote zero fill faults\n", uvmexp.flt_przero);
955
956 (void)printf("%9u times daemon wokeup\n",uvmexp.pdwoke);
957 (void)printf("%9u revolutions of the clock hand\n", uvmexp.pdrevs);
958 (void)printf("%9u pages freed by daemon\n", uvmexp.pdfreed);
959 (void)printf("%9u pages scanned by daemon\n", uvmexp.pdscans);
960 (void)printf("%9u anonymous pages scanned by daemon\n",
961 uvmexp.pdanscan);
962 (void)printf("%9u object pages scanned by daemon\n", uvmexp.pdobscan);
963 (void)printf("%9u pages reactivated\n", uvmexp.pdreact);
964 (void)printf("%9u pages found busy by daemon\n", uvmexp.pdbusy);
965 (void)printf("%9u total pending pageouts\n", uvmexp.pdpending);
966 (void)printf("%9u pages deactivated\n", uvmexp.pddeact);
967
968 if (active_kernel) {
969 ssize = sizeof(nch_stats);
970 if (sysctlbyname("vfs.namecache_stats", &nch_stats, &ssize,
971 NULL, 0)) {
972 warn("vfs.namecache_stats failed");
973 memset(&nch_stats, 0, sizeof(nch_stats));
974 }
975 } else {
976 struct nchstats nch_stats_kvm;
977
978 kread(namelist, X_NCHSTATS, &nch_stats_kvm,
979 sizeof(nch_stats_kvm));
980 nch_stats.ncs_goodhits = nch_stats_kvm.ncs_goodhits;
981 nch_stats.ncs_neghits = nch_stats_kvm.ncs_neghits;
982 nch_stats.ncs_badhits = nch_stats_kvm.ncs_badhits;
983 nch_stats.ncs_falsehits = nch_stats_kvm.ncs_falsehits;
984 nch_stats.ncs_miss = nch_stats_kvm.ncs_miss;
985 nch_stats.ncs_long = nch_stats_kvm.ncs_long;
986 nch_stats.ncs_pass2 = nch_stats_kvm.ncs_pass2;
987 nch_stats.ncs_2passes = nch_stats_kvm.ncs_2passes;
988 nch_stats.ncs_revhits = nch_stats_kvm.ncs_revhits;
989 nch_stats.ncs_revmiss = nch_stats_kvm.ncs_revmiss;
990 }
991
992 nchtotal = nch_stats.ncs_goodhits + nch_stats.ncs_neghits +
993 nch_stats.ncs_badhits + nch_stats.ncs_falsehits +
994 nch_stats.ncs_miss + nch_stats.ncs_long;
995 (void)printf("%9" PRIu64 " total name lookups\n", nchtotal);
996 (void)printf("%9" PRIu64 " good hits\n", nch_stats.ncs_goodhits);
997 (void)printf("%9" PRIu64 " negative hits\n", nch_stats.ncs_neghits);
998 (void)printf("%9" PRIu64 " bad hits\n", nch_stats.ncs_badhits);
999 (void)printf("%9" PRIu64 " false hits\n", nch_stats.ncs_falsehits);
1000 (void)printf("%9" PRIu64 " miss\n", nch_stats.ncs_miss);
1001 (void)printf("%9" PRIu64 " too long\n", nch_stats.ncs_long);
1002 (void)printf("%9" PRIu64 " pass2 hits\n", nch_stats.ncs_pass2);
1003 (void)printf("%9" PRIu64 " 2passes\n", nch_stats.ncs_2passes);
1004 (void)printf(
1005 "%9s cache hits (%d%% pos + %d%% neg) system %d%% per-process\n",
1006 "", PCT(nch_stats.ncs_goodhits, nchtotal),
1007 PCT(nch_stats.ncs_neghits, nchtotal),
1008 PCT(nch_stats.ncs_pass2, nchtotal));
1009 (void)printf("%9s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
1010 PCT(nch_stats.ncs_badhits, nchtotal),
1011 PCT(nch_stats.ncs_falsehits, nchtotal),
1012 PCT(nch_stats.ncs_long, nchtotal));
1013 }
1014
1015 void
1016 doforkst(void)
1017 {
1018 kread(namelist, X_UVMEXP, &uvmexp, sizeof(uvmexp));
1019
1020 (void)printf("%u forks total\n", uvmexp.forks);
1021 (void)printf("%u forks blocked parent\n", uvmexp.forks_ppwait);
1022 (void)printf("%u forks shared address space with parent\n",
1023 uvmexp.forks_sharevm);
1024 }
1025
1026 void
1027 drvstats(int *ovflwp)
1028 {
1029 size_t dn;
1030 double etime;
1031 int ovflw = *ovflwp;
1032
1033 /* Calculate disk stat deltas. */
1034 cpuswap();
1035 drvswap();
1036 tkswap();
1037 etime = cur.cp_etime;
1038
1039 for (dn = 0; dn < ndrive; ++dn) {
1040 if (!drv_select[dn])
1041 continue;
1042 PRWORD(ovflw, " %*.0f", 3, 1,
1043 (cur.rxfer[dn] + cur.wxfer[dn]) / etime);
1044 }
1045 *ovflwp = ovflw;
1046 }
1047
1048 void
1049 cpucounters(struct cpu_counter *cc)
1050 {
1051 struct cpu_info **slot = cpu_infos;
1052
1053 memset(cc, 0, sizeof(*cc));
1054
1055 for (;;) {
1056 struct cpu_info tci, *ci = NULL;
1057
1058 deref_kptr(slot++, &ci, sizeof(ci), "CPU array trashed");
1059 if (!ci) {
1060 break;
1061 }
1062
1063 if ((size_t)kvm_read(kd, (u_long)ci, &tci, sizeof(tci))
1064 != sizeof(tci)) {
1065 warnx("Can't read cpu info from %p (%s)",
1066 ci, kvm_geterr(kd));
1067 memset(cc, 0, sizeof(*cc));
1068 return;
1069 }
1070 cc->nintr += tci.ci_data.cpu_nintr;
1071 cc->nsyscall += tci.ci_data.cpu_nsyscall;
1072 cc->nswtch = tci.ci_data.cpu_nswtch;
1073 cc->nfault = tci.ci_data.cpu_nfault;
1074 cc->ntrap = tci.ci_data.cpu_ntrap;
1075 cc->nsoft = tci.ci_data.cpu_nsoft;
1076 }
1077 }
1078
1079 void
1080 cpustats(int *ovflwp)
1081 {
1082 int state;
1083 double pcnt, total;
1084 double stat_us, stat_sy, stat_id;
1085 int ovflw = *ovflwp;
1086
1087 total = 0;
1088 for (state = 0; state < CPUSTATES; ++state)
1089 total += cur.cp_time[state];
1090 if (total)
1091 pcnt = 100 / total;
1092 else
1093 pcnt = 0;
1094 stat_us = (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * pcnt;
1095 stat_sy = (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * pcnt;
1096 stat_id = cur.cp_time[CP_IDLE] * pcnt;
1097 PRWORD(ovflw, " %*.0f", ((stat_sy >= 100) ? 2 : 3), 1, stat_us);
1098 PRWORD(ovflw, " %*.0f", ((stat_us >= 100 || stat_id >= 100) ? 2 : 3), 1,
1099 stat_sy);
1100 PRWORD(ovflw, " %*.0f", 3, 1, stat_id);
1101 *ovflwp = ovflw;
1102 }
1103
1104 void
1105 dointr(int verbose)
1106 {
1107 unsigned long *intrcnt, *ointrcnt;
1108 unsigned long long inttotal, uptime;
1109 int nintr, inamlen;
1110 char *intrname, *ointrname;
1111
1112 inttotal = 0;
1113 uptime = getuptime();
1114 (void)printf("%-34s %16s %8s\n", "interrupt", "total", "rate");
1115 nintr = intrnl[X_EINTRCNT].n_value - intrnl[X_INTRCNT].n_value;
1116 inamlen = intrnl[X_EINTRNAMES].n_value - intrnl[X_INTRNAMES].n_value;
1117 if (nintr != 0 && inamlen != 0) {
1118 ointrcnt = intrcnt = malloc((size_t)nintr);
1119 ointrname = intrname = malloc((size_t)inamlen);
1120 if (intrcnt == NULL || intrname == NULL)
1121 errx(1, "%s", "");
1122 kread(intrnl, X_INTRCNT, intrcnt, (size_t)nintr);
1123 kread(intrnl, X_INTRNAMES, intrname, (size_t)inamlen);
1124 nintr /= sizeof(long);
1125 while (--nintr >= 0) {
1126 if (*intrcnt || verbose)
1127 (void)printf("%-34s %16llu %8llu\n", intrname,
1128 (unsigned long long)*intrcnt,
1129 (unsigned long long)
1130 (*intrcnt / uptime));
1131 intrname += strlen(intrname) + 1;
1132 inttotal += *intrcnt++;
1133 }
1134 free(ointrcnt);
1135 free(ointrname);
1136 }
1137
1138 doevcnt(verbose, EVCNT_TYPE_INTR);
1139 }
1140
1141 void
1142 doevcnt(int verbose, int type)
1143 {
1144 static const char * const evtypes [] = { "misc", "intr", "trap" };
1145 uint64_t counttotal, uptime;
1146 struct evcntlist allevents;
1147 struct evcnt evcnt, *evptr;
1148 char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
1149
1150 counttotal = 0;
1151 uptime = getuptime();
1152 if (type == EVCNT_TYPE_ANY)
1153 (void)printf("%-34s %16s %8s %s\n", "event", "total", "rate",
1154 "type");
1155
1156 if (memf == NULL) do {
1157 const int mib[4] = { CTL_KERN, KERN_EVCNT, type,
1158 verbose ? KERN_EVCNT_COUNT_ANY : KERN_EVCNT_COUNT_NONZERO };
1159 size_t buflen = 0;
1160 void *buf = NULL;
1161 const struct evcnt_sysctl *evs, *last_evs;
1162 for (;;) {
1163 size_t newlen;
1164 int error;
1165 if (buflen)
1166 buf = malloc(buflen);
1167 error = sysctl(mib, __arraycount(mib),
1168 buf, &newlen, NULL, 0);
1169 if (error) {
1170 err(1, "kern.evcnt");
1171 if (buf)
1172 free(buf);
1173 return;
1174 }
1175 if (newlen <= buflen) {
1176 buflen = newlen;
1177 break;
1178 }
1179 if (buf)
1180 free(buf);
1181 buflen = newlen;
1182 }
1183 evs = buf;
1184 last_evs = (void *)((char *)buf + buflen);
1185 buflen /= sizeof(uint64_t);
1186 while (evs < last_evs
1187 && buflen >= sizeof(*evs)/sizeof(uint64_t)
1188 && buflen >= evs->ev_len) {
1189 (void)printf(type == EVCNT_TYPE_ANY ?
1190 "%s %s%*s %16"PRIu64" %8"PRIu64" %s\n" :
1191 "%s %s%*s %16"PRIu64" %8"PRIu64"\n",
1192 evs->ev_strings,
1193 evs->ev_strings + evs->ev_grouplen + 1,
1194 34 - (evs->ev_grouplen + 1 + evs->ev_namelen), "",
1195 evs->ev_count,
1196 evs->ev_count / uptime,
1197 (evs->ev_type < __arraycount(evtypes) ?
1198 evtypes[evs->ev_type] : "?"));
1199 buflen -= evs->ev_len;
1200 counttotal += evs->ev_count;
1201 evs = (const void *)((const uint64_t *)evs + evs->ev_len);
1202 }
1203 free(buf);
1204 if (type != EVCNT_TYPE_ANY)
1205 (void)printf("%-34s %16"PRIu64" %8"PRIu64"\n",
1206 "Total", counttotal, counttotal / uptime);
1207 return;
1208 } while (/*CONSTCOND*/ 0);
1209
1210 kread(namelist, X_ALLEVENTS, &allevents, sizeof allevents);
1211 evptr = TAILQ_FIRST(&allevents);
1212 while (evptr) {
1213 deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
1214
1215 evptr = TAILQ_NEXT(&evcnt, ev_list);
1216 if (evcnt.ev_count == 0 && !verbose)
1217 continue;
1218 if (type != EVCNT_TYPE_ANY && evcnt.ev_type != type)
1219 continue;
1220
1221 deref_kptr(evcnt.ev_group, evgroup,
1222 (size_t)evcnt.ev_grouplen + 1, "event chain trashed");
1223 deref_kptr(evcnt.ev_name, evname,
1224 (size_t)evcnt.ev_namelen + 1, "event chain trashed");
1225
1226 (void)printf(type == EVCNT_TYPE_ANY ?
1227 "%s %s%*s %16"PRIu64" %8"PRIu64" %s\n" :
1228 "%s %s%*s %16"PRIu64" %8"PRIu64"\n",
1229 evgroup, evname,
1230 34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
1231 evcnt.ev_count,
1232 (evcnt.ev_count / uptime),
1233 (evcnt.ev_type < __arraycount(evtypes) ?
1234 evtypes[evcnt.ev_type] : "?"));
1235
1236 counttotal += evcnt.ev_count;
1237 }
1238 if (type != EVCNT_TYPE_ANY)
1239 (void)printf("%-34s %16"PRIu64" %8"PRIu64"\n",
1240 "Total", counttotal, counttotal / uptime);
1241 }
1242
1243 void
1244 dopool(int verbose, int wide)
1245 {
1246 int first, ovflw;
1247 void *addr;
1248 long total, inuse, this_total, this_inuse;
1249 struct {
1250 uint64_t pt_nget;
1251 uint64_t pt_nfail;
1252 uint64_t pt_nput;
1253 uint64_t pt_nout;
1254 uint64_t pt_nitems;
1255 uint64_t pt_npagealloc;
1256 uint64_t pt_npagefree;
1257 uint64_t pt_npages;
1258 } pool_totals;
1259 char in_use[8];
1260 char avail[8];
1261 TAILQ_HEAD(,pool) pool_head;
1262 struct pool pool, *pp = &pool;
1263 struct pool_allocator pa;
1264 char name[32], maxp[32];
1265
1266 memset(&pool_totals, 0, sizeof pool_totals);
1267 kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
1268 addr = TAILQ_FIRST(&pool_head);
1269
1270 total = inuse = 0;
1271
1272 for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
1273 deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
1274 deref_kptr(pp->pr_alloc, &pa, sizeof(pa),
1275 "pool allocator trashed");
1276 deref_kptr(pp->pr_wchan, name, sizeof(name),
1277 "pool wait channel trashed");
1278 name[sizeof(name)-1] = '\0';
1279
1280 if (first) {
1281 (void)printf("Memory resource pool statistics\n");
1282 (void)printf(
1283 "%-*s%*s%*s%5s%*s%s%s%*s%*s%6s%s%6s%6s%6s%5s%s%s\n",
1284 wide ? 16 : 11, "Name",
1285 wide ? 6 : 5, "Size",
1286 wide ? 12 : 9, "Requests",
1287 "Fail",
1288 wide ? 12 : 9, "Releases",
1289 wide ? " InUse" : "",
1290 wide ? " Avail" : "",
1291 wide ? 7 : 6, "Pgreq",
1292 wide ? 7 : 6, "Pgrel",
1293 "Npage",
1294 wide ? " PageSz" : "",
1295 "Hiwat",
1296 "Minpg",
1297 "Maxpg",
1298 "Idle",
1299 wide ? " Flags" : "",
1300 wide ? " Util" : "");
1301 first = 0;
1302 }
1303 if (pp->pr_nget == 0 && !verbose)
1304 continue;
1305 if (pp->pr_maxpages == UINT_MAX)
1306 (void)snprintf(maxp, sizeof(maxp), "inf");
1307 else
1308 (void)snprintf(maxp, sizeof(maxp), "%u",
1309 pp->pr_maxpages);
1310 ovflw = 0;
1311 PRWORD(ovflw, "%-*s", wide ? 16 : 11, 0, name);
1312 PRWORD(ovflw, " %*u", wide ? 6 : 5, 1, pp->pr_size);
1313 PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nget);
1314 pool_totals.pt_nget += pp->pr_nget;
1315 PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nfail);
1316 pool_totals.pt_nfail += pp->pr_nfail;
1317 PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nput);
1318 pool_totals.pt_nput += pp->pr_nput;
1319 if (wide) {
1320 PRWORD(ovflw, " %*u", 7, 1, pp->pr_nout);
1321 pool_totals.pt_nout += pp->pr_nout;
1322 }
1323 if (wide) {
1324 PRWORD(ovflw, " %*u", 6, 1, pp->pr_nitems);
1325 pool_totals.pt_nitems += pp->pr_nitems;
1326 }
1327 PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagealloc);
1328 pool_totals.pt_npagealloc += pp->pr_npagealloc;
1329 PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagefree);
1330 pool_totals.pt_npagefree += pp->pr_npagefree;
1331 PRWORD(ovflw, " %*u", 6, 1, pp->pr_npages);
1332 pool_totals.pt_npages += pp->pr_npages;
1333 if (wide)
1334 PRWORD(ovflw, " %*u", 7, 1, pa.pa_pagesz);
1335 PRWORD(ovflw, " %*u", 6, 1, pp->pr_hiwat);
1336 PRWORD(ovflw, " %*u", 6, 1, pp->pr_minpages);
1337 PRWORD(ovflw, " %*s", 6, 1, maxp);
1338 PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nidle);
1339 if (wide)
1340 PRWORD(ovflw, " 0x%0*x", 4, 1,
1341 pp->pr_flags | pp->pr_roflags);
1342
1343 this_inuse = pp->pr_nout * pp->pr_size;
1344 this_total = pp->pr_npages * pa.pa_pagesz;
1345 if (pp->pr_roflags & PR_RECURSIVE) {
1346 /*
1347 * Don't count in-use memory, since it's part
1348 * of another pool and will be accounted for
1349 * there.
1350 */
1351 total += (this_total - this_inuse);
1352 } else {
1353 inuse += this_inuse;
1354 total += this_total;
1355 }
1356 if (wide) {
1357 if (this_total == 0)
1358 (void)printf(" ---");
1359 else
1360 (void)printf(" %5.1f%%",
1361 (100.0 * this_inuse) / this_total);
1362 }
1363 (void)printf("\n");
1364 }
1365 if (wide) {
1366 snprintf(in_use, sizeof in_use, "%7"PRId64, pool_totals.pt_nout);
1367 snprintf(avail, sizeof avail, "%6"PRId64, pool_totals.pt_nitems);
1368 } else {
1369 in_use[0] = '\0';
1370 avail[0] = '\0';
1371 }
1372 (void)printf(
1373 "%-*s%*s%*"PRId64"%5"PRId64"%*"PRId64"%s%s%*"PRId64"%*"PRId64"%6"PRId64"\n",
1374 wide ? 16 : 11, "Totals",
1375 wide ? 6 : 5, "",
1376 wide ? 12 : 9, pool_totals.pt_nget,
1377 pool_totals.pt_nfail,
1378 wide ? 12 : 9, pool_totals.pt_nput,
1379 in_use,
1380 avail,
1381 wide ? 7 : 6, pool_totals.pt_npagealloc,
1382 wide ? 7 : 6, pool_totals.pt_npagefree,
1383 pool_totals.pt_npages);
1384
1385 inuse /= KILO;
1386 total /= KILO;
1387 (void)printf(
1388 "\nIn use %ldK, total allocated %ldK; utilization %.1f%%\n",
1389 inuse, total, (100.0 * inuse) / total);
1390 }
1391
1392 void
1393 dopoolcache(int verbose)
1394 {
1395 struct pool_cache pool_cache, *pc = &pool_cache;
1396 pool_cache_cpu_t cache_cpu, *cc = &cache_cpu;
1397 TAILQ_HEAD(,pool) pool_head;
1398 struct pool pool, *pp = &pool;
1399 char name[32];
1400 uint64_t cpuhit, cpumiss, tot;
1401 void *addr;
1402 int first, ovflw;
1403 size_t i;
1404 double p;
1405
1406 kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
1407 addr = TAILQ_FIRST(&pool_head);
1408
1409 for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
1410 deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
1411 if (pp->pr_cache == NULL)
1412 continue;
1413 deref_kptr(pp->pr_wchan, name, sizeof(name),
1414 "pool wait channel trashed");
1415 deref_kptr(pp->pr_cache, pc, sizeof(*pc), "pool cache trashed");
1416 if (pc->pc_misses == 0 && !verbose)
1417 continue;
1418 name[sizeof(name)-1] = '\0';
1419
1420 cpuhit = 0;
1421 cpumiss = 0;
1422 for (i = 0; i < __arraycount(pc->pc_cpus); i++) {
1423 if ((addr = pc->pc_cpus[i]) == NULL)
1424 continue;
1425 deref_kptr(addr, cc, sizeof(*cc),
1426 "pool cache cpu trashed");
1427 cpuhit += cc->cc_hits;
1428 cpumiss += cc->cc_misses;
1429 }
1430
1431 if (first) {
1432 (void)printf("Pool cache statistics.\n");
1433 (void)printf("%-*s%*s%*s%*s%*s%*s%*s%*s%*s%*s\n",
1434 12, "Name",
1435 6, "Spin",
1436 6, "GrpSz",
1437 5, "Full",
1438 5, "Emty",
1439 10, "PoolLayer",
1440 11, "CacheLayer",
1441 6, "Hit%",
1442 12, "CpuLayer",
1443 6, "Hit%"
1444 );
1445 first = 0;
1446 }
1447
1448 ovflw = 0;
1449 PRWORD(ovflw, "%-*s", 13, 1, name);
1450 PRWORD(ovflw, " %*llu", 6, 1, (long long)pc->pc_contended);
1451 PRWORD(ovflw, " %*u", 6, 1, pc->pc_pcgsize);
1452 PRWORD(ovflw, " %*u", 5, 1, pc->pc_nfull);
1453 PRWORD(ovflw, " %*u", 5, 1, pc->pc_nempty);
1454 PRWORD(ovflw, " %*llu", 10, 1, (long long)pc->pc_misses);
1455
1456 tot = pc->pc_hits + pc->pc_misses;
1457 p = pc->pc_hits * 100.0 / (tot);
1458 PRWORD(ovflw, " %*llu", 11, 1, (long long)tot);
1459 PRWORD(ovflw, " %*.1f", 6, 1, p);
1460
1461 tot = cpuhit + cpumiss;
1462 p = cpuhit * 100.0 / (tot);
1463 PRWORD(ovflw, " %*llu", 12, 1, (long long)tot);
1464 PRWORD(ovflw, " %*.1f", 6, 1, p);
1465 printf("\n");
1466 }
1467 }
1468
1469 enum hashtype { /* from <sys/systm.h> */
1470 HASH_LIST,
1471 HASH_TAILQ
1472 };
1473
1474 struct uidinfo { /* XXX: no kernel header file */
1475 LIST_ENTRY(uidinfo) ui_hash;
1476 uid_t ui_uid;
1477 long ui_proccnt;
1478 };
1479
1480 struct kernel_hash {
1481 const char * description; /* description */
1482 int hashsize; /* nlist index for hash size */
1483 int hashtbl; /* nlist index for hash table */
1484 enum hashtype type; /* type of hash table */
1485 size_t offset; /* offset of {LIST,TAILQ}_NEXT */
1486 } khashes[] =
1487 {
1488 {
1489 "buffer hash",
1490 X_BUFHASH, X_BUFHASHTBL,
1491 HASH_LIST, offsetof(struct buf, b_hash)
1492 }, {
1493 "ipv4 address -> interface hash",
1494 X_IFADDRHASH, X_IFADDRHASHTBL,
1495 HASH_LIST, offsetof(struct in_ifaddr, ia_hash),
1496 }, {
1497 "name cache hash",
1498 X_NCHASH, X_NCHASHTBL,
1499 HASH_LIST, offsetof(struct namecache, nc_hash),
1500 }, {
1501 "name cache directory hash",
1502 X_NCVHASH, X_NCVHASHTBL,
1503 HASH_LIST, offsetof(struct namecache, nc_vhash),
1504 }, {
1505 "user info (uid -> used processes) hash",
1506 X_UIHASH, X_UIHASHTBL,
1507 HASH_LIST, offsetof(struct uidinfo, ui_hash),
1508 }, {
1509 NULL, -1, -1, 0, 0,
1510 }
1511 };
1512
1513 void
1514 dohashstat(int verbose, int todo, const char *hashname)
1515 {
1516 LIST_HEAD(, generic) *hashtbl_list;
1517 TAILQ_HEAD(, generic) *hashtbl_tailq;
1518 struct kernel_hash *curhash;
1519 void *hashaddr, *hashbuf, *nhashbuf, *nextaddr;
1520 size_t elemsize, hashbufsize, thissize;
1521 u_long hashsize, i;
1522 int used, items, chain, maxchain;
1523
1524 hashbuf = NULL;
1525 hashbufsize = 0;
1526
1527 if (todo & HASHLIST) {
1528 (void)printf("Supported hashes:\n");
1529 for (curhash = khashes; curhash->description; curhash++) {
1530 if (hashnl[curhash->hashsize].n_value == 0 ||
1531 hashnl[curhash->hashtbl].n_value == 0)
1532 continue;
1533 (void)printf("\t%-16s%s\n",
1534 hashnl[curhash->hashsize].n_name + 1,
1535 curhash->description);
1536 }
1537 return;
1538 }
1539
1540 if (hashname != NULL) {
1541 for (curhash = khashes; curhash->description; curhash++) {
1542 if (strcmp(hashnl[curhash->hashsize].n_name + 1,
1543 hashname) == 0 &&
1544 hashnl[curhash->hashsize].n_value != 0 &&
1545 hashnl[curhash->hashtbl].n_value != 0)
1546 break;
1547 }
1548 if (curhash->description == NULL) {
1549 warnx("%s: no such hash", hashname);
1550 return;
1551 }
1552 }
1553
1554 (void)printf(
1555 "%-16s %8s %8s %8s %8s %8s %8s\n"
1556 "%-16s %8s %8s %8s %8s %8s %8s\n",
1557 "", "total", "used", "util", "num", "average", "maximum",
1558 "hash table", "buckets", "buckets", "%", "items", "chain",
1559 "chain");
1560
1561 for (curhash = khashes; curhash->description; curhash++) {
1562 if (hashnl[curhash->hashsize].n_value == 0 ||
1563 hashnl[curhash->hashtbl].n_value == 0)
1564 continue;
1565 if (hashname != NULL &&
1566 strcmp(hashnl[curhash->hashsize].n_name + 1, hashname))
1567 continue;
1568 elemsize = curhash->type == HASH_LIST ?
1569 sizeof(*hashtbl_list) : sizeof(*hashtbl_tailq);
1570 deref_kptr((void *)hashnl[curhash->hashsize].n_value,
1571 &hashsize, sizeof(hashsize),
1572 hashnl[curhash->hashsize].n_name);
1573 hashsize++;
1574 deref_kptr((void *)hashnl[curhash->hashtbl].n_value,
1575 &hashaddr, sizeof(hashaddr),
1576 hashnl[curhash->hashtbl].n_name);
1577 if (verbose)
1578 (void)printf(
1579 "%s %lu, %s %p, offset %ld, elemsize %llu\n",
1580 hashnl[curhash->hashsize].n_name + 1, hashsize,
1581 hashnl[curhash->hashtbl].n_name + 1, hashaddr,
1582 (long)curhash->offset,
1583 (unsigned long long)elemsize);
1584 thissize = hashsize * elemsize;
1585 if (hashbuf == NULL || thissize > hashbufsize) {
1586 if ((nhashbuf = realloc(hashbuf, thissize)) == NULL)
1587 errx(1, "malloc hashbuf %llu",
1588 (unsigned long long)hashbufsize);
1589 hashbuf = nhashbuf;
1590 hashbufsize = thissize;
1591 }
1592 deref_kptr(hashaddr, hashbuf, thissize,
1593 hashnl[curhash->hashtbl].n_name);
1594 used = 0;
1595 items = maxchain = 0;
1596 if (curhash->type == HASH_LIST) {
1597 hashtbl_list = hashbuf;
1598 hashtbl_tailq = NULL;
1599 } else {
1600 hashtbl_list = NULL;
1601 hashtbl_tailq = hashbuf;
1602 }
1603 for (i = 0; i < hashsize; i++) {
1604 if (curhash->type == HASH_LIST)
1605 nextaddr = LIST_FIRST(&hashtbl_list[i]);
1606 else
1607 nextaddr = TAILQ_FIRST(&hashtbl_tailq[i]);
1608 if (nextaddr == NULL)
1609 continue;
1610 if (verbose)
1611 (void)printf("%5lu: %p\n", i, nextaddr);
1612 used++;
1613 chain = 0;
1614 do {
1615 chain++;
1616 deref_kptr((char *)nextaddr + curhash->offset,
1617 &nextaddr, sizeof(void *),
1618 "hash chain corrupted");
1619 if (verbose > 1)
1620 (void)printf("got nextaddr as %p\n",
1621 nextaddr);
1622 } while (nextaddr != NULL);
1623 items += chain;
1624 if (verbose && chain > 1)
1625 (void)printf("\tchain = %d\n", chain);
1626 if (chain > maxchain)
1627 maxchain = chain;
1628 }
1629 (void)printf("%-16s %8ld %8d %8.2f %8d %8.2f %8d\n",
1630 hashnl[curhash->hashsize].n_name + 1,
1631 hashsize, used, used * 100.0 / hashsize,
1632 items, used ? (double)items / used : 0.0, maxchain);
1633 }
1634 }
1635
1636 /*
1637 * kreadc like kread but returns 1 if sucessful, 0 otherwise
1638 */
1639 int
1640 kreadc(struct nlist *nl, int nlx, void *addr, size_t size)
1641 {
1642 const char *sym;
1643
1644 sym = nl[nlx].n_name;
1645 if (*sym == '_')
1646 ++sym;
1647 if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
1648 return 0;
1649 deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
1650 return 1;
1651 }
1652
1653 /*
1654 * kread reads something from the kernel, given its nlist index in namelist[].
1655 */
1656 void
1657 kread(struct nlist *nl, int nlx, void *addr, size_t size)
1658 {
1659 const char *sym;
1660
1661 sym = nl[nlx].n_name;
1662 if (*sym == '_')
1663 ++sym;
1664 if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
1665 errx(1, "symbol %s not defined", sym);
1666 deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
1667 }
1668
1669 /*
1670 * Dereference the kernel pointer `kptr' and fill in the local copy
1671 * pointed to by `ptr'. The storage space must be pre-allocated,
1672 * and the size of the copy passed in `len'.
1673 */
1674 void
1675 deref_kptr(const void *kptr, void *ptr, size_t len, const char *msg)
1676 {
1677
1678 if (*msg == '_')
1679 msg++;
1680 if ((size_t)kvm_read(kd, (u_long)kptr, (char *)ptr, len) != len)
1681 errx(1, "kptr %lx: %s: %s", (u_long)kptr, msg, kvm_geterr(kd));
1682 }
1683
1684 /*
1685 * Traverse the kernel history buffers, performing the requested action.
1686 *
1687 * Note, we assume that if we're not listing, we're dumping.
1688 */
1689 void
1690 hist_traverse(int todo, const char *histname)
1691 {
1692 struct kern_history_head histhead;
1693 struct kern_history hist, *histkva;
1694 char *name = NULL;
1695 size_t namelen = 0;
1696
1697 if (histnl[0].n_value == 0) {
1698 warnx("kernel history is not compiled into the kernel.");
1699 return;
1700 }
1701
1702 deref_kptr((void *)histnl[X_KERN_HISTORIES].n_value, &histhead,
1703 sizeof(histhead), histnl[X_KERN_HISTORIES].n_name);
1704
1705 if (histhead.lh_first == NULL) {
1706 warnx("No active kernel history logs.");
1707 return;
1708 }
1709
1710 if (todo & HISTLIST)
1711 (void)printf("Active kernel histories:");
1712
1713 for (histkva = LIST_FIRST(&histhead); histkva != NULL;
1714 histkva = LIST_NEXT(&hist, list)) {
1715 deref_kptr(histkva, &hist, sizeof(hist), "histkva");
1716 if (name == NULL || hist.namelen > namelen) {
1717 if (name != NULL)
1718 free(name);
1719 namelen = hist.namelen;
1720 if ((name = malloc(namelen + 1)) == NULL)
1721 err(1, "malloc history name");
1722 }
1723
1724 deref_kptr(hist.name, name, namelen, "history name");
1725 name[namelen] = '\0';
1726 if (todo & HISTLIST)
1727 (void)printf(" %s", name);
1728 else {
1729 /*
1730 * If we're dumping all histories, do it, else
1731 * check to see if this is the one we want.
1732 */
1733 if (histname == NULL || strcmp(histname, name) == 0) {
1734 if (histname == NULL)
1735 (void)printf(
1736 "\nkernel history `%s':\n", name);
1737 hist_dodump(&hist);
1738 }
1739 }
1740 }
1741
1742 if (todo & HISTLIST)
1743 (void)putchar('\n');
1744
1745 if (name != NULL)
1746 free(name);
1747 }
1748
1749 /*
1750 * Actually dump the history buffer at the specified KVA.
1751 */
1752 void
1753 hist_dodump(struct kern_history *histp)
1754 {
1755 struct kern_history_ent *histents, *e;
1756 size_t histsize;
1757 char *fmt = NULL, *fn = NULL;
1758 size_t fmtlen = 0, fnlen = 0;
1759 unsigned i;
1760
1761 histsize = sizeof(struct kern_history_ent) * histp->n;
1762
1763 if ((histents = malloc(histsize)) == NULL)
1764 err(1, "malloc history entries");
1765
1766 (void)memset(histents, 0, histsize);
1767
1768 deref_kptr(histp->e, histents, histsize, "history entries");
1769 i = histp->f;
1770 do {
1771 e = &histents[i];
1772 if (e->fmt != NULL) {
1773 if (fmt == NULL || e->fmtlen > fmtlen) {
1774 if (fmt != NULL)
1775 free(fmt);
1776 fmtlen = e->fmtlen;
1777 if ((fmt = malloc(fmtlen + 1)) == NULL)
1778 err(1, "malloc printf format");
1779 }
1780 if (fn == NULL || e->fnlen > fnlen) {
1781 if (fn != NULL)
1782 free(fn);
1783 fnlen = e->fnlen;
1784 if ((fn = malloc(fnlen + 1)) == NULL)
1785 err(1, "malloc function name");
1786 }
1787
1788 deref_kptr(e->fmt, fmt, fmtlen, "printf format");
1789 fmt[fmtlen] = '\0';
1790
1791 deref_kptr(e->fn, fn, fnlen, "function name");
1792 fn[fnlen] = '\0';
1793
1794 (void)printf("%06ld.%06ld ", (long int)e->tv.tv_sec,
1795 (long int)e->tv.tv_usec);
1796 (void)printf("%s#%ld: ", fn, e->call);
1797 (void)printf(fmt, e->v[0], e->v[1], e->v[2], e->v[3]);
1798 (void)putchar('\n');
1799 }
1800 i = (i + 1) % histp->n;
1801 } while (i != histp->f);
1802
1803 free(histents);
1804 if (fmt != NULL)
1805 free(fmt);
1806 if (fn != NULL)
1807 free(fn);
1808 }
1809
1810 static void
1811 usage(void)
1812 {
1813
1814 (void)fprintf(stderr,
1815 "usage: %s [-CefHiLlmstUvW] [-c count] [-h hashname] [-M core] [-N system]\n"
1816 "\t\t[-u histname] [-w wait] [disks]\n", getprogname());
1817 exit(1);
1818 }
1819