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