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