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