Home | History | Annotate | Line # | Download | only in vmstat
vmstat.c revision 1.237
      1 /* $NetBSD: vmstat.c,v 1.237 2020/03/22 14:39:28 ad Exp $ */
      2 
      3 /*-
      4  * Copyright (c) 1998, 2000, 2001, 2007, 2019, 2020
      5  *     The NetBSD Foundation, Inc.
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation by:
      9  *	- Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
     10  *	  NASA Ames Research Center.
     11  *	- Simon Burge and Luke Mewburn of Wasabi Systems, Inc.
     12  *
     13  * Redistribution and use in source and binary forms, with or without
     14  * modification, are permitted provided that the following conditions
     15  * are met:
     16  * 1. Redistributions of source code must retain the above copyright
     17  *    notice, this list of conditions and the following disclaimer.
     18  * 2. Redistributions in binary form must reproduce the above copyright
     19  *    notice, this list of conditions and the following disclaimer in the
     20  *    documentation and/or other materials provided with the distribution.
     21  *
     22  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     23  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     24  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     25  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     26  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     27  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     28  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     29  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     30  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     31  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     32  * POSSIBILITY OF SUCH DAMAGE.
     33  */
     34 
     35 /*
     36  * Copyright (c) 1980, 1986, 1991, 1993
     37  *	The Regents of the University of California.  All rights reserved.
     38  *
     39  * Redistribution and use in source and binary forms, with or without
     40  * modification, are permitted provided that the following conditions
     41  * are met:
     42  * 1. Redistributions of source code must retain the above copyright
     43  *    notice, this list of conditions and the following disclaimer.
     44  * 2. Redistributions in binary form must reproduce the above copyright
     45  *    notice, this list of conditions and the following disclaimer in the
     46  *    documentation and/or other materials provided with the distribution.
     47  * 3. Neither the name of the University nor the names of its contributors
     48  *    may be used to endorse or promote products derived from this software
     49  *    without specific prior written permission.
     50  *
     51  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     52  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     53  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     54  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     55  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     56  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     57  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     58  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     59  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     60  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     61  * SUCH DAMAGE.
     62  */
     63 
     64 #include <sys/cdefs.h>
     65 #ifndef lint
     66 __COPYRIGHT("@(#) Copyright (c) 1980, 1986, 1991, 1993\
     67  The Regents of the University of California.  All rights reserved.");
     68 #endif /* not lint */
     69 
     70 #ifndef lint
     71 #if 0
     72 static char sccsid[] = "@(#)vmstat.c	8.2 (Berkeley) 3/1/95";
     73 #else
     74 __RCSID("$NetBSD: vmstat.c,v 1.237 2020/03/22 14:39:28 ad Exp $");
     75 #endif
     76 #endif /* not lint */
     77 
     78 #define	__POOL_EXPOSE
     79 #define __NAMECACHE_PRIVATE
     80 
     81 #include <sys/param.h>
     82 #include <sys/types.h>
     83 #include <sys/mount.h>
     84 #include <sys/uio.h>
     85 
     86 #include <sys/buf.h>
     87 #include <sys/evcnt.h>
     88 #include <sys/ioctl.h>
     89 #include <sys/malloc.h>
     90 #include <sys/mallocvar.h>
     91 #include <sys/namei.h>
     92 #include <sys/pool.h>
     93 #include <sys/proc.h>
     94 #include <sys/sched.h>
     95 #include <sys/socket.h>
     96 #include <sys/sysctl.h>
     97 #include <sys/time.h>
     98 #include <sys/queue.h>
     99 #include <sys/kernhist.h>
    100 #include <sys/vnode.h>
    101 #include <sys/vnode_impl.h>
    102 
    103 #include <uvm/uvm_extern.h>
    104 #include <uvm/uvm_stat.h>
    105 
    106 #include <net/if.h>
    107 #include <netinet/in.h>
    108 #include <netinet/in_var.h>
    109 
    110 #include <ufs/ufs/inode.h>
    111 
    112 #include <nfs/rpcv2.h>
    113 #include <nfs/nfsproto.h>
    114 #include <nfs/nfsnode.h>
    115 
    116 #include <ctype.h>
    117 #include <err.h>
    118 #include <errno.h>
    119 #include <fcntl.h>
    120 #include <kvm.h>
    121 #include <limits.h>
    122 #include <nlist.h>
    123 #undef n_hash
    124 #include <paths.h>
    125 #include <signal.h>
    126 #include <stdio.h>
    127 #include <stddef.h>
    128 #include <stdlib.h>
    129 #include <string.h>
    130 #include <time.h>
    131 #include <unistd.h>
    132 #include <util.h>
    133 
    134 #include "drvstats.h"
    135 
    136 /*
    137  * All this mess will go away once everything is converted.
    138  */
    139 #ifdef __HAVE_CPU_DATA_FIRST
    140 
    141 # include <sys/cpu_data.h>
    142 struct cpu_info {
    143 	struct cpu_data ci_data;
    144 };
    145 #else
    146 # include <sys/cpu.h>
    147 #endif
    148 
    149 /*
    150  * General namelist
    151  */
    152 struct nlist namelist[] =
    153 {
    154 #define	X_HZ		0
    155 	{ .n_name = "_hz" },
    156 #define	X_STATHZ	1
    157 	{ .n_name = "_stathz" },
    158 #define	X_NCHSTATS	2
    159 	{ .n_name = "_nchstats" },
    160 #define	X_ALLEVENTS	3
    161 	{ .n_name = "_allevents" },
    162 #define	X_POOLHEAD	4
    163 	{ .n_name = "_pool_head" },
    164 #define	X_UVMEXP	5
    165 	{ .n_name = "_uvmexp" },
    166 #define X_CPU_INFOS	6
    167 	{ .n_name = "_cpu_infos" },
    168 #define	X_NL_SIZE	7
    169 	{ .n_name = NULL },
    170 };
    171 
    172 /*
    173  * Namelist for time data.
    174  */
    175 struct nlist timenl[] =
    176 {
    177 #define	X_TIMEBASEBIN	0
    178 	{ .n_name = "_timebasebin" },
    179 #define	X_TIME_SECOND	1
    180 	{ .n_name = "_time_second" },
    181 #define X_TIME		2
    182 	{ .n_name = "_time" },
    183 #define	X_TIMENL_SIZE	3
    184 	{ .n_name = NULL },
    185 };
    186 
    187 /*
    188  * Namelist for pre-evcnt interrupt counters.
    189  */
    190 struct nlist intrnl[] =
    191 {
    192 #define	X_INTRNAMES	0
    193 	{ .n_name = "_intrnames" },
    194 #define	X_EINTRNAMES	1
    195 	{ .n_name = "_eintrnames" },
    196 #define	X_INTRCNT	2
    197 	{ .n_name = "_intrcnt" },
    198 #define	X_EINTRCNT	3
    199 	{ .n_name = "_eintrcnt" },
    200 #define	X_INTRNL_SIZE	4
    201 	{ .n_name = NULL },
    202 };
    203 
    204 
    205 /*
    206  * Namelist for hash statistics
    207  */
    208 struct nlist hashnl[] =
    209 {
    210 #define	X_NFSNODE	0
    211 	{ .n_name = "_nfsnodehash" },
    212 #define	X_NFSNODETBL	1
    213 	{ .n_name = "_nfsnodehashtbl" },
    214 #define	X_IHASH		2
    215 	{ .n_name = "_ihash" },
    216 #define	X_IHASHTBL	3
    217 	{ .n_name = "_ihashtbl" },
    218 #define	X_BUFHASH	4
    219 	{ .n_name = "_bufhash" },
    220 #define	X_BUFHASHTBL	5
    221 	{ .n_name = "_bufhashtbl" },
    222 #define	X_UIHASH	6
    223 	{ .n_name = "_uihash" },
    224 #define	X_UIHASHTBL	7
    225 	{ .n_name = "_uihashtbl" },
    226 #define	X_IFADDRHASH	8
    227 	{ .n_name = "_in_ifaddrhash" },
    228 #define	X_IFADDRHASHTBL	9
    229 	{ .n_name = "_in_ifaddrhashtbl" },
    230 #define	X_VCACHEHASH	10
    231 	{ .n_name = "_vcache_hashmask" },
    232 #define	X_VCACHETBL	11
    233 	{ .n_name = "_vcache_hashtab" },
    234 #define X_HASHNL_SIZE	12	/* must be last */
    235 	{ .n_name = NULL },
    236 };
    237 
    238 /*
    239  * Namelist for kernel histories
    240  */
    241 struct nlist histnl[] =
    242 {
    243 	{ .n_name = "_kern_histories" },
    244 #define	X_KERN_HISTORIES		0
    245 	{ .n_name = NULL },
    246 };
    247 
    248 
    249 #define KILO	1024
    250 
    251 struct cpu_counter {
    252 	uint64_t nintr;
    253 	uint64_t nsyscall;
    254 	uint64_t nswtch;
    255 	uint64_t nfault;
    256 	uint64_t ntrap;
    257 	uint64_t nsoft;
    258 } cpucounter, ocpucounter;
    259 
    260 struct	uvmexp_sysctl uvmexp, ouvmexp;
    261 int	ndrives;
    262 
    263 int	winlines = 20;
    264 
    265 kvm_t *kd;
    266 
    267 
    268 #define	FORKSTAT	0x001
    269 #define	INTRSTAT	0x002
    270 #define	MEMSTAT		0x004
    271 #define	SUMSTAT		0x008
    272 #define	EVCNTSTAT	0x010
    273 #define	VMSTAT		0x020
    274 #define	HISTLIST	0x040
    275 #define	HISTDUMP	0x080
    276 #define	HASHSTAT	0x100
    277 #define	HASHLIST	0x200
    278 #define	VMTOTAL		0x400
    279 #define	POOLCACHESTAT	0x800
    280 
    281 /*
    282  * Print single word.  `ovflow' is number of characters didn't fit
    283  * on the last word.  `fmt' is a format string to print this word.
    284  * It must contain asterisk for field width.  `width' is a width
    285  * occupied by this word.  `fixed' is a number of constant chars in
    286  * `fmt'.  `val' is a value to be printed using format string `fmt'.
    287  */
    288 #define	PRWORD(ovflw, fmt, width, fixed, val) do {	\
    289 	(ovflw) += printf((fmt),			\
    290 	    (width) - (fixed) - (ovflw) > 0 ?		\
    291 	    (width) - (fixed) - (ovflw) : 0,		\
    292 	    (val)) - (width);				\
    293 	if ((ovflw) < 0)				\
    294 		(ovflw) = 0;				\
    295 } while (/* CONSTCOND */0)
    296 
    297 void	cpustats(int *);
    298 void	cpucounters(struct cpu_counter *);
    299 void	deref_kptr(const void *, void *, size_t, const char *);
    300 void	drvstats(int *);
    301 void	doevcnt(int verbose, int type);
    302 void	dohashstat(int, int, const char *);
    303 void	dointr(int verbose);
    304 void	dopool(int, int);
    305 void	dopoolcache(int);
    306 void	dosum(void);
    307 void	dovmstat(struct timespec *, int);
    308 void	print_total_hdr(void);
    309 void	dovmtotal(struct timespec *, int);
    310 void	kread(struct nlist *, int, void *, size_t);
    311 int	kreadc(struct nlist *, int, void *, size_t);
    312 void	needhdr(int);
    313 void	getnlist(int);
    314 long	getuptime(void);
    315 void	printhdr(void);
    316 long	pct(u_long, u_long);
    317 __dead static void	usage(void);
    318 void	doforkst(void);
    319 
    320 void	hist_traverse(int, const char *);
    321 void	hist_dodump(struct kern_history *);
    322 void	hist_traverse_sysctl(int, const char *);
    323 void	hist_dodump_sysctl(int[], unsigned int);
    324 
    325 char	**choosedrives(char **);
    326 
    327 /* Namelist and memory file names. */
    328 char	*nlistf, *memf;
    329 
    330 /* allow old usage [vmstat 1] */
    331 #define	BACKWARD_COMPATIBILITY
    332 
    333 static const int clockrate_mib[] = { CTL_KERN, KERN_CLOCKRATE };
    334 static const int vmmeter_mib[] = { CTL_VM, VM_METER };
    335 static const int uvmexp2_mib[] = { CTL_VM, VM_UVMEXP2 };
    336 static const int boottime_mib[] = { CTL_KERN, KERN_BOOTTIME };
    337 static char kvm_errbuf[_POSIX2_LINE_MAX];
    338 
    339 int
    340 main(int argc, char *argv[])
    341 {
    342 	int c, todo, verbose, wide;
    343 	struct timespec interval;
    344 	int reps;
    345 	gid_t egid = getegid();
    346 	const char *histname, *hashname;
    347 
    348 	histname = hashname = NULL;
    349 	(void)setegid(getgid());
    350 	memf = nlistf = NULL;
    351 	reps = todo = verbose = wide = 0;
    352 	interval.tv_sec = 0;
    353 	interval.tv_nsec = 0;
    354 	while ((c = getopt(argc, argv, "Cc:efh:HilLM:mN:stu:UvWw:")) != -1) {
    355 		switch (c) {
    356 		case 'c':
    357 			reps = atoi(optarg);
    358 			break;
    359 		case 'C':
    360 			todo |= POOLCACHESTAT;
    361 			break;
    362 		case 'e':
    363 			todo |= EVCNTSTAT;
    364 			break;
    365 		case 'f':
    366 			todo |= FORKSTAT;
    367 			break;
    368 		case 'h':
    369 			hashname = optarg;
    370 			/* FALLTHROUGH */
    371 		case 'H':
    372 			todo |= HASHSTAT;
    373 			break;
    374 		case 'i':
    375 			todo |= INTRSTAT;
    376 			break;
    377 		case 'l':
    378 			todo |= HISTLIST;
    379 			break;
    380 		case 'L':
    381 			todo |= HASHLIST;
    382 			break;
    383 		case 'M':
    384 			memf = optarg;
    385 			break;
    386 		case 'm':
    387 			todo |= MEMSTAT;
    388 			break;
    389 		case 'N':
    390 			nlistf = optarg;
    391 			break;
    392 		case 's':
    393 			todo |= SUMSTAT;
    394 			break;
    395 		case 't':
    396 			todo |= VMTOTAL;
    397 			break;
    398 		case 'u':
    399 			histname = optarg;
    400 			/* FALLTHROUGH */
    401 		case 'U':
    402 			todo |= HISTDUMP;
    403 			break;
    404 		case 'v':
    405 			verbose++;
    406 			break;
    407 		case 'W':
    408 			wide++;
    409 			break;
    410 		case 'w':
    411 			interval.tv_sec = atol(optarg);
    412 			break;
    413 		case '?':
    414 		default:
    415 			usage();
    416 		}
    417 	}
    418 	argc -= optind;
    419 	argv += optind;
    420 
    421 	if (todo == 0)
    422 		todo = VMSTAT;
    423 
    424 	/*
    425 	 * Discard setgid privileges.  If not the running kernel, we toss
    426 	 * them away totally so that bad guys can't print interesting stuff
    427 	 * from kernel memory, otherwise switch back to kmem for the
    428 	 * duration of the kvm_openfiles() call.
    429 	 */
    430 	if (nlistf != NULL || memf != NULL)
    431 		(void)setgid(getgid());
    432 	else
    433 		(void)setegid(egid);
    434 
    435 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, kvm_errbuf);
    436 	if (kd == NULL) {
    437 		if (nlistf != NULL || memf != NULL) {
    438 			errx(1, "kvm_openfiles: %s", kvm_errbuf);
    439 		}
    440 	}
    441 
    442 	if (nlistf == NULL && memf == NULL)
    443 		(void)setgid(getgid());
    444 
    445 
    446 	if (todo & VMSTAT) {
    447 		struct winsize winsize;
    448 
    449 		(void)drvinit(0);/* Initialize disk stats, no disks selected. */
    450 
    451 		(void)setgid(getgid()); /* don't need privs anymore */
    452 
    453 		argv = choosedrives(argv);	/* Select disks. */
    454 		winsize.ws_row = 0;
    455 		(void)ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
    456 		if (winsize.ws_row > 0)
    457 			winlines = winsize.ws_row;
    458 
    459 	}
    460 
    461 #ifdef	BACKWARD_COMPATIBILITY
    462 	if (*argv) {
    463 		interval.tv_sec = atol(*argv);
    464 		if (*++argv)
    465 			reps = atoi(*argv);
    466 	}
    467 #endif
    468 
    469 	if (interval.tv_sec) {
    470 		if (!reps)
    471 			reps = -1;
    472 	} else if (reps)
    473 		interval.tv_sec = 1;
    474 
    475 
    476 	getnlist(todo);
    477 	/*
    478 	 * Statistics dumping is incompatible with the default
    479 	 * VMSTAT/dovmstat() output. So perform the interval/reps handling
    480 	 * for it here.
    481 	 */
    482 	if ((todo & (VMSTAT|VMTOTAL)) == 0) {
    483 		for (;;) {
    484 			if (todo & (HISTLIST|HISTDUMP)) {
    485 				if ((todo & (HISTLIST|HISTDUMP)) ==
    486 				    (HISTLIST|HISTDUMP))
    487 					errx(1, "you may list or dump,"
    488 					    " but not both!");
    489 				if (memf != NULL)
    490 					hist_traverse(todo, histname);
    491 				else
    492 					hist_traverse_sysctl(todo, histname);
    493 				(void)putchar('\n');
    494 			}
    495 			if (todo & FORKSTAT) {
    496 				doforkst();
    497 				(void)putchar('\n');
    498 			}
    499 			if (todo & MEMSTAT) {
    500 				dopool(verbose, wide);
    501 				(void)putchar('\n');
    502 			}
    503 			if (todo & POOLCACHESTAT) {
    504 				dopoolcache(verbose);
    505 				(void)putchar('\n');
    506 			}
    507 			if (todo & SUMSTAT) {
    508 				dosum();
    509 				(void)putchar('\n');
    510 			}
    511 			if (todo & INTRSTAT) {
    512 				dointr(verbose);
    513 				(void)putchar('\n');
    514 			}
    515 			if (todo & EVCNTSTAT) {
    516 				doevcnt(verbose, EVCNT_TYPE_ANY);
    517 				(void)putchar('\n');
    518 			}
    519 			if (todo & (HASHLIST|HASHSTAT)) {
    520 				if ((todo & (HASHLIST|HASHSTAT)) ==
    521 				    (HASHLIST|HASHSTAT))
    522 					errx(1, "you may list or display,"
    523 					    " but not both!");
    524 				dohashstat(verbose, todo, hashname);
    525 				(void)putchar('\n');
    526 			}
    527 
    528 			fflush(stdout);
    529 			if (reps >= 0 && --reps <=0)
    530 				break;
    531 			(void)nanosleep(&interval, NULL);
    532 		}
    533 	} else {
    534 		if ((todo & (VMSTAT|VMTOTAL)) == (VMSTAT|VMTOTAL)) {
    535 			errx(1, "you may not both do vmstat and vmtotal");
    536 		}
    537 		if (todo & VMSTAT)
    538 			dovmstat(&interval, reps);
    539 		if (todo & VMTOTAL)
    540 			dovmtotal(&interval, reps);
    541 	}
    542 	return 0;
    543 }
    544 
    545 void
    546 getnlist(int todo)
    547 {
    548 	static int namelist_done = 0;
    549 	static int done = 0;
    550 	int c;
    551 	size_t i;
    552 
    553 	if (kd == NULL)
    554 		errx(1, "kvm_openfiles: %s", kvm_errbuf);
    555 
    556 	if (!namelist_done) {
    557 		namelist_done = 1;
    558 		if ((c = kvm_nlist(kd, namelist)) != 0) {
    559 			int doexit = 0;
    560 			if (c == -1)
    561 				errx(1, "kvm_nlist: %s %s",
    562 				    "namelist", kvm_geterr(kd));
    563 			for (i = 0; i < __arraycount(namelist)-1; i++)
    564 				if (namelist[i].n_type == 0) {
    565 					if (doexit++ == 0)
    566 						(void)fprintf(stderr,
    567 						    "%s: undefined symbols:",
    568 						    getprogname());
    569 					(void)fprintf(stderr, " %s",
    570 					    namelist[i].n_name);
    571 				}
    572 			if (doexit) {
    573 				(void)fputc('\n', stderr);
    574 				exit(1);
    575 			}
    576 		}
    577 	}
    578 	if ((todo & (VMSTAT|INTRSTAT)) && !(done & (VMSTAT))) {
    579 		done |= VMSTAT;
    580 		if ((c = kvm_nlist(kd, timenl)) == -1 || c == X_TIMENL_SIZE)
    581 			errx(1, "kvm_nlist: %s %s", "timenl", kvm_geterr(kd));
    582 	}
    583 	if ((todo & (SUMSTAT|INTRSTAT)) && !(done & (SUMSTAT|INTRSTAT))) {
    584 		done |= SUMSTAT|INTRSTAT;
    585 		(void) kvm_nlist(kd, intrnl);
    586 	}
    587 	if ((todo & (HASHLIST|HASHSTAT)) && !(done & (HASHLIST|HASHSTAT))) {
    588 		done |= HASHLIST|HASHSTAT;
    589 		if ((c = kvm_nlist(kd, hashnl)) == -1 || c == X_HASHNL_SIZE)
    590 			errx(1, "kvm_nlist: %s %s", "hashnl", kvm_geterr(kd));
    591 	}
    592 	if ((todo & (HISTLIST|HISTDUMP)) && !(done & (HISTLIST|HISTDUMP))) {
    593 		done |= HISTLIST|HISTDUMP;
    594 		if (kvm_nlist(kd, histnl) == -1)
    595 			errx(1, "kvm_nlist: %s %s", "histnl", kvm_geterr(kd));
    596 	}
    597 }
    598 
    599 char **
    600 choosedrives(char **argv)
    601 {
    602 	size_t i;
    603 
    604 	/*
    605 	 * Choose drives to be displayed.  Priority goes to (in order) drives
    606 	 * supplied as arguments, default drives.  If everything isn't filled
    607 	 * in and there are drives not taken care of, display the first few
    608 	 * that fit.
    609 	 */
    610 #define	BACKWARD_COMPATIBILITY
    611 	for (ndrives = 0; *argv; ++argv) {
    612 #ifdef	BACKWARD_COMPATIBILITY
    613 		if (isdigit((unsigned char)**argv))
    614 			break;
    615 #endif
    616 		for (i = 0; i < ndrive; i++) {
    617 			if (strcmp(dr_name[i], *argv))
    618 				continue;
    619 			drv_select[i] = 1;
    620 			++ndrives;
    621 			break;
    622 		}
    623 	}
    624 	for (i = 0; i < ndrive && ndrives < 2; i++) {
    625 		if (drv_select[i])
    626 			continue;
    627 		drv_select[i] = 1;
    628 		++ndrives;
    629 	}
    630 
    631 	return (argv);
    632 }
    633 
    634 long
    635 getuptime(void)
    636 {
    637 	static struct timespec boottime;
    638 	struct timespec now;
    639 	time_t uptime, nowsec;
    640 
    641 	if (memf == NULL) {
    642 		if (boottime.tv_sec == 0) {
    643 			size_t buflen = sizeof(boottime);
    644 			if (sysctl(boottime_mib, __arraycount(boottime_mib),
    645 			    &boottime, &buflen, NULL, 0) == -1)
    646 				warn("Can't get boottime");
    647 		}
    648 		clock_gettime(CLOCK_REALTIME, &now);
    649 	} else {
    650 		if (boottime.tv_sec == 0) {
    651 			struct bintime bt;
    652 
    653 			kread(timenl, X_TIMEBASEBIN, &bt, sizeof(bt));
    654 			bintime2timespec(&bt, &boottime);
    655 		}
    656 		if (kreadc(timenl, X_TIME_SECOND, &nowsec, sizeof(nowsec))) {
    657 			/*
    658 			 * XXX this assignment dance can be removed once
    659 			 * timeval tv_sec is SUS mandated time_t
    660 			 */
    661 			now.tv_sec = nowsec;
    662 			now.tv_nsec = 0;
    663 		} else {
    664 			kread(timenl, X_TIME, &now, sizeof(now));
    665 		}
    666 	}
    667 	uptime = now.tv_sec - boottime.tv_sec;
    668 	if (uptime <= 0 || uptime > 60*60*24*365*10)
    669 		errx(1, "time makes no sense; namelist must be wrong.");
    670 	return (uptime);
    671 }
    672 
    673 int	hz, hdrcnt;
    674 
    675 void
    676 print_total_hdr(void)
    677 {
    678 
    679 	(void)printf("procs         memory\n");
    680 	(void)printf("ru dw pw sl");
    681 	(void)printf("   total-v  active-v  active-r");
    682 	(void)printf(" vm-sh avm-sh rm-sh arm-sh free\n");
    683 	hdrcnt = winlines - 2;
    684 }
    685 
    686 void
    687 dovmtotal(struct timespec *interval, int reps)
    688 {
    689 	struct vmtotal total;
    690 	size_t size;
    691 
    692 	(void)signal(SIGCONT, needhdr);
    693 
    694 	for (hdrcnt = 1;;) {
    695 		if (!--hdrcnt)
    696 			print_total_hdr();
    697 		if (memf != NULL) {
    698 			warnx("Unable to get vmtotals from crash dump.");
    699 			(void)memset(&total, 0, sizeof(total));
    700 		} else {
    701 			size = sizeof(total);
    702 			if (sysctl(vmmeter_mib, __arraycount(vmmeter_mib),
    703 			    &total, &size, NULL, 0) == -1) {
    704 				warn("Can't get vmtotals");
    705 				(void)memset(&total, 0, sizeof(total));
    706 			}
    707 		}
    708 		(void)printf("%2d ", total.t_rq);
    709 		(void)printf("%2d ", total.t_dw);
    710 		(void)printf("%2d ", total.t_pw);
    711 		(void)printf("%2d ", total.t_sl);
    712 
    713 		(void)printf("%9d ", total.t_vm);
    714 		(void)printf("%9d ", total.t_avm);
    715 		(void)printf("%9d ", total.t_arm);
    716 		(void)printf("%5d ", total.t_vmshr);
    717 		(void)printf("%6d ", total.t_avmshr);
    718 		(void)printf("%5d ", total.t_rmshr);
    719 		(void)printf("%6d ", total.t_armshr);
    720 		(void)printf("%5d",  total.t_free);
    721 
    722 		(void)putchar('\n');
    723 
    724 		(void)fflush(stdout);
    725 		if (reps >= 0 && --reps <= 0)
    726 			break;
    727 
    728 		(void)nanosleep(interval, NULL);
    729 	}
    730 }
    731 
    732 void
    733 dovmstat(struct timespec *interval, int reps)
    734 {
    735 	struct vmtotal total;
    736 	time_t uptime, halfuptime;
    737 	size_t size;
    738 	int pagesize = getpagesize();
    739 	int ovflw;
    740 
    741 	uptime = getuptime();
    742 	halfuptime = uptime / 2;
    743 	(void)signal(SIGCONT, needhdr);
    744 
    745 	if (memf != NULL) {
    746 		if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
    747 			kread(namelist, X_STATHZ, &hz, sizeof(hz));
    748 		if (!hz)
    749 			kread(namelist, X_HZ, &hz, sizeof(hz));
    750 	} else {
    751 		struct clockinfo clockinfo;
    752 		size = sizeof(clockinfo);
    753 		if (sysctl(clockrate_mib, 2, &clockinfo, &size, NULL, 0) == -1)
    754 			err(1, "sysctl kern.clockrate failed");
    755 		hz = clockinfo.stathz;
    756 		if (!hz)
    757 			hz = clockinfo.hz;
    758 	}
    759 
    760 	for (hdrcnt = 1;;) {
    761 		if (!--hdrcnt)
    762 			printhdr();
    763 		/* Read new disk statistics */
    764 		cpureadstats();
    765 		drvreadstats();
    766 		tkreadstats();
    767 		if (memf != NULL) {
    768 			struct uvmexp uvmexp_kernel;
    769 			/*
    770 			 * XXX Can't do this if we're reading a crash
    771 			 * XXX dump because they're lazily-calculated.
    772 			 */
    773 			warnx("Unable to get vmtotals from crash dump.");
    774 			(void)memset(&total, 0, sizeof(total));
    775 			kread(namelist, X_UVMEXP, &uvmexp_kernel, sizeof(uvmexp_kernel));
    776 #define COPY(field) uvmexp.field = uvmexp_kernel.field
    777 			COPY(pdreact);
    778 			COPY(pageins);
    779 			COPY(pgswapout);
    780 			COPY(pdfreed);
    781 			COPY(pdscans);
    782 #undef COPY
    783 		} else {
    784 			size = sizeof(total);
    785 			if (sysctl(vmmeter_mib, __arraycount(vmmeter_mib),
    786 			    &total, &size, NULL, 0) == -1) {
    787 				warn("Can't get vmtotals");
    788 				(void)memset(&total, 0, sizeof(total));
    789 			}
    790 			size = sizeof(uvmexp);
    791 			if (sysctl(uvmexp2_mib, __arraycount(uvmexp2_mib), &uvmexp,
    792 			    &size, NULL, 0) == -1)
    793 				warn("sysctl vm.uvmexp2 failed");
    794 		}
    795 		cpucounters(&cpucounter);
    796 		ovflw = 0;
    797 		PRWORD(ovflw, " %*d", 2, 1, total.t_rq - 1);
    798 		PRWORD(ovflw, " %*d", 2, 1, total.t_dw + total.t_pw);
    799 #define	pgtok(a) (long)((a) * ((uint32_t)pagesize >> 10))
    800 #define	rate(x)	(u_long)(((x) + halfuptime) / uptime)	/* round */
    801 		PRWORD(ovflw, " %*ld", 9, 1, pgtok(total.t_avm));
    802 		PRWORD(ovflw, " %*ld", 7, 1, pgtok(total.t_free));
    803 		PRWORD(ovflw, " %*ld", 5, 1,
    804 		    rate(cpucounter.nfault - ocpucounter.nfault));
    805 		PRWORD(ovflw, " %*ld", 4, 1,
    806 		    rate(uvmexp.pdreact - ouvmexp.pdreact));
    807 		PRWORD(ovflw, " %*ld", 4, 1,
    808 		    rate(uvmexp.pageins - ouvmexp.pageins));
    809 		PRWORD(ovflw, " %*ld", 5, 1,
    810 		    rate(uvmexp.pgswapout - ouvmexp.pgswapout));
    811 		PRWORD(ovflw, " %*ld", 5, 1,
    812 		    rate(uvmexp.pdfreed - ouvmexp.pdfreed));
    813 		PRWORD(ovflw, " %*ld", 6, 2,
    814 		    rate(uvmexp.pdscans - ouvmexp.pdscans));
    815 		drvstats(&ovflw);
    816 		PRWORD(ovflw, " %*ld", 5, 1,
    817 		    rate(cpucounter.nintr - ocpucounter.nintr));
    818 		PRWORD(ovflw, " %*ld", 5, 1,
    819 		    rate(cpucounter.nsyscall - ocpucounter.nsyscall));
    820 		PRWORD(ovflw, " %*ld", 4, 1,
    821 		    rate(cpucounter.nswtch - ocpucounter.nswtch));
    822 		cpustats(&ovflw);
    823 		(void)putchar('\n');
    824 		(void)fflush(stdout);
    825 		if (reps >= 0 && --reps <= 0)
    826 			break;
    827 		ouvmexp = uvmexp;
    828 		ocpucounter = cpucounter;
    829 		uptime = interval->tv_sec;
    830 		/*
    831 		 * We round upward to avoid losing low-frequency events
    832 		 * (i.e., >= 1 per interval but < 1 per second).
    833 		 */
    834 		halfuptime = uptime == 1 ? 0 : (uptime + 1) / 2;
    835 		(void)nanosleep(interval, NULL);
    836 	}
    837 }
    838 
    839 void
    840 printhdr(void)
    841 {
    842 	size_t i;
    843 
    844 	(void)printf(" procs    memory      page%*s", 23, "");
    845 	if (ndrives > 0)
    846 		(void)printf("%s %*sfaults      cpu\n",
    847 		    ((ndrives > 1) ? "disks" : "disk"),
    848 		    ((ndrives > 1) ? ndrives * 3 - 4 : 0), "");
    849 	else
    850 		(void)printf("%*s  faults   cpu\n",
    851 		    ndrives * 3, "");
    852 
    853 	(void)printf(" r b      avm    fre  flt  re  pi   po   fr   sr ");
    854 	for (i = 0; i < ndrive; i++)
    855 		if (drv_select[i])
    856 			(void)printf("%c%c ", dr_name[i][0],
    857 			    dr_name[i][strlen(dr_name[i]) - 1]);
    858 	(void)printf("  in   sy  cs us sy id\n");
    859 	hdrcnt = winlines - 2;
    860 }
    861 
    862 /*
    863  * Force a header to be prepended to the next output.
    864  */
    865 void
    866 /*ARGSUSED*/
    867 needhdr(int dummy)
    868 {
    869 
    870 	hdrcnt = 1;
    871 }
    872 
    873 long
    874 pct(u_long top, u_long bot)
    875 {
    876 	long ans;
    877 
    878 	if (bot == 0)
    879 		return (0);
    880 	ans = (long)((quad_t)top * 100 / bot);
    881 	return (ans);
    882 }
    883 
    884 #define	PCT(top, bot) (int)pct((u_long)(top), (u_long)(bot))
    885 
    886 void
    887 dosum(void)
    888 {
    889 	struct nchstats nch_stats;
    890 	uint64_t nchtotal;
    891 	size_t ssize;
    892 	int active_kernel;
    893 	struct cpu_counter cc;
    894 
    895 	/*
    896 	 * The "active" and "inactive" variables
    897 	 * are now estimated by the kernel and sadly
    898 	 * can not easily be dug out of a crash dump.
    899 	 */
    900 	ssize = sizeof(uvmexp);
    901 	memset(&uvmexp, 0, ssize);
    902 	active_kernel = (memf == NULL);
    903 	if (active_kernel) {
    904 		/* only on active kernel */
    905 		if (sysctl(uvmexp2_mib, __arraycount(uvmexp2_mib), &uvmexp,
    906 		    &ssize, NULL, 0) == -1)
    907 			warn("sysctl vm.uvmexp2 failed");
    908 	} else {
    909 		struct uvmexp uvmexp_kernel;
    910 		struct pool pool, *pp = &pool;
    911 		struct pool_allocator pa;
    912 		TAILQ_HEAD(,pool) pool_head;
    913 		void *addr;
    914 		uint64_t bytes;
    915 
    916 		kread(namelist, X_UVMEXP, &uvmexp_kernel, sizeof(uvmexp_kernel));
    917 #define COPY(field) uvmexp.field = uvmexp_kernel.field
    918 		COPY(pagesize);
    919 		COPY(ncolors);
    920 		COPY(npages);
    921 		COPY(free);
    922 		COPY(paging);
    923 		COPY(wired);
    924 		COPY(zeropages);
    925 		COPY(reserve_pagedaemon);
    926 		COPY(reserve_kernel);
    927 		COPY(anonpages);
    928 		COPY(filepages);
    929 		COPY(execpages);
    930 		COPY(freemin);
    931 		COPY(freetarg);
    932 		COPY(wiredmax);
    933 		COPY(nswapdev);
    934 		COPY(swpages);
    935 		COPY(swpginuse);
    936 		COPY(nswget);
    937 		COPY(pageins);
    938 		COPY(pdpageouts);
    939 		COPY(pgswapin);
    940 		COPY(pgswapout);
    941 		COPY(forks);
    942 		COPY(forks_ppwait);
    943 		COPY(forks_sharevm);
    944 		COPY(pga_zerohit);
    945 		COPY(pga_zeromiss);
    946 		COPY(zeroaborts);
    947 		COPY(colorhit);
    948 		COPY(colormiss);
    949 		COPY(cpuhit);
    950 		COPY(cpumiss);
    951 		COPY(fltnoram);
    952 		COPY(fltnoanon);
    953 		COPY(fltpgwait);
    954 		COPY(fltpgrele);
    955 		COPY(fltrelck);
    956 		COPY(fltrelckok);
    957 		COPY(fltanget);
    958 		COPY(fltanretry);
    959 		COPY(fltamcopy);
    960 		COPY(fltamcopy);
    961 		COPY(fltnomap);
    962 		COPY(fltlget);
    963 		COPY(fltget);
    964 		COPY(flt_anon);
    965 		COPY(flt_acow);
    966 		COPY(flt_obj);
    967 		COPY(flt_prcopy);
    968 		COPY(flt_przero);
    969 		COPY(pdwoke);
    970 		COPY(pdrevs);
    971 		COPY(pdfreed);
    972 		COPY(pdscans);
    973 		COPY(pdanscan);
    974 		COPY(pdobscan);
    975 		COPY(pdreact);
    976 		COPY(pdbusy);
    977 		COPY(pdpending);
    978 		COPY(pddeact);
    979 		COPY(bootpages);
    980 #undef COPY
    981 		kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
    982 		addr = TAILQ_FIRST(&pool_head);
    983 		uvmexp.poolpages = 0;
    984 		for (; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist)) {
    985 			deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
    986 			deref_kptr(pp->pr_alloc, &pa, sizeof(pa),
    987 			    "pool allocator trashed");
    988 			bytes = pp->pr_npages * pa.pa_pagesz;
    989 			if ((pp->pr_roflags & PR_RECURSIVE) != 0)
    990 				bytes -= (pp->pr_nout * pp->pr_size);
    991 			uvmexp.poolpages += bytes / uvmexp.pagesize;
    992 		}
    993 	}
    994 
    995 
    996 	(void)printf("%9" PRIu64 " bytes per page\n", uvmexp.pagesize);
    997 
    998 	(void)printf("%9" PRIu64 " page color%s\n",
    999 	    uvmexp.ncolors, uvmexp.ncolors == 1 ? "" : "s");
   1000 
   1001 	(void)printf("%9" PRIu64 " pages managed\n", uvmexp.npages);
   1002 	(void)printf("%9" PRIu64 " pages free\n", uvmexp.free);
   1003 	if (active_kernel) {
   1004 		(void)printf("%9" PRIu64 " pages active\n", uvmexp.active);
   1005 		(void)printf("%9" PRIu64 " pages inactive\n", uvmexp.inactive);
   1006 	}
   1007 	(void)printf("%9" PRIu64 " pages paging\n", uvmexp.paging);
   1008 	(void)printf("%9" PRIu64 " pages wired\n", uvmexp.wired);
   1009 	(void)printf("%9" PRIu64 " zero pages\n", uvmexp.zeropages);
   1010 	(void)printf("%9" PRIu64 " reserve pagedaemon pages\n",
   1011 	    uvmexp.reserve_pagedaemon);
   1012 	(void)printf("%9" PRIu64 " reserve kernel pages\n", uvmexp.reserve_kernel);
   1013 	(void)printf("%9" PRIu64 " boot kernel pages\n", uvmexp.bootpages);
   1014 	(void)printf("%9" PRIu64 " kernel pool pages\n", uvmexp.poolpages);
   1015 	(void)printf("%9" PRIu64 " anonymous pages\n", uvmexp.anonpages);
   1016 	(void)printf("%9" PRIu64 " cached file pages\n", uvmexp.filepages);
   1017 	(void)printf("%9" PRIu64 " cached executable pages\n", uvmexp.execpages);
   1018 
   1019 	(void)printf("%9" PRIu64 " minimum free pages\n", uvmexp.freemin);
   1020 	(void)printf("%9" PRIu64 " target free pages\n", uvmexp.freetarg);
   1021 	(void)printf("%9" PRIu64 " maximum wired pages\n", uvmexp.wiredmax);
   1022 
   1023 	(void)printf("%9" PRIu64 " swap devices\n", uvmexp.nswapdev);
   1024 	(void)printf("%9" PRIu64 " swap pages\n", uvmexp.swpages);
   1025 	(void)printf("%9" PRIu64 " swap pages in use\n", uvmexp.swpginuse);
   1026 	(void)printf("%9" PRIu64 " swap allocations\n", uvmexp.nswget);
   1027 
   1028 	cpucounters(&cc);
   1029 
   1030 	(void)printf("%9" PRIu64 " total faults taken\n", cc.nfault);
   1031 	(void)printf("%9" PRIu64 " traps\n", cc.ntrap);
   1032 	(void)printf("%9" PRIu64 " device interrupts\n", cc.nintr);
   1033 	(void)printf("%9" PRIu64 " CPU context switches\n", cc.nswtch);
   1034 	(void)printf("%9" PRIu64 " software interrupts\n", cc.nsoft);
   1035 	(void)printf("%9" PRIu64 " system calls\n", cc.nsyscall);
   1036 	(void)printf("%9" PRIu64 " pagein requests\n", uvmexp.pageins);
   1037 	(void)printf("%9" PRIu64 " pageout requests\n", uvmexp.pdpageouts);
   1038 	(void)printf("%9" PRIu64 " pages swapped in\n", uvmexp.pgswapin);
   1039 	(void)printf("%9" PRIu64 " pages swapped out\n", uvmexp.pgswapout);
   1040 	(void)printf("%9" PRIu64 " forks total\n", uvmexp.forks);
   1041 	(void)printf("%9" PRIu64 " forks blocked parent\n", uvmexp.forks_ppwait);
   1042 	(void)printf("%9" PRIu64 " forks shared address space with parent\n",
   1043 	    uvmexp.forks_sharevm);
   1044 	(void)printf("%9" PRIu64 " pagealloc zero wanted and avail\n",
   1045 	    uvmexp.pga_zerohit);
   1046 	(void)printf("%9" PRIu64 " pagealloc zero wanted and not avail\n",
   1047 	    uvmexp.pga_zeromiss);
   1048 	(void)printf("%9" PRIu64 " aborts of idle page zeroing\n",
   1049 	    uvmexp.zeroaborts);
   1050 	(void)printf("%9" PRIu64 " pagealloc desired color avail\n",
   1051 	    uvmexp.colorhit);
   1052 	(void)printf("%9" PRIu64 " pagealloc desired color not avail\n",
   1053 	    uvmexp.colormiss);
   1054 	(void)printf("%9" PRIu64 " pagealloc local cpu avail\n",
   1055 	    uvmexp.cpuhit);
   1056 	(void)printf("%9" PRIu64 " pagealloc local cpu not avail\n",
   1057 	    uvmexp.cpumiss);
   1058 
   1059 	(void)printf("%9" PRIu64 " faults with no memory\n", uvmexp.fltnoram);
   1060 	(void)printf("%9" PRIu64 " faults with no anons\n", uvmexp.fltnoanon);
   1061 	(void)printf("%9" PRIu64 " faults had to wait on pages\n", uvmexp.fltpgwait);
   1062 	(void)printf("%9" PRIu64 " faults found released page\n", uvmexp.fltpgrele);
   1063 	(void)printf("%9" PRIu64 " faults relock (%" PRIu64 " ok)\n", uvmexp.fltrelck,
   1064 	    uvmexp.fltrelckok);
   1065 	(void)printf("%9" PRIu64 " anon page faults\n", uvmexp.fltanget);
   1066 	(void)printf("%9" PRIu64 " anon retry faults\n", uvmexp.fltanretry);
   1067 	(void)printf("%9" PRIu64 " amap copy faults\n", uvmexp.fltamcopy);
   1068 	(void)printf("%9" PRIu64 " neighbour anon page faults\n", uvmexp.fltnamap);
   1069 	(void)printf("%9" PRIu64 " neighbour object page faults\n", uvmexp.fltnomap);
   1070 	(void)printf("%9" PRIu64 " locked pager get faults\n", uvmexp.fltlget);
   1071 	(void)printf("%9" PRIu64 " unlocked pager get faults\n", uvmexp.fltget);
   1072 	(void)printf("%9" PRIu64 " anon faults\n", uvmexp.flt_anon);
   1073 	(void)printf("%9" PRIu64 " anon copy on write faults\n", uvmexp.flt_acow);
   1074 	(void)printf("%9" PRIu64 " object faults\n", uvmexp.flt_obj);
   1075 	(void)printf("%9" PRIu64 " promote copy faults\n", uvmexp.flt_prcopy);
   1076 	(void)printf("%9" PRIu64 " promote zero fill faults\n", uvmexp.flt_przero);
   1077 
   1078 	(void)printf("%9" PRIu64 " times daemon wokeup\n",uvmexp.pdwoke);
   1079 	(void)printf("%9" PRIu64 " revolutions of the clock hand\n", uvmexp.pdrevs);
   1080 	(void)printf("%9" PRIu64 " pages freed by daemon\n", uvmexp.pdfreed);
   1081 	(void)printf("%9" PRIu64 " pages scanned by daemon\n", uvmexp.pdscans);
   1082 	(void)printf("%9" PRIu64 " anonymous pages scanned by daemon\n",
   1083 	    uvmexp.pdanscan);
   1084 	(void)printf("%9" PRIu64 " object pages scanned by daemon\n", uvmexp.pdobscan);
   1085 	(void)printf("%9" PRIu64 " pages reactivated\n", uvmexp.pdreact);
   1086 	(void)printf("%9" PRIu64 " pages found busy by daemon\n", uvmexp.pdbusy);
   1087 	(void)printf("%9" PRIu64 " total pending pageouts\n", uvmexp.pdpending);
   1088 	(void)printf("%9" PRIu64 " pages deactivated\n", uvmexp.pddeact);
   1089 	(void)printf("%9" PRIu64 " per-cpu stats one synced\n", uvmexp.countsyncone);
   1090 	(void)printf("%9" PRIu64 " per-cpu stats all synced\n", uvmexp.countsyncall);
   1091 	(void)printf("%9" PRIu64 " anon pages possibly dirty\n", uvmexp.anonunknown);
   1092 	(void)printf("%9" PRIu64 " anon pages dirty\n", uvmexp.anondirty);
   1093 	(void)printf("%9" PRIu64 " anon pages clean\n", uvmexp.anonclean);
   1094 	(void)printf("%9" PRIu64 " file pages possibly dirty\n", uvmexp.fileunknown);
   1095 	(void)printf("%9" PRIu64 " file pages dirty\n", uvmexp.filedirty);
   1096 	(void)printf("%9" PRIu64 " file pages clean\n", uvmexp.fileclean);
   1097 
   1098 	if (active_kernel) {
   1099 		ssize = sizeof(nch_stats);
   1100 		if (sysctlbyname("vfs.namecache_stats", &nch_stats, &ssize,
   1101 		    NULL, 0)) {
   1102 			warn("vfs.namecache_stats failed");
   1103 			memset(&nch_stats, 0, sizeof(nch_stats));
   1104 		}
   1105 	} else {
   1106 		kread(namelist, X_NCHSTATS, &nch_stats, sizeof(nch_stats));
   1107 	}
   1108 
   1109 	nchtotal = nch_stats.ncs_goodhits + nch_stats.ncs_neghits +
   1110 	    nch_stats.ncs_badhits + nch_stats.ncs_falsehits +
   1111 	    nch_stats.ncs_miss + nch_stats.ncs_long;
   1112 	(void)printf("%9" PRIu64 " total name lookups\n", nchtotal);
   1113 	(void)printf("%9" PRIu64 " good hits\n", nch_stats.ncs_goodhits);
   1114 	(void)printf("%9" PRIu64 " negative hits\n", nch_stats.ncs_neghits);
   1115 	(void)printf("%9" PRIu64 " bad hits\n", nch_stats.ncs_badhits);
   1116 	(void)printf("%9" PRIu64 " false hits\n", nch_stats.ncs_falsehits);
   1117 	(void)printf("%9" PRIu64 " miss\n", nch_stats.ncs_miss);
   1118 	(void)printf("%9" PRIu64 " too long\n", nch_stats.ncs_long);
   1119 	(void)printf("%9" PRIu64 " pass2 hits\n", nch_stats.ncs_pass2);
   1120 	(void)printf("%9" PRIu64 " 2passes\n", nch_stats.ncs_2passes);
   1121 	(void)printf("%9" PRIu64 " reverse hits\n", nch_stats.ncs_revhits);
   1122 	(void)printf("%9" PRIu64 " reverse miss\n", nch_stats.ncs_revmiss);
   1123 	(void)printf("%9" PRIu64 " hash collisions\n", nch_stats.ncs_collisions);
   1124 	(void)printf("%9" PRIu64 " access denied\n", nch_stats.ncs_denied);
   1125 	(void)printf(
   1126 	    "%9s cache hits (%d%% pos + %d%% neg) system %d%% per-process\n",
   1127 	    "", PCT(nch_stats.ncs_goodhits, nchtotal),
   1128 	    PCT(nch_stats.ncs_neghits, nchtotal),
   1129 	    PCT(nch_stats.ncs_pass2, nchtotal));
   1130 	(void)printf("%9s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
   1131 	    PCT(nch_stats.ncs_badhits, nchtotal),
   1132 	    PCT(nch_stats.ncs_falsehits, nchtotal),
   1133 	    PCT(nch_stats.ncs_long, nchtotal));
   1134 }
   1135 
   1136 void
   1137 doforkst(void)
   1138 {
   1139 	if (memf != NULL) {
   1140 		struct uvmexp uvmexp_kernel;
   1141 		kread(namelist, X_UVMEXP, &uvmexp_kernel, sizeof(uvmexp_kernel));
   1142 #define COPY(field) uvmexp.field = uvmexp_kernel.field
   1143 		COPY(forks);
   1144 		COPY(forks_ppwait);
   1145 		COPY(forks_sharevm);
   1146 #undef COPY
   1147 	} else {
   1148 		size_t size = sizeof(uvmexp);
   1149 		if (sysctl(uvmexp2_mib, __arraycount(uvmexp2_mib), &uvmexp,
   1150 		    &size, NULL, 0) == -1)
   1151 			warn("sysctl vm.uvmexp2 failed");
   1152 	}
   1153 
   1154 	(void)printf("%" PRIu64 " forks total\n", uvmexp.forks);
   1155 	(void)printf("%" PRIu64 " forks blocked parent\n", uvmexp.forks_ppwait);
   1156 	(void)printf("%" PRIu64 " forks shared address space with parent\n",
   1157 	    uvmexp.forks_sharevm);
   1158 }
   1159 
   1160 void
   1161 drvstats(int *ovflwp)
   1162 {
   1163 	size_t dn;
   1164 	double dtime;
   1165 	int ovflw = *ovflwp;
   1166 
   1167 	/* Calculate disk stat deltas. */
   1168 	cpuswap();
   1169 	drvswap();
   1170 	tkswap();
   1171 
   1172 	for (dn = 0; dn < ndrive; ++dn) {
   1173 		/* elapsed time for disk stats */
   1174 		dtime = cur.cp_etime;
   1175 		if (cur.timestamp[dn].tv_sec || cur.timestamp[dn].tv_usec) {
   1176 			dtime = (double)cur.timestamp[dn].tv_sec +
   1177 				((double)cur.timestamp[dn].tv_usec / (double)1000000);
   1178 		}
   1179 
   1180 		if (!drv_select[dn])
   1181 	 		continue;
   1182 		PRWORD(ovflw, " %*.0f", 3, 1,
   1183 		    (cur.rxfer[dn] + cur.wxfer[dn]) / dtime);
   1184 	}
   1185 	*ovflwp = ovflw;
   1186 }
   1187 
   1188 void
   1189 cpucounters(struct cpu_counter *cc)
   1190 {
   1191 	static struct cpu_info **cpu_infos;
   1192 	static int initialised;
   1193 	struct cpu_info **slot;
   1194 
   1195 	if (memf == NULL) {
   1196 		cc->nintr = uvmexp.intrs;
   1197 		cc->nsyscall = uvmexp.syscalls;
   1198 		cc->nswtch = uvmexp.swtch;
   1199 		cc->nfault = uvmexp.faults;
   1200 		cc->ntrap = uvmexp.traps;
   1201 		cc->nsoft = uvmexp.softs;
   1202 		return;
   1203 	}
   1204 
   1205 	if (!initialised) {
   1206 		kread(namelist, X_CPU_INFOS, &cpu_infos, sizeof(cpu_infos));
   1207 		initialised = 1;
   1208 	}
   1209 
   1210 	slot = cpu_infos;
   1211 
   1212 	memset(cc, 0, sizeof(*cc));
   1213 
   1214 	for (;;) {
   1215 		struct cpu_info tci, *ci = NULL;
   1216 
   1217 		deref_kptr(slot++, &ci, sizeof(ci), "CPU array trashed");
   1218 		if (!ci) {
   1219 			break;
   1220 		}
   1221 
   1222 		if ((size_t)kvm_read(kd, (u_long)ci, &tci, sizeof(tci))
   1223 		    != sizeof(tci)) {
   1224 			warnx("Can't read cpu info from %p (%s)",
   1225 			    ci, kvm_geterr(kd));
   1226 			memset(cc, 0, sizeof(*cc));
   1227 			return;
   1228 		}
   1229 		cc->nintr += tci.ci_data.cpu_nintr;
   1230 		cc->nsyscall += tci.ci_data.cpu_nsyscall;
   1231 		cc->nswtch = tci.ci_data.cpu_nswtch;
   1232 		cc->nfault = tci.ci_data.cpu_nfault;
   1233 		cc->ntrap = tci.ci_data.cpu_ntrap;
   1234 		cc->nsoft = tci.ci_data.cpu_nsoft;
   1235 	}
   1236 }
   1237 
   1238 void
   1239 cpustats(int *ovflwp)
   1240 {
   1241 	int state;
   1242 	double pcnt, total;
   1243 	double stat_us, stat_sy, stat_id;
   1244 	int ovflw = *ovflwp;
   1245 
   1246 	total = 0;
   1247 	for (state = 0; state < CPUSTATES; ++state)
   1248 		total += cur.cp_time[state];
   1249 	if (total)
   1250 		pcnt = 100 / total;
   1251 	else
   1252 		pcnt = 0;
   1253 	stat_us = (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * pcnt;
   1254 	stat_sy = (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * pcnt;
   1255 	stat_id = cur.cp_time[CP_IDLE] * pcnt;
   1256 	PRWORD(ovflw, " %*.0f", ((stat_sy >= 100) ? 2 : 3), 1, stat_us);
   1257 	PRWORD(ovflw, " %*.0f", ((stat_us >= 100 || stat_id >= 100) ? 2 : 3), 1,
   1258 	    stat_sy);
   1259 	PRWORD(ovflw, " %*.0f", 3, 1, stat_id);
   1260 	*ovflwp = ovflw;
   1261 }
   1262 
   1263 void
   1264 dointr(int verbose)
   1265 {
   1266 	unsigned long *intrcnt, *ointrcnt;
   1267 	unsigned long long inttotal, uptime;
   1268 	int nintr, inamlen;
   1269 	char *intrname, *ointrname;
   1270 
   1271 	inttotal = 0;
   1272 	uptime = getuptime();
   1273 	nintr = intrnl[X_EINTRCNT].n_value - intrnl[X_INTRCNT].n_value;
   1274 	inamlen = intrnl[X_EINTRNAMES].n_value - intrnl[X_INTRNAMES].n_value;
   1275 	if (nintr != 0 && inamlen != 0) {
   1276 		(void)printf("%-34s %16s %8s\n", "interrupt", "total", "rate");
   1277 
   1278 		ointrcnt = intrcnt = malloc((size_t)nintr);
   1279 		ointrname = intrname = malloc((size_t)inamlen);
   1280 		if (intrcnt == NULL || intrname == NULL)
   1281 			errx(1, "%s", "");
   1282 		kread(intrnl, X_INTRCNT, intrcnt, (size_t)nintr);
   1283 		kread(intrnl, X_INTRNAMES, intrname, (size_t)inamlen);
   1284 		nintr /= sizeof(long);
   1285 		while (--nintr >= 0) {
   1286 			if (*intrcnt || verbose)
   1287 				(void)printf("%-34s %16llu %8llu\n", intrname,
   1288 					     (unsigned long long)*intrcnt,
   1289 					     (unsigned long long)
   1290 					     (*intrcnt / uptime));
   1291 			intrname += strlen(intrname) + 1;
   1292 			inttotal += *intrcnt++;
   1293 		}
   1294 		free(ointrcnt);
   1295 		free(ointrname);
   1296 	}
   1297 
   1298 	doevcnt(verbose, EVCNT_TYPE_INTR);
   1299 }
   1300 
   1301 void
   1302 doevcnt(int verbose, int type)
   1303 {
   1304 	static const char * const evtypes [] = { "misc", "intr", "trap" };
   1305 	uint64_t counttotal, uptime;
   1306 	struct evcntlist allevents;
   1307 	struct evcnt evcnt, *evptr;
   1308 	size_t evlen_max, total_max, rate_max;
   1309 	char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
   1310 
   1311 	counttotal = 0;
   1312 	uptime = getuptime();
   1313 
   1314 	if (memf == NULL) do {
   1315 		const int mib[4] = { CTL_KERN, KERN_EVCNT, type,
   1316 		    verbose ? KERN_EVCNT_COUNT_ANY : KERN_EVCNT_COUNT_NONZERO };
   1317 		size_t buflen0, buflen = 0;
   1318 		void *buf0, *buf = NULL;
   1319 		const struct evcnt_sysctl *evs, *last_evs;
   1320 		for (;;) {
   1321 			size_t newlen;
   1322 			int error;
   1323 			if (buflen)
   1324 				buf = malloc(buflen);
   1325 			error = sysctl(mib, __arraycount(mib),
   1326 			    buf, &newlen, NULL, 0);
   1327 			if (error) {
   1328 				err(1, "kern.evcnt");
   1329 				if (buf)
   1330 					free(buf);
   1331 				return;
   1332 			}
   1333 			if (newlen <= buflen) {
   1334 				buflen = newlen;
   1335 				break;
   1336 			}
   1337 			if (buf)
   1338 				free(buf);
   1339 			buflen = newlen;
   1340 		}
   1341 		buflen0 = buflen;
   1342 		evs = buf0 = buf;
   1343 		last_evs = (void *)((char *)buf + buflen);
   1344 		buflen /= sizeof(uint64_t);
   1345 		/* calc columns */
   1346 		evlen_max = 0;
   1347 		total_max = sizeof("total") - 1;
   1348 		rate_max = sizeof("rate") - 1;
   1349 		while (evs < last_evs
   1350 		    && buflen >= sizeof(*evs)/sizeof(uint64_t)
   1351 		    && buflen >= evs->ev_len) {
   1352 			char cbuf[64];
   1353 			size_t len;
   1354 			len = strlen(evs->ev_strings + evs->ev_grouplen + 1);
   1355 			len += evs->ev_grouplen + 1;
   1356 			if (evlen_max < len)
   1357 				evlen_max= len;
   1358 			len = snprintf(cbuf, sizeof(cbuf), "%"PRIu64,
   1359 			    evs->ev_count);
   1360 			if (total_max < len)
   1361 				total_max = len;
   1362 			len = snprintf(cbuf, sizeof(cbuf), "%"PRIu64,
   1363 			    evs->ev_count / uptime);
   1364 			if (rate_max < len)
   1365 				rate_max = len;
   1366 			buflen -= evs->ev_len;
   1367 			evs = (const void *)
   1368 			    ((const uint64_t *)evs + evs->ev_len);
   1369 		}
   1370 
   1371 		(void)printf(type == EVCNT_TYPE_ANY ?
   1372 		    "%-*s  %*s %*s %s\n" :
   1373 		    "%-*s  %*s %*s\n",
   1374 		    (int)evlen_max, "interrupt",
   1375 		    (int)total_max, "total",
   1376 		    (int)rate_max, "rate",
   1377 		    "type");
   1378 
   1379 		buflen = buflen0;
   1380 		evs = buf0;
   1381 		last_evs = (void *)((char *)buf + buflen);
   1382 		buflen /= sizeof(uint64_t);
   1383 		while (evs < last_evs
   1384 		    && buflen >= sizeof(*evs)/sizeof(uint64_t)
   1385 		    && buflen >= evs->ev_len) {
   1386 			(void)printf(type == EVCNT_TYPE_ANY ?
   1387 			    "%s %s%*s  %*"PRIu64" %*"PRIu64" %s\n" :
   1388 			    "%s %s%*s  %*"PRIu64" %*"PRIu64"\n",
   1389 			    evs->ev_strings,
   1390 			    evs->ev_strings + evs->ev_grouplen + 1,
   1391 			    (int)evlen_max - (evs->ev_grouplen + 1
   1392 			    + evs->ev_namelen), "",
   1393 			    (int)total_max, evs->ev_count,
   1394 			    (int)rate_max, evs->ev_count / uptime,
   1395 			    (evs->ev_type < __arraycount(evtypes) ?
   1396 			    evtypes[evs->ev_type] : "?"));
   1397 			buflen -= evs->ev_len;
   1398 			counttotal += evs->ev_count;
   1399 			evs = (const void *)
   1400 			    ((const uint64_t *)evs + evs->ev_len);
   1401 		}
   1402 		free(buf);
   1403 		if (type != EVCNT_TYPE_ANY)
   1404 			(void)printf("%-*s  %*"PRIu64" %*"PRIu64"\n",
   1405 			    (int)evlen_max, "Total",
   1406 			    (int)total_max, counttotal,
   1407 			    (int)rate_max, counttotal / uptime);
   1408 		return;
   1409 	} while (/*CONSTCOND*/ 0);
   1410 
   1411 	if (type == EVCNT_TYPE_ANY)
   1412 		(void)printf("%-34s %16s %8s %s\n", "event", "total", "rate",
   1413 		    "type");
   1414 
   1415 	kread(namelist, X_ALLEVENTS, &allevents, sizeof allevents);
   1416 	evptr = TAILQ_FIRST(&allevents);
   1417 	while (evptr) {
   1418 		deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
   1419 
   1420 		evptr = TAILQ_NEXT(&evcnt, ev_list);
   1421 		if (evcnt.ev_count == 0 && !verbose)
   1422 			continue;
   1423 		if (type != EVCNT_TYPE_ANY && evcnt.ev_type != type)
   1424 			continue;
   1425 
   1426 		deref_kptr(evcnt.ev_group, evgroup,
   1427 		    (size_t)evcnt.ev_grouplen + 1, "event chain trashed");
   1428 		deref_kptr(evcnt.ev_name, evname,
   1429 		    (size_t)evcnt.ev_namelen + 1, "event chain trashed");
   1430 
   1431 		(void)printf(type == EVCNT_TYPE_ANY ?
   1432 		    "%s %s%*s %16"PRIu64" %8"PRIu64" %s\n" :
   1433 		    "%s %s%*s %16"PRIu64" %8"PRIu64"\n",
   1434 		    evgroup, evname,
   1435 		    34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
   1436 		    evcnt.ev_count,
   1437 		    (evcnt.ev_count / uptime),
   1438 		    (evcnt.ev_type < __arraycount(evtypes) ?
   1439 			evtypes[evcnt.ev_type] : "?"));
   1440 
   1441 		counttotal += evcnt.ev_count;
   1442 	}
   1443 	if (type != EVCNT_TYPE_ANY)
   1444 		(void)printf("%-34s %16"PRIu64" %8"PRIu64"\n",
   1445 		    "Total", counttotal, counttotal / uptime);
   1446 }
   1447 
   1448 static void
   1449 dopool_sysctl(int verbose, int wide)
   1450 {
   1451 	uint64_t total, inuse, this_total, this_inuse;
   1452 	struct {
   1453 		uint64_t pt_nget;
   1454 		uint64_t pt_nfail;
   1455 		uint64_t pt_nput;
   1456 		uint64_t pt_nout;
   1457 		uint64_t pt_nitems;
   1458 		uint64_t pt_npagealloc;
   1459 		uint64_t pt_npagefree;
   1460 		uint64_t pt_npages;
   1461 	} pool_totals;
   1462 	size_t i, len;
   1463 	int name_len, ovflw;
   1464 	struct pool_sysctl *pp, *data;
   1465 	char maxp[32];
   1466 
   1467 	data = asysctlbyname("kern.pool", &len);
   1468 	if (data == NULL)
   1469 		err(1, "failed to read kern.pool");
   1470 
   1471 	memset(&pool_totals, 0, sizeof pool_totals);
   1472 	total = inuse = 0;
   1473 	len /= sizeof(*data);
   1474 
   1475 	(void)printf("Memory resource pool statistics\n");
   1476 	(void)printf(
   1477 	    "%-*s%*s%*s%*s%*s%s%s%*s%*s%*s%s%*s%6s%*s%5s%s%s\n",
   1478 	    wide ? 16 : 11, "Name",
   1479 	    wide ? 7 : 5, "Size",
   1480 	    wide ? 12 : 9, "Requests",
   1481 	    wide ? 8 : 5, "Fail",
   1482 	    wide ? 12 : 9, "Releases",
   1483 	    wide ? "    InUse" : "",
   1484 	    wide ? "    Avail" : "",
   1485 	    wide ? 11 : 6, "Pgreq",
   1486 	    wide ? 11 : 6, "Pgrel",
   1487 	    wide ? 8 : 6, "Npage",
   1488 	    wide ? " PageSz" : "",
   1489 	    wide ? 7 : 6, "Hiwat",
   1490 	    "Minpg",
   1491 	    wide ? 7 : 6, "Maxpg",
   1492 	    "Idle",
   1493 	    wide ? "   Flags" : "",
   1494 	    wide ? "   Util" : "");
   1495 
   1496 	name_len = MIN((int)sizeof(pp->pr_wchan), wide ? 16 : 11);
   1497 	for (i = 0; i < len; ++i) {
   1498 		pp = &data[i];
   1499 		if (pp->pr_nget == 0 && !verbose)
   1500 			continue;
   1501 		if (pp->pr_maxpages == UINT_MAX)
   1502 			(void)snprintf(maxp, sizeof(maxp), "inf");
   1503 		else
   1504 			(void)snprintf(maxp, sizeof(maxp), "%" PRIu64,
   1505 			    pp->pr_maxpages);
   1506 		ovflw = 0;
   1507 		PRWORD(ovflw, "%-*s", name_len, 0, pp->pr_wchan);
   1508 		PRWORD(ovflw, " %*" PRIu64, wide ? 7 : 5, 1, pp->pr_size);
   1509 		PRWORD(ovflw, " %*" PRIu64, wide ? 12 : 9, 1, pp->pr_nget);
   1510 		pool_totals.pt_nget += pp->pr_nget;
   1511 		PRWORD(ovflw, " %*" PRIu64, wide ? 8 : 5, 1, pp->pr_nfail);
   1512 		pool_totals.pt_nfail += pp->pr_nfail;
   1513 		PRWORD(ovflw, " %*" PRIu64, wide ? 12 : 9, 1, pp->pr_nput);
   1514 		pool_totals.pt_nput += pp->pr_nput;
   1515 		if (wide) {
   1516 			PRWORD(ovflw, " %*" PRIu64, 9, 1, pp->pr_nout);
   1517 			pool_totals.pt_nout += pp->pr_nout;
   1518 			PRWORD(ovflw, " %*" PRIu64, 9, 1, pp->pr_nitems);
   1519 			pool_totals.pt_nitems += pp->pr_nitems;
   1520 		}
   1521 		PRWORD(ovflw, " %*" PRIu64, wide ? 11 : 6, 1, pp->pr_npagealloc);
   1522 		pool_totals.pt_npagealloc += pp->pr_npagealloc;
   1523 		PRWORD(ovflw, " %*" PRIu64, wide ? 11 : 6, 1, pp->pr_npagefree);
   1524 		pool_totals.pt_npagefree += pp->pr_npagefree;
   1525 		PRWORD(ovflw, " %*" PRIu64, wide ? 8 : 6, 1, pp->pr_npages);
   1526 		pool_totals.pt_npages += pp->pr_npages;
   1527 		if (wide)
   1528 			PRWORD(ovflw, " %*" PRIu64, 7, 1, pp->pr_pagesize);
   1529 		PRWORD(ovflw, " %*" PRIu64, wide ? 7 : 6, 1, pp->pr_hiwat);
   1530 		PRWORD(ovflw, " %*" PRIu64, 6, 1, pp->pr_minpages);
   1531 		PRWORD(ovflw, " %*s", wide ? 7 : 6, 1, maxp);
   1532 		PRWORD(ovflw, " %*" PRIu64, 5, 1, pp->pr_nidle);
   1533 		if (wide)
   1534 			PRWORD(ovflw, " 0x%0*" PRIx64, 6, 1,
   1535 			    pp->pr_flags);
   1536 
   1537 		this_inuse = pp->pr_nout * pp->pr_size;
   1538 		this_total = pp->pr_npages * pp->pr_pagesize;
   1539 		if (pp->pr_flags & PR_RECURSIVE) {
   1540 			/*
   1541 			 * Don't count in-use memory, since it's part
   1542 			 * of another pool and will be accounted for
   1543 			 * there.
   1544 			 */
   1545 			total += (this_total - this_inuse);
   1546 		} else {
   1547 			inuse += this_inuse;
   1548 			total += this_total;
   1549 		}
   1550 		if (wide) {
   1551 			if (this_total == 0)
   1552 				(void)printf("   ---");
   1553 			else
   1554 				(void)printf(" %5.1f%%",
   1555 				    (100.0 * this_inuse) / this_total);
   1556 		}
   1557 		(void)printf("\n");
   1558 	}
   1559 	ovflw = 0;
   1560 	PRWORD(ovflw, "%-*s", name_len, 0, "Totals");
   1561 	PRWORD(ovflw, " %*s", wide ? 7 : 5, 1, "");
   1562 	PRWORD(ovflw, " %*" PRIu64, wide ? 12 : 9, 1, pool_totals.pt_nget);
   1563 	PRWORD(ovflw, " %*" PRIu64, wide ? 8 : 5, 1, pool_totals.pt_nfail);
   1564 	PRWORD(ovflw, " %*" PRIu64, wide ? 12 : 9, 1, pool_totals.pt_nput);
   1565 	if (wide) {
   1566 		PRWORD(ovflw, " %*" PRIu64, 9, 1, pool_totals.pt_nout);
   1567 		PRWORD(ovflw, " %*" PRIu64, 9, 1, pool_totals.pt_nitems);
   1568 	}
   1569 	PRWORD(ovflw, " %*" PRIu64, wide ? 11 : 6, 1, pool_totals.pt_npagealloc);
   1570 	PRWORD(ovflw, " %*" PRIu64, wide ? 11 : 6, 1, pool_totals.pt_npagefree);
   1571 	PRWORD(ovflw, " %*" PRIu64, wide ? 8 : 6, 1, pool_totals.pt_npages);
   1572 	(void)printf("\n");
   1573 
   1574 	inuse /= KILO;
   1575 	total /= KILO;
   1576 	(void)printf(
   1577 	    "\nIn use %" PRIu64 "K, "
   1578 	    "total allocated %" PRIu64 "K; utilization %.1f%%\n",
   1579 	    inuse, total, (100.0 * inuse) / total);
   1580 
   1581 	free(data);
   1582 }
   1583 
   1584 void
   1585 dopool(int verbose, int wide)
   1586 {
   1587 	int first, ovflw;
   1588 	void *addr;
   1589 	long total, inuse, this_total, this_inuse;
   1590 	struct {
   1591 		uint64_t pt_nget;
   1592 		uint64_t pt_nfail;
   1593 		uint64_t pt_nput;
   1594 		uint64_t pt_nout;
   1595 		uint64_t pt_nitems;
   1596 		uint64_t pt_npagealloc;
   1597 		uint64_t pt_npagefree;
   1598 		uint64_t pt_npages;
   1599 	} pool_totals;
   1600 	TAILQ_HEAD(,pool) pool_head;
   1601 	struct pool pool, *pp = &pool;
   1602 	struct pool_allocator pa;
   1603 	char maxp[32], name[32];
   1604 
   1605 	if (memf == NULL)
   1606 		return dopool_sysctl(verbose, wide);
   1607 
   1608 	memset(&pool_totals, 0, sizeof pool_totals);
   1609 	kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
   1610 	addr = TAILQ_FIRST(&pool_head);
   1611 
   1612 	total = inuse = 0;
   1613 
   1614 	for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
   1615 		deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
   1616 		deref_kptr(pp->pr_alloc, &pa, sizeof(pa),
   1617 		    "pool allocator trashed");
   1618 		deref_kptr(pp->pr_wchan, name, sizeof(name),
   1619 		    "pool wait channel trashed");
   1620 		name[sizeof(name)-1] = '\0';
   1621 
   1622 		if (first) {
   1623 			(void)printf("Memory resource pool statistics\n");
   1624 			(void)printf(
   1625 			    "%-*s%*s%*s%*s%*s%s%s%*s%*s%*s%s%*s%6s%*s%5s%s%s\n",
   1626 			    wide ? 16 : 11, "Name",
   1627 			    wide ? 7 : 5, "Size",
   1628 			    wide ? 12 : 9, "Requests",
   1629 			    wide ? 8 : 5, "Fail",
   1630 			    wide ? 12 : 9, "Releases",
   1631 			    wide ? "    InUse" : "",
   1632 			    wide ? "    Avail" : "",
   1633 			    wide ? 11 : 6, "Pgreq",
   1634 			    wide ? 11 : 6, "Pgrel",
   1635 			    wide ? 8 : 6, "Npage",
   1636 			    wide ? " PageSz" : "",
   1637 			    wide ? 7 : 6, "Hiwat",
   1638 			    "Minpg",
   1639 			    wide ? 7 : 6, "Maxpg",
   1640 			    "Idle",
   1641 			    wide ? "   Flags" : "",
   1642 			    wide ? "   Util" : "");
   1643 			first = 0;
   1644 		}
   1645 		if (pp->pr_nget == 0 && !verbose)
   1646 			continue;
   1647 		if (pp->pr_maxpages == UINT_MAX)
   1648 			(void)snprintf(maxp, sizeof(maxp), "inf");
   1649 		else
   1650 			(void)snprintf(maxp, sizeof(maxp), "%u",
   1651 			    pp->pr_maxpages);
   1652 		ovflw = 0;
   1653 		PRWORD(ovflw, "%-*s", wide ? 16 : 11, 0, name);
   1654 		PRWORD(ovflw, " %*u", wide ? 7 : 5, 1, pp->pr_size);
   1655 		PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nget);
   1656 		pool_totals.pt_nget += pp->pr_nget;
   1657 		PRWORD(ovflw, " %*lu", wide ? 8 : 5, 1, pp->pr_nfail);
   1658 		pool_totals.pt_nfail += pp->pr_nfail;
   1659 		PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nput);
   1660 		pool_totals.pt_nput += pp->pr_nput;
   1661 		if (wide) {
   1662 			PRWORD(ovflw, " %*u", 9, 1, pp->pr_nout);
   1663 			pool_totals.pt_nout += pp->pr_nout;
   1664 			PRWORD(ovflw, " %*u", 9, 1, pp->pr_nitems);
   1665 			pool_totals.pt_nitems += pp->pr_nitems;
   1666 		}
   1667 		PRWORD(ovflw, " %*lu", wide ? 11 : 6, 1, pp->pr_npagealloc);
   1668 		pool_totals.pt_npagealloc += pp->pr_npagealloc;
   1669 		PRWORD(ovflw, " %*lu", wide ? 11 : 6, 1, pp->pr_npagefree);
   1670 		pool_totals.pt_npagefree += pp->pr_npagefree;
   1671 		PRWORD(ovflw, " %*u", wide ? 8 : 6, 1, pp->pr_npages);
   1672 		pool_totals.pt_npages += pp->pr_npages;
   1673 		if (wide)
   1674 			PRWORD(ovflw, " %*u", 7, 1, pa.pa_pagesz);
   1675 		PRWORD(ovflw, " %*u", wide ? 7 : 6, 1, pp->pr_hiwat);
   1676 		PRWORD(ovflw, " %*u", 6, 1, pp->pr_minpages);
   1677 		PRWORD(ovflw, " %*s", wide ? 7 : 6, 1, maxp);
   1678 		PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nidle);
   1679 		if (wide)
   1680 			PRWORD(ovflw, " 0x%0*x", 6, 1,
   1681 			    pp->pr_flags | pp->pr_roflags);
   1682 
   1683 		this_inuse = pp->pr_nout * pp->pr_size;
   1684 		this_total = pp->pr_npages * pa.pa_pagesz;
   1685 		if (pp->pr_roflags & PR_RECURSIVE) {
   1686 			/*
   1687 			 * Don't count in-use memory, since it's part
   1688 			 * of another pool and will be accounted for
   1689 			 * there.
   1690 			 */
   1691 			total += (this_total - this_inuse);
   1692 		} else {
   1693 			inuse += this_inuse;
   1694 			total += this_total;
   1695 		}
   1696 		if (wide) {
   1697 			if (this_total == 0)
   1698 				(void)printf("   ---");
   1699 			else
   1700 				(void)printf(" %5.1f%%",
   1701 				    (100.0 * this_inuse) / this_total);
   1702 		}
   1703 		(void)printf("\n");
   1704 	}
   1705 	ovflw = 0;
   1706 	PRWORD(ovflw, "%-*s", wide ? 16 : 11, 0, "Totals");
   1707 	PRWORD(ovflw, " %*s", wide ? 7 : 5, 1, "");
   1708 	PRWORD(ovflw, " %*" PRIu64, wide ? 12 : 9, 1, pool_totals.pt_nget);
   1709 	PRWORD(ovflw, " %*" PRIu64, wide ? 8 : 5, 1, pool_totals.pt_nfail);
   1710 	PRWORD(ovflw, " %*" PRIu64, wide ? 12 : 9, 1, pool_totals.pt_nput);
   1711  	if (wide) {
   1712 		PRWORD(ovflw, " %*" PRIu64, 9, 1, pool_totals.pt_nout);
   1713 		PRWORD(ovflw, " %*" PRIu64, 9, 1, pool_totals.pt_nitems);
   1714  	}
   1715 	PRWORD(ovflw, " %*" PRIu64, wide ? 11 : 6, 1, pool_totals.pt_npagealloc);
   1716 	PRWORD(ovflw, " %*" PRIu64, wide ? 11 : 6, 1, pool_totals.pt_npagefree);
   1717 	PRWORD(ovflw, " %*" PRIu64, wide ? 8 : 6, 1, pool_totals.pt_npages);
   1718 	(void)printf("\n");
   1719 
   1720 	inuse /= KILO;
   1721 	total /= KILO;
   1722 	(void)printf(
   1723 	    "\nIn use %ldK, total allocated %ldK; utilization %.1f%%\n",
   1724 	    inuse, total, (100.0 * inuse) / total);
   1725 }
   1726 
   1727 static void
   1728 dopoolcache_sysctl(int verbose)
   1729 {
   1730 	struct pool_sysctl *data, *pp;
   1731 	size_t i, len;
   1732 	bool first = true;
   1733 	int ovflw;
   1734 	uint64_t tot;
   1735 	double p;
   1736 
   1737 	data = asysctlbyname("kern.pool", &len);
   1738 	if (data == NULL)
   1739 		err(1, "failed to read kern.pool");
   1740 	len /= sizeof(*data);
   1741 
   1742 	for (i = 0; i < len; ++i) {
   1743 		pp = &data[i];
   1744 		if (pp->pr_cache_meta_size == 0)
   1745 			continue;
   1746 
   1747 		if (pp->pr_cache_nmiss_global == 0 && !verbose)
   1748 			continue;
   1749 
   1750 		if (first) {
   1751 			(void)printf("Pool cache statistics.\n");
   1752 			(void)printf("%-*s%*s%*s%*s%*s%*s%*s%*s%*s%*s\n",
   1753 			    12, "Name",
   1754 			    6, "Spin",
   1755 			    6, "GrpSz",
   1756 			    5, "Full",
   1757 			    5, "Emty",
   1758 			    10, "PoolLayer",
   1759 			    11, "CacheLayer",
   1760 			    6, "Hit%",
   1761 			    12, "CpuLayer",
   1762 			    6, "Hit%"
   1763 			);
   1764 			first = false;
   1765 		}
   1766 
   1767 		ovflw = 0;
   1768 		PRWORD(ovflw, "%-*s", MIN((int)sizeof(pp->pr_wchan), 13), 1,
   1769 		    pp->pr_wchan);
   1770 		PRWORD(ovflw, " %*" PRIu64, 6, 1, pp->pr_cache_ncontended);
   1771 		PRWORD(ovflw, " %*" PRIu64, 6, 1, pp->pr_cache_meta_size);
   1772 		PRWORD(ovflw, " %*" PRIu64, 5, 1, pp->pr_cache_nfull);
   1773 		PRWORD(ovflw, " %*" PRIu64, 5, 1, pp->pr_cache_nempty);
   1774 		PRWORD(ovflw, " %*" PRIu64, 10, 1, pp->pr_cache_nmiss_global);
   1775 
   1776 		tot = pp->pr_cache_nhit_global + pp->pr_cache_nmiss_global;
   1777 		p = pp->pr_cache_nhit_global * 100.0 / tot;
   1778 		PRWORD(ovflw, " %*" PRIu64, 11, 1, tot);
   1779 		PRWORD(ovflw, " %*.1f", 6, 1, p);
   1780 
   1781 		tot = pp->pr_cache_nhit_pcpu + pp->pr_cache_nmiss_pcpu;
   1782 		p = pp->pr_cache_nhit_pcpu * 100.0 / tot;
   1783 		PRWORD(ovflw, " %*" PRIu64, 12, 1, tot);
   1784 		PRWORD(ovflw, " %*.1f", 6, 1, p);
   1785 		printf("\n");
   1786 	}
   1787 }
   1788 
   1789 void
   1790 dopoolcache(int verbose)
   1791 {
   1792 	struct pool_cache pool_cache, *pc = &pool_cache;
   1793 	pool_cache_cpu_t cache_cpu, *cc = &cache_cpu;
   1794 	TAILQ_HEAD(,pool) pool_head;
   1795 	struct pool pool, *pp = &pool;
   1796 	char name[32];
   1797 	uint64_t cpuhit, cpumiss, tot;
   1798 	void *addr;
   1799 	int first, ovflw;
   1800 	size_t i;
   1801 	double p;
   1802 
   1803 	if (memf == NULL)
   1804 		return dopoolcache_sysctl(verbose);
   1805 
   1806 	kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
   1807 	addr = TAILQ_FIRST(&pool_head);
   1808 
   1809 	for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
   1810 		deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
   1811 		if (pp->pr_cache == NULL)
   1812 			continue;
   1813 		deref_kptr(pp->pr_wchan, name, sizeof(name),
   1814 		    "pool wait channel trashed");
   1815 		deref_kptr(pp->pr_cache, pc, sizeof(*pc), "pool cache trashed");
   1816 		if (pc->pc_misses == 0 && !verbose)
   1817 			continue;
   1818 		name[sizeof(name)-1] = '\0';
   1819 
   1820 		cpuhit = 0;
   1821 		cpumiss = 0;
   1822 		for (i = 0; i < __arraycount(pc->pc_cpus); i++) {
   1823 		    	if ((addr = pc->pc_cpus[i]) == NULL)
   1824 		    		continue;
   1825 			deref_kptr(addr, cc, sizeof(*cc),
   1826 			    "pool cache cpu trashed");
   1827 			cpuhit += cc->cc_hits;
   1828 			cpumiss += cc->cc_misses;
   1829 		}
   1830 
   1831 		if (first) {
   1832 			(void)printf("Pool cache statistics.\n");
   1833 			(void)printf("%-*s%*s%*s%*s%*s%*s%*s%*s%*s%*s\n",
   1834 			    12, "Name",
   1835 			    6, "Spin",
   1836 			    6, "GrpSz",
   1837 			    5, "Full",
   1838 			    5, "Emty",
   1839 			    10, "PoolLayer",
   1840 			    11, "CacheLayer",
   1841 			    6, "Hit%",
   1842 			    12, "CpuLayer",
   1843 			    6, "Hit%"
   1844 			);
   1845 			first = 0;
   1846 		}
   1847 
   1848 		ovflw = 0;
   1849 		PRWORD(ovflw, "%-*s", 13, 1, name);
   1850 		PRWORD(ovflw, " %*llu", 6, 1, (long long)pc->pc_contended);
   1851 		PRWORD(ovflw, " %*u", 6, 1, pc->pc_pcgsize);
   1852 		PRWORD(ovflw, " %*u", 5, 1, pc->pc_nfull);
   1853 		PRWORD(ovflw, " %*u", 5, 1, pc->pc_nempty);
   1854 		PRWORD(ovflw, " %*llu", 10, 1, (long long)pc->pc_misses);
   1855 
   1856 		tot = pc->pc_hits + pc->pc_misses;
   1857 		p = pc->pc_hits * 100.0 / (tot);
   1858 		PRWORD(ovflw, " %*llu", 11, 1, (long long)tot);
   1859 		PRWORD(ovflw, " %*.1f", 6, 1, p);
   1860 
   1861 		tot = cpuhit + cpumiss;
   1862 		p = cpuhit * 100.0 / (tot);
   1863 		PRWORD(ovflw, " %*llu", 12, 1, (long long)tot);
   1864 		PRWORD(ovflw, " %*.1f", 6, 1, p);
   1865 		printf("\n");
   1866 	}
   1867 }
   1868 
   1869 enum hashtype {			/* from <sys/systm.h> */
   1870 	HASH_LIST,
   1871 	HASH_SLIST,
   1872 	HASH_TAILQ,
   1873 	HASH_PSLIST
   1874 };
   1875 
   1876 struct uidinfo {		/* XXX: no kernel header file */
   1877 	LIST_ENTRY(uidinfo) ui_hash;
   1878 	uid_t	ui_uid;
   1879 	long	ui_proccnt;
   1880 };
   1881 
   1882 struct kernel_hash {
   1883 	const char *	description;	/* description */
   1884 	int		hashsize;	/* nlist index for hash size */
   1885 	int		hashtbl;	/* nlist index for hash table */
   1886 	enum hashtype	type;		/* type of hash table */
   1887 	size_t		offset;		/* offset of {LIST,TAILQ}_NEXT */
   1888 } khashes[] =
   1889 {
   1890 	{
   1891 		"buffer hash",
   1892 		X_BUFHASH, X_BUFHASHTBL,
   1893 		HASH_LIST, offsetof(struct buf, b_hash)
   1894 	}, {
   1895 		"ipv4 address -> interface hash",
   1896 		X_IFADDRHASH, X_IFADDRHASHTBL,
   1897 		HASH_LIST, offsetof(struct in_ifaddr, ia_hash),
   1898 	}, {
   1899 		"user info (uid -> used processes) hash",
   1900 		X_UIHASH, X_UIHASHTBL,
   1901 		HASH_LIST, offsetof(struct uidinfo, ui_hash),
   1902 	}, {
   1903 		"vnode cache hash",
   1904 		X_VCACHEHASH, X_VCACHETBL,
   1905 		HASH_SLIST, offsetof(struct vnode_impl, vi_hash),
   1906 	}, {
   1907 		NULL, -1, -1, 0, 0,
   1908 	}
   1909 };
   1910 
   1911 void
   1912 dohashstat(int verbose, int todo, const char *hashname)
   1913 {
   1914 	LIST_HEAD(, generic)	*hashtbl_list;
   1915 	SLIST_HEAD(, generic)	*hashtbl_slist;
   1916 	TAILQ_HEAD(, generic)	*hashtbl_tailq;
   1917 	struct kernel_hash	*curhash;
   1918 	void	*hashaddr, *hashbuf, *nhashbuf, *nextaddr;
   1919 	size_t	elemsize, hashbufsize, thissize;
   1920 	u_long	hashsize, i;
   1921 	int	used, items, chain, maxchain;
   1922 
   1923 	hashbuf = NULL;
   1924 	hashbufsize = 0;
   1925 
   1926 	if (todo & HASHLIST) {
   1927 		(void)printf("Supported hashes:\n");
   1928 		for (curhash = khashes; curhash->description; curhash++) {
   1929 			if (hashnl[curhash->hashsize].n_value == 0 ||
   1930 			    hashnl[curhash->hashtbl].n_value == 0)
   1931 				continue;
   1932 			(void)printf("\t%-16s%s\n",
   1933 			    hashnl[curhash->hashsize].n_name + 1,
   1934 			    curhash->description);
   1935 		}
   1936 		return;
   1937 	}
   1938 
   1939 	if (hashname != NULL) {
   1940 		for (curhash = khashes; curhash->description; curhash++) {
   1941 			if (strcmp(hashnl[curhash->hashsize].n_name + 1,
   1942 			    hashname) == 0 &&
   1943 			    hashnl[curhash->hashsize].n_value != 0 &&
   1944 			    hashnl[curhash->hashtbl].n_value != 0)
   1945 				break;
   1946 		}
   1947 		if (curhash->description == NULL) {
   1948 			warnx("%s: no such hash", hashname);
   1949 			return;
   1950 		}
   1951 	}
   1952 
   1953 	(void)printf(
   1954 	    "%-16s %8s %8s %8s %8s %8s %8s\n"
   1955 	    "%-16s %8s %8s %8s %8s %8s %8s\n",
   1956 	    "", "total", "used", "util", "num", "average", "maximum",
   1957 	    "hash table", "buckets", "buckets", "%", "items", "chain",
   1958 	    "chain");
   1959 
   1960 	for (curhash = khashes; curhash->description; curhash++) {
   1961 		if (hashnl[curhash->hashsize].n_value == 0 ||
   1962 		    hashnl[curhash->hashtbl].n_value == 0)
   1963 			continue;
   1964 		if (hashname != NULL &&
   1965 		    strcmp(hashnl[curhash->hashsize].n_name + 1, hashname))
   1966 			continue;
   1967 		elemsize = curhash->type == HASH_LIST ?
   1968 		    sizeof(*hashtbl_list) : sizeof(*hashtbl_tailq);
   1969 		deref_kptr((void *)hashnl[curhash->hashsize].n_value,
   1970 		    &hashsize, sizeof(hashsize),
   1971 		    hashnl[curhash->hashsize].n_name);
   1972 		hashsize++;
   1973 		deref_kptr((void *)hashnl[curhash->hashtbl].n_value,
   1974 		    &hashaddr, sizeof(hashaddr),
   1975 		    hashnl[curhash->hashtbl].n_name);
   1976 		if (verbose)
   1977 			(void)printf(
   1978 			    "%s %lu, %s %p, offset %ld, elemsize %llu\n",
   1979 			    hashnl[curhash->hashsize].n_name + 1, hashsize,
   1980 			    hashnl[curhash->hashtbl].n_name + 1, hashaddr,
   1981 			    (long)curhash->offset,
   1982 			    (unsigned long long)elemsize);
   1983 		thissize = hashsize * elemsize;
   1984 		if (hashbuf == NULL || thissize > hashbufsize) {
   1985 			if ((nhashbuf = realloc(hashbuf, thissize)) == NULL)
   1986 				errx(1, "malloc hashbuf %llu",
   1987 				    (unsigned long long)hashbufsize);
   1988 			hashbuf = nhashbuf;
   1989 			hashbufsize = thissize;
   1990 		}
   1991 		deref_kptr(hashaddr, hashbuf, thissize,
   1992 		    hashnl[curhash->hashtbl].n_name);
   1993 		used = 0;
   1994 		items = maxchain = 0;
   1995 		if (curhash->type == HASH_LIST) {
   1996 			hashtbl_list = hashbuf;
   1997 			hashtbl_slist = NULL;
   1998 			hashtbl_tailq = NULL;
   1999 		} else if (curhash->type == HASH_SLIST) {
   2000 			hashtbl_list = NULL;
   2001 			hashtbl_slist = hashbuf;
   2002 			hashtbl_tailq = NULL;
   2003 		} else {
   2004 			hashtbl_list = NULL;
   2005 			hashtbl_slist = NULL;
   2006 			hashtbl_tailq = hashbuf;
   2007 		}
   2008 		for (i = 0; i < hashsize; i++) {
   2009 			if (curhash->type == HASH_LIST)
   2010 				nextaddr = LIST_FIRST(&hashtbl_list[i]);
   2011 			else if (curhash->type == HASH_SLIST)
   2012 				nextaddr = SLIST_FIRST(&hashtbl_slist[i]);
   2013 			else
   2014 				nextaddr = TAILQ_FIRST(&hashtbl_tailq[i]);
   2015 			if (nextaddr == NULL)
   2016 				continue;
   2017 			if (verbose)
   2018 				(void)printf("%5lu: %p\n", i, nextaddr);
   2019 			used++;
   2020 			chain = 0;
   2021 			do {
   2022 				chain++;
   2023 				deref_kptr((char *)nextaddr + curhash->offset,
   2024 				    &nextaddr, sizeof(void *),
   2025 				    "hash chain corrupted");
   2026 				if (verbose > 1)
   2027 					(void)printf("got nextaddr as %p\n",
   2028 					    nextaddr);
   2029 			} while (nextaddr != NULL);
   2030 			items += chain;
   2031 			if (verbose && chain > 1)
   2032 				(void)printf("\tchain = %d\n", chain);
   2033 			if (chain > maxchain)
   2034 				maxchain = chain;
   2035 		}
   2036 		(void)printf("%-16s %8ld %8d %8.2f %8d %8.2f %8d\n",
   2037 		    hashnl[curhash->hashsize].n_name + 1,
   2038 		    hashsize, used, used * 100.0 / hashsize,
   2039 		    items, used ? (double)items / used : 0.0, maxchain);
   2040 	}
   2041 }
   2042 
   2043 /*
   2044  * kreadc like kread but returns 1 if successful, 0 otherwise
   2045  */
   2046 int
   2047 kreadc(struct nlist *nl, int nlx, void *addr, size_t size)
   2048 {
   2049 	const char *sym;
   2050 
   2051 	sym = nl[nlx].n_name;
   2052 	if (*sym == '_')
   2053 		++sym;
   2054 	if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
   2055 		return 0;
   2056 	deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
   2057 	return 1;
   2058 }
   2059 
   2060 /*
   2061  * kread reads something from the kernel, given its nlist index in namelist[].
   2062  */
   2063 void
   2064 kread(struct nlist *nl, int nlx, void *addr, size_t size)
   2065 {
   2066 	const char *sym;
   2067 
   2068 	sym = nl[nlx].n_name;
   2069 	if (*sym == '_')
   2070 		++sym;
   2071 	if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
   2072 		errx(1, "symbol %s not defined", sym);
   2073 	deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
   2074 }
   2075 
   2076 /*
   2077  * Dereference the kernel pointer `kptr' and fill in the local copy
   2078  * pointed to by `ptr'.  The storage space must be pre-allocated,
   2079  * and the size of the copy passed in `len'.
   2080  */
   2081 void
   2082 deref_kptr(const void *kptr, void *ptr, size_t len, const char *msg)
   2083 {
   2084 
   2085 	if (*msg == '_')
   2086 		msg++;
   2087 	if ((size_t)kvm_read(kd, (u_long)kptr, (char *)ptr, len) != len)
   2088 		errx(1, "kptr %lx: %s: %s", (u_long)kptr, msg, kvm_geterr(kd));
   2089 }
   2090 
   2091 /*
   2092  * Traverse the kernel history buffers, performing the requested action.
   2093  *
   2094  * Note, we assume that if we're not listing, we're dumping.
   2095  */
   2096 void
   2097 hist_traverse(int todo, const char *histname)
   2098 {
   2099 	struct kern_history_head histhead;
   2100 	struct kern_history hist, *histkva;
   2101 	char *name = NULL;
   2102 	size_t namelen = 0;
   2103 
   2104 	if (histnl[0].n_value == 0) {
   2105 		warnx("kernel history is not compiled into the kernel.");
   2106 		return;
   2107 	}
   2108 
   2109 	deref_kptr((void *)histnl[X_KERN_HISTORIES].n_value, &histhead,
   2110 	    sizeof(histhead), histnl[X_KERN_HISTORIES].n_name);
   2111 
   2112 	if (histhead.lh_first == NULL) {
   2113 		warnx("No active kernel history logs.");
   2114 		return;
   2115 	}
   2116 
   2117 	if (todo & HISTLIST)
   2118 		(void)printf("Active kernel histories:");
   2119 
   2120 	for (histkva = LIST_FIRST(&histhead); histkva != NULL;
   2121 	    histkva = LIST_NEXT(&hist, list)) {
   2122 		deref_kptr(histkva, &hist, sizeof(hist), "histkva");
   2123 		if (name == NULL || hist.namelen > namelen) {
   2124 			if (name != NULL)
   2125 				free(name);
   2126 			namelen = hist.namelen;
   2127 			if ((name = malloc(namelen + 1)) == NULL)
   2128 				err(1, "malloc history name");
   2129 		}
   2130 
   2131 		deref_kptr(hist.name, name, namelen, "history name");
   2132 		name[namelen] = '\0';
   2133 		if (todo & HISTLIST)
   2134 			(void)printf(" %s", name);
   2135 		else {
   2136 			/*
   2137 			 * If we're dumping all histories, do it, else
   2138 			 * check to see if this is the one we want.
   2139 			 */
   2140 			if (histname == NULL || strcmp(histname, name) == 0) {
   2141 				if (histname == NULL)
   2142 					(void)printf(
   2143 					    "\nkernel history `%s':\n", name);
   2144 				hist_dodump(&hist);
   2145 			}
   2146 		}
   2147 	}
   2148 
   2149 	if (todo & HISTLIST)
   2150 		(void)putchar('\n');
   2151 
   2152 	if (name != NULL)
   2153 		free(name);
   2154 }
   2155 
   2156 /*
   2157  * Actually dump the history buffer at the specified KVA.
   2158  */
   2159 void
   2160 hist_dodump(struct kern_history *histp)
   2161 {
   2162 	struct kern_history_ent *histents, *e;
   2163 	struct timeval tv;
   2164 	size_t histsize;
   2165 	char *fmt = NULL, *fn = NULL;
   2166 	size_t fmtlen = 0, fnlen = 0;
   2167 	unsigned i;
   2168 
   2169 	histsize = sizeof(struct kern_history_ent) * histp->n;
   2170 
   2171 	if ((histents = malloc(histsize)) == NULL)
   2172 		err(1, "malloc history entries");
   2173 
   2174 	(void)memset(histents, 0, histsize);
   2175 
   2176 	(void)printf("%"PRIu32" entries, next is %"PRIu32"\n",
   2177 	    histp->n, histp->f);
   2178 
   2179 	deref_kptr(histp->e, histents, histsize, "history entries");
   2180 	i = histp->f;
   2181 	do {
   2182 		e = &histents[i];
   2183 		if (e->fmt != NULL) {
   2184 			if (fmt == NULL || e->fmtlen > fmtlen) {
   2185 				free(fmt);
   2186 				fmtlen = e->fmtlen;
   2187 				if ((fmt = malloc(fmtlen + 1)) == NULL)
   2188 					err(1, "malloc printf format");
   2189 			}
   2190 			if (fn == NULL || e->fnlen > fnlen) {
   2191 				free(fn);
   2192 				fnlen = e->fnlen;
   2193 				if ((fn = malloc(fnlen + 1)) == NULL)
   2194 					err(1, "malloc function name");
   2195 			}
   2196 
   2197 			deref_kptr(e->fmt, fmt, fmtlen, "printf format");
   2198 			fmt[fmtlen] = '\0';
   2199 			for (unsigned z = 0; z < fmtlen - 1; z++) {
   2200 				if (fmt[z] == '%' && fmt[z+1] == 's')
   2201 					fmt[z+1] = 'p';
   2202 			}
   2203 
   2204 			deref_kptr(e->fn, fn, fnlen, "function name");
   2205 			fn[fnlen] = '\0';
   2206 
   2207 			bintime2timeval(&e->bt, &tv);
   2208 			(void)printf("%06ld.%06ld ", (long int)tv.tv_sec,
   2209 			    (long int)tv.tv_usec);
   2210 			(void)printf("%s#%" PRId32 "@%" PRId32 "d: ",
   2211 			    fn, e->call, e->cpunum);
   2212 			(void)printf(fmt, e->v[0], e->v[1], e->v[2], e->v[3]);
   2213 			(void)putchar('\n');
   2214 		}
   2215 		i = (i + 1) % histp->n;
   2216 	} while (i != histp->f);
   2217 
   2218 	free(histents);
   2219 	free(fmt);
   2220 	free(fn);
   2221 }
   2222 
   2223 void
   2224 hist_traverse_sysctl(int todo, const char *histname)
   2225 {
   2226 	int error;
   2227 	int mib[4];
   2228 	unsigned int i;
   2229 	size_t len, miblen;
   2230 	struct sysctlnode query, histnode[32];
   2231 
   2232 	/* retrieve names of available histories */
   2233 	miblen = __arraycount(mib);
   2234 	error = sysctlnametomib("kern.hist", mib, &miblen);
   2235 	if (error != 0) {
   2236 		if (errno == ENOENT) {
   2237  			warnx("kernel history is not compiled into the kernel.");
   2238 			return;
   2239 		} else
   2240 			err(EXIT_FAILURE, "nametomib failed");
   2241 	}
   2242 
   2243 	/* get the list of nodenames below kern.hist */
   2244 	mib[2] = CTL_QUERY;
   2245 	memset(&query, 0, sizeof(query));
   2246 	query.sysctl_flags = SYSCTL_VERSION;
   2247 	len = sizeof(histnode);
   2248 	error = sysctl(mib, 3, &histnode[0], &len, &query, sizeof(query));
   2249 	if (error != 0) {
   2250 		err(1, "query failed");
   2251 		return;
   2252 	}
   2253 	if (len == 0) {
   2254  		warnx("No active kernel history logs.");
   2255  		return;
   2256  	}
   2257 
   2258 	len = len / sizeof(histnode[0]);	/* get # of entries returned */
   2259 
   2260  	if (todo & HISTLIST)
   2261  		(void)printf("Active kernel histories:");
   2262 
   2263 	for (i = 0; i < len; i++) {
   2264  		if (todo & HISTLIST)
   2265 			(void)printf(" %s", histnode[i].sysctl_name);
   2266  		else {
   2267  			/*
   2268  			 * If we're dumping all histories, do it, else
   2269  			 * check to see if this is the one we want.
   2270  			 */
   2271 			if (histname == NULL ||
   2272 			    strcmp(histname, histnode[i].sysctl_name) == 0) {
   2273  				if (histname == NULL)
   2274  					(void)printf(
   2275 					    "\nkernel history `%s':\n",
   2276 					    histnode[i].sysctl_name);
   2277 				mib[2] = histnode[i].sysctl_num;
   2278 				mib[3] = CTL_EOL;
   2279 				hist_dodump_sysctl(mib, 4);
   2280  			}
   2281  		}
   2282  	}
   2283 
   2284  	if (todo & HISTLIST)
   2285  		(void)putchar('\n');
   2286 	else if (mib[2] == CTL_QUERY)
   2287 		warnx("history %s not found", histname);
   2288  }
   2289 
   2290  /*
   2291   * Actually dump the history buffer at the specified KVA.
   2292   */
   2293 void
   2294 hist_dodump_sysctl(int mib[], unsigned int miblen)
   2295 {
   2296 	struct sysctl_history *hist;
   2297 	struct timeval tv;
   2298 	struct sysctl_history_event *e;
   2299  	size_t histsize;
   2300 	char *strp;
   2301  	unsigned i;
   2302 	char *fmt = NULL, *fn = NULL;
   2303 
   2304 	hist = NULL;
   2305 	histsize = 0;
   2306  	do {
   2307 		errno = 0;
   2308 		if (sysctl(mib, miblen, hist, &histsize, NULL, 0) == 0)
   2309 			break;
   2310 		if (errno != ENOMEM)
   2311 			break;
   2312 		if ((hist = realloc(hist, histsize)) == NULL)
   2313 			errx(1, "realloc history buffer");
   2314 	} while (errno == ENOMEM);
   2315 	if (errno != 0)
   2316 		err(1, "sysctl failed");
   2317 
   2318 	strp = (char *)(&hist->sh_events[hist->sh_numentries]);
   2319 
   2320 	(void)printf("%"PRIu32" entries, next is %"PRIu32"\n",
   2321 	    hist->sh_numentries,
   2322 	    hist->sh_nextfree);
   2323 
   2324 	i = hist->sh_nextfree;
   2325 
   2326 	do {
   2327 		e = &hist->sh_events[i];
   2328 		if (e->she_fmtoffset != 0) {
   2329 			fmt = &strp[e->she_fmtoffset];
   2330 			size_t fmtlen = strlen(fmt);
   2331 			for (unsigned z = 0; z < fmtlen - 1; z++) {
   2332 				if (fmt[z] == '%' && fmt[z+1] == 's')
   2333 					fmt[z+1] = 'p';
   2334 			}
   2335 			fn = &strp[e->she_funcoffset];
   2336 			bintime2timeval(&e->she_bintime, &tv);
   2337 			(void)printf("%06ld.%06ld %s#%"PRIu32"@%"PRIu32": ",
   2338 			    (long int)tv.tv_sec, (long int)tv.tv_usec,
   2339 			    fn, e->she_callnumber, e->she_cpunum);
   2340 			(void)printf(fmt, e->she_values[0], e->she_values[1],
   2341 			     e->she_values[2], e->she_values[3]);
   2342  			(void)putchar('\n');
   2343  		}
   2344 		i = (i + 1) % hist->sh_numentries;
   2345 	} while (i != hist->sh_nextfree);
   2346 
   2347 	free(hist);
   2348  }
   2349 
   2350 static void
   2351 usage(void)
   2352 {
   2353 
   2354 	(void)fprintf(stderr,
   2355 	    "usage: %s [-CefHiLlmstUvW] [-c count] [-h hashname] [-M core] [-N system]\n"
   2356 	    "\t\t[-u histname] [-w wait] [disks]\n", getprogname());
   2357 	exit(1);
   2358 }
   2359