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