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