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