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