Home | History | Annotate | Line # | Download | only in vmstat
vmstat.c revision 1.186.2.2
      1 /* $NetBSD: vmstat.c,v 1.186.2.2 2011/11/14 14:27:53 yamt 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.186.2.2 2011/11/14 14:27:53 yamt 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 		(void)printf("%9" PRIu64 " file pages known clean\n",
    896 		    uvmexp2.cleanpages);
    897 		(void)printf("%9" PRIu64 " file pages possibly dirty\n",
    898 		    uvmexp2.possiblydirtypages);
    899 		(void)printf("%9" PRIu64 " file pages known dirty\n",
    900 		    uvmexp2.dirtypages);
    901 		(void)printf("%9" PRIu64 " anonymous pages known clean\n",
    902 		    uvmexp2.cleananonpages);
    903 		(void)printf("%9" PRIu64 " anonymous pages possibly dirty\n",
    904 		    uvmexp2.possiblydirtyanonpages);
    905 		(void)printf("%9" PRIu64 " anonymous pages known dirty\n",
    906 		    uvmexp2.dirtyanonpages);
    907 	}
    908 	(void)printf("%9u pages paging\n", uvmexp.paging);
    909 	(void)printf("%9u pages wired\n", uvmexp.wired);
    910 	(void)printf("%9u zero pages\n", uvmexp.zeropages);
    911 	(void)printf("%9u reserve pagedaemon pages\n",
    912 	    uvmexp.reserve_pagedaemon);
    913 	(void)printf("%9u reserve kernel pages\n", uvmexp.reserve_kernel);
    914 	(void)printf("%9u anonymous pages\n", uvmexp.anonpages);
    915 	(void)printf("%9u cached file pages\n", uvmexp.filepages);
    916 	(void)printf("%9u cached executable pages\n", uvmexp.execpages);
    917 
    918 	(void)printf("%9u minimum free pages\n", uvmexp.freemin);
    919 	(void)printf("%9u target free pages\n", uvmexp.freetarg);
    920 	(void)printf("%9u maximum wired pages\n", uvmexp.wiredmax);
    921 
    922 	(void)printf("%9u swap devices\n", uvmexp.nswapdev);
    923 	(void)printf("%9u swap pages\n", uvmexp.swpages);
    924 	(void)printf("%9u swap pages in use\n", uvmexp.swpginuse);
    925 	(void)printf("%9u swap allocations\n", uvmexp.nswget);
    926 
    927 	kread(namelist, X_CPU_QUEUE, &cpu_queue, sizeof(cpu_queue));
    928 	cpucounters(&cc);
    929 	(void)printf("%9" PRIu64 " total faults taken\n", cc.nfault);
    930 	(void)printf("%9" PRIu64 " traps\n", cc.ntrap);
    931 	(void)printf("%9" PRIu64 " device interrupts\n", cc.nintr);
    932 	(void)printf("%9" PRIu64 " CPU context switches\n", cc.nswtch);
    933 	(void)printf("%9" PRIu64 " software interrupts\n", cc.nsoft);
    934 	(void)printf("%9" PRIu64 " system calls\n", cc.nsyscall);
    935 	(void)printf("%9u pagein requests\n", uvmexp.pageins);
    936 	(void)printf("%9u pageout requests\n", uvmexp.pdpageouts);
    937 	(void)printf("%9u pages swapped in\n", uvmexp.pgswapin);
    938 	(void)printf("%9u pages swapped out\n", uvmexp.pgswapout);
    939 	(void)printf("%9u forks total\n", uvmexp.forks);
    940 	(void)printf("%9u forks blocked parent\n", uvmexp.forks_ppwait);
    941 	(void)printf("%9u forks shared address space with parent\n",
    942 	    uvmexp.forks_sharevm);
    943 	(void)printf("%9u pagealloc zero wanted and avail\n",
    944 	    uvmexp.pga_zerohit);
    945 	(void)printf("%9u pagealloc zero wanted and not avail\n",
    946 	    uvmexp.pga_zeromiss);
    947 	(void)printf("%9u aborts of idle page zeroing\n",
    948 	    uvmexp.zeroaborts);
    949 	(void)printf("%9u pagealloc desired color avail\n",
    950 	    uvmexp.colorhit);
    951 	(void)printf("%9u pagealloc desired color not avail\n",
    952 	    uvmexp.colormiss);
    953 	(void)printf("%9u pagealloc local cpu avail\n",
    954 	    uvmexp.cpuhit);
    955 	(void)printf("%9u pagealloc local cpu not avail\n",
    956 	    uvmexp.cpumiss);
    957 
    958 	(void)printf("%9u faults with no memory\n", uvmexp.fltnoram);
    959 	(void)printf("%9u faults with no anons\n", uvmexp.fltnoanon);
    960 	(void)printf("%9u faults had to wait on pages\n", uvmexp.fltpgwait);
    961 	(void)printf("%9u faults found released page\n", uvmexp.fltpgrele);
    962 	(void)printf("%9u faults relock (%u ok)\n", uvmexp.fltrelck,
    963 	    uvmexp.fltrelckok);
    964 	(void)printf("%9u anon page faults\n", uvmexp.fltanget);
    965 	(void)printf("%9u anon retry faults\n", uvmexp.fltanretry);
    966 	(void)printf("%9u amap copy faults\n", uvmexp.fltamcopy);
    967 	(void)printf("%9u neighbour anon page faults\n", uvmexp.fltnamap);
    968 	(void)printf("%9u neighbour object page faults\n", uvmexp.fltnomap);
    969 	(void)printf("%9u locked pager get faults\n", uvmexp.fltlget);
    970 	(void)printf("%9u unlocked pager get faults\n", uvmexp.fltget);
    971 	(void)printf("%9u anon faults\n", uvmexp.flt_anon);
    972 	(void)printf("%9u anon copy on write faults\n", uvmexp.flt_acow);
    973 	(void)printf("%9u object faults\n", uvmexp.flt_obj);
    974 	(void)printf("%9u promote copy faults\n", uvmexp.flt_prcopy);
    975 	(void)printf("%9u promote zero fill faults\n", uvmexp.flt_przero);
    976 
    977 	(void)printf("%9u times daemon wokeup\n",uvmexp.pdwoke);
    978 	(void)printf("%9u revolutions of the clock hand\n", uvmexp.pdrevs);
    979 	(void)printf("%9u pages freed by daemon\n", uvmexp.pdfreed);
    980 	(void)printf("%9u pages scanned by daemon\n", uvmexp.pdscans);
    981 	(void)printf("%9u anonymous pages scanned by daemon\n",
    982 	    uvmexp.pdanscan);
    983 	(void)printf("%9u object pages scanned by daemon\n", uvmexp.pdobscan);
    984 	(void)printf("%9u pages reactivated\n", uvmexp.pdreact);
    985 	(void)printf("%9u pages found busy by daemon\n", uvmexp.pdbusy);
    986 	(void)printf("%9u total pending pageouts\n", uvmexp.pdpending);
    987 	(void)printf("%9u pages deactivated\n", uvmexp.pddeact);
    988 
    989 	kread(namelist, X_NCHSTATS, &nchstats, sizeof(nchstats));
    990 	nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
    991 	    nchstats.ncs_badhits + nchstats.ncs_falsehits +
    992 	    nchstats.ncs_miss + nchstats.ncs_long;
    993 	(void)printf("%9lu total name lookups\n", nchtotal);
    994 	(void)printf("%9lu good hits\n", nchstats.ncs_goodhits);
    995 	(void)printf("%9lu negative hits\n", nchstats.ncs_neghits);
    996 	(void)printf("%9lu bad hits\n", nchstats.ncs_badhits);
    997 	(void)printf("%9lu false hits\n", nchstats.ncs_falsehits);
    998 	(void)printf("%9lu miss\n", nchstats.ncs_miss);
    999 	(void)printf("%9lu too long\n", nchstats.ncs_long);
   1000 	(void)printf("%9lu pass2 hits\n", nchstats.ncs_pass2);
   1001 	(void)printf("%9lu 2passes\n", nchstats.ncs_2passes);
   1002 	(void)printf(
   1003 	    "%9s cache hits (%d%% pos + %d%% neg) system %d%% per-process\n",
   1004 	    "", PCT(nchstats.ncs_goodhits, nchtotal),
   1005 	    PCT(nchstats.ncs_neghits, nchtotal),
   1006 	    PCT(nchstats.ncs_pass2, nchtotal));
   1007 	(void)printf("%9s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
   1008 	    PCT(nchstats.ncs_badhits, nchtotal),
   1009 	    PCT(nchstats.ncs_falsehits, nchtotal),
   1010 	    PCT(nchstats.ncs_long, nchtotal));
   1011 }
   1012 
   1013 void
   1014 doforkst(void)
   1015 {
   1016 	kread(namelist, X_UVMEXP, &uvmexp, sizeof(uvmexp));
   1017 
   1018 	(void)printf("%u forks total\n", uvmexp.forks);
   1019 	(void)printf("%u forks blocked parent\n", uvmexp.forks_ppwait);
   1020 	(void)printf("%u forks shared address space with parent\n",
   1021 	    uvmexp.forks_sharevm);
   1022 }
   1023 
   1024 void
   1025 drvstats(int *ovflwp)
   1026 {
   1027 	size_t dn;
   1028 	double etime;
   1029 	int ovflw = *ovflwp;
   1030 
   1031 	/* Calculate disk stat deltas. */
   1032 	cpuswap();
   1033 	drvswap();
   1034 	tkswap();
   1035 	etime = cur.cp_etime;
   1036 
   1037 	for (dn = 0; dn < ndrive; ++dn) {
   1038 		if (!drv_select[dn])
   1039 	 		continue;
   1040 		PRWORD(ovflw, " %*.0f", 3, 1,
   1041 		    (cur.rxfer[dn] + cur.wxfer[dn]) / etime);
   1042 	}
   1043 	*ovflwp = ovflw;
   1044 }
   1045 
   1046 void
   1047 cpucounters(struct cpu_counter *cc)
   1048 {
   1049 	struct cpu_info *ci, *first = NULL;
   1050 	(void)memset(cc, 0, sizeof(*cc));
   1051 	CIRCLEQ_FOREACH(ci, &cpu_queue, ci_data.cpu_qchain) {
   1052 		struct cpu_info tci;
   1053 		if ((size_t)kvm_read(kd, (u_long)ci, &tci, sizeof(tci))
   1054 		    != sizeof(tci)) {
   1055 		    warnx("Can't read cpu info from %p (%s)",
   1056 			ci, kvm_geterr(kd));
   1057 		    (void)memset(cc, 0, sizeof(*cc));
   1058 		    return;
   1059 		}
   1060 		if (first == NULL)
   1061 			first = tci.ci_data.cpu_qchain.cqe_prev;
   1062 		cc->nintr += tci.ci_data.cpu_nintr;
   1063 		cc->nsyscall += tci.ci_data.cpu_nsyscall;
   1064 		cc->nswtch = tci.ci_data.cpu_nswtch;
   1065 		cc->nfault = tci.ci_data.cpu_nfault;
   1066 		cc->ntrap = tci.ci_data.cpu_ntrap;
   1067 		cc->nsoft = tci.ci_data.cpu_nsoft;
   1068 		ci = &tci;
   1069 		if (tci.ci_data.cpu_qchain.cqe_next == first)
   1070 			break;
   1071 	}
   1072 }
   1073 
   1074 void
   1075 cpustats(int *ovflwp)
   1076 {
   1077 	int state;
   1078 	double pcnt, total;
   1079 	double stat_us, stat_sy, stat_id;
   1080 	int ovflw = *ovflwp;
   1081 
   1082 	total = 0;
   1083 	for (state = 0; state < CPUSTATES; ++state)
   1084 		total += cur.cp_time[state];
   1085 	if (total)
   1086 		pcnt = 100 / total;
   1087 	else
   1088 		pcnt = 0;
   1089 	stat_us = (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * pcnt;
   1090 	stat_sy = (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * pcnt;
   1091 	stat_id = cur.cp_time[CP_IDLE] * pcnt;
   1092 	PRWORD(ovflw, " %*.0f", ((stat_sy >= 100) ? 2 : 3), 1, stat_us);
   1093 	PRWORD(ovflw, " %*.0f", ((stat_us >= 100 || stat_id >= 100) ? 2 : 3), 1,
   1094 	    stat_sy);
   1095 	PRWORD(ovflw, " %*.0f", 3, 1, stat_id);
   1096 	*ovflwp = ovflw;
   1097 }
   1098 
   1099 void
   1100 dointr(int verbose)
   1101 {
   1102 	unsigned long *intrcnt, *ointrcnt;
   1103 	unsigned long long inttotal, uptime;
   1104 	int nintr, inamlen;
   1105 	char *intrname, *ointrname;
   1106 
   1107 	inttotal = 0;
   1108 	uptime = getuptime();
   1109 	(void)printf("%-34s %16s %8s\n", "interrupt", "total", "rate");
   1110 	nintr = intrnl[X_EINTRCNT].n_value - intrnl[X_INTRCNT].n_value;
   1111 	inamlen = intrnl[X_EINTRNAMES].n_value - intrnl[X_INTRNAMES].n_value;
   1112 	if (nintr != 0 && inamlen != 0) {
   1113 		ointrcnt = intrcnt = malloc((size_t)nintr);
   1114 		ointrname = intrname = malloc((size_t)inamlen);
   1115 		if (intrcnt == NULL || intrname == NULL)
   1116 			errx(1, "%s", "");
   1117 		kread(intrnl, X_INTRCNT, intrcnt, (size_t)nintr);
   1118 		kread(intrnl, X_INTRNAMES, intrname, (size_t)inamlen);
   1119 		nintr /= sizeof(long);
   1120 		while (--nintr >= 0) {
   1121 			if (*intrcnt || verbose)
   1122 				(void)printf("%-34s %16llu %8llu\n", intrname,
   1123 					     (unsigned long long)*intrcnt,
   1124 					     (unsigned long long)
   1125 					     (*intrcnt / uptime));
   1126 			intrname += strlen(intrname) + 1;
   1127 			inttotal += *intrcnt++;
   1128 		}
   1129 		free(ointrcnt);
   1130 		free(ointrname);
   1131 	}
   1132 
   1133 	doevcnt(verbose, EVCNT_TYPE_INTR);
   1134 }
   1135 
   1136 void
   1137 doevcnt(int verbose, int type)
   1138 {
   1139 	static const char * const evtypes [] = { "misc", "intr", "trap" };
   1140 	uint64_t counttotal, uptime;
   1141 	struct evcntlist allevents;
   1142 	struct evcnt evcnt, *evptr;
   1143 	char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
   1144 
   1145 	counttotal = 0;
   1146 	uptime = getuptime();
   1147 	if (type == EVCNT_TYPE_ANY)
   1148 		(void)printf("%-34s %16s %8s %s\n", "event", "total", "rate",
   1149 		    "type");
   1150 
   1151 	if (memf == NULL) do {
   1152 		const int mib[4] = { CTL_KERN, KERN_EVCNT, type,
   1153 		    verbose ? KERN_EVCNT_COUNT_ANY : KERN_EVCNT_COUNT_NONZERO };
   1154 		size_t buflen = 0;
   1155 		void *buf = NULL;
   1156 		const struct evcnt_sysctl *evs, *last_evs;
   1157 		for (;;) {
   1158 			size_t newlen;
   1159 			int error;
   1160 			if (buflen)
   1161 				buf = malloc(buflen);
   1162 			error = sysctl(mib, __arraycount(mib),
   1163 			    buf, &newlen, NULL, 0);
   1164 			if (error) {
   1165 				/* if the sysctl is unknown, try groveling */
   1166 				if (error == ENOENT)
   1167 					break;
   1168 				warn("kern.evcnt");
   1169 				if (buf)
   1170 					free(buf);
   1171 				return;
   1172 			}
   1173 			if (newlen <= buflen) {
   1174 				buflen = newlen;
   1175 				break;
   1176 			}
   1177 			if (buf)
   1178 				free(buf);
   1179 			buflen = newlen;
   1180 		}
   1181 		evs = buf;
   1182 		last_evs = (void *)((char *)buf + buflen);
   1183 		buflen /= sizeof(uint64_t);
   1184 		while (evs < last_evs
   1185 		    && buflen >= sizeof(*evs)/sizeof(uint64_t)
   1186 		    && buflen >= evs->ev_len) {
   1187 			(void)printf(type == EVCNT_TYPE_ANY ?
   1188 			    "%s %s%*s %16"PRIu64" %8"PRIu64" %s\n" :
   1189 			    "%s %s%*s %16"PRIu64" %8"PRIu64"\n",
   1190 			    evs->ev_strings,
   1191 			    evs->ev_strings + evs->ev_grouplen + 1,
   1192 			    34 - (evs->ev_grouplen + 1 + evs->ev_namelen), "",
   1193 			    evs->ev_count,
   1194 			    evs->ev_count / uptime,
   1195 			    (evs->ev_type < __arraycount(evtypes) ?
   1196 				evtypes[evs->ev_type] : "?"));
   1197 			buflen -= evs->ev_len;
   1198 			counttotal += evs->ev_count;
   1199 			evs = (const void *)((const uint64_t *)evs + evs->ev_len);
   1200 		}
   1201 		free(buf);
   1202 		if (type != EVCNT_TYPE_ANY)
   1203 			(void)printf("%-34s %16"PRIu64" %8"PRIu64"\n",
   1204 			    "Total", counttotal, counttotal / uptime);
   1205 		return;
   1206 	} while (/*CONSTCOND*/ 0);
   1207 
   1208 	kread(namelist, X_ALLEVENTS, &allevents, sizeof allevents);
   1209 	evptr = TAILQ_FIRST(&allevents);
   1210 	while (evptr) {
   1211 		deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
   1212 
   1213 		evptr = TAILQ_NEXT(&evcnt, ev_list);
   1214 		if (evcnt.ev_count == 0 && !verbose)
   1215 			continue;
   1216 		if (type != EVCNT_TYPE_ANY && evcnt.ev_type != type)
   1217 			continue;
   1218 
   1219 		deref_kptr(evcnt.ev_group, evgroup,
   1220 		    (size_t)evcnt.ev_grouplen + 1, "event chain trashed");
   1221 		deref_kptr(evcnt.ev_name, evname,
   1222 		    (size_t)evcnt.ev_namelen + 1, "event chain trashed");
   1223 
   1224 		(void)printf(type == EVCNT_TYPE_ANY ?
   1225 		    "%s %s%*s %16"PRIu64" %8"PRIu64" %s\n" :
   1226 		    "%s %s%*s %16"PRIu64" %8"PRIu64"\n",
   1227 		    evgroup, evname,
   1228 		    34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
   1229 		    evcnt.ev_count,
   1230 		    (evcnt.ev_count / uptime),
   1231 		    (evcnt.ev_type < __arraycount(evtypes) ?
   1232 			evtypes[evcnt.ev_type] : "?"));
   1233 
   1234 		counttotal += evcnt.ev_count;
   1235 	}
   1236 	if (type != EVCNT_TYPE_ANY)
   1237 		(void)printf("%-34s %16"PRIu64" %8"PRIu64"\n",
   1238 		    "Total", counttotal, counttotal / uptime);
   1239 }
   1240 
   1241 static char memname[64];
   1242 
   1243 void
   1244 domem(void)
   1245 {
   1246 	struct kmembuckets *kp;
   1247 	struct malloc_type ks, *ksp;
   1248 	int i, j;
   1249 	int len, size, first;
   1250 	long totuse = 0, totfree = 0, totreq = 0;
   1251 	struct kmembuckets buckets[MINBUCKET + 16];
   1252 
   1253 	kread(namelist, X_KMEMBUCKETS, buckets, sizeof(buckets));
   1254 	for (first = 1, i = MINBUCKET, kp = &buckets[i]; i < MINBUCKET + 16;
   1255 	    i++, kp++) {
   1256 		if (kp->kb_calls == 0)
   1257 			continue;
   1258 		if (first) {
   1259 			(void)printf("Memory statistics by bucket size\n");
   1260 			(void)printf(
   1261 		 "    Size   In Use   Free   Requests  HighWater  Couldfree\n");
   1262 			first = 0;
   1263 		}
   1264 		size = 1 << i;
   1265 		(void)printf("%8d %8ld %6ld %10ld %7ld %10ld\n", size,
   1266 		    kp->kb_total - kp->kb_totalfree,
   1267 		    kp->kb_totalfree, kp->kb_calls,
   1268 		    kp->kb_highwat, kp->kb_couldfree);
   1269 		totfree += size * kp->kb_totalfree;
   1270 	}
   1271 
   1272 	/*
   1273 	 * If kmem statistics are not being gathered by the kernel,
   1274 	 * first will still be 1.
   1275 	 */
   1276 	if (first) {
   1277 		warnx("Kmem statistics are not being gathered by the kernel.");
   1278 		return;
   1279 	}
   1280 
   1281 	(void)printf("\nMemory usage type by bucket size\n");
   1282 	(void)printf("    Size  Type(s)\n");
   1283 	kp = &buckets[MINBUCKET];
   1284 	for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1, kp++) {
   1285 		if (kp->kb_calls == 0)
   1286 			continue;
   1287 		first = 1;
   1288 		len = 8;
   1289 		for (kread(namelist, X_KMEMSTAT, &ksp, sizeof(ksp));
   1290 		     ksp != NULL; ksp = ks.ks_next) {
   1291 			deref_kptr(ksp, &ks, sizeof(ks), "malloc type");
   1292 			if (ks.ks_calls == 0)
   1293 				continue;
   1294 			if ((ks.ks_size & j) == 0)
   1295 				continue;
   1296 			deref_kptr(ks.ks_shortdesc, memname,
   1297 			    sizeof(memname), "malloc type name");
   1298 			len += 2 + strlen(memname);
   1299 			if (first)
   1300 				(void)printf("%8d  %s", j, memname);
   1301 			else
   1302 				(void)printf(",");
   1303 			if (len >= 80) {
   1304 				(void)printf("\n\t ");
   1305 				len = 10 + strlen(memname);
   1306 			}
   1307 			if (!first)
   1308 				(void)printf(" %s", memname);
   1309 			first = 0;
   1310 		}
   1311 		(void)putchar('\n');
   1312 	}
   1313 
   1314 	(void)printf(
   1315 	    "\nMemory statistics by type                                Type  Kern\n");
   1316 	(void)printf(
   1317 "           Type InUse  MemUse HighUse   Limit   Requests Limit Limit Size(s)\n");
   1318 	for (kread(namelist, X_KMEMSTAT, &ksp, sizeof(ksp));
   1319 	     ksp != NULL; ksp = ks.ks_next) {
   1320 		deref_kptr(ksp, &ks, sizeof(ks), "malloc type");
   1321 		if (ks.ks_calls == 0)
   1322 			continue;
   1323 		deref_kptr(ks.ks_shortdesc, memname,
   1324 		    sizeof(memname), "malloc type name");
   1325 		(void)printf("%15s %5ld %6ldK %6ldK %6ldK %10ld %5u %5u",
   1326 		    memname,
   1327 		    ks.ks_inuse, howmany(ks.ks_memuse, KILO),
   1328 		    howmany(ks.ks_maxused, KILO),
   1329 		    howmany(ks.ks_limit, KILO), ks.ks_calls,
   1330 		    ks.ks_limblocks, ks.ks_mapblocks);
   1331 		first = 1;
   1332 		for (j = 1 << MINBUCKET, i = MINBUCKET;
   1333 		     j < 1 << (MINBUCKET + 16);
   1334 		     j <<= 1, i++)
   1335 		{
   1336 			if ((ks.ks_size & j) == 0)
   1337 				continue;
   1338 			if (first)
   1339 				(void)printf(" %d", j);
   1340 			else
   1341 				(void)printf(",%d", j);
   1342 			first = 0;
   1343 			(void)printf(":%u", ks.ks_active[i - MINBUCKET]);
   1344 		}
   1345 		(void)printf("\n");
   1346 		totuse += ks.ks_memuse;
   1347 		totreq += ks.ks_calls;
   1348 	}
   1349 	(void)printf("\nMemory totals:  In Use    Free    Requests\n");
   1350 	(void)printf("              %7ldK %6ldK    %8ld\n\n",
   1351 	    howmany(totuse, KILO), howmany(totfree, KILO), totreq);
   1352 }
   1353 
   1354 void
   1355 dopool(int verbose, int wide)
   1356 {
   1357 	int first, ovflw;
   1358 	void *addr;
   1359 	long total, inuse, this_total, this_inuse;
   1360 	TAILQ_HEAD(,pool) pool_head;
   1361 	struct pool pool, *pp = &pool;
   1362 	struct pool_allocator pa;
   1363 	char name[32], maxp[32];
   1364 
   1365 	kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
   1366 	addr = TAILQ_FIRST(&pool_head);
   1367 
   1368 	total = inuse = 0;
   1369 
   1370 	for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
   1371 		deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
   1372 		deref_kptr(pp->pr_alloc, &pa, sizeof(pa),
   1373 		    "pool allocator trashed");
   1374 		deref_kptr(pp->pr_wchan, name, sizeof(name),
   1375 		    "pool wait channel trashed");
   1376 		name[sizeof(name)-1] = '\0';
   1377 
   1378 		if (first) {
   1379 			(void)printf("Memory resource pool statistics\n");
   1380 			(void)printf(
   1381 			    "%-*s%*s%*s%5s%*s%s%s%*s%*s%6s%s%6s%6s%6s%5s%s%s\n",
   1382 			    wide ? 16 : 11, "Name",
   1383 			    wide ? 6 : 5, "Size",
   1384 			    wide ? 12 : 9, "Requests",
   1385 			    "Fail",
   1386 			    wide ? 12 : 9, "Releases",
   1387 			    wide ? "  InUse" : "",
   1388 			    wide ? " Avail" : "",
   1389 			    wide ? 7 : 6, "Pgreq",
   1390 			    wide ? 7 : 6, "Pgrel",
   1391 			    "Npage",
   1392 			    wide ? " PageSz" : "",
   1393 			    "Hiwat",
   1394 			    "Minpg",
   1395 			    "Maxpg",
   1396 			    "Idle",
   1397 			    wide ? " Flags" : "",
   1398 			    wide ? "   Util" : "");
   1399 			first = 0;
   1400 		}
   1401 		if (pp->pr_nget == 0 && !verbose)
   1402 			continue;
   1403 		if (pp->pr_maxpages == UINT_MAX)
   1404 			(void)snprintf(maxp, sizeof(maxp), "inf");
   1405 		else
   1406 			(void)snprintf(maxp, sizeof(maxp), "%u",
   1407 			    pp->pr_maxpages);
   1408 		ovflw = 0;
   1409 		PRWORD(ovflw, "%-*s", wide ? 16 : 11, 0, name);
   1410 		PRWORD(ovflw, " %*u", wide ? 6 : 5, 1, pp->pr_size);
   1411 		PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nget);
   1412 		PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nfail);
   1413 		PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nput);
   1414 		if (wide)
   1415 			PRWORD(ovflw, " %*u", 7, 1, pp->pr_nout);
   1416 		if (wide)
   1417 			PRWORD(ovflw, " %*u", 6, 1, pp->pr_nitems);
   1418 		PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagealloc);
   1419 		PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagefree);
   1420 		PRWORD(ovflw, " %*u", 6, 1, pp->pr_npages);
   1421 		if (wide)
   1422 			PRWORD(ovflw, " %*u", 7, 1, pa.pa_pagesz);
   1423 		PRWORD(ovflw, " %*u", 6, 1, pp->pr_hiwat);
   1424 		PRWORD(ovflw, " %*u", 6, 1, pp->pr_minpages);
   1425 		PRWORD(ovflw, " %*s", 6, 1, maxp);
   1426 		PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nidle);
   1427 		if (wide)
   1428 			PRWORD(ovflw, " 0x%0*x", 4, 1,
   1429 			    pp->pr_flags | pp->pr_roflags);
   1430 
   1431 		this_inuse = pp->pr_nout * pp->pr_size;
   1432 		this_total = pp->pr_npages * pa.pa_pagesz;
   1433 		if (pp->pr_roflags & PR_RECURSIVE) {
   1434 			/*
   1435 			 * Don't count in-use memory, since it's part
   1436 			 * of another pool and will be accounted for
   1437 			 * there.
   1438 			 */
   1439 			total += (this_total - this_inuse);
   1440 		} else {
   1441 			inuse += this_inuse;
   1442 			total += this_total;
   1443 		}
   1444 		if (wide) {
   1445 			if (this_total == 0)
   1446 				(void)printf("   ---");
   1447 			else
   1448 				(void)printf(" %5.1f%%",
   1449 				    (100.0 * this_inuse) / this_total);
   1450 		}
   1451 		(void)printf("\n");
   1452 	}
   1453 
   1454 	inuse /= KILO;
   1455 	total /= KILO;
   1456 	(void)printf(
   1457 	    "\nIn use %ldK, total allocated %ldK; utilization %.1f%%\n",
   1458 	    inuse, total, (100.0 * inuse) / total);
   1459 }
   1460 
   1461 void
   1462 dopoolcache(int verbose)
   1463 {
   1464 	struct pool_cache pool_cache, *pc = &pool_cache;
   1465 	pool_cache_cpu_t cache_cpu, *cc = &cache_cpu;
   1466 	TAILQ_HEAD(,pool) pool_head;
   1467 	struct pool pool, *pp = &pool;
   1468 	char name[32];
   1469 	uint64_t cpuhit, cpumiss, tot;
   1470 	void *addr;
   1471 	int first, ovflw;
   1472 	size_t i;
   1473 	double p;
   1474 
   1475 	kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
   1476 	addr = TAILQ_FIRST(&pool_head);
   1477 
   1478 	for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
   1479 		deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
   1480 		if (pp->pr_cache == NULL)
   1481 			continue;
   1482 		deref_kptr(pp->pr_wchan, name, sizeof(name),
   1483 		    "pool wait channel trashed");
   1484 		deref_kptr(pp->pr_cache, pc, sizeof(*pc), "pool cache trashed");
   1485 		if (pc->pc_misses == 0 && !verbose)
   1486 			continue;
   1487 		name[sizeof(name)-1] = '\0';
   1488 
   1489 		cpuhit = 0;
   1490 		cpumiss = 0;
   1491 		for (i = 0; i < __arraycount(pc->pc_cpus); i++) {
   1492 		    	if ((addr = pc->pc_cpus[i]) == NULL)
   1493 		    		continue;
   1494 			deref_kptr(addr, cc, sizeof(*cc),
   1495 			    "pool cache cpu trashed");
   1496 			cpuhit += cc->cc_hits;
   1497 			cpumiss += cc->cc_misses;
   1498 		}
   1499 
   1500 		if (first) {
   1501 			(void)printf("Pool cache statistics.\n");
   1502 			(void)printf("%-*s%*s%*s%*s%*s%*s%*s%*s%*s%*s\n",
   1503 			    12, "Name",
   1504 			    6, "Spin",
   1505 			    6, "GrpSz",
   1506 			    5, "Full",
   1507 			    5, "Emty",
   1508 			    10, "PoolLayer",
   1509 			    11, "CacheLayer",
   1510 			    6, "Hit%",
   1511 			    12, "CpuLayer",
   1512 			    6, "Hit%"
   1513 			);
   1514 			first = 0;
   1515 		}
   1516 
   1517 		ovflw = 0;
   1518 		PRWORD(ovflw, "%-*s", 13, 1, name);
   1519 		PRWORD(ovflw, " %*llu", 6, 1, (long long)pc->pc_contended);
   1520 		PRWORD(ovflw, " %*u", 6, 1, pc->pc_pcgsize);
   1521 		PRWORD(ovflw, " %*u", 5, 1, pc->pc_nfull);
   1522 		PRWORD(ovflw, " %*u", 5, 1, pc->pc_nempty);
   1523 		PRWORD(ovflw, " %*llu", 10, 1, (long long)pc->pc_misses);
   1524 
   1525 		tot = pc->pc_hits + pc->pc_misses;
   1526 		p = pc->pc_hits * 100.0 / (tot);
   1527 		PRWORD(ovflw, " %*llu", 11, 1, (long long)tot);
   1528 		PRWORD(ovflw, " %*.1f", 6, 1, p);
   1529 
   1530 		tot = cpuhit + cpumiss;
   1531 		p = cpuhit * 100.0 / (tot);
   1532 		PRWORD(ovflw, " %*llu", 12, 1, (long long)tot);
   1533 		PRWORD(ovflw, " %*.1f", 6, 1, p);
   1534 		printf("\n");
   1535 	}
   1536 }
   1537 
   1538 enum hashtype {			/* from <sys/systm.h> */
   1539 	HASH_LIST,
   1540 	HASH_TAILQ
   1541 };
   1542 
   1543 struct uidinfo {		/* XXX: no kernel header file */
   1544 	LIST_ENTRY(uidinfo) ui_hash;
   1545 	uid_t	ui_uid;
   1546 	long	ui_proccnt;
   1547 };
   1548 
   1549 struct kernel_hash {
   1550 	const char *	description;	/* description */
   1551 	int		hashsize;	/* nlist index for hash size */
   1552 	int		hashtbl;	/* nlist index for hash table */
   1553 	enum hashtype	type;		/* type of hash table */
   1554 	size_t		offset;		/* offset of {LIST,TAILQ}_NEXT */
   1555 } khashes[] =
   1556 {
   1557 	{
   1558 		"buffer hash",
   1559 		X_BUFHASH, X_BUFHASHTBL,
   1560 		HASH_LIST, offsetof(struct buf, b_hash)
   1561 	}, {
   1562 		"inode cache (ihash)",
   1563 		X_IHASH, X_IHASHTBL,
   1564 		HASH_LIST, offsetof(struct inode, i_hash)
   1565 	}, {
   1566 		"ipv4 address -> interface hash",
   1567 		X_IFADDRHASH, X_IFADDRHASHTBL,
   1568 		HASH_LIST, offsetof(struct in_ifaddr, ia_hash),
   1569 	}, {
   1570 		"name cache hash",
   1571 		X_NCHASH, X_NCHASHTBL,
   1572 		HASH_LIST, offsetof(struct namecache, nc_hash),
   1573 	}, {
   1574 		"name cache directory hash",
   1575 		X_NCVHASH, X_NCVHASHTBL,
   1576 		HASH_LIST, offsetof(struct namecache, nc_vhash),
   1577 	}, {
   1578 		"user info (uid -> used processes) hash",
   1579 		X_UIHASH, X_UIHASHTBL,
   1580 		HASH_LIST, offsetof(struct uidinfo, ui_hash),
   1581 	}, {
   1582 		NULL, -1, -1, 0, 0,
   1583 	}
   1584 };
   1585 
   1586 void
   1587 dohashstat(int verbose, int todo, const char *hashname)
   1588 {
   1589 	LIST_HEAD(, generic)	*hashtbl_list;
   1590 	TAILQ_HEAD(, generic)	*hashtbl_tailq;
   1591 	struct kernel_hash	*curhash;
   1592 	void	*hashaddr, *hashbuf, *nhashbuf, *nextaddr;
   1593 	size_t	elemsize, hashbufsize, thissize;
   1594 	u_long	hashsize, i;
   1595 	int	used, items, chain, maxchain;
   1596 
   1597 	hashbuf = NULL;
   1598 	hashbufsize = 0;
   1599 
   1600 	if (todo & HASHLIST) {
   1601 		(void)printf("Supported hashes:\n");
   1602 		for (curhash = khashes; curhash->description; curhash++) {
   1603 			if (hashnl[curhash->hashsize].n_value == 0 ||
   1604 			    hashnl[curhash->hashtbl].n_value == 0)
   1605 				continue;
   1606 			(void)printf("\t%-16s%s\n",
   1607 			    hashnl[curhash->hashsize].n_name + 1,
   1608 			    curhash->description);
   1609 		}
   1610 		return;
   1611 	}
   1612 
   1613 	if (hashname != NULL) {
   1614 		for (curhash = khashes; curhash->description; curhash++) {
   1615 			if (strcmp(hashnl[curhash->hashsize].n_name + 1,
   1616 			    hashname) == 0 &&
   1617 			    hashnl[curhash->hashsize].n_value != 0 &&
   1618 			    hashnl[curhash->hashtbl].n_value != 0)
   1619 				break;
   1620 		}
   1621 		if (curhash->description == NULL) {
   1622 			warnx("%s: no such hash", hashname);
   1623 			return;
   1624 		}
   1625 	}
   1626 
   1627 	(void)printf(
   1628 	    "%-16s %8s %8s %8s %8s %8s %8s\n"
   1629 	    "%-16s %8s %8s %8s %8s %8s %8s\n",
   1630 	    "", "total", "used", "util", "num", "average", "maximum",
   1631 	    "hash table", "buckets", "buckets", "%", "items", "chain",
   1632 	    "chain");
   1633 
   1634 	for (curhash = khashes; curhash->description; curhash++) {
   1635 		if (hashnl[curhash->hashsize].n_value == 0 ||
   1636 		    hashnl[curhash->hashtbl].n_value == 0)
   1637 			continue;
   1638 		if (hashname != NULL &&
   1639 		    strcmp(hashnl[curhash->hashsize].n_name + 1, hashname))
   1640 			continue;
   1641 		elemsize = curhash->type == HASH_LIST ?
   1642 		    sizeof(*hashtbl_list) : sizeof(*hashtbl_tailq);
   1643 		deref_kptr((void *)hashnl[curhash->hashsize].n_value,
   1644 		    &hashsize, sizeof(hashsize),
   1645 		    hashnl[curhash->hashsize].n_name);
   1646 		hashsize++;
   1647 		deref_kptr((void *)hashnl[curhash->hashtbl].n_value,
   1648 		    &hashaddr, sizeof(hashaddr),
   1649 		    hashnl[curhash->hashtbl].n_name);
   1650 		if (verbose)
   1651 			(void)printf(
   1652 			    "%s %lu, %s %p, offset %ld, elemsize %llu\n",
   1653 			    hashnl[curhash->hashsize].n_name + 1, hashsize,
   1654 			    hashnl[curhash->hashtbl].n_name + 1, hashaddr,
   1655 			    (long)curhash->offset,
   1656 			    (unsigned long long)elemsize);
   1657 		thissize = hashsize * elemsize;
   1658 		if (hashbuf == NULL || thissize > hashbufsize) {
   1659 			if ((nhashbuf = realloc(hashbuf, thissize)) == NULL)
   1660 				errx(1, "malloc hashbuf %llu",
   1661 				    (unsigned long long)hashbufsize);
   1662 			hashbuf = nhashbuf;
   1663 			hashbufsize = thissize;
   1664 		}
   1665 		deref_kptr(hashaddr, hashbuf, thissize,
   1666 		    hashnl[curhash->hashtbl].n_name);
   1667 		used = 0;
   1668 		items = maxchain = 0;
   1669 		if (curhash->type == HASH_LIST) {
   1670 			hashtbl_list = hashbuf;
   1671 			hashtbl_tailq = NULL;
   1672 		} else {
   1673 			hashtbl_list = NULL;
   1674 			hashtbl_tailq = hashbuf;
   1675 		}
   1676 		for (i = 0; i < hashsize; i++) {
   1677 			if (curhash->type == HASH_LIST)
   1678 				nextaddr = LIST_FIRST(&hashtbl_list[i]);
   1679 			else
   1680 				nextaddr = TAILQ_FIRST(&hashtbl_tailq[i]);
   1681 			if (nextaddr == NULL)
   1682 				continue;
   1683 			if (verbose)
   1684 				(void)printf("%5lu: %p\n", i, nextaddr);
   1685 			used++;
   1686 			chain = 0;
   1687 			do {
   1688 				chain++;
   1689 				deref_kptr((char *)nextaddr + curhash->offset,
   1690 				    &nextaddr, sizeof(void *),
   1691 				    "hash chain corrupted");
   1692 				if (verbose > 1)
   1693 					(void)printf("got nextaddr as %p\n",
   1694 					    nextaddr);
   1695 			} while (nextaddr != NULL);
   1696 			items += chain;
   1697 			if (verbose && chain > 1)
   1698 				(void)printf("\tchain = %d\n", chain);
   1699 			if (chain > maxchain)
   1700 				maxchain = chain;
   1701 		}
   1702 		(void)printf("%-16s %8ld %8d %8.2f %8d %8.2f %8d\n",
   1703 		    hashnl[curhash->hashsize].n_name + 1,
   1704 		    hashsize, used, used * 100.0 / hashsize,
   1705 		    items, used ? (double)items / used : 0.0, maxchain);
   1706 	}
   1707 }
   1708 
   1709 /*
   1710  * kreadc like kread but returns 1 if sucessful, 0 otherwise
   1711  */
   1712 int
   1713 kreadc(struct nlist *nl, int nlx, void *addr, size_t size)
   1714 {
   1715 	const char *sym;
   1716 
   1717 	sym = nl[nlx].n_name;
   1718 	if (*sym == '_')
   1719 		++sym;
   1720 	if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
   1721 		return 0;
   1722 	deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
   1723 	return 1;
   1724 }
   1725 
   1726 /*
   1727  * kread reads something from the kernel, given its nlist index in namelist[].
   1728  */
   1729 void
   1730 kread(struct nlist *nl, int nlx, void *addr, size_t size)
   1731 {
   1732 	const char *sym;
   1733 
   1734 	sym = nl[nlx].n_name;
   1735 	if (*sym == '_')
   1736 		++sym;
   1737 	if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
   1738 		errx(1, "symbol %s not defined", sym);
   1739 	deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
   1740 }
   1741 
   1742 /*
   1743  * Dereference the kernel pointer `kptr' and fill in the local copy
   1744  * pointed to by `ptr'.  The storage space must be pre-allocated,
   1745  * and the size of the copy passed in `len'.
   1746  */
   1747 void
   1748 deref_kptr(const void *kptr, void *ptr, size_t len, const char *msg)
   1749 {
   1750 
   1751 	if (*msg == '_')
   1752 		msg++;
   1753 	if ((size_t)kvm_read(kd, (u_long)kptr, (char *)ptr, len) != len)
   1754 		errx(1, "kptr %lx: %s: %s", (u_long)kptr, msg, kvm_geterr(kd));
   1755 }
   1756 
   1757 /*
   1758  * Traverse the kernel history buffers, performing the requested action.
   1759  *
   1760  * Note, we assume that if we're not listing, we're dumping.
   1761  */
   1762 void
   1763 hist_traverse(int todo, const char *histname)
   1764 {
   1765 	struct kern_history_head histhead;
   1766 	struct kern_history hist, *histkva;
   1767 	char *name = NULL;
   1768 	size_t namelen = 0;
   1769 
   1770 	if (histnl[0].n_value == 0) {
   1771 		warnx("kernel history is not compiled into the kernel.");
   1772 		return;
   1773 	}
   1774 
   1775 	deref_kptr((void *)histnl[X_KERN_HISTORIES].n_value, &histhead,
   1776 	    sizeof(histhead), histnl[X_KERN_HISTORIES].n_name);
   1777 
   1778 	if (histhead.lh_first == NULL) {
   1779 		warnx("No active kernel history logs.");
   1780 		return;
   1781 	}
   1782 
   1783 	if (todo & HISTLIST)
   1784 		(void)printf("Active kernel histories:");
   1785 
   1786 	for (histkva = LIST_FIRST(&histhead); histkva != NULL;
   1787 	    histkva = LIST_NEXT(&hist, list)) {
   1788 		deref_kptr(histkva, &hist, sizeof(hist), "histkva");
   1789 		if (name == NULL || hist.namelen > namelen) {
   1790 			if (name != NULL)
   1791 				free(name);
   1792 			namelen = hist.namelen;
   1793 			if ((name = malloc(namelen + 1)) == NULL)
   1794 				err(1, "malloc history name");
   1795 		}
   1796 
   1797 		deref_kptr(hist.name, name, namelen, "history name");
   1798 		name[namelen] = '\0';
   1799 		if (todo & HISTLIST)
   1800 			(void)printf(" %s", name);
   1801 		else {
   1802 			/*
   1803 			 * If we're dumping all histories, do it, else
   1804 			 * check to see if this is the one we want.
   1805 			 */
   1806 			if (histname == NULL || strcmp(histname, name) == 0) {
   1807 				if (histname == NULL)
   1808 					(void)printf(
   1809 					    "\nkernel history `%s':\n", name);
   1810 				hist_dodump(&hist);
   1811 			}
   1812 		}
   1813 	}
   1814 
   1815 	if (todo & HISTLIST)
   1816 		(void)putchar('\n');
   1817 
   1818 	if (name != NULL)
   1819 		free(name);
   1820 }
   1821 
   1822 /*
   1823  * Actually dump the history buffer at the specified KVA.
   1824  */
   1825 void
   1826 hist_dodump(struct kern_history *histp)
   1827 {
   1828 	struct kern_history_ent *histents, *e;
   1829 	size_t histsize;
   1830 	char *fmt = NULL, *fn = NULL;
   1831 	size_t fmtlen = 0, fnlen = 0;
   1832 	unsigned i;
   1833 
   1834 	histsize = sizeof(struct kern_history_ent) * histp->n;
   1835 
   1836 	if ((histents = malloc(histsize)) == NULL)
   1837 		err(1, "malloc history entries");
   1838 
   1839 	(void)memset(histents, 0, histsize);
   1840 
   1841 	deref_kptr(histp->e, histents, histsize, "history entries");
   1842 	i = histp->f;
   1843 	do {
   1844 		e = &histents[i];
   1845 		if (e->fmt != NULL) {
   1846 			if (fmt == NULL || e->fmtlen > fmtlen) {
   1847 				if (fmt != NULL)
   1848 					free(fmt);
   1849 				fmtlen = e->fmtlen;
   1850 				if ((fmt = malloc(fmtlen + 1)) == NULL)
   1851 					err(1, "malloc printf format");
   1852 			}
   1853 			if (fn == NULL || e->fnlen > fnlen) {
   1854 				if (fn != NULL)
   1855 					free(fn);
   1856 				fnlen = e->fnlen;
   1857 				if ((fn = malloc(fnlen + 1)) == NULL)
   1858 					err(1, "malloc function name");
   1859 			}
   1860 
   1861 			deref_kptr(e->fmt, fmt, fmtlen, "printf format");
   1862 			fmt[fmtlen] = '\0';
   1863 
   1864 			deref_kptr(e->fn, fn, fnlen, "function name");
   1865 			fn[fnlen] = '\0';
   1866 
   1867 			(void)printf("%06ld.%06ld ", (long int)e->tv.tv_sec,
   1868 			    (long int)e->tv.tv_usec);
   1869 			(void)printf("%s#%ld: ", fn, e->call);
   1870 			(void)printf(fmt, e->v[0], e->v[1], e->v[2], e->v[3]);
   1871 			(void)putchar('\n');
   1872 		}
   1873 		i = (i + 1) % histp->n;
   1874 	} while (i != histp->f);
   1875 
   1876 	free(histents);
   1877 	if (fmt != NULL)
   1878 		free(fmt);
   1879 	if (fn != NULL)
   1880 		free(fn);
   1881 }
   1882 
   1883 static void
   1884 usage(void)
   1885 {
   1886 
   1887 	(void)fprintf(stderr,
   1888 	    "usage: %s [-CefHiLlmstUvW] [-c count] [-h hashname] [-M core] [-N system]\n"
   1889 	    "\t\t[-u histname] [-w wait] [disks]\n", getprogname());
   1890 	exit(1);
   1891 }
   1892