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