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