Home | History | Annotate | Line # | Download | only in vmstat
vmstat.c revision 1.62
      1 /*	$NetBSD: vmstat.c,v 1.62 2000/04/14 06:11:11 simonb Exp $	*/
      2 
      3 /*-
      4  * Copyright (c) 1998 The NetBSD Foundation, Inc.
      5  * All rights reserved.
      6  *
      7  * This code is derived from software contributed to The NetBSD Foundation
      8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
      9  * NASA Ames Research Center.
     10  *
     11  * Redistribution and use in source and binary forms, with or without
     12  * modification, are permitted provided that the following conditions
     13  * are met:
     14  * 1. Redistributions of source code must retain the above copyright
     15  *    notice, this list of conditions and the following disclaimer.
     16  * 2. Redistributions in binary form must reproduce the above copyright
     17  *    notice, this list of conditions and the following disclaimer in the
     18  *    documentation and/or other materials provided with the distribution.
     19  * 3. All advertising materials mentioning features or use of this software
     20  *    must display the following acknowledgement:
     21  *	This product includes software developed by the NetBSD
     22  *	Foundation, Inc. and its contributors.
     23  * 4. Neither the name of The NetBSD Foundation nor the names of its
     24  *    contributors may be used to endorse or promote products derived
     25  *    from this software without specific prior written permission.
     26  *
     27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     37  * POSSIBILITY OF SUCH DAMAGE.
     38  */
     39 
     40 /*
     41  * Copyright (c) 1980, 1986, 1991, 1993
     42  *	The Regents of the University of California.  All rights reserved.
     43  *
     44  * Redistribution and use in source and binary forms, with or without
     45  * modification, are permitted provided that the following conditions
     46  * are met:
     47  * 1. Redistributions of source code must retain the above copyright
     48  *    notice, this list of conditions and the following disclaimer.
     49  * 2. Redistributions in binary form must reproduce the above copyright
     50  *    notice, this list of conditions and the following disclaimer in the
     51  *    documentation and/or other materials provided with the distribution.
     52  * 3. All advertising materials mentioning features or use of this software
     53  *    must display the following acknowledgement:
     54  *	This product includes software developed by the University of
     55  *	California, Berkeley and its contributors.
     56  * 4. Neither the name of the University nor the names of its contributors
     57  *    may be used to endorse or promote products derived from this software
     58  *    without specific prior written permission.
     59  *
     60  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     61  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     62  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     63  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     64  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     65  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     66  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     67  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     68  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     69  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     70  * SUCH DAMAGE.
     71  */
     72 
     73 #include <sys/cdefs.h>
     74 #ifndef lint
     75 __COPYRIGHT("@(#) Copyright (c) 1980, 1986, 1991, 1993\n\
     76 	The Regents of the University of California.  All rights reserved.\n");
     77 #endif /* not lint */
     78 
     79 #ifndef lint
     80 #if 0
     81 static char sccsid[] = "@(#)vmstat.c	8.2 (Berkeley) 3/1/95";
     82 #else
     83 __RCSID("$NetBSD: vmstat.c,v 1.62 2000/04/14 06:11:11 simonb Exp $");
     84 #endif
     85 #endif /* not lint */
     86 
     87 #define	__POOL_EXPOSE
     88 
     89 #include <sys/param.h>
     90 #include <sys/time.h>
     91 #include <sys/proc.h>
     92 #include <sys/user.h>
     93 #include <sys/dkstat.h>
     94 #include <sys/buf.h>
     95 #include <sys/namei.h>
     96 #include <sys/malloc.h>
     97 #include <sys/ioctl.h>
     98 #include <sys/sysctl.h>
     99 #include <sys/device.h>
    100 #include <sys/pool.h>
    101 #include <vm/vm.h>
    102 #include <err.h>
    103 #include <fcntl.h>
    104 #include <time.h>
    105 #include <nlist.h>
    106 #include <kvm.h>
    107 #include <errno.h>
    108 #include <unistd.h>
    109 #include <signal.h>
    110 #include <stdio.h>
    111 #include <ctype.h>
    112 #include <stdlib.h>
    113 #include <string.h>
    114 #include <paths.h>
    115 #include <limits.h>
    116 #include "dkstats.h"
    117 
    118 #include <uvm/uvm_stat.h>
    119 
    120 struct nlist namelist[] = {
    121 #define	X_CPTIME	0
    122 	{ "_cp_time" },
    123 #define	X_BOOTTIME	1
    124 	{ "_boottime" },
    125 #define X_HZ		2
    126 	{ "_hz" },
    127 #define X_STATHZ	3
    128 	{ "_stathz" },
    129 #define X_NCHSTATS	4
    130 	{ "_nchstats" },
    131 #define	X_INTRNAMES	5
    132 	{ "_intrnames" },
    133 #define	X_EINTRNAMES	6
    134 	{ "_eintrnames" },
    135 #define	X_INTRCNT	7
    136 	{ "_intrcnt" },
    137 #define	X_EINTRCNT	8
    138 	{ "_eintrcnt" },
    139 #define	X_KMEMSTAT	9
    140 	{ "_kmemstats" },
    141 #define	X_KMEMBUCKETS	10
    142 	{ "_bucket" },
    143 #define X_ALLEVENTS	11
    144 	{ "_allevents" },
    145 #define X_POOLHEAD	12
    146 	{ "_pool_head" },
    147 #define	X_UVMEXP	13
    148 	{ "_uvmexp" },
    149 #define X_END		14
    150 #if defined(pc532)
    151 #define	X_IVT		(X_END)
    152 	{ "_ivt" },
    153 #endif
    154 	{ "" },
    155 };
    156 
    157 /* Objects defined in dkstats.c */
    158 extern struct _disk	cur;
    159 extern char	**dr_name;
    160 extern int	*dk_select, dk_ndrive;
    161 
    162 struct	uvmexp uvmexp, ouvmexp;
    163 int		ndrives;
    164 
    165 int	winlines = 20;
    166 
    167 kvm_t *kd;
    168 
    169 #define	FORKSTAT	0x01
    170 #define	INTRSTAT	0x02
    171 #define	MEMSTAT		0x04
    172 #define	SUMSTAT		0x08
    173 #define	VMSTAT		0x20
    174 #define	HISTLIST	0x40
    175 #define	HISTDUMP	0x80
    176 
    177 void	cpustats __P((void));
    178 void	dkstats __P((void));
    179 void	dointr __P((void));
    180 void	domem __P((void));
    181 void	dopool __P((void));
    182 void	dosum __P((void));
    183 void	dovmstat __P((u_int, int));
    184 void	kread __P((int, void *, size_t));
    185 void	needhdr __P((int));
    186 long	getuptime __P((void));
    187 void	printhdr __P((void));
    188 long	pct __P((long, long));
    189 void	usage __P((void));
    190 void	doforkst __P((void));
    191 
    192 void	hist_traverse __P((int, const char *));
    193 void	hist_dodump __P((struct uvm_history *));
    194 
    195 int	main __P((int, char **));
    196 char	**choosedrives __P((char **));
    197 
    198 extern int dkinit __P((int, gid_t));
    199 extern void dkreadstats __P((void));
    200 extern void dkswap __P((void));
    201 
    202 /* Namelist and memory file names. */
    203 char	*nlistf, *memf;
    204 
    205 /* allow old usage [vmstat 1] */
    206 #define	BACKWARD_COMPATIBILITY
    207 
    208 int
    209 main(argc, argv)
    210 	int argc;
    211 	char **argv;
    212 {
    213 	int c, todo;
    214 	u_int interval;
    215 	int reps;
    216         char errbuf[_POSIX2_LINE_MAX];
    217 	gid_t	egid = getegid();
    218 	const char *histname = NULL;
    219 
    220 	(void)setegid(getgid());
    221 	memf = nlistf = NULL;
    222 	interval = reps = todo = 0;
    223 	while ((c = getopt(argc, argv, "c:fh:HilM:mN:sw:")) != -1) {
    224 		switch (c) {
    225 		case 'c':
    226 			reps = atoi(optarg);
    227 			break;
    228 		case 'f':
    229 			todo |= FORKSTAT;
    230 			break;
    231 		case 'h':
    232 			histname = optarg;
    233 			/* FALLTHROUGH */
    234 		case 'H':
    235 			todo |= HISTDUMP;
    236 			break;
    237 		case 'i':
    238 			todo |= INTRSTAT;
    239 			break;
    240 		case 'l':
    241 			todo |= HISTLIST;
    242 			break;
    243 		case 'M':
    244 			memf = optarg;
    245 			break;
    246 		case 'm':
    247 			todo |= MEMSTAT;
    248 			break;
    249 		case 'N':
    250 			nlistf = optarg;
    251 			break;
    252 		case 's':
    253 			todo |= SUMSTAT;
    254 			break;
    255 		case 'w':
    256 			interval = atoi(optarg);
    257 			break;
    258 		case '?':
    259 		default:
    260 			usage();
    261 		}
    262 	}
    263 	argc -= optind;
    264 	argv += optind;
    265 
    266 	if (todo == 0)
    267 		todo = VMSTAT;
    268 
    269 	/*
    270 	 * Discard setgid privileges.  If not the running kernel, we toss
    271 	 * them away totally so that bad guys can't print interesting stuff
    272 	 * from kernel memory, otherwise switch back to kmem for the
    273 	 * duration of the kvm_openfiles() call.
    274 	 */
    275 	if (nlistf != NULL || memf != NULL)
    276 		(void)setgid(getgid());
    277 	else
    278 		(void)setegid(egid);
    279 
    280         kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
    281 	if (kd == 0)
    282 		errx(1, "kvm_openfiles: %s\n", errbuf);
    283 
    284 	if (nlistf == NULL && memf == NULL) {
    285 		if (todo & VMSTAT)
    286 			(void)setegid(getgid());	/* XXX: dkinit */
    287 		else
    288 			(void)setgid(getgid());
    289 	}
    290 
    291 	if ((c = kvm_nlist(kd, namelist)) != 0) {
    292 		if (c > 0) {
    293 			(void)fprintf(stderr,
    294 			    "vmstat: undefined symbols:");
    295 			for (c = 0;
    296 			    c < sizeof(namelist)/sizeof(namelist[0]); c++)
    297 				if (namelist[c].n_type == 0)
    298 					fprintf(stderr, " %s",
    299 					    namelist[c].n_name);
    300 			(void)fputc('\n', stderr);
    301 		} else
    302 			(void)fprintf(stderr, "vmstat: kvm_nlist: %s\n",
    303 			    kvm_geterr(kd));
    304 		exit(1);
    305 	}
    306 
    307 	if (todo & VMSTAT) {
    308 		struct winsize winsize;
    309 
    310 		dkinit(0, egid); /* Initialize disk stats, no disks selected. */
    311 
    312 		(void)setgid(getgid()); /* don't need privs anymore */
    313 
    314 		argv = choosedrives(argv);	/* Select disks. */
    315 		winsize.ws_row = 0;
    316 		(void)ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
    317 		if (winsize.ws_row > 0)
    318 			winlines = winsize.ws_row;
    319 
    320 	}
    321 
    322 #ifdef	BACKWARD_COMPATIBILITY
    323 	if (*argv) {
    324 		interval = atoi(*argv);
    325 		if (*++argv)
    326 			reps = atoi(*argv);
    327 	}
    328 #endif
    329 
    330 	if (interval) {
    331 		if (!reps)
    332 			reps = -1;
    333 	} else if (reps)
    334 		interval = 1;
    335 
    336 	if (todo & (HISTLIST|HISTDUMP)) {
    337 		if ((todo & (HISTLIST|HISTDUMP)) == (HISTLIST|HISTDUMP))
    338 			errx(1, "you may list or dump, but not both!");
    339 		hist_traverse(todo, histname);
    340 	}
    341 	if (todo & FORKSTAT)
    342 		doforkst();
    343 	if (todo & MEMSTAT) {
    344 		domem();
    345 		dopool();
    346 	}
    347 	if (todo & SUMSTAT)
    348 		dosum();
    349 	if (todo & INTRSTAT)
    350 		dointr();
    351 	if (todo & VMSTAT)
    352 		dovmstat(interval, reps);
    353 	exit(0);
    354 }
    355 
    356 char **
    357 choosedrives(argv)
    358 	char **argv;
    359 {
    360 	int i;
    361 
    362 	/*
    363 	 * Choose drives to be displayed.  Priority goes to (in order) drives
    364 	 * supplied as arguments, default drives.  If everything isn't filled
    365 	 * in and there are drives not taken care of, display the first few
    366 	 * that fit.
    367 	 */
    368 #define BACKWARD_COMPATIBILITY
    369 	for (ndrives = 0; *argv; ++argv) {
    370 #ifdef	BACKWARD_COMPATIBILITY
    371 		if (isdigit(**argv))
    372 			break;
    373 #endif
    374 		for (i = 0; i < dk_ndrive; i++) {
    375 			if (strcmp(dr_name[i], *argv))
    376 				continue;
    377 			dk_select[i] = 1;
    378 			++ndrives;
    379 			break;
    380 		}
    381 	}
    382 	for (i = 0; i < dk_ndrive && ndrives < 4; i++) {
    383 		if (dk_select[i])
    384 			continue;
    385 		dk_select[i] = 1;
    386 		++ndrives;
    387 	}
    388 	return(argv);
    389 }
    390 
    391 long
    392 getuptime()
    393 {
    394 	static time_t now;
    395 	static struct timeval boottime;
    396 	time_t uptime;
    397 
    398 	if (boottime.tv_sec == 0)
    399 		kread(X_BOOTTIME, &boottime, sizeof(boottime));
    400 	(void)time(&now);
    401 	uptime = now - boottime.tv_sec;
    402 	if (uptime <= 0 || uptime > 60*60*24*365*10) {
    403 		(void)fprintf(stderr,
    404 		    "vmstat: time makes no sense; namelist must be wrong.\n");
    405 		exit(1);
    406 	}
    407 	return(uptime);
    408 }
    409 
    410 int	hz, hdrcnt;
    411 
    412 void
    413 dovmstat(interval, reps)
    414 	u_int interval;
    415 	int reps;
    416 {
    417 	struct vmtotal total;
    418 	time_t uptime, halfuptime;
    419 	int mib[2];
    420 	size_t size;
    421 	int pagesize = getpagesize();
    422 
    423 	uptime = getuptime();
    424 	halfuptime = uptime / 2;
    425 	(void)signal(SIGCONT, needhdr);
    426 
    427 	if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
    428 		kread(X_STATHZ, &hz, sizeof(hz));
    429 	if (!hz)
    430 		kread(X_HZ, &hz, sizeof(hz));
    431 
    432 	for (hdrcnt = 1;;) {
    433 		if (!--hdrcnt)
    434 			printhdr();
    435 		/* Read new disk statistics */
    436 		dkreadstats();
    437 		kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
    438 		if (memf != NULL) {
    439 			/*
    440 			 * XXX Can't do this if we're reading a crash
    441 			 * XXX dump because they're lazily-calculated.
    442 			 */
    443 			printf("Unable to get vmtotals from crash dump.\n");
    444 			memset(&total, 0, sizeof(total));
    445 		} else {
    446 			size = sizeof(total);
    447 			mib[0] = CTL_VM;
    448 			mib[1] = VM_METER;
    449 			if (sysctl(mib, 2, &total, &size, NULL, 0) < 0) {
    450 				printf("Can't get vmtotals: %s\n",
    451 				    strerror(errno));
    452 				memset(&total, 0, sizeof(total));
    453 			}
    454 		}
    455 		(void)printf("%2d%2d%2d",
    456 		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
    457 #define pgtok(a) (long)((a) * (pagesize >> 10))
    458 #define	rate(x)	(u_long)(((x) + halfuptime) / uptime)	/* round */
    459 		(void)printf("%6ld%6ld ",
    460 		    pgtok(total.t_avm), pgtok(total.t_free));
    461 		(void)printf("%4lu ", rate(uvmexp.faults - ouvmexp.faults));
    462 		(void)printf("%3lu ", rate(uvmexp.pdreact - ouvmexp.pdreact));
    463 		(void)printf("%3lu ", rate(uvmexp.pageins - ouvmexp.pageins));
    464 		(void)printf("%4lu ",
    465 		    rate(uvmexp.pgswapout - ouvmexp.pgswapout));
    466 		(void)printf("%4lu ", rate(uvmexp.pdfreed - ouvmexp.pdfreed));
    467 		(void)printf("%4lu ", rate(uvmexp.pdscans - ouvmexp.pdscans));
    468 		dkstats();
    469 		(void)printf("%4lu %4lu %3lu ",
    470 		    rate(uvmexp.intrs - ouvmexp.intrs),
    471 		    rate(uvmexp.syscalls - ouvmexp.syscalls),
    472 		    rate(uvmexp.swtch - ouvmexp.swtch));
    473 		cpustats();
    474 		(void)printf("\n");
    475 		(void)fflush(stdout);
    476 		if (reps >= 0 && --reps <= 0)
    477 			break;
    478 		ouvmexp = uvmexp;
    479 		uptime = interval;
    480 		/*
    481 		 * We round upward to avoid losing low-frequency events
    482 		 * (i.e., >= 1 per interval but < 1 per second).
    483 		 */
    484 		halfuptime = uptime == 1 ? 0 : (uptime + 1) / 2;
    485 		(void)sleep(interval);
    486 	}
    487 }
    488 
    489 void
    490 printhdr()
    491 {
    492 	int i;
    493 
    494 	(void)printf(" procs   memory     page%*s", 23, "");
    495 	if (ndrives > 0)
    496 		(void)printf("%s %*sfaults   cpu\n",
    497 		   ((ndrives > 1) ? "disks" : "disk"),
    498 		   ((ndrives > 1) ? ndrives * 3 - 4 : 0), "");
    499 	else
    500 		(void)printf("%*s  faults   cpu\n",
    501 		   ndrives * 3, "");
    502 
    503 	(void)printf(" r b w   avm   fre  flt  re  pi   po   fr   sr ");
    504 	for (i = 0; i < dk_ndrive; i++)
    505 		if (dk_select[i])
    506 			(void)printf("%c%c ", dr_name[i][0],
    507 			    dr_name[i][strlen(dr_name[i]) - 1]);
    508 	(void)printf("  in   sy  cs us sy id\n");
    509 	hdrcnt = winlines - 2;
    510 }
    511 
    512 /*
    513  * Force a header to be prepended to the next output.
    514  */
    515 void
    516 needhdr(dummy)
    517 	int dummy;
    518 {
    519 
    520 	hdrcnt = 1;
    521 }
    522 
    523 long
    524 pct(top, bot)
    525 	long top, bot;
    526 {
    527 	long ans;
    528 
    529 	if (bot == 0)
    530 		return(0);
    531 	ans = (quad_t)top * 100 / bot;
    532 	return (ans);
    533 }
    534 
    535 #define	PCT(top, bot) (int)pct((long)(top), (long)(bot))
    536 
    537 void
    538 dosum()
    539 {
    540 	struct nchstats nchstats;
    541 	long nchtotal;
    542 
    543 	kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
    544 
    545 	(void)printf("%9u bytes per page\n", uvmexp.pagesize);
    546 
    547 	(void)printf("%9u pages managed\n", uvmexp.npages);
    548 	(void)printf("%9u pages free\n", uvmexp.free);
    549 	(void)printf("%9u pages active\n", uvmexp.active);
    550 	(void)printf("%9u pages inactive\n", uvmexp.inactive);
    551 	(void)printf("%9u pages paging\n", uvmexp.paging);
    552 	(void)printf("%9u pages wired\n", uvmexp.wired);
    553 	(void)printf("%9u reserve pagedaemon pages\n",
    554 	    uvmexp.reserve_pagedaemon);
    555 	(void)printf("%9u reserve kernel pages\n", uvmexp.reserve_kernel);
    556 
    557 	(void)printf("%9u minimum free pages\n", uvmexp.freemin);
    558 	(void)printf("%9u target free pages\n", uvmexp.freetarg);
    559 	(void)printf("%9u target inactive pages\n", uvmexp.inactarg);
    560 	(void)printf("%9u maximum wired pages\n", uvmexp.wiredmax);
    561 
    562 	(void)printf("%9u swap devices\n", uvmexp.nswapdev);
    563 	(void)printf("%9u swap pages\n", uvmexp.swpages);
    564 	(void)printf("%9u swap pages in use\n", uvmexp.swpginuse);
    565 	(void)printf("%9u swap allocations\n", uvmexp.nswget);
    566 	(void)printf("%9u anons\n", uvmexp.nanon);
    567 	(void)printf("%9u free anons\n", uvmexp.nfreeanon);
    568 
    569 	(void)printf("%9u total faults taken\n", uvmexp.faults);
    570 	(void)printf("%9u traps\n", uvmexp.traps);
    571 	(void)printf("%9u device interrupts\n", uvmexp.intrs);
    572 	(void)printf("%9u cpu context switches\n", uvmexp.swtch);
    573 	(void)printf("%9u software interrupts\n", uvmexp.softs);
    574 	(void)printf("%9u system calls\n", uvmexp.syscalls);
    575 	(void)printf("%9u pagein requests\n", uvmexp.pageins);
    576 	(void)printf("%9u pageout requests\n", uvmexp.pdpageouts);
    577 	(void)printf("%9u swap ins\n", uvmexp.swapins);
    578 	(void)printf("%9u swap outs\n", uvmexp.swapouts);
    579 	(void)printf("%9u pages swapped in\n", uvmexp.pgswapin);
    580 	(void)printf("%9u pages swapped out\n", uvmexp.pgswapout);
    581 	(void)printf("%9u forks total\n", uvmexp.forks);
    582 	(void)printf("%9u forks blocked parent\n", uvmexp.forks_ppwait);
    583 	(void)printf("%9u forks shared address space with parent\n",
    584 	    uvmexp.forks_sharevm);
    585 
    586 	(void)printf("%9u faults with no memory\n", uvmexp.fltnoram);
    587 	(void)printf("%9u faults with no anons\n", uvmexp.fltnoanon);
    588 	(void)printf("%9u faults had to wait on pages\n", uvmexp.fltpgwait);
    589 	(void)printf("%9u faults found released page\n", uvmexp.fltpgrele);
    590 	(void)printf("%9u faults relock (%u ok)\n", uvmexp.fltrelck,
    591 	    uvmexp.fltrelckok);
    592 	(void)printf("%9u anon page faults\n", uvmexp.fltanget);
    593 	(void)printf("%9u anon retry faults\n", uvmexp.fltanretry);
    594 	(void)printf("%9u amap copy faults\n", uvmexp.fltamcopy);
    595 	(void)printf("%9u neighbour anon page faults\n", uvmexp.fltnamap);
    596 	(void)printf("%9u neighbour object page faults\n", uvmexp.fltnomap);
    597 	(void)printf("%9u locked pager get faults\n", uvmexp.fltlget);
    598 	(void)printf("%9u unlocked pager get faults\n", uvmexp.fltget);
    599 	(void)printf("%9u anon faults\n", uvmexp.flt_anon);
    600 	(void)printf("%9u anon copy on write faults\n", uvmexp.flt_acow);
    601 	(void)printf("%9u object faults\n", uvmexp.flt_obj);
    602 	(void)printf("%9u promote copy faults\n", uvmexp.flt_prcopy);
    603 	(void)printf("%9u promote zero fill faults\n", uvmexp.flt_przero);
    604 
    605 	(void)printf("%9u times daemon wokeup\n",uvmexp.pdwoke);
    606 	(void)printf("%9u revolutions of the clock hand\n", uvmexp.pdrevs);
    607 	(void)printf("%9u times daemon attempted swapout\n", uvmexp.pdswout);
    608 	(void)printf("%9u pages freed by daemon\n", uvmexp.pdfreed);
    609 	(void)printf("%9u pages scanned by daemon\n", uvmexp.pdscans);
    610 	(void)printf("%9u anonymous pages scanned by daemon\n", uvmexp.pdanscan);
    611 	(void)printf("%9u object pages scanned by daemon\n", uvmexp.pdobscan);
    612 	(void)printf("%9u pages reactivated\n", uvmexp.pdreact);
    613 	(void)printf("%9u pages found busy by daemon\n", uvmexp.pdbusy);
    614 	(void)printf("%9u total pending pageouts\n", uvmexp.pdpending);
    615 	(void)printf("%9u pages deactivated\n", uvmexp.pddeact);
    616 	kread(X_NCHSTATS, &nchstats, sizeof(nchstats));
    617 	nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
    618 	    nchstats.ncs_badhits + nchstats.ncs_falsehits +
    619 	    nchstats.ncs_miss + nchstats.ncs_long;
    620 	(void)printf("%9ld total name lookups\n", nchtotal);
    621 	(void)printf(
    622 	    "%9s cache hits (%d%% pos + %d%% neg) system %d%% per-process\n",
    623 	    "", PCT(nchstats.ncs_goodhits, nchtotal),
    624 	    PCT(nchstats.ncs_neghits, nchtotal),
    625 	    PCT(nchstats.ncs_pass2, nchtotal));
    626 	(void)printf("%9s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
    627 	    PCT(nchstats.ncs_badhits, nchtotal),
    628 	    PCT(nchstats.ncs_falsehits, nchtotal),
    629 	    PCT(nchstats.ncs_long, nchtotal));
    630 }
    631 
    632 void
    633 doforkst()
    634 {
    635 
    636 	kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
    637 
    638 	(void)printf("%u forks total\n", uvmexp.forks);
    639 	(void)printf("%u forks blocked parent\n", uvmexp.forks_ppwait);
    640 	(void)printf("%u forks shared address space with parent\n",
    641 	    uvmexp.forks_sharevm);
    642 }
    643 
    644 void
    645 dkstats()
    646 {
    647 	int dn, state;
    648 	double etime;
    649 
    650 	/* Calculate disk stat deltas. */
    651 	dkswap();
    652 	etime = 0;
    653 	for (state = 0; state < CPUSTATES; ++state) {
    654 		etime += cur.cp_time[state];
    655 	}
    656 	if (etime == 0)
    657 		etime = 1;
    658 	etime /= hz;
    659 	for (dn = 0; dn < dk_ndrive; ++dn) {
    660 		if (!dk_select[dn])
    661 			continue;
    662 		(void)printf("%2.0f ", cur.dk_xfer[dn] / etime);
    663 	}
    664 }
    665 
    666 void
    667 cpustats()
    668 {
    669 	int state;
    670 	double pct, total;
    671 
    672 	total = 0;
    673 	for (state = 0; state < CPUSTATES; ++state)
    674 		total += cur.cp_time[state];
    675 	if (total)
    676 		pct = 100 / total;
    677 	else
    678 		pct = 0;
    679 	(void)printf("%2.0f ", (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * pct);
    680 	(void)printf("%2.0f ", (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * pct);
    681 	(void)printf("%2.0f", cur.cp_time[CP_IDLE] * pct);
    682 }
    683 
    684 #if defined(pc532)
    685 /* To get struct iv ...*/
    686 #define _KERNEL
    687 #include <machine/psl.h>
    688 #undef _KERNEL
    689 void
    690 dointr()
    691 {
    692 	long i, j, inttotal, uptime;
    693 	static char iname[64];
    694 	struct iv ivt[32], *ivp = ivt;
    695 
    696 	iname[63] = '\0';
    697 	uptime = getuptime();
    698 	kread(X_IVT, ivp, sizeof(ivt));
    699 
    700 	for (i = 0; i < 2; i++) {
    701 		(void)printf("%sware interrupts:\n", i ? "\nsoft" : "hard");
    702 		(void)printf("interrupt       total     rate\n");
    703 		inttotal = 0;
    704 		for (j = 0; j < 16; j++, ivp++) {
    705 			if (ivp->iv_vec && ivp->iv_use && ivp->iv_cnt) {
    706 				if (kvm_read(kd, (u_long)ivp->iv_use, iname, 63) != 63) {
    707 					(void)fprintf(stderr, "vmstat: iv_use: %s\n",
    708 					    kvm_geterr(kd));
    709 					exit(1);
    710 				}
    711 				(void)printf("%-12s %8ld %8ld\n", iname,
    712 				    ivp->iv_cnt, ivp->iv_cnt / uptime);
    713 				inttotal += ivp->iv_cnt;
    714 			}
    715 		}
    716 		(void)printf("Total        %8ld %8ld\n",
    717 		    inttotal, inttotal / uptime);
    718 	}
    719 }
    720 #else
    721 void
    722 dointr()
    723 {
    724 	long *intrcnt, inttotal, uptime;
    725 	int nintr, inamlen;
    726 	char *intrname;
    727 	struct evcntlist allevents;
    728 	struct evcnt evcnt, *evptr;
    729 	struct device dev;
    730 
    731 	uptime = getuptime();
    732 	nintr = namelist[X_EINTRCNT].n_value - namelist[X_INTRCNT].n_value;
    733 	inamlen =
    734 	    namelist[X_EINTRNAMES].n_value - namelist[X_INTRNAMES].n_value;
    735 	intrcnt = malloc((size_t)nintr);
    736 	intrname = malloc((size_t)inamlen);
    737 	if (intrcnt == NULL || intrname == NULL) {
    738 		(void)fprintf(stderr, "vmstat: %s.\n", strerror(errno));
    739 		exit(1);
    740 	}
    741 	kread(X_INTRCNT, intrcnt, (size_t)nintr);
    742 	kread(X_INTRNAMES, intrname, (size_t)inamlen);
    743 	(void)printf("interrupt         total     rate\n");
    744 	inttotal = 0;
    745 	nintr /= sizeof(long);
    746 	while (--nintr >= 0) {
    747 		if (*intrcnt)
    748 			(void)printf("%-14s %8ld %8ld\n", intrname,
    749 			    *intrcnt, *intrcnt / uptime);
    750 		intrname += strlen(intrname) + 1;
    751 		inttotal += *intrcnt++;
    752 	}
    753 	kread(X_ALLEVENTS, &allevents, sizeof allevents);
    754 	evptr = allevents.tqh_first;
    755 	while (evptr) {
    756 		if (kvm_read(kd, (long)evptr, (void *)&evcnt,
    757 		    sizeof evcnt) != sizeof evcnt) {
    758 			(void)fprintf(stderr, "vmstat: event chain trashed: %s\n",
    759 			    kvm_geterr(kd));
    760 			exit(1);
    761 		}
    762 		if (kvm_read(kd, (long)evcnt.ev_dev, (void *)&dev,
    763 		    sizeof dev) != sizeof dev) {
    764 			(void)fprintf(stderr, "vmstat: event chain trashed: %s\n",
    765 			    kvm_geterr(kd));
    766 			exit(1);
    767 		}
    768 		if (evcnt.ev_count)
    769 			(void)printf("%-14s %8ld %8ld\n", dev.dv_xname,
    770 			    (long)evcnt.ev_count, evcnt.ev_count / uptime);
    771 		inttotal += evcnt.ev_count++;
    772 
    773 		evptr = evcnt.ev_list.tqe_next;
    774 	}
    775 	(void)printf("Total          %8ld %8ld\n", inttotal, inttotal / uptime);
    776 }
    777 #endif
    778 
    779 /*
    780  * These names are defined in <sys/malloc.h>.
    781  */
    782 char *kmemnames[] = INITKMEMNAMES;
    783 
    784 void
    785 domem()
    786 {
    787 	struct kmembuckets *kp;
    788 	struct kmemstats *ks;
    789 	int i, j;
    790 	int len, size, first;
    791 	long totuse = 0, totfree = 0, totreq = 0;
    792 	char *name;
    793 	struct kmemstats kmemstats[M_LAST];
    794 	struct kmembuckets buckets[MINBUCKET + 16];
    795 
    796 	kread(X_KMEMBUCKETS, buckets, sizeof(buckets));
    797 	for (first = 1, i = MINBUCKET, kp = &buckets[i]; i < MINBUCKET + 16;
    798 	    i++, kp++) {
    799 		if (kp->kb_calls == 0)
    800 			continue;
    801 		if (first) {
    802 			(void)printf("Memory statistics by bucket size\n");
    803 			(void)printf(
    804 		 "    Size   In Use   Free   Requests  HighWater  Couldfree\n");
    805 			first = 0;
    806 		}
    807 		size = 1 << i;
    808 		(void)printf("%8d %8ld %6ld %10ld %7ld %10ld\n", size,
    809 			kp->kb_total - kp->kb_totalfree,
    810 			kp->kb_totalfree, kp->kb_calls,
    811 			kp->kb_highwat, kp->kb_couldfree);
    812 		totfree += size * kp->kb_totalfree;
    813 	}
    814 
    815 	/*
    816 	 * If kmem statistics are not being gathered by the kernel,
    817 	 * first will still be 1.
    818 	 */
    819 	if (first) {
    820 		printf(
    821 		    "Kmem statistics are not being gathered by the kernel.\n");
    822 		return;
    823 	}
    824 
    825 	kread(X_KMEMSTAT, kmemstats, sizeof(kmemstats));
    826 	(void)printf("\nMemory usage type by bucket size\n");
    827 	(void)printf("    Size  Type(s)\n");
    828 	kp = &buckets[MINBUCKET];
    829 	for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1, kp++) {
    830 		if (kp->kb_calls == 0)
    831 			continue;
    832 		first = 1;
    833 		len = 8;
    834 		for (i = 0, ks = &kmemstats[0]; i < M_LAST; i++, ks++) {
    835 			if (ks->ks_calls == 0)
    836 				continue;
    837 			if ((ks->ks_size & j) == 0)
    838 				continue;
    839 			if (kmemnames[i] == 0) {
    840 				kmemnames[i] = malloc(10);
    841 						/* strlen("undef/")+3+1);*/
    842 				snprintf(kmemnames[i], 10, "undef/%d", i);
    843 						/* same 10 as above!!! */
    844 			}
    845 			name = kmemnames[i];
    846 			len += 2 + strlen(name);
    847 			if (first)
    848 				printf("%8d  %s", j, name);
    849 			else
    850 				printf(",");
    851 			if (len >= 80) {
    852 				printf("\n\t ");
    853 				len = 10 + strlen(name);
    854 			}
    855 			if (!first)
    856 				printf(" %s", name);
    857 			first = 0;
    858 		}
    859 		printf("\n");
    860 	}
    861 
    862 	(void)printf(
    863 	    "\nMemory statistics by type                        Type  Kern\n");
    864 	(void)printf(
    865 "         Type  InUse MemUse HighUse  Limit Requests Limit Limit Size(s)\n");
    866 	for (i = 0, ks = &kmemstats[0]; i < M_LAST; i++, ks++) {
    867 		if (ks->ks_calls == 0)
    868 			continue;
    869 		(void)printf("%14s%6ld%6ldK%7ldK%6ldK%9ld%5u%6u",
    870 		    kmemnames[i] ? kmemnames[i] : "undefined",
    871 		    ks->ks_inuse, (ks->ks_memuse + 1023) / 1024,
    872 		    (ks->ks_maxused + 1023) / 1024,
    873 		    (ks->ks_limit + 1023) / 1024, ks->ks_calls,
    874 		    ks->ks_limblocks, ks->ks_mapblocks);
    875 		first = 1;
    876 		for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
    877 			if ((ks->ks_size & j) == 0)
    878 				continue;
    879 			if (first)
    880 				printf("  %d", j);
    881 			else
    882 				printf(",%d", j);
    883 			first = 0;
    884 		}
    885 		printf("\n");
    886 		totuse += ks->ks_memuse;
    887 		totreq += ks->ks_calls;
    888 	}
    889 	(void)printf("\nMemory Totals:  In Use    Free    Requests\n");
    890 	(void)printf("              %7ldK %6ldK    %8ld\n",
    891 	     (totuse + 1023) / 1024, (totfree + 1023) / 1024, totreq);
    892 }
    893 
    894 void
    895 dopool()
    896 {
    897 	int first;
    898 	long addr;
    899 	long total = 0, inuse = 0;
    900 	TAILQ_HEAD(,pool) pool_head;
    901 	struct pool pool, *pp = &pool;
    902 
    903 	kread(X_POOLHEAD, &pool_head, sizeof(pool_head));
    904 	addr = (long)TAILQ_FIRST(&pool_head);
    905 
    906 	for (first = 1; addr != 0; ) {
    907 		char name[32], maxp[32];
    908 		if (kvm_read(kd, addr, (void *)pp, sizeof *pp) != sizeof *pp) {
    909 			(void)fprintf(stderr, "vmstat: pool chain trashed: %s\n",
    910 			    kvm_geterr(kd));
    911 			exit(1);
    912 		}
    913 		if (kvm_read(kd, (long)pp->pr_wchan, name, sizeof name) < 0) {
    914 			(void)fprintf(stderr, "vmstat: pool name trashed: %s\n",
    915 			    kvm_geterr(kd));
    916 			exit(1);
    917 		}
    918 		name[31]='\0';
    919 
    920 		if (first) {
    921 			(void)printf("Memory resource pool statistics\n");
    922 			(void)printf(
    923 			"%-11s%5s%9s%5s%9s%6s%6s%6s%6s%6s%6s%5s\n",
    924 		 		"Name",
    925 				"Size",
    926 				"Requests",
    927 				"Fail",
    928 				"Releases",
    929 				"Pgreq",
    930 				"Pgrel",
    931 				"Npage",
    932 				"Hiwat",
    933 				"Minpg",
    934 				"Maxpg",
    935 				"Idle");
    936 			first = 0;
    937 		}
    938 		if (pp->pr_maxpages == UINT_MAX)
    939 			sprintf(maxp, "inf");
    940 		else
    941 			sprintf(maxp, "%6u", pp->pr_maxpages);
    942 		(void)printf(
    943 		    "%-11s%5u%9lu%5lu%9lu%6lu%6lu%6d%6d%6d%6s%5lu\n",
    944 			name,
    945 			pp->pr_size,
    946 			pp->pr_nget,
    947 			pp->pr_nfail,
    948 			pp->pr_nput,
    949 			pp->pr_npagealloc,
    950 			pp->pr_npagefree,
    951 			pp->pr_npages,
    952 			pp->pr_hiwat,
    953 			pp->pr_minpages,
    954 			maxp,
    955 			pp->pr_nidle);
    956 
    957 		inuse += (pp->pr_nget - pp->pr_nput) * pp->pr_size;
    958 		total += pp->pr_npages * pp->pr_pagesz;
    959 		addr = (long)TAILQ_NEXT(pp, pr_poollist);
    960 	}
    961 
    962 	printf("\nIn use %ldK, total allocated %ldK; utilization %.1f%%\n",
    963 		inuse/1024, total/1024, (double)(100 * inuse) / total);
    964 
    965 }
    966 
    967 /*
    968  * kread reads something from the kernel, given its nlist index.
    969  */
    970 void
    971 kread(nlx, addr, size)
    972 	int nlx;
    973 	void *addr;
    974 	size_t size;
    975 {
    976 	const char *sym;
    977 
    978 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
    979 		sym = namelist[nlx].n_name;
    980 		if (*sym == '_')
    981 			++sym;
    982 		(void)fprintf(stderr,
    983 		    "vmstat: symbol %s not defined\n", sym);
    984 		exit(1);
    985 	}
    986 	if (kvm_read(kd, namelist[nlx].n_value, addr, size) != size) {
    987 		sym = namelist[nlx].n_name;
    988 		if (*sym == '_')
    989 			++sym;
    990 		(void)fprintf(stderr, "vmstat: %s: %s\n", sym, kvm_geterr(kd));
    991 		exit(1);
    992 	}
    993 }
    994 
    995 struct nlist histnl[] = {
    996 	{ "_uvm_histories" },
    997 #define	X_UVM_HISTORIES		0
    998 	{ NULL },
    999 };
   1000 
   1001 /*
   1002  * Traverse the UVM history buffers, performing the requested action.
   1003  *
   1004  * Note, we assume that if we're not listing, we're dumping.
   1005  */
   1006 void
   1007 hist_traverse(todo, histname)
   1008 	int todo;
   1009 	const char *histname;
   1010 {
   1011 	struct uvm_history_head histhead;
   1012 	struct uvm_history hist, *histkva;
   1013 	char *name = NULL;
   1014 	size_t namelen = 0;
   1015 
   1016 	if (kvm_nlist(kd, histnl) != 0) {
   1017 		printf("UVM history is not compiled into the kernel.\n");
   1018 		return;
   1019 	}
   1020 
   1021 	if (kvm_read(kd, histnl[X_UVM_HISTORIES].n_value, &histhead,
   1022 	    sizeof(histhead)) != sizeof(histhead)) {
   1023 		warnx("unable to read %s: %s",
   1024 		    histnl[X_UVM_HISTORIES].n_name, kvm_geterr(kd));
   1025 		return;
   1026 	}
   1027 
   1028 	if (histhead.lh_first == NULL) {
   1029 		printf("No active UVM history logs.\n");
   1030 		return;
   1031 	}
   1032 
   1033 	if (todo & HISTLIST)
   1034 		printf("Active UVM histories:");
   1035 
   1036 	for (histkva = histhead.lh_first; histkva != NULL;
   1037 	    histkva = hist.list.le_next) {
   1038 		if (kvm_read(kd, (u_long)histkva, &hist, sizeof(hist)) !=
   1039 		    sizeof(hist)) {
   1040 			warnx("unable to read history at %p: %s",
   1041 			    histkva, kvm_geterr(kd));
   1042 			goto out;
   1043 		}
   1044 
   1045 		if (hist.namelen > namelen) {
   1046 			if (name != NULL)
   1047 				free(name);
   1048 			namelen = hist.namelen;
   1049 			if ((name = malloc(namelen + 1)) == NULL)
   1050 				err(1, "malloc history name");
   1051 		}
   1052 
   1053 		if (kvm_read(kd, (u_long)hist.name, name, namelen) !=
   1054 		    namelen) {
   1055 			warnx("unable to read history name at %p: %s",
   1056 			    hist.name, kvm_geterr(kd));
   1057 			goto out;
   1058 		}
   1059 		name[namelen] = '\0';
   1060 		if (todo & HISTLIST)
   1061 			printf(" %s", name);
   1062 		else {
   1063 			/*
   1064 			 * If we're dumping all histories, do it, else
   1065 			 * check to see if this is the one we want.
   1066 			 */
   1067 			if (histname == NULL || strcmp(histname, name) == 0) {
   1068 				if (histname == NULL)
   1069 					printf("\nUVM history `%s':\n", name);
   1070 				hist_dodump(&hist);
   1071 			}
   1072 		}
   1073 	}
   1074 
   1075 	if (todo & HISTLIST)
   1076 		printf("\n");
   1077 
   1078  out:
   1079 	if (name != NULL)
   1080 		free(name);
   1081 }
   1082 
   1083 /*
   1084  * Actually dump the history buffer at the specified KVA.
   1085  */
   1086 void
   1087 hist_dodump(histp)
   1088 	struct uvm_history *histp;
   1089 {
   1090 	struct uvm_history_ent *histents, *e;
   1091 	size_t histsize;
   1092 	char *fmt = NULL, *fn = NULL;
   1093 	size_t fmtlen = 0, fnlen = 0;
   1094 	int i;
   1095 
   1096 	histsize = sizeof(struct uvm_history_ent) * histp->n;
   1097 
   1098 	if ((histents = malloc(histsize)) == NULL)
   1099 		err(1, "malloc history entries");
   1100 
   1101 	memset(histents, 0, histsize);
   1102 
   1103 	if (kvm_read(kd, (u_long)histp->e, histents, histsize) != histsize) {
   1104 		warnx("unable to read history entries at %p: %s",
   1105 		    histp->e, kvm_geterr(kd));
   1106 		goto out;
   1107 	}
   1108 
   1109 	i = histp->f;
   1110 	do {
   1111 		e = &histents[i];
   1112 		if (e->fmt != NULL) {
   1113 			if (e->fmtlen > fmtlen) {
   1114 				if (fmt != NULL)
   1115 					free(fmt);
   1116 				fmtlen = e->fmtlen;
   1117 				if ((fmt = malloc(fmtlen + 1)) == NULL)
   1118 					err(1, "malloc printf format");
   1119 			}
   1120 			if (e->fnlen > fnlen) {
   1121 				if (fn != NULL)
   1122 					free(fn);
   1123 				fnlen = e->fnlen;
   1124 				if ((fn = malloc(fnlen + 1)) == NULL)
   1125 					err(1, "malloc function name");
   1126 			}
   1127 
   1128 			if (kvm_read(kd, (u_long)e->fmt, fmt, fmtlen)
   1129 			    != fmtlen) {
   1130 				warnx("unable to read printf format "
   1131 				    "at %p: %s", e->fmt, kvm_geterr(kd));
   1132 				goto out;
   1133 			}
   1134 			fmt[fmtlen] = '\0';
   1135 
   1136 			if (kvm_read(kd, (u_long)e->fn, fn, fnlen) != fnlen) {
   1137 				warnx("unable to read function name "
   1138 				    "at %p: %s", e->fn, kvm_geterr(kd));
   1139 				goto out;
   1140 			}
   1141 			fn[fnlen] = '\0';
   1142 
   1143 			printf("%06ld.%06ld ", (long int)e->tv.tv_sec,
   1144 			    (long int)e->tv.tv_usec);
   1145 			printf("%s#%ld: ", fn, e->call);
   1146 			printf(fmt, e->v[0], e->v[1], e->v[2], e->v[3]);
   1147 			printf("\n");
   1148 		}
   1149 		i = (i + 1) % histp->n;
   1150 	} while (i != histp->f);
   1151 
   1152  out:
   1153 	free(histents);
   1154 	if (fmt != NULL)
   1155 		free(fmt);
   1156 	if (fn != NULL)
   1157 		free(fn);
   1158 }
   1159 
   1160 void
   1161 usage()
   1162 {
   1163 
   1164 	(void)fprintf(stderr,
   1165 	    "usage: vmstat [-fHilms] [-h histname] [-c count] [-M core] \
   1166 [-N system] [-w wait] [disks]\n");
   1167 	exit(1);
   1168 }
   1169