Home | History | Annotate | Line # | Download | only in vmstat
vmstat.c revision 1.118
      1 /* $NetBSD: vmstat.c,v 1.118 2003/09/19 07:10:30 itojun Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 1998, 2000, 2001 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  * 3. All advertising materials mentioning features or use of this software
     21  *    must display the following acknowledgement:
     22  *	This product includes software developed by the NetBSD
     23  *	Foundation, Inc. and its contributors.
     24  * 4. Neither the name of The NetBSD Foundation nor the names of its
     25  *    contributors may be used to endorse or promote products derived
     26  *    from this software without specific prior written permission.
     27  *
     28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     38  * POSSIBILITY OF SUCH DAMAGE.
     39  */
     40 
     41 /*
     42  * Copyright (c) 1980, 1986, 1991, 1993
     43  *	The Regents of the University of California.  All rights reserved.
     44  *
     45  * Redistribution and use in source and binary forms, with or without
     46  * modification, are permitted provided that the following conditions
     47  * are met:
     48  * 1. Redistributions of source code must retain the above copyright
     49  *    notice, this list of conditions and the following disclaimer.
     50  * 2. Redistributions in binary form must reproduce the above copyright
     51  *    notice, this list of conditions and the following disclaimer in the
     52  *    documentation and/or other materials provided with the distribution.
     53  * 3. Neither the name of the University nor the names of its contributors
     54  *    may be used to endorse or promote products derived from this software
     55  *    without specific prior written permission.
     56  *
     57  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     58  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     59  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     60  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     61  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     62  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     63  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     64  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     65  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     66  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     67  * SUCH DAMAGE.
     68  */
     69 
     70 #include <sys/cdefs.h>
     71 #ifndef lint
     72 __COPYRIGHT("@(#) Copyright (c) 1980, 1986, 1991, 1993\n\
     73 	The Regents of the University of California.  All rights reserved.\n");
     74 #endif /* not lint */
     75 
     76 #ifndef lint
     77 #if 0
     78 static char sccsid[] = "@(#)vmstat.c	8.2 (Berkeley) 3/1/95";
     79 #else
     80 __RCSID("$NetBSD: vmstat.c,v 1.118 2003/09/19 07:10:30 itojun Exp $");
     81 #endif
     82 #endif /* not lint */
     83 
     84 #define	__POOL_EXPOSE
     85 
     86 #include <sys/param.h>
     87 #include <sys/mount.h>
     88 #include <sys/uio.h>
     89 
     90 #include <sys/buf.h>
     91 #include <sys/device.h>
     92 #include <sys/ioctl.h>
     93 #include <sys/malloc.h>
     94 #include <sys/mallocvar.h>
     95 #include <sys/namei.h>
     96 #include <sys/pool.h>
     97 #include <sys/proc.h>
     98 #include <sys/sched.h>
     99 #include <sys/socket.h>
    100 #include <sys/sysctl.h>
    101 #include <sys/time.h>
    102 #include <sys/user.h>
    103 
    104 #include <uvm/uvm_extern.h>
    105 #include <uvm/uvm_stat.h>
    106 
    107 #include <net/if.h>
    108 #include <netinet/in.h>
    109 #include <netinet/in_var.h>
    110 
    111 #include <ufs/ufs/inode.h>
    112 
    113 #include <nfs/rpcv2.h>
    114 #include <nfs/nfsproto.h>
    115 #include <nfs/nfsnode.h>
    116 
    117 #include <ctype.h>
    118 #include <err.h>
    119 #include <errno.h>
    120 #include <fcntl.h>
    121 #include <kvm.h>
    122 #include <limits.h>
    123 #include <nlist.h>
    124 #undef n_hash
    125 #include <paths.h>
    126 #include <signal.h>
    127 #include <stdio.h>
    128 #include <stddef.h>
    129 #include <stdlib.h>
    130 #include <string.h>
    131 #include <time.h>
    132 #include <unistd.h>
    133 #include <util.h>
    134 
    135 #include "dkstats.h"
    136 
    137 /*
    138  * General namelist
    139  */
    140 struct nlist namelist[] =
    141 {
    142 #define	X_BOOTTIME	0
    143 	{ "_boottime" },
    144 #define	X_HZ		1
    145 	{ "_hz" },
    146 #define	X_STATHZ	2
    147 	{ "_stathz" },
    148 #define	X_NCHSTATS	3
    149 	{ "_nchstats" },
    150 #define	X_INTRNAMES	4
    151 	{ "_intrnames" },
    152 #define	X_EINTRNAMES	5
    153 	{ "_eintrnames" },
    154 #define	X_INTRCNT	6
    155 	{ "_intrcnt" },
    156 #define	X_EINTRCNT	7
    157 	{ "_eintrcnt" },
    158 #define	X_KMEMSTAT	8
    159 	{ "_kmemstatistics" },
    160 #define	X_KMEMBUCKETS	9
    161 	{ "_bucket" },
    162 #define	X_ALLEVENTS	10
    163 	{ "_allevents" },
    164 #define	X_POOLHEAD	11
    165 	{ "_pool_head" },
    166 #define	X_UVMEXP	12
    167 	{ "_uvmexp" },
    168 #define	X_TIME		13
    169 	{ "_time" },
    170 #define	X_END		14
    171 	{ NULL },
    172 };
    173 
    174 /*
    175  * Namelist for hash statistics
    176  */
    177 struct nlist hashnl[] =
    178 {
    179 #define	X_NFSNODE	0
    180 	{ "_nfsnodehash" },
    181 #define	X_NFSNODETBL	1
    182 	{ "_nfsnodehashtbl" },
    183 #define	X_IHASH		2
    184 	{ "_ihash" },
    185 #define	X_IHASHTBL	3
    186 	{ "_ihashtbl" },
    187 #define	X_BUFHASH	4
    188 	{ "_bufhash" },
    189 #define	X_BUFHASHTBL	5
    190 	{ "_bufhashtbl" },
    191 #define	X_PIDHASH	6
    192 	{ "_pidhash" },
    193 #define	X_PIDHASHTBL	7
    194 	{ "_pidhashtbl" },
    195 #define	X_PGRPHASH	8
    196 	{ "_pgrphash" },
    197 #define	X_PGRPHASHTBL	9
    198 	{ "_pgrphashtbl" },
    199 #define	X_UIHASH	10
    200 	{ "_uihash" },
    201 #define	X_UIHASHTBL	11
    202 	{ "_uihashtbl" },
    203 #define	X_IFADDRHASH	12
    204 	{ "_in_ifaddrhash" },
    205 #define	X_IFADDRHASHTBL	13
    206 	{ "_in_ifaddrhashtbl" },
    207 #define	X_NCHASH	14
    208 	{ "_nchash" },
    209 #define	X_NCHASHTBL	15
    210 	{ "_nchashtbl" },
    211 #define	X_NCVHASH	16
    212 	{ "_ncvhash" },
    213 #define	X_NCVHASHTBL	17
    214 	{ "_ncvhashtbl" },
    215 #define X_HASHNL_SIZE	18	/* must be last */
    216 	{ NULL },
    217 
    218 };
    219 
    220 /*
    221  * Namelist for UVM histories
    222  */
    223 struct nlist histnl[] =
    224 {
    225 	{ "_uvm_histories" },
    226 #define	X_UVM_HISTORIES		0
    227 	{ NULL },
    228 };
    229 
    230 
    231 
    232 struct	uvmexp uvmexp, ouvmexp;
    233 int	ndrives;
    234 
    235 int	winlines = 20;
    236 
    237 kvm_t *kd;
    238 
    239 #define	FORKSTAT	1<<0
    240 #define	INTRSTAT	1<<1
    241 #define	MEMSTAT		1<<2
    242 #define	SUMSTAT		1<<3
    243 #define	EVCNTSTAT	1<<4
    244 #define	VMSTAT		1<<5
    245 #define	HISTLIST	1<<6
    246 #define	HISTDUMP	1<<7
    247 #define	HASHSTAT	1<<8
    248 #define	HASHLIST	1<<9
    249 
    250 void	cpustats(void);
    251 void	deref_kptr(const void *, void *, size_t, const char *);
    252 void	dkstats(void);
    253 void	doevcnt(int verbose);
    254 void	dohashstat(int, int, const char *);
    255 void	dointr(int verbose);
    256 void	domem(void);
    257 void	dopool(int);
    258 void	dopoolcache(struct pool *, int);
    259 void	dosum(void);
    260 void	dovmstat(struct timespec *, int);
    261 void	kread(int, void *, size_t);
    262 void	needhdr(int);
    263 long	getuptime(void);
    264 void	printhdr(void);
    265 long	pct(long, long);
    266 void	usage(void);
    267 void	doforkst(void);
    268 
    269 void	hist_traverse(int, const char *);
    270 void	hist_dodump(struct uvm_history *);
    271 
    272 int	main(int, char **);
    273 char	**choosedrives(char **);
    274 
    275 /* Namelist and memory file names. */
    276 char	*nlistf, *memf;
    277 
    278 /* allow old usage [vmstat 1] */
    279 #define	BACKWARD_COMPATIBILITY
    280 
    281 int
    282 main(int argc, char *argv[])
    283 {
    284 	int c, todo, verbose;
    285 	struct timespec interval;
    286 	int reps;
    287 	char errbuf[_POSIX2_LINE_MAX];
    288 	gid_t egid = getegid();
    289 	const char *histname, *hashname;
    290 
    291 	histname = hashname = NULL;
    292 	(void)setegid(getgid());
    293 	memf = nlistf = NULL;
    294 	reps = todo = verbose = 0;
    295 	interval.tv_sec = 0;
    296 	interval.tv_nsec = 0;
    297 	while ((c = getopt(argc, argv, "c:efh:HilLM:mN:su:Uvw:")) != -1) {
    298 		switch (c) {
    299 		case 'c':
    300 			reps = atoi(optarg);
    301 			break;
    302 		case 'e':
    303 			todo |= EVCNTSTAT;
    304 			break;
    305 		case 'f':
    306 			todo |= FORKSTAT;
    307 			break;
    308 		case 'h':
    309 			hashname = optarg;
    310 			/* FALLTHROUGH */
    311 		case 'H':
    312 			todo |= HASHSTAT;
    313 			break;
    314 		case 'i':
    315 			todo |= INTRSTAT;
    316 			break;
    317 		case 'l':
    318 			todo |= HISTLIST;
    319 			break;
    320 		case 'L':
    321 			todo |= HASHLIST;
    322 			break;
    323 		case 'M':
    324 			memf = optarg;
    325 			break;
    326 		case 'm':
    327 			todo |= MEMSTAT;
    328 			break;
    329 		case 'N':
    330 			nlistf = optarg;
    331 			break;
    332 		case 's':
    333 			todo |= SUMSTAT;
    334 			break;
    335 		case 'u':
    336 			histname = optarg;
    337 			/* FALLTHROUGH */
    338 		case 'U':
    339 			todo |= HISTDUMP;
    340 			break;
    341 		case 'v':
    342 			verbose++;
    343 			break;
    344 		case 'w':
    345 			interval.tv_sec = atol(optarg);
    346 			break;
    347 		case '?':
    348 		default:
    349 			usage();
    350 		}
    351 	}
    352 	argc -= optind;
    353 	argv += optind;
    354 
    355 	if (todo == 0)
    356 		todo = VMSTAT;
    357 
    358 	/*
    359 	 * Discard setgid privileges.  If not the running kernel, we toss
    360 	 * them away totally so that bad guys can't print interesting stuff
    361 	 * from kernel memory, otherwise switch back to kmem for the
    362 	 * duration of the kvm_openfiles() call.
    363 	 */
    364 	if (nlistf != NULL || memf != NULL)
    365 		(void)setgid(getgid());
    366 	else
    367 		(void)setegid(egid);
    368 
    369 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
    370 	if (kd == NULL)
    371 		errx(1, "kvm_openfiles: %s", errbuf);
    372 
    373 	if (nlistf == NULL && memf == NULL)
    374 		(void)setgid(getgid());
    375 
    376 	if ((c = kvm_nlist(kd, namelist)) != 0) {
    377 		if (c == -1)
    378 			errx(1, "kvm_nlist: %s %s", "namelist", kvm_geterr(kd));
    379 		(void)fprintf(stderr, "vmstat: undefined symbols:");
    380 		for (c = 0; c < sizeof(namelist) / sizeof(namelist[0])-1; c++)
    381 			if (namelist[c].n_type == 0)
    382 				fprintf(stderr, " %s", namelist[c].n_name);
    383 		(void)fputc('\n', stderr);
    384 		exit(1);
    385 	}
    386 	if ((c = kvm_nlist(kd, hashnl)) == -1 || c == X_HASHNL_SIZE)
    387 		errx(1, "kvm_nlist: %s %s", "hashnl", kvm_geterr(kd));
    388 	if (kvm_nlist(kd, histnl) == -1)
    389 		errx(1, "kvm_nlist: %s %s", "histnl", kvm_geterr(kd));
    390 
    391 	if (todo & VMSTAT) {
    392 		struct winsize winsize;
    393 
    394 		dkinit(0);	/* Initialize disk stats, no disks selected. */
    395 
    396 		(void)setgid(getgid()); /* don't need privs anymore */
    397 
    398 		argv = choosedrives(argv);	/* Select disks. */
    399 		winsize.ws_row = 0;
    400 		(void)ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
    401 		if (winsize.ws_row > 0)
    402 			winlines = winsize.ws_row;
    403 
    404 	}
    405 
    406 #ifdef	BACKWARD_COMPATIBILITY
    407 	if (*argv) {
    408 		interval.tv_sec = atol(*argv);
    409 		if (*++argv)
    410 			reps = atoi(*argv);
    411 	}
    412 #endif
    413 
    414 	if (interval.tv_sec) {
    415 		if (!reps)
    416 			reps = -1;
    417 	} else if (reps)
    418 		interval.tv_sec = 1;
    419 
    420 
    421 	/*
    422 	 * Statistics dumping is incompatible with the default
    423 	 * VMSTAT/dovmstat() output. So perform the interval/reps handling
    424 	 * for it here.
    425 	 */
    426 	if ((todo & VMSTAT) == 0) {
    427 		for (;;) {
    428 			if (todo & (HISTLIST|HISTDUMP)) {
    429 				if ((todo & (HISTLIST|HISTDUMP)) ==
    430 				    (HISTLIST|HISTDUMP))
    431 					errx(1, "you may list or dump,"
    432 					    " but not both!");
    433 				hist_traverse(todo, histname);
    434 				putchar('\n');
    435 			}
    436 			if (todo & FORKSTAT) {
    437 				doforkst();
    438 				putchar('\n');
    439 			}
    440 			if (todo & MEMSTAT) {
    441 				domem();
    442 				dopool(verbose);
    443 				putchar('\n');
    444 			}
    445 			if (todo & SUMSTAT) {
    446 				dosum();
    447 				putchar('\n');
    448 			}
    449 			if (todo & INTRSTAT) {
    450 				dointr(verbose);
    451 				putchar('\n');
    452 			}
    453 			if (todo & EVCNTSTAT) {
    454 				doevcnt(verbose);
    455 				putchar('\n');
    456 			}
    457 			if (todo & (HASHLIST|HASHSTAT)) {
    458 				if ((todo & (HASHLIST|HASHSTAT)) ==
    459 				    (HASHLIST|HASHSTAT))
    460 					errx(1, "you may list or display,"
    461 					    " but not both!");
    462 				dohashstat(verbose, todo, hashname);
    463 				putchar('\n');
    464 			}
    465 
    466 			if (reps >= 0 && --reps <=0)
    467 				break;
    468 			nanosleep(&interval, NULL);
    469 		}
    470 	} else
    471 		dovmstat(&interval, reps);
    472 	exit(0);
    473 }
    474 
    475 char **
    476 choosedrives(char **argv)
    477 {
    478 	int i;
    479 
    480 	/*
    481 	 * Choose drives to be displayed.  Priority goes to (in order) drives
    482 	 * supplied as arguments, default drives.  If everything isn't filled
    483 	 * in and there are drives not taken care of, display the first few
    484 	 * that fit.
    485 	 */
    486 #define	BACKWARD_COMPATIBILITY
    487 	for (ndrives = 0; *argv; ++argv) {
    488 #ifdef	BACKWARD_COMPATIBILITY
    489 		if (isdigit(**argv))
    490 			break;
    491 #endif
    492 		for (i = 0; i < dk_ndrive; i++) {
    493 			if (strcmp(dr_name[i], *argv))
    494 				continue;
    495 			dk_select[i] = 1;
    496 			++ndrives;
    497 			break;
    498 		}
    499 	}
    500 	for (i = 0; i < dk_ndrive && ndrives < 4; i++) {
    501 		if (dk_select[i])
    502 			continue;
    503 		dk_select[i] = 1;
    504 		++ndrives;
    505 	}
    506 	return (argv);
    507 }
    508 
    509 long
    510 getuptime(void)
    511 {
    512 	static struct timeval boottime;
    513 	struct timeval now, diff;
    514 	time_t uptime;
    515 
    516 	if (boottime.tv_sec == 0)
    517 		kread(X_BOOTTIME, &boottime, sizeof(boottime));
    518 	kread(X_TIME, &now, sizeof(now));
    519 	timersub(&now, &boottime, &diff);
    520 	uptime = diff.tv_sec;
    521 	if (uptime <= 0 || uptime > 60*60*24*365*10)
    522 		errx(1, "time makes no sense; namelist must be wrong.");
    523 	return (uptime);
    524 }
    525 
    526 int	hz, hdrcnt;
    527 
    528 void
    529 dovmstat(struct timespec *interval, int reps)
    530 {
    531 	struct vmtotal total;
    532 	time_t uptime, halfuptime;
    533 	int mib[2];
    534 	size_t size;
    535 	int pagesize = getpagesize();
    536 
    537 	uptime = getuptime();
    538 	halfuptime = uptime / 2;
    539 	(void)signal(SIGCONT, needhdr);
    540 
    541 	if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
    542 		kread(X_STATHZ, &hz, sizeof(hz));
    543 	if (!hz)
    544 		kread(X_HZ, &hz, sizeof(hz));
    545 
    546 	for (hdrcnt = 1;;) {
    547 		if (!--hdrcnt)
    548 			printhdr();
    549 		/* Read new disk statistics */
    550 		dkreadstats();
    551 		kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
    552 		if (memf != NULL) {
    553 			/*
    554 			 * XXX Can't do this if we're reading a crash
    555 			 * XXX dump because they're lazily-calculated.
    556 			 */
    557 			printf("Unable to get vmtotals from crash dump.\n");
    558 			memset(&total, 0, sizeof(total));
    559 		} else {
    560 			size = sizeof(total);
    561 			mib[0] = CTL_VM;
    562 			mib[1] = VM_METER;
    563 			if (sysctl(mib, 2, &total, &size, NULL, 0) < 0) {
    564 				printf("Can't get vmtotals: %s\n",
    565 				    strerror(errno));
    566 				memset(&total, 0, sizeof(total));
    567 			}
    568 		}
    569 		(void)printf("%2d%2d%2d",
    570 		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
    571 #define	pgtok(a) (long)((a) * (pagesize >> 10))
    572 #define	rate(x)	(u_long)(((x) + halfuptime) / uptime)	/* round */
    573 		(void)printf(" %6ld %6ld ",
    574 		    pgtok(total.t_avm), pgtok(total.t_free));
    575 		(void)printf("%4lu ", rate(uvmexp.faults - ouvmexp.faults));
    576 		(void)printf("%3lu ", rate(uvmexp.pdreact - ouvmexp.pdreact));
    577 		(void)printf("%3lu ", rate(uvmexp.pageins - ouvmexp.pageins));
    578 		(void)printf("%4lu ",
    579 		    rate(uvmexp.pgswapout - ouvmexp.pgswapout));
    580 		(void)printf("%4lu ", rate(uvmexp.pdfreed - ouvmexp.pdfreed));
    581 		(void)printf("%4lu ", rate(uvmexp.pdscans - ouvmexp.pdscans));
    582 		dkstats();
    583 		(void)printf("%4lu %4lu %3lu ",
    584 		    rate(uvmexp.intrs - ouvmexp.intrs),
    585 		    rate(uvmexp.syscalls - ouvmexp.syscalls),
    586 		    rate(uvmexp.swtch - ouvmexp.swtch));
    587 		cpustats();
    588 		putchar('\n');
    589 		(void)fflush(stdout);
    590 		if (reps >= 0 && --reps <= 0)
    591 			break;
    592 		ouvmexp = uvmexp;
    593 		uptime = interval->tv_sec;
    594 		/*
    595 		 * We round upward to avoid losing low-frequency events
    596 		 * (i.e., >= 1 per interval but < 1 per second).
    597 		 */
    598 		halfuptime = uptime == 1 ? 0 : (uptime + 1) / 2;
    599 		nanosleep(interval, NULL);
    600 	}
    601 }
    602 
    603 void
    604 printhdr(void)
    605 {
    606 	int i;
    607 
    608 	(void)printf(" procs    memory      page%*s", 23, "");
    609 	if (ndrives > 0)
    610 		(void)printf("%s %*sfaults      cpu\n",
    611 		    ((ndrives > 1) ? "disks" : "disk"),
    612 		    ((ndrives > 1) ? ndrives * 3 - 4 : 0), "");
    613 	else
    614 		(void)printf("%*s  faults   cpu\n",
    615 		    ndrives * 3, "");
    616 
    617 	(void)printf(" r b w    avm    fre  flt  re  pi   po   fr   sr ");
    618 	for (i = 0; i < dk_ndrive; i++)
    619 		if (dk_select[i])
    620 			(void)printf("%c%c ", dr_name[i][0],
    621 			    dr_name[i][strlen(dr_name[i]) - 1]);
    622 	(void)printf("  in   sy  cs us sy id\n");
    623 	hdrcnt = winlines - 2;
    624 }
    625 
    626 /*
    627  * Force a header to be prepended to the next output.
    628  */
    629 void
    630 needhdr(int dummy)
    631 {
    632 
    633 	hdrcnt = 1;
    634 }
    635 
    636 long
    637 pct(long top, long bot)
    638 {
    639 	long ans;
    640 
    641 	if (bot == 0)
    642 		return (0);
    643 	ans = (quad_t)top * 100 / bot;
    644 	return (ans);
    645 }
    646 
    647 #define	PCT(top, bot) (int)pct((long)(top), (long)(bot))
    648 
    649 void
    650 dosum(void)
    651 {
    652 	struct nchstats nchstats;
    653 	long nchtotal;
    654 
    655 	kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
    656 
    657 	(void)printf("%9u bytes per page\n", uvmexp.pagesize);
    658 
    659 	(void)printf("%9u page color%s\n",
    660 	    uvmexp.ncolors, uvmexp.ncolors == 1 ? "" : "s");
    661 
    662 	(void)printf("%9u pages managed\n", uvmexp.npages);
    663 	(void)printf("%9u pages free\n", uvmexp.free);
    664 	(void)printf("%9u pages active\n", uvmexp.active);
    665 	(void)printf("%9u pages inactive\n", uvmexp.inactive);
    666 	(void)printf("%9u pages paging\n", uvmexp.paging);
    667 	(void)printf("%9u pages wired\n", uvmexp.wired);
    668 	(void)printf("%9u zero pages\n", uvmexp.zeropages);
    669 	(void)printf("%9u reserve pagedaemon pages\n",
    670 	    uvmexp.reserve_pagedaemon);
    671 	(void)printf("%9u reserve kernel pages\n", uvmexp.reserve_kernel);
    672 	(void)printf("%9u anonymous pages\n", uvmexp.anonpages);
    673 	(void)printf("%9u cached file pages\n", uvmexp.filepages);
    674 	(void)printf("%9u cached executable pages\n", uvmexp.execpages);
    675 
    676 	(void)printf("%9u minimum free pages\n", uvmexp.freemin);
    677 	(void)printf("%9u target free pages\n", uvmexp.freetarg);
    678 	(void)printf("%9u target inactive pages\n", uvmexp.inactarg);
    679 	(void)printf("%9u maximum wired pages\n", uvmexp.wiredmax);
    680 
    681 	(void)printf("%9u swap devices\n", uvmexp.nswapdev);
    682 	(void)printf("%9u swap pages\n", uvmexp.swpages);
    683 	(void)printf("%9u swap pages in use\n", uvmexp.swpginuse);
    684 	(void)printf("%9u swap allocations\n", uvmexp.nswget);
    685 	(void)printf("%9u anons\n", uvmexp.nanon);
    686 	(void)printf("%9u free anons\n", uvmexp.nfreeanon);
    687 
    688 	(void)printf("%9u total faults taken\n", uvmexp.faults);
    689 	(void)printf("%9u traps\n", uvmexp.traps);
    690 	(void)printf("%9u device interrupts\n", uvmexp.intrs);
    691 	(void)printf("%9u cpu context switches\n", uvmexp.swtch);
    692 	(void)printf("%9u software interrupts\n", uvmexp.softs);
    693 	(void)printf("%9u system calls\n", uvmexp.syscalls);
    694 	(void)printf("%9u pagein requests\n", uvmexp.pageins);
    695 	(void)printf("%9u pageout requests\n", uvmexp.pdpageouts);
    696 	(void)printf("%9u swap ins\n", uvmexp.swapins);
    697 	(void)printf("%9u swap outs\n", uvmexp.swapouts);
    698 	(void)printf("%9u pages swapped in\n", uvmexp.pgswapin);
    699 	(void)printf("%9u pages swapped out\n", uvmexp.pgswapout);
    700 	(void)printf("%9u forks total\n", uvmexp.forks);
    701 	(void)printf("%9u forks blocked parent\n", uvmexp.forks_ppwait);
    702 	(void)printf("%9u forks shared address space with parent\n",
    703 	    uvmexp.forks_sharevm);
    704 	(void)printf("%9u pagealloc zero wanted and avail\n",
    705 	    uvmexp.pga_zerohit);
    706 	(void)printf("%9u pagealloc zero wanted and not avail\n",
    707 	    uvmexp.pga_zeromiss);
    708 	(void)printf("%9u aborts of idle page zeroing\n",
    709 	    uvmexp.zeroaborts);
    710 	(void)printf("%9u pagealloc desired color avail\n",
    711 	    uvmexp.colorhit);
    712 	(void)printf("%9u pagealloc desired color not avail\n",
    713 	    uvmexp.colormiss);
    714 
    715 	(void)printf("%9u faults with no memory\n", uvmexp.fltnoram);
    716 	(void)printf("%9u faults with no anons\n", uvmexp.fltnoanon);
    717 	(void)printf("%9u faults had to wait on pages\n", uvmexp.fltpgwait);
    718 	(void)printf("%9u faults found released page\n", uvmexp.fltpgrele);
    719 	(void)printf("%9u faults relock (%u ok)\n", uvmexp.fltrelck,
    720 	    uvmexp.fltrelckok);
    721 	(void)printf("%9u anon page faults\n", uvmexp.fltanget);
    722 	(void)printf("%9u anon retry faults\n", uvmexp.fltanretry);
    723 	(void)printf("%9u amap copy faults\n", uvmexp.fltamcopy);
    724 	(void)printf("%9u neighbour anon page faults\n", uvmexp.fltnamap);
    725 	(void)printf("%9u neighbour object page faults\n", uvmexp.fltnomap);
    726 	(void)printf("%9u locked pager get faults\n", uvmexp.fltlget);
    727 	(void)printf("%9u unlocked pager get faults\n", uvmexp.fltget);
    728 	(void)printf("%9u anon faults\n", uvmexp.flt_anon);
    729 	(void)printf("%9u anon copy on write faults\n", uvmexp.flt_acow);
    730 	(void)printf("%9u object faults\n", uvmexp.flt_obj);
    731 	(void)printf("%9u promote copy faults\n", uvmexp.flt_prcopy);
    732 	(void)printf("%9u promote zero fill faults\n", uvmexp.flt_przero);
    733 
    734 	(void)printf("%9u times daemon wokeup\n",uvmexp.pdwoke);
    735 	(void)printf("%9u revolutions of the clock hand\n", uvmexp.pdrevs);
    736 	(void)printf("%9u times daemon attempted swapout\n", uvmexp.pdswout);
    737 	(void)printf("%9u pages freed by daemon\n", uvmexp.pdfreed);
    738 	(void)printf("%9u pages scanned by daemon\n", uvmexp.pdscans);
    739 	(void)printf("%9u anonymous pages scanned by daemon\n",
    740 	    uvmexp.pdanscan);
    741 	(void)printf("%9u object pages scanned by daemon\n", uvmexp.pdobscan);
    742 	(void)printf("%9u pages reactivated\n", uvmexp.pdreact);
    743 	(void)printf("%9u pages found busy by daemon\n", uvmexp.pdbusy);
    744 	(void)printf("%9u total pending pageouts\n", uvmexp.pdpending);
    745 	(void)printf("%9u pages deactivated\n", uvmexp.pddeact);
    746 	kread(X_NCHSTATS, &nchstats, sizeof(nchstats));
    747 	nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
    748 	    nchstats.ncs_badhits + nchstats.ncs_falsehits +
    749 	    nchstats.ncs_miss + nchstats.ncs_long;
    750 	(void)printf("%9ld total name lookups\n", nchtotal);
    751 	(void)printf(
    752 	    "%9s cache hits (%d%% pos + %d%% neg) system %d%% per-process\n",
    753 	    "", PCT(nchstats.ncs_goodhits, nchtotal),
    754 	    PCT(nchstats.ncs_neghits, nchtotal),
    755 	    PCT(nchstats.ncs_pass2, nchtotal));
    756 	(void)printf("%9s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
    757 	    PCT(nchstats.ncs_badhits, nchtotal),
    758 	    PCT(nchstats.ncs_falsehits, nchtotal),
    759 	    PCT(nchstats.ncs_long, nchtotal));
    760 }
    761 
    762 void
    763 doforkst(void)
    764 {
    765 
    766 	kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
    767 
    768 	(void)printf("%u forks total\n", uvmexp.forks);
    769 	(void)printf("%u forks blocked parent\n", uvmexp.forks_ppwait);
    770 	(void)printf("%u forks shared address space with parent\n",
    771 	    uvmexp.forks_sharevm);
    772 }
    773 
    774 void
    775 dkstats(void)
    776 {
    777 	int dn;
    778 	double etime;
    779 
    780 	/* Calculate disk stat deltas. */
    781 	dkswap();
    782 	etime = cur.cp_etime;
    783 
    784 	for (dn = 0; dn < dk_ndrive; ++dn) {
    785 		if (!dk_select[dn])
    786 			continue;
    787 		(void)printf("%2.0f ",
    788 		    (cur.dk_rxfer[dn] + cur.dk_wxfer[dn]) / etime);
    789 	}
    790 }
    791 
    792 void
    793 cpustats(void)
    794 {
    795 	int state;
    796 	double pct, total;
    797 
    798 	total = 0;
    799 	for (state = 0; state < CPUSTATES; ++state)
    800 		total += cur.cp_time[state];
    801 	if (total)
    802 		pct = 100 / total;
    803 	else
    804 		pct = 0;
    805 	(void)printf("%2.0f ",
    806 	    (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * pct);
    807 	(void)printf("%2.0f ",
    808 	    (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * pct);
    809 	(void)printf("%2.0f", cur.cp_time[CP_IDLE] * pct);
    810 }
    811 
    812 void
    813 dointr(int verbose)
    814 {
    815 	unsigned long *intrcnt;
    816 	unsigned long long inttotal, uptime;
    817 	int nintr, inamlen;
    818 	char *intrname;
    819 	struct evcntlist allevents;
    820 	struct evcnt evcnt, *evptr;
    821 	char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
    822 
    823 	uptime = getuptime();
    824 	nintr = namelist[X_EINTRCNT].n_value - namelist[X_INTRCNT].n_value;
    825 	inamlen =
    826 	    namelist[X_EINTRNAMES].n_value - namelist[X_INTRNAMES].n_value;
    827 	intrcnt = malloc((size_t)nintr);
    828 	intrname = malloc((size_t)inamlen);
    829 	if (intrcnt == NULL || intrname == NULL)
    830 		errx(1, "%s", "");
    831 	kread(X_INTRCNT, intrcnt, (size_t)nintr);
    832 	kread(X_INTRNAMES, intrname, (size_t)inamlen);
    833 	(void)printf("%-34s %16s %8s\n", "interrupt", "total", "rate");
    834 	inttotal = 0;
    835 	nintr /= sizeof(long);
    836 	while (--nintr >= 0) {
    837 		if (*intrcnt || verbose)
    838 			(void)printf("%-34s %16llu %8llu\n", intrname,
    839 			    (unsigned long long)*intrcnt,
    840 			    (unsigned long long)(*intrcnt / uptime));
    841 		intrname += strlen(intrname) + 1;
    842 		inttotal += *intrcnt++;
    843 	}
    844 	kread(X_ALLEVENTS, &allevents, sizeof allevents);
    845 	evptr = allevents.tqh_first;
    846 	while (evptr) {
    847 		deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
    848 		evptr = evcnt.ev_list.tqe_next;
    849 		if (evcnt.ev_type != EVCNT_TYPE_INTR)
    850 			continue;
    851 
    852 		if (evcnt.ev_count == 0 && !verbose)
    853 			continue;
    854 
    855 		deref_kptr(evcnt.ev_group, evgroup, evcnt.ev_grouplen + 1,
    856 		    "event chain trashed");
    857 		deref_kptr(evcnt.ev_name, evname, evcnt.ev_namelen + 1,
    858 		    "event chain trashed");
    859 
    860 		(void)printf("%s %s%*s %16llu %8llu\n", evgroup, evname,
    861 		    34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
    862 		    (unsigned long long)evcnt.ev_count,
    863 		    (unsigned long long)(evcnt.ev_count / uptime));
    864 
    865 		inttotal += evcnt.ev_count++;
    866 	}
    867 	(void)printf("%-34s %16llu %8llu\n", "Total", inttotal,
    868 	    (unsigned long long)(inttotal / uptime));
    869 }
    870 
    871 void
    872 doevcnt(int verbose)
    873 {
    874 	static const char * evtypes [] = { "misc", "intr", "trap" };
    875 	unsigned long long uptime;
    876 	struct evcntlist allevents;
    877 	struct evcnt evcnt, *evptr;
    878 	char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
    879 
    880 	/* XXX should print type! */
    881 
    882 	uptime = getuptime();
    883 	(void)printf("%-34s %16s %8s %s\n", "event", "total", "rate", "type");
    884 	kread(X_ALLEVENTS, &allevents, sizeof allevents);
    885 	evptr = allevents.tqh_first;
    886 	while (evptr) {
    887 		deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
    888 
    889 		evptr = evcnt.ev_list.tqe_next;
    890 		if (evcnt.ev_count == 0 && !verbose)
    891 			continue;
    892 
    893 		deref_kptr(evcnt.ev_group, evgroup, evcnt.ev_grouplen + 1,
    894 		    "event chain trashed");
    895 		deref_kptr(evcnt.ev_name, evname, evcnt.ev_namelen + 1,
    896 		    "event chain trashed");
    897 
    898 		(void)printf("%s %s%*s %16llu %8llu %s\n", evgroup, evname,
    899 		    34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
    900 		    (unsigned long long)evcnt.ev_count,
    901 		    (unsigned long long)(evcnt.ev_count / uptime),
    902 		    (evcnt.ev_type < sizeof(evtypes)/sizeof(evtypes[0]) ?
    903 			evtypes[evcnt.ev_type] : "?"));
    904 	}
    905 }
    906 
    907 static char memname[64];
    908 
    909 void
    910 domem(void)
    911 {
    912 	struct kmembuckets *kp;
    913 	struct malloc_type ks, *ksp;
    914 	int i, j;
    915 	int len, size, first;
    916 	long totuse = 0, totfree = 0, totreq = 0;
    917 	struct kmembuckets buckets[MINBUCKET + 16];
    918 
    919 	kread(X_KMEMBUCKETS, buckets, sizeof(buckets));
    920 	for (first = 1, i = MINBUCKET, kp = &buckets[i]; i < MINBUCKET + 16;
    921 	    i++, kp++) {
    922 		if (kp->kb_calls == 0)
    923 			continue;
    924 		if (first) {
    925 			(void)printf("Memory statistics by bucket size\n");
    926 			(void)printf(
    927 		 "    Size   In Use   Free   Requests  HighWater  Couldfree\n");
    928 			first = 0;
    929 		}
    930 		size = 1 << i;
    931 		(void)printf("%8d %8ld %6ld %10ld %7ld %10ld\n", size,
    932 		    kp->kb_total - kp->kb_totalfree,
    933 		    kp->kb_totalfree, kp->kb_calls,
    934 		    kp->kb_highwat, kp->kb_couldfree);
    935 		totfree += size * kp->kb_totalfree;
    936 	}
    937 
    938 	/*
    939 	 * If kmem statistics are not being gathered by the kernel,
    940 	 * first will still be 1.
    941 	 */
    942 	if (first) {
    943 		warnx("Kmem statistics are not being gathered by the kernel.");
    944 		return;
    945 	}
    946 
    947 	(void)printf("\nMemory usage type by bucket size\n");
    948 	(void)printf("    Size  Type(s)\n");
    949 	kp = &buckets[MINBUCKET];
    950 	for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1, kp++) {
    951 		if (kp->kb_calls == 0)
    952 			continue;
    953 		first = 1;
    954 		len = 8;
    955 		for (kread(X_KMEMSTAT, &ksp, sizeof(ksp));
    956 		     ksp != NULL; ksp = ks.ks_next) {
    957 			deref_kptr(ksp, &ks, sizeof(ks), "malloc type");
    958 			if (ks.ks_calls == 0)
    959 				continue;
    960 			if ((ks.ks_size & j) == 0)
    961 				continue;
    962 			deref_kptr(ks.ks_shortdesc, memname,
    963 			    sizeof(memname), "malloc type name");
    964 			len += 2 + strlen(memname);
    965 			if (first)
    966 				printf("%8d  %s", j, memname);
    967 			else
    968 				printf(",");
    969 			if (len >= 80) {
    970 				printf("\n\t ");
    971 				len = 10 + strlen(memname);
    972 			}
    973 			if (!first)
    974 				printf(" %s", memname);
    975 			first = 0;
    976 		}
    977 		putchar('\n');
    978 	}
    979 
    980 	(void)printf(
    981 	    "\nMemory statistics by type                        Type  Kern\n");
    982 	(void)printf(
    983 "         Type  InUse MemUse HighUse  Limit Requests Limit Limit Size(s)\n");
    984 	for (kread(X_KMEMSTAT, &ksp, sizeof(ksp));
    985 	     ksp != NULL; ksp = ks.ks_next) {
    986 		deref_kptr(ksp, &ks, sizeof(ks), "malloc type");
    987 		if (ks.ks_calls == 0)
    988 			continue;
    989 		deref_kptr(ks.ks_shortdesc, memname,
    990 		    sizeof(memname), "malloc type name");
    991 		(void)printf("%14s%6ld%6ldK%7ldK%6ldK%9ld%5u%6u",
    992 		    memname,
    993 		    ks.ks_inuse, (ks.ks_memuse + 1023) / 1024,
    994 		    (ks.ks_maxused + 1023) / 1024,
    995 		    (ks.ks_limit + 1023) / 1024, ks.ks_calls,
    996 		    ks.ks_limblocks, ks.ks_mapblocks);
    997 		first = 1;
    998 		for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
    999 			if ((ks.ks_size & j) == 0)
   1000 				continue;
   1001 			if (first)
   1002 				printf("  %d", j);
   1003 			else
   1004 				printf(",%d", j);
   1005 			first = 0;
   1006 		}
   1007 		printf("\n");
   1008 		totuse += ks.ks_memuse;
   1009 		totreq += ks.ks_calls;
   1010 	}
   1011 	(void)printf("\nMemory totals:  In Use    Free    Requests\n");
   1012 	(void)printf("              %7ldK %6ldK    %8ld\n\n",
   1013 	    (totuse + 1023) / 1024, (totfree + 1023) / 1024, totreq);
   1014 }
   1015 
   1016 void
   1017 dopool(int verbose)
   1018 {
   1019 	int first, ovflw;
   1020 	void *addr;
   1021 	long total = 0, inuse = 0;
   1022 	TAILQ_HEAD(,pool) pool_head;
   1023 	struct pool pool, *pp = &pool;
   1024 	struct pool_allocator pa;
   1025 	char name[32], maxp[32];
   1026 
   1027 	kread(X_POOLHEAD, &pool_head, sizeof(pool_head));
   1028 	addr = TAILQ_FIRST(&pool_head);
   1029 
   1030 	for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
   1031 		deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
   1032 		deref_kptr(pp->pr_alloc, &pa, sizeof(pa),
   1033 		    "pool allocatior trashed");
   1034 		deref_kptr(pp->pr_wchan, name, sizeof(name),
   1035 		    "pool wait channel trashed");
   1036 		name[sizeof(name)-1] = '\0';
   1037 
   1038 		if (first) {
   1039 			(void)printf("Memory resource pool statistics\n");
   1040 			(void)printf(
   1041 			    "%-11s%5s%9s%5s%9s%6s%6s%6s%6s%6s%6s%5s\n",
   1042 			    "Name",
   1043 			    "Size",
   1044 			    "Requests",
   1045 			    "Fail",
   1046 			    "Releases",
   1047 			    "Pgreq",
   1048 			    "Pgrel",
   1049 			    "Npage",
   1050 			    "Hiwat",
   1051 			    "Minpg",
   1052 			    "Maxpg",
   1053 			    "Idle");
   1054 			first = 0;
   1055 		}
   1056 		if (pp->pr_nget == 0 && !verbose)
   1057 			continue;
   1058 		if (pp->pr_maxpages == UINT_MAX)
   1059 			snprintf(maxp, sizeof(maxp), "inf");
   1060 		else
   1061 			snprintf(maxp, sizeof(maxp), "%u", pp->pr_maxpages);
   1062 /*
   1063  * Print single word.  `ovflow' is number of characters didn't fit
   1064  * on the last word.  `fmt' is a format string to print this word.
   1065  * It must contain asterisk for field width.  `width' is a width
   1066  * occupied by this word.  `fixed' is a number of constant chars in
   1067  * `fmt'.  `val' is a value to be printed using format string `fmt'.
   1068  */
   1069 #define	PRWORD(ovflw, fmt, width, fixed, val) do {	\
   1070 	(ovflw) += printf((fmt),			\
   1071 	    (width) - (fixed) - (ovflw) > 0 ?		\
   1072 	    (width) - (fixed) - (ovflw) : 0,		\
   1073 	    (val)) - (width);				\
   1074 	if ((ovflw) < 0)				\
   1075 		(ovflw) = 0;				\
   1076 } while (/* CONSTCOND */0)
   1077 		ovflw = 0;
   1078 		PRWORD(ovflw, "%-*s", 11, 0, name);
   1079 		PRWORD(ovflw, " %*u", 5, 1, pp->pr_size);
   1080 		PRWORD(ovflw, " %*lu", 9, 1, pp->pr_nget);
   1081 		PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nfail);
   1082 		PRWORD(ovflw, " %*lu", 9, 1, pp->pr_nput);
   1083 		PRWORD(ovflw, " %*lu", 6, 1, pp->pr_npagealloc);
   1084 		PRWORD(ovflw, " %*lu", 6, 1, pp->pr_npagefree);
   1085 		PRWORD(ovflw, " %*d", 6, 1, pp->pr_npages);
   1086 		PRWORD(ovflw, " %*d", 6, 1, pp->pr_hiwat);
   1087 		PRWORD(ovflw, " %*d", 6, 1, pp->pr_minpages);
   1088 		PRWORD(ovflw, " %*s", 6, 1, maxp);
   1089 		PRWORD(ovflw, " %*lu\n", 5, 1, pp->pr_nidle);
   1090 
   1091 		if (pp->pr_roflags & PR_RECURSIVE) {
   1092 			/*
   1093 			 * Don't count in-use memory, since it's part
   1094 			 * of another pool and will be accounted for
   1095 			 * there.
   1096 			 */
   1097 			total += pp->pr_npages * pa.pa_pagesz -
   1098 			     (pp->pr_nget - pp->pr_nput) * pp->pr_size;
   1099 		} else {
   1100 			inuse += (pp->pr_nget - pp->pr_nput) * pp->pr_size;
   1101 			total += pp->pr_npages * pa.pa_pagesz;
   1102 		}
   1103 		dopoolcache(pp, verbose);
   1104 	}
   1105 
   1106 	inuse /= 1024;
   1107 	total /= 1024;
   1108 	printf("\nIn use %ldK, total allocated %ldK; utilization %.1f%%\n",
   1109 	    inuse, total, (double)(100 * inuse) / total);
   1110 }
   1111 
   1112 void
   1113 dopoolcache(struct pool *pp, int verbose)
   1114 {
   1115 	struct pool_cache pool_cache, *pc = &pool_cache;
   1116 	struct pool_cache_group pool_cache_group, *pcg = &pool_cache_group;
   1117 	void *addr, *pcg_addr;
   1118 	int i;
   1119 
   1120 	if (verbose < 1)
   1121 		return;
   1122 
   1123 	for (addr = TAILQ_FIRST(&pp->pr_cachelist); addr != NULL;
   1124 	    addr = TAILQ_NEXT(pc, pc_poollist)) {
   1125 		deref_kptr(addr, pc, sizeof(*pc), "pool cache trashed");
   1126 		printf("\tcache %p: allocfrom %p freeto %p\n", addr,
   1127 		    pc->pc_allocfrom, pc->pc_freeto);
   1128 		printf("\t    hits %lu misses %lu ngroups %lu nitems %lu\n",
   1129 		    pc->pc_hits, pc->pc_misses, pc->pc_ngroups, pc->pc_nitems);
   1130 		if (verbose < 2)
   1131 			continue;
   1132 		for (pcg_addr = TAILQ_FIRST(&pc->pc_grouplist);
   1133 		    pcg_addr != NULL; pcg_addr = TAILQ_NEXT(pcg, pcg_list)) {
   1134 			deref_kptr(pcg_addr, pcg, sizeof(*pcg),
   1135 			    "pool cache group trashed");
   1136 			printf("\t\tgroup %p: avail %d\n", pcg_addr,
   1137 			    pcg->pcg_avail);
   1138 			for (i = 0; i < PCG_NOBJECTS; i++) {
   1139 				if (pcg->pcg_objects[i].pcgo_pa !=
   1140 				    POOL_PADDR_INVALID) {
   1141 					printf("\t\t\t%p, 0x%llx\n",
   1142 					    pcg->pcg_objects[i].pcgo_va,
   1143 					    (unsigned long long)
   1144 					    pcg->pcg_objects[i].pcgo_pa);
   1145 				} else {
   1146 					printf("\t\t\t%p\n",
   1147 					    pcg->pcg_objects[i].pcgo_va);
   1148 				}
   1149 			}
   1150 		}
   1151 	}
   1152 
   1153 }
   1154 
   1155 enum hashtype {			/* from <sys/systm.h> */
   1156 	HASH_LIST,
   1157 	HASH_TAILQ
   1158 };
   1159 
   1160 struct uidinfo {		/* XXX: no kernel header file */
   1161 	LIST_ENTRY(uidinfo) ui_hash;
   1162 	uid_t	ui_uid;
   1163 	long	ui_proccnt;
   1164 };
   1165 
   1166 struct kernel_hash {
   1167 	const char *	description;	/* description */
   1168 	int		hashsize;	/* nlist index for hash size */
   1169 	int		hashtbl;	/* nlist index for hash table */
   1170 	enum hashtype	type;		/* type of hash table */
   1171 	size_t		offset;		/* offset of {LIST,TAILQ}_NEXT */
   1172 } khashes[] =
   1173 {
   1174 	{
   1175 		"buffer hash",
   1176 		X_BUFHASH, X_BUFHASHTBL,
   1177 		HASH_LIST, offsetof(struct buf, b_hash)
   1178 	}, {
   1179 		"inode cache (ihash)",
   1180 		X_IHASH, X_IHASHTBL,
   1181 		HASH_LIST, offsetof(struct inode, i_hash)
   1182 	}, {
   1183 		"ipv4 address -> interface hash",
   1184 		X_IFADDRHASH, X_IFADDRHASHTBL,
   1185 		HASH_LIST, offsetof(struct in_ifaddr, ia_hash),
   1186 	}, {
   1187 		"name cache hash",
   1188 		X_NCHASH, X_NCHASHTBL,
   1189 		HASH_LIST, offsetof(struct namecache, nc_hash),
   1190 	}, {
   1191 		"name cache directory hash",
   1192 		X_NCVHASH, X_NCVHASHTBL,
   1193 		HASH_LIST, offsetof(struct namecache, nc_vhash),
   1194 	}, {
   1195 		"nfs client node cache",
   1196 		X_NFSNODE, X_NFSNODETBL,
   1197 		HASH_LIST, offsetof(struct nfsnode, n_hash)
   1198 	}, {
   1199 		"user info (uid -> used processes) hash",
   1200 		X_UIHASH, X_UIHASHTBL,
   1201 		HASH_LIST, offsetof(struct uidinfo, ui_hash),
   1202 	}, {
   1203 		NULL, -1, -1, 0, 0,
   1204 	}
   1205 };
   1206 
   1207 void
   1208 dohashstat(int verbose, int todo, const char *hashname)
   1209 {
   1210 	LIST_HEAD(, generic)	*hashtbl_list;
   1211 	TAILQ_HEAD(, generic)	*hashtbl_tailq;
   1212 	struct kernel_hash	*curhash;
   1213 	void	*hashaddr, *hashbuf, *nhashbuf, *nextaddr;
   1214 	size_t	elemsize, hashbufsize, thissize;
   1215 	u_long	hashsize;
   1216 	int	i, used, items, chain, maxchain;
   1217 
   1218 	hashbuf = NULL;
   1219 	hashbufsize = 0;
   1220 
   1221 	if (todo & HASHLIST) {
   1222 		printf("Supported hashes:\n");
   1223 		for (curhash = khashes; curhash->description; curhash++) {
   1224 			if (hashnl[curhash->hashsize].n_value == 0 ||
   1225 			    hashnl[curhash->hashtbl].n_value == 0)
   1226 				continue;
   1227 			printf("\t%-16s%s\n",
   1228 			    hashnl[curhash->hashsize].n_name + 1,
   1229 			    curhash->description);
   1230 		}
   1231 		return;
   1232 	}
   1233 
   1234 	if (hashname != NULL) {
   1235 		for (curhash = khashes; curhash->description; curhash++) {
   1236 			if (strcmp(hashnl[curhash->hashsize].n_name + 1,
   1237 			    hashname) == 0 &&
   1238 			    hashnl[curhash->hashsize].n_value != 0 &&
   1239 			    hashnl[curhash->hashtbl].n_value != 0)
   1240 				break;
   1241 		}
   1242 		if (curhash->description == NULL) {
   1243 			warnx("%s: no such hash", hashname);
   1244 			return;
   1245 		}
   1246 	}
   1247 
   1248 	printf(
   1249 	    "%-16s %8s %8s %8s %8s %8s %8s\n"
   1250 	    "%-16s %8s %8s %8s %8s %8s %8s\n",
   1251 	    "", "total", "used", "util", "num", "average", "maximum",
   1252 	    "hash table", "buckets", "buckets", "%", "items", "chain",
   1253 	    "chain");
   1254 
   1255 	for (curhash = khashes; curhash->description; curhash++) {
   1256 		if (hashnl[curhash->hashsize].n_value == 0 ||
   1257 		    hashnl[curhash->hashtbl].n_value == 0)
   1258 			continue;
   1259 		if (hashname != NULL &&
   1260 		    strcmp(hashnl[curhash->hashsize].n_name + 1, hashname))
   1261 			continue;
   1262 		elemsize = curhash->type == HASH_LIST ?
   1263 		    sizeof(*hashtbl_list) : sizeof(*hashtbl_tailq);
   1264 		deref_kptr((void *)hashnl[curhash->hashsize].n_value,
   1265 		    &hashsize, sizeof(hashsize),
   1266 		    hashnl[curhash->hashsize].n_name);
   1267 		hashsize++;
   1268 		deref_kptr((void *)hashnl[curhash->hashtbl].n_value,
   1269 		    &hashaddr, sizeof(hashaddr),
   1270 		    hashnl[curhash->hashtbl].n_name);
   1271 		if (verbose)
   1272 			printf("%s %lu, %s %p, offset %ld, elemsize %llu\n",
   1273 			    hashnl[curhash->hashsize].n_name + 1, hashsize,
   1274 			    hashnl[curhash->hashtbl].n_name + 1, hashaddr,
   1275 			    (long)curhash->offset,
   1276 			    (unsigned long long)elemsize);
   1277 		thissize = hashsize * elemsize;
   1278 		if (thissize > hashbufsize) {
   1279 			if ((nhashbuf = realloc(hashbuf, thissize)) == NULL)
   1280 				errx(1, "malloc hashbuf %llu",
   1281 				    (unsigned long long)hashbufsize);
   1282 			hashbuf = nhashbuf;
   1283 			hashbufsize = thissize;
   1284 		}
   1285 		deref_kptr(hashaddr, hashbuf, thissize,
   1286 		    hashnl[curhash->hashtbl].n_name);
   1287 		used = 0;
   1288 		items = maxchain = 0;
   1289 		if (curhash->type == HASH_LIST)
   1290 			hashtbl_list = hashbuf;
   1291 		else
   1292 			hashtbl_tailq = hashbuf;
   1293 		for (i = 0; i < hashsize; i++) {
   1294 			if (curhash->type == HASH_LIST)
   1295 				nextaddr = LIST_FIRST(&hashtbl_list[i]);
   1296 			else
   1297 				nextaddr = TAILQ_FIRST(&hashtbl_tailq[i]);
   1298 			if (nextaddr == NULL)
   1299 				continue;
   1300 			if (verbose)
   1301 				printf("%5d: %p\n", i, nextaddr);
   1302 			used++;
   1303 			chain = 0;
   1304 			do {
   1305 				chain++;
   1306 				deref_kptr((char *)nextaddr + curhash->offset,
   1307 				    &nextaddr, sizeof(void *),
   1308 				    "hash chain corrupted");
   1309 				if (verbose > 1)
   1310 					printf("got nextaddr as %p\n",
   1311 					    nextaddr);
   1312 			} while (nextaddr != NULL);
   1313 			items += chain;
   1314 			if (verbose && chain > 1)
   1315 				printf("\tchain = %d\n", chain);
   1316 			if (chain > maxchain)
   1317 				maxchain = chain;
   1318 		}
   1319 		printf("%-16s %8ld %8d %8.2f %8d %8.2f %8d\n",
   1320 		    hashnl[curhash->hashsize].n_name + 1,
   1321 		    hashsize, used, used * 100.0 / hashsize,
   1322 		    items, used ? (double)items / used : 0.0, maxchain);
   1323 	}
   1324 }
   1325 
   1326 /*
   1327  * kread reads something from the kernel, given its nlist index in namelist[].
   1328  */
   1329 void
   1330 kread(int nlx, void *addr, size_t size)
   1331 {
   1332 	const char *sym;
   1333 
   1334 	sym = namelist[nlx].n_name;
   1335 	if (*sym == '_')
   1336 		++sym;
   1337 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0)
   1338 		errx(1, "symbol %s not defined", sym);
   1339 	deref_kptr((void *)namelist[nlx].n_value, addr, size, sym);
   1340 }
   1341 
   1342 /*
   1343  * Dereference the kernel pointer `kptr' and fill in the local copy
   1344  * pointed to by `ptr'.  The storage space must be pre-allocated,
   1345  * and the size of the copy passed in `len'.
   1346  */
   1347 void
   1348 deref_kptr(const void *kptr, void *ptr, size_t len, const char *msg)
   1349 {
   1350 
   1351 	if (*msg == '_')
   1352 		msg++;
   1353 	if (kvm_read(kd, (u_long)kptr, (char *)ptr, len) != len)
   1354 		errx(1, "kptr %lx: %s: %s", (u_long)kptr, msg, kvm_geterr(kd));
   1355 }
   1356 
   1357 /*
   1358  * Traverse the UVM history buffers, performing the requested action.
   1359  *
   1360  * Note, we assume that if we're not listing, we're dumping.
   1361  */
   1362 void
   1363 hist_traverse(int todo, const char *histname)
   1364 {
   1365 	struct uvm_history_head histhead;
   1366 	struct uvm_history hist, *histkva;
   1367 	char *name = NULL;
   1368 	size_t namelen = 0;
   1369 
   1370 	if (histnl[0].n_value == 0) {
   1371 		warnx("UVM history is not compiled into the kernel.");
   1372 		return;
   1373 	}
   1374 
   1375 	deref_kptr((void *)histnl[X_UVM_HISTORIES].n_value, &histhead,
   1376 	    sizeof(histhead), histnl[X_UVM_HISTORIES].n_name);
   1377 
   1378 	if (histhead.lh_first == NULL) {
   1379 		warnx("No active UVM history logs.");
   1380 		return;
   1381 	}
   1382 
   1383 	if (todo & HISTLIST)
   1384 		printf("Active UVM histories:");
   1385 
   1386 	for (histkva = LIST_FIRST(&histhead); histkva != NULL;
   1387 	    histkva = LIST_NEXT(&hist, list)) {
   1388 		deref_kptr(histkva, &hist, sizeof(hist), "histkva");
   1389 		if (hist.namelen > namelen) {
   1390 			if (name != NULL)
   1391 				free(name);
   1392 			namelen = hist.namelen;
   1393 			if ((name = malloc(namelen + 1)) == NULL)
   1394 				err(1, "malloc history name");
   1395 		}
   1396 
   1397 		deref_kptr(hist.name, name, namelen, "history name");
   1398 		name[namelen] = '\0';
   1399 		if (todo & HISTLIST)
   1400 			printf(" %s", name);
   1401 		else {
   1402 			/*
   1403 			 * If we're dumping all histories, do it, else
   1404 			 * check to see if this is the one we want.
   1405 			 */
   1406 			if (histname == NULL || strcmp(histname, name) == 0) {
   1407 				if (histname == NULL)
   1408 					printf("\nUVM history `%s':\n", name);
   1409 				hist_dodump(&hist);
   1410 			}
   1411 		}
   1412 	}
   1413 
   1414 	if (todo & HISTLIST)
   1415 		putchar('\n');
   1416 
   1417 	if (name != NULL)
   1418 		free(name);
   1419 }
   1420 
   1421 /*
   1422  * Actually dump the history buffer at the specified KVA.
   1423  */
   1424 void
   1425 hist_dodump(struct uvm_history *histp)
   1426 {
   1427 	struct uvm_history_ent *histents, *e;
   1428 	size_t histsize;
   1429 	char *fmt = NULL, *fn = NULL;
   1430 	size_t fmtlen = 0, fnlen = 0;
   1431 	int i;
   1432 
   1433 	histsize = sizeof(struct uvm_history_ent) * histp->n;
   1434 
   1435 	if ((histents = malloc(histsize)) == NULL)
   1436 		err(1, "malloc history entries");
   1437 
   1438 	memset(histents, 0, histsize);
   1439 
   1440 	deref_kptr(histp->e, histents, histsize, "history entries");
   1441 	i = histp->f;
   1442 	do {
   1443 		e = &histents[i];
   1444 		if (e->fmt != NULL) {
   1445 			if (e->fmtlen > fmtlen) {
   1446 				if (fmt != NULL)
   1447 					free(fmt);
   1448 				fmtlen = e->fmtlen;
   1449 				if ((fmt = malloc(fmtlen + 1)) == NULL)
   1450 					err(1, "malloc printf format");
   1451 			}
   1452 			if (e->fnlen > fnlen) {
   1453 				if (fn != NULL)
   1454 					free(fn);
   1455 				fnlen = e->fnlen;
   1456 				if ((fn = malloc(fnlen + 1)) == NULL)
   1457 					err(1, "malloc function name");
   1458 			}
   1459 
   1460 			deref_kptr(e->fmt, fmt, fmtlen, "printf format");
   1461 			fmt[fmtlen] = '\0';
   1462 
   1463 			deref_kptr(e->fn, fn, fnlen, "function name");
   1464 			fn[fnlen] = '\0';
   1465 
   1466 			printf("%06ld.%06ld ", (long int)e->tv.tv_sec,
   1467 			    (long int)e->tv.tv_usec);
   1468 			printf("%s#%ld: ", fn, e->call);
   1469 			printf(fmt, e->v[0], e->v[1], e->v[2], e->v[3]);
   1470 			putchar('\n');
   1471 		}
   1472 		i = (i + 1) % histp->n;
   1473 	} while (i != histp->f);
   1474 
   1475 	free(histents);
   1476 	if (fmt != NULL)
   1477 		free(fmt);
   1478 	if (fn != NULL)
   1479 		free(fn);
   1480 }
   1481 
   1482 void
   1483 usage(void)
   1484 {
   1485 
   1486 	(void)fprintf(stderr,
   1487 	    "usage: %s [-efHilmsUv] [-h hashname] [-u histname] [-c count]\n"
   1488 	    "\t\t[-M core] [-N system] [-w wait] [disks]\n", getprogname());
   1489 	exit(1);
   1490 }
   1491