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