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