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