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