xref: /netbsd-src/usr.bin/vmstat/vmstat.c (revision 4b896b232495b7a9b8b94a1cf1e21873296d53b8)
1 /* $NetBSD: vmstat.c,v 1.122 2004/02/28 05:14:55 junyoung Exp $ */
2 
3 /*-
4  * Copyright (c) 1998, 2000, 2001 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  * 3. All advertising materials mentioning features or use of this software
21  *    must display the following acknowledgement:
22  *	This product includes software developed by the NetBSD
23  *	Foundation, Inc. and its contributors.
24  * 4. Neither the name of The NetBSD Foundation nor the names of its
25  *    contributors may be used to endorse or promote products derived
26  *    from this software without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
29  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
30  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
31  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
32  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
33  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
34  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
35  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
36  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
37  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
38  * POSSIBILITY OF SUCH DAMAGE.
39  */
40 
41 /*
42  * Copyright (c) 1980, 1986, 1991, 1993
43  *	The Regents of the University of California.  All rights reserved.
44  *
45  * Redistribution and use in source and binary forms, with or without
46  * modification, are permitted provided that the following conditions
47  * are met:
48  * 1. Redistributions of source code must retain the above copyright
49  *    notice, this list of conditions and the following disclaimer.
50  * 2. Redistributions in binary form must reproduce the above copyright
51  *    notice, this list of conditions and the following disclaimer in the
52  *    documentation and/or other materials provided with the distribution.
53  * 3. Neither the name of the University nor the names of its contributors
54  *    may be used to endorse or promote products derived from this software
55  *    without specific prior written permission.
56  *
57  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
58  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
61  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
62  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
63  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
64  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
65  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67  * SUCH DAMAGE.
68  */
69 
70 #include <sys/cdefs.h>
71 #ifndef lint
72 __COPYRIGHT("@(#) Copyright (c) 1980, 1986, 1991, 1993\n\
73 	The Regents of the University of California.  All rights reserved.\n");
74 #endif /* not lint */
75 
76 #ifndef lint
77 #if 0
78 static char sccsid[] = "@(#)vmstat.c	8.2 (Berkeley) 3/1/95";
79 #else
80 __RCSID("$NetBSD: vmstat.c,v 1.122 2004/02/28 05:14:55 junyoung Exp $");
81 #endif
82 #endif /* not lint */
83 
84 #define	__POOL_EXPOSE
85 
86 #include <sys/param.h>
87 #include <sys/mount.h>
88 #include <sys/uio.h>
89 
90 #include <sys/buf.h>
91 #include <sys/device.h>
92 #include <sys/ioctl.h>
93 #include <sys/malloc.h>
94 #include <sys/mallocvar.h>
95 #include <sys/namei.h>
96 #include <sys/pool.h>
97 #include <sys/proc.h>
98 #include <sys/sched.h>
99 #include <sys/socket.h>
100 #include <sys/sysctl.h>
101 #include <sys/time.h>
102 #include <sys/user.h>
103 
104 #include <uvm/uvm_extern.h>
105 #include <uvm/uvm_stat.h>
106 
107 #include <net/if.h>
108 #include <netinet/in.h>
109 #include <netinet/in_var.h>
110 
111 #include <ufs/ufs/inode.h>
112 
113 #include <nfs/rpcv2.h>
114 #include <nfs/nfsproto.h>
115 #include <nfs/nfsnode.h>
116 
117 #include <ctype.h>
118 #include <err.h>
119 #include <errno.h>
120 #include <fcntl.h>
121 #include <kvm.h>
122 #include <limits.h>
123 #include <nlist.h>
124 #undef n_hash
125 #include <paths.h>
126 #include <signal.h>
127 #include <stdio.h>
128 #include <stddef.h>
129 #include <stdlib.h>
130 #include <string.h>
131 #include <time.h>
132 #include <unistd.h>
133 #include <util.h>
134 
135 #include "dkstats.h"
136 
137 /*
138  * General namelist
139  */
140 struct nlist namelist[] =
141 {
142 #define	X_BOOTTIME	0
143 	{ "_boottime" },
144 #define	X_HZ		1
145 	{ "_hz" },
146 #define	X_STATHZ	2
147 	{ "_stathz" },
148 #define	X_NCHSTATS	3
149 	{ "_nchstats" },
150 #define	X_INTRNAMES	4
151 	{ "_intrnames" },
152 #define	X_EINTRNAMES	5
153 	{ "_eintrnames" },
154 #define	X_INTRCNT	6
155 	{ "_intrcnt" },
156 #define	X_EINTRCNT	7
157 	{ "_eintrcnt" },
158 #define	X_KMEMSTAT	8
159 	{ "_kmemstatistics" },
160 #define	X_KMEMBUCKETS	9
161 	{ "_bucket" },
162 #define	X_ALLEVENTS	10
163 	{ "_allevents" },
164 #define	X_POOLHEAD	11
165 	{ "_pool_head" },
166 #define	X_UVMEXP	12
167 	{ "_uvmexp" },
168 #define	X_TIME		13
169 	{ "_time" },
170 #define	X_END		14
171 	{ NULL },
172 };
173 
174 /*
175  * Namelist for hash statistics
176  */
177 struct nlist hashnl[] =
178 {
179 #define	X_NFSNODE	0
180 	{ "_nfsnodehash" },
181 #define	X_NFSNODETBL	1
182 	{ "_nfsnodehashtbl" },
183 #define	X_IHASH		2
184 	{ "_ihash" },
185 #define	X_IHASHTBL	3
186 	{ "_ihashtbl" },
187 #define	X_BUFHASH	4
188 	{ "_bufhash" },
189 #define	X_BUFHASHTBL	5
190 	{ "_bufhashtbl" },
191 #define	X_UIHASH	6
192 	{ "_uihash" },
193 #define	X_UIHASHTBL	7
194 	{ "_uihashtbl" },
195 #define	X_IFADDRHASH	8
196 	{ "_in_ifaddrhash" },
197 #define	X_IFADDRHASHTBL	9
198 	{ "_in_ifaddrhashtbl" },
199 #define	X_NCHASH	10
200 	{ "_nchash" },
201 #define	X_NCHASHTBL	11
202 	{ "_nchashtbl" },
203 #define	X_NCVHASH	12
204 	{ "_ncvhash" },
205 #define	X_NCVHASHTBL	13
206 	{ "_ncvhashtbl" },
207 #define X_HASHNL_SIZE	14	/* must be last */
208 	{ NULL },
209 };
210 
211 /*
212  * Namelist for UVM histories
213  */
214 struct nlist histnl[] =
215 {
216 	{ "_uvm_histories" },
217 #define	X_UVM_HISTORIES		0
218 	{ NULL },
219 };
220 
221 
222 
223 struct	uvmexp uvmexp, ouvmexp;
224 int	ndrives;
225 
226 int	winlines = 20;
227 
228 kvm_t *kd;
229 
230 #define	FORKSTAT	1<<0
231 #define	INTRSTAT	1<<1
232 #define	MEMSTAT		1<<2
233 #define	SUMSTAT		1<<3
234 #define	EVCNTSTAT	1<<4
235 #define	VMSTAT		1<<5
236 #define	HISTLIST	1<<6
237 #define	HISTDUMP	1<<7
238 #define	HASHSTAT	1<<8
239 #define	HASHLIST	1<<9
240 
241 void	cpustats(void);
242 void	deref_kptr(const void *, void *, size_t, const char *);
243 void	dkstats(void);
244 void	doevcnt(int verbose);
245 void	dohashstat(int, int, const char *);
246 void	dointr(int verbose);
247 void	domem(void);
248 void	dopool(int);
249 void	dopoolcache(struct pool *, int);
250 void	dosum(void);
251 void	dovmstat(struct timespec *, int);
252 void	kread(int, void *, size_t);
253 void	needhdr(int);
254 long	getuptime(void);
255 void	printhdr(void);
256 long	pct(long, long);
257 void	usage(void);
258 void	doforkst(void);
259 
260 void	hist_traverse(int, const char *);
261 void	hist_dodump(struct uvm_history *);
262 
263 int	main(int, char **);
264 char	**choosedrives(char **);
265 
266 /* Namelist and memory file names. */
267 char	*nlistf, *memf;
268 
269 /* allow old usage [vmstat 1] */
270 #define	BACKWARD_COMPATIBILITY
271 
272 int
273 main(int argc, char *argv[])
274 {
275 	int c, todo, verbose;
276 	struct timespec interval;
277 	int reps;
278 	char errbuf[_POSIX2_LINE_MAX];
279 	gid_t egid = getegid();
280 	const char *histname, *hashname;
281 
282 	histname = hashname = NULL;
283 	(void)setegid(getgid());
284 	memf = nlistf = NULL;
285 	reps = todo = verbose = 0;
286 	interval.tv_sec = 0;
287 	interval.tv_nsec = 0;
288 	while ((c = getopt(argc, argv, "c:efh:HilLM:mN:su:Uvw:")) != -1) {
289 		switch (c) {
290 		case 'c':
291 			reps = atoi(optarg);
292 			break;
293 		case 'e':
294 			todo |= EVCNTSTAT;
295 			break;
296 		case 'f':
297 			todo |= FORKSTAT;
298 			break;
299 		case 'h':
300 			hashname = optarg;
301 			/* FALLTHROUGH */
302 		case 'H':
303 			todo |= HASHSTAT;
304 			break;
305 		case 'i':
306 			todo |= INTRSTAT;
307 			break;
308 		case 'l':
309 			todo |= HISTLIST;
310 			break;
311 		case 'L':
312 			todo |= HASHLIST;
313 			break;
314 		case 'M':
315 			memf = optarg;
316 			break;
317 		case 'm':
318 			todo |= MEMSTAT;
319 			break;
320 		case 'N':
321 			nlistf = optarg;
322 			break;
323 		case 's':
324 			todo |= SUMSTAT;
325 			break;
326 		case 'u':
327 			histname = optarg;
328 			/* FALLTHROUGH */
329 		case 'U':
330 			todo |= HISTDUMP;
331 			break;
332 		case 'v':
333 			verbose++;
334 			break;
335 		case 'w':
336 			interval.tv_sec = atol(optarg);
337 			break;
338 		case '?':
339 		default:
340 			usage();
341 		}
342 	}
343 	argc -= optind;
344 	argv += optind;
345 
346 	if (todo == 0)
347 		todo = VMSTAT;
348 
349 	/*
350 	 * Discard setgid privileges.  If not the running kernel, we toss
351 	 * them away totally so that bad guys can't print interesting stuff
352 	 * from kernel memory, otherwise switch back to kmem for the
353 	 * duration of the kvm_openfiles() call.
354 	 */
355 	if (nlistf != NULL || memf != NULL)
356 		(void)setgid(getgid());
357 	else
358 		(void)setegid(egid);
359 
360 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
361 	if (kd == NULL)
362 		errx(1, "kvm_openfiles: %s", errbuf);
363 
364 	if (nlistf == NULL && memf == NULL)
365 		(void)setgid(getgid());
366 
367 	if ((c = kvm_nlist(kd, namelist)) != 0) {
368 		if (c == -1)
369 			errx(1, "kvm_nlist: %s %s", "namelist", kvm_geterr(kd));
370 		(void)fprintf(stderr, "vmstat: undefined symbols:");
371 		for (c = 0; c < sizeof(namelist) / sizeof(namelist[0])-1; c++)
372 			if (namelist[c].n_type == 0)
373 				fprintf(stderr, " %s", namelist[c].n_name);
374 		(void)fputc('\n', stderr);
375 		exit(1);
376 	}
377 	if ((c = kvm_nlist(kd, hashnl)) == -1 || c == X_HASHNL_SIZE)
378 		errx(1, "kvm_nlist: %s %s", "hashnl", kvm_geterr(kd));
379 	if (kvm_nlist(kd, histnl) == -1)
380 		errx(1, "kvm_nlist: %s %s", "histnl", kvm_geterr(kd));
381 
382 	if (todo & VMSTAT) {
383 		struct winsize winsize;
384 
385 		dkinit(0);	/* Initialize disk stats, no disks selected. */
386 
387 		(void)setgid(getgid()); /* don't need privs anymore */
388 
389 		argv = choosedrives(argv);	/* Select disks. */
390 		winsize.ws_row = 0;
391 		(void)ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
392 		if (winsize.ws_row > 0)
393 			winlines = winsize.ws_row;
394 
395 	}
396 
397 #ifdef	BACKWARD_COMPATIBILITY
398 	if (*argv) {
399 		interval.tv_sec = atol(*argv);
400 		if (*++argv)
401 			reps = atoi(*argv);
402 	}
403 #endif
404 
405 	if (interval.tv_sec) {
406 		if (!reps)
407 			reps = -1;
408 	} else if (reps)
409 		interval.tv_sec = 1;
410 
411 
412 	/*
413 	 * Statistics dumping is incompatible with the default
414 	 * VMSTAT/dovmstat() output. So perform the interval/reps handling
415 	 * for it here.
416 	 */
417 	if ((todo & VMSTAT) == 0) {
418 		for (;;) {
419 			if (todo & (HISTLIST|HISTDUMP)) {
420 				if ((todo & (HISTLIST|HISTDUMP)) ==
421 				    (HISTLIST|HISTDUMP))
422 					errx(1, "you may list or dump,"
423 					    " but not both!");
424 				hist_traverse(todo, histname);
425 				putchar('\n');
426 			}
427 			if (todo & FORKSTAT) {
428 				doforkst();
429 				putchar('\n');
430 			}
431 			if (todo & MEMSTAT) {
432 				domem();
433 				dopool(verbose);
434 				putchar('\n');
435 			}
436 			if (todo & SUMSTAT) {
437 				dosum();
438 				putchar('\n');
439 			}
440 			if (todo & INTRSTAT) {
441 				dointr(verbose);
442 				putchar('\n');
443 			}
444 			if (todo & EVCNTSTAT) {
445 				doevcnt(verbose);
446 				putchar('\n');
447 			}
448 			if (todo & (HASHLIST|HASHSTAT)) {
449 				if ((todo & (HASHLIST|HASHSTAT)) ==
450 				    (HASHLIST|HASHSTAT))
451 					errx(1, "you may list or display,"
452 					    " but not both!");
453 				dohashstat(verbose, todo, hashname);
454 				putchar('\n');
455 			}
456 
457 			if (reps >= 0 && --reps <=0)
458 				break;
459 			nanosleep(&interval, NULL);
460 		}
461 	} else
462 		dovmstat(&interval, reps);
463 	exit(0);
464 }
465 
466 char **
467 choosedrives(char **argv)
468 {
469 	int i;
470 
471 	/*
472 	 * Choose drives to be displayed.  Priority goes to (in order) drives
473 	 * supplied as arguments, default drives.  If everything isn't filled
474 	 * in and there are drives not taken care of, display the first few
475 	 * that fit.
476 	 */
477 #define	BACKWARD_COMPATIBILITY
478 	for (ndrives = 0; *argv; ++argv) {
479 #ifdef	BACKWARD_COMPATIBILITY
480 		if (isdigit(**argv))
481 			break;
482 #endif
483 		for (i = 0; i < dk_ndrive; i++) {
484 			if (strcmp(dr_name[i], *argv))
485 				continue;
486 			dk_select[i] = 1;
487 			++ndrives;
488 			break;
489 		}
490 	}
491 	for (i = 0; i < dk_ndrive && ndrives < 3; i++) {
492 		if (dk_select[i])
493 			continue;
494 		dk_select[i] = 1;
495 		++ndrives;
496 	}
497 	return (argv);
498 }
499 
500 long
501 getuptime(void)
502 {
503 	static struct timeval boottime;
504 	struct timeval now, diff;
505 	time_t uptime;
506 
507 	if (boottime.tv_sec == 0)
508 		kread(X_BOOTTIME, &boottime, sizeof(boottime));
509 	kread(X_TIME, &now, sizeof(now));
510 	timersub(&now, &boottime, &diff);
511 	uptime = diff.tv_sec;
512 	if (uptime <= 0 || uptime > 60*60*24*365*10)
513 		errx(1, "time makes no sense; namelist must be wrong.");
514 	return (uptime);
515 }
516 
517 int	hz, hdrcnt;
518 
519 void
520 dovmstat(struct timespec *interval, int reps)
521 {
522 	struct vmtotal total;
523 	time_t uptime, halfuptime;
524 	int mib[2];
525 	size_t size;
526 	int pagesize = getpagesize();
527 
528 	uptime = getuptime();
529 	halfuptime = uptime / 2;
530 	(void)signal(SIGCONT, needhdr);
531 
532 	if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
533 		kread(X_STATHZ, &hz, sizeof(hz));
534 	if (!hz)
535 		kread(X_HZ, &hz, sizeof(hz));
536 
537 	for (hdrcnt = 1;;) {
538 		if (!--hdrcnt)
539 			printhdr();
540 		/* Read new disk statistics */
541 		dkreadstats();
542 		kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
543 		if (memf != NULL) {
544 			/*
545 			 * XXX Can't do this if we're reading a crash
546 			 * XXX dump because they're lazily-calculated.
547 			 */
548 			printf("Unable to get vmtotals from crash dump.\n");
549 			memset(&total, 0, sizeof(total));
550 		} else {
551 			size = sizeof(total);
552 			mib[0] = CTL_VM;
553 			mib[1] = VM_METER;
554 			if (sysctl(mib, 2, &total, &size, NULL, 0) < 0) {
555 				printf("Can't get vmtotals: %s\n",
556 				    strerror(errno));
557 				memset(&total, 0, sizeof(total));
558 			}
559 		}
560 		(void)printf("%2d %d %d",
561 		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
562 #define	pgtok(a) (long)((a) * (pagesize >> 10))
563 #define	rate(x)	(u_long)(((x) + halfuptime) / uptime)	/* round */
564 		(void)printf(" %6ld %6ld ",
565 		    pgtok(total.t_avm), pgtok(total.t_free));
566 		(void)printf("%4lu ", rate(uvmexp.faults - ouvmexp.faults));
567 		(void)printf("%3lu ", rate(uvmexp.pdreact - ouvmexp.pdreact));
568 		(void)printf("%3lu ", rate(uvmexp.pageins - ouvmexp.pageins));
569 		(void)printf("%4lu ",
570 		    rate(uvmexp.pgswapout - ouvmexp.pgswapout));
571 		(void)printf("%4lu ", rate(uvmexp.pdfreed - ouvmexp.pdfreed));
572 		(void)printf("%4lu ", rate(uvmexp.pdscans - ouvmexp.pdscans));
573 		dkstats();
574 		(void)printf("%4lu %4lu %3lu ",
575 		    rate(uvmexp.intrs - ouvmexp.intrs),
576 		    rate(uvmexp.syscalls - ouvmexp.syscalls),
577 		    rate(uvmexp.swtch - ouvmexp.swtch));
578 		cpustats();
579 		putchar('\n');
580 		(void)fflush(stdout);
581 		if (reps >= 0 && --reps <= 0)
582 			break;
583 		ouvmexp = uvmexp;
584 		uptime = interval->tv_sec;
585 		/*
586 		 * We round upward to avoid losing low-frequency events
587 		 * (i.e., >= 1 per interval but < 1 per second).
588 		 */
589 		halfuptime = uptime == 1 ? 0 : (uptime + 1) / 2;
590 		nanosleep(interval, NULL);
591 	}
592 }
593 
594 void
595 printhdr(void)
596 {
597 	int i;
598 
599 	(void)printf(" procs    memory      page%*s", 23, "");
600 	if (ndrives > 0)
601 		(void)printf("%s %*sfaults      cpu\n",
602 		    ((ndrives > 1) ? "disks" : "disk"),
603 		    ((ndrives > 1) ? ndrives * 3 - 4 : 0), "");
604 	else
605 		(void)printf("%*s  faults   cpu\n",
606 		    ndrives * 3, "");
607 
608 	(void)printf(" r b w    avm    fre  flt  re  pi   po   fr   sr ");
609 	for (i = 0; i < dk_ndrive; i++)
610 		if (dk_select[i])
611 			(void)printf("%c%c ", dr_name[i][0],
612 			    dr_name[i][strlen(dr_name[i]) - 1]);
613 	(void)printf("  in   sy  cs us sy id\n");
614 	hdrcnt = winlines - 2;
615 }
616 
617 /*
618  * Force a header to be prepended to the next output.
619  */
620 void
621 needhdr(int dummy)
622 {
623 
624 	hdrcnt = 1;
625 }
626 
627 long
628 pct(long top, long bot)
629 {
630 	long ans;
631 
632 	if (bot == 0)
633 		return (0);
634 	ans = (quad_t)top * 100 / bot;
635 	return (ans);
636 }
637 
638 #define	PCT(top, bot) (int)pct((long)(top), (long)(bot))
639 
640 void
641 dosum(void)
642 {
643 	struct nchstats nchstats;
644 	long nchtotal;
645 
646 	kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
647 
648 	(void)printf("%9u bytes per page\n", uvmexp.pagesize);
649 
650 	(void)printf("%9u page color%s\n",
651 	    uvmexp.ncolors, uvmexp.ncolors == 1 ? "" : "s");
652 
653 	(void)printf("%9u pages managed\n", uvmexp.npages);
654 	(void)printf("%9u pages free\n", uvmexp.free);
655 	(void)printf("%9u pages active\n", uvmexp.active);
656 	(void)printf("%9u pages inactive\n", uvmexp.inactive);
657 	(void)printf("%9u pages paging\n", uvmexp.paging);
658 	(void)printf("%9u pages wired\n", uvmexp.wired);
659 	(void)printf("%9u zero pages\n", uvmexp.zeropages);
660 	(void)printf("%9u reserve pagedaemon pages\n",
661 	    uvmexp.reserve_pagedaemon);
662 	(void)printf("%9u reserve kernel pages\n", uvmexp.reserve_kernel);
663 	(void)printf("%9u anonymous pages\n", uvmexp.anonpages);
664 	(void)printf("%9u cached file pages\n", uvmexp.filepages);
665 	(void)printf("%9u cached executable pages\n", uvmexp.execpages);
666 
667 	(void)printf("%9u minimum free pages\n", uvmexp.freemin);
668 	(void)printf("%9u target free pages\n", uvmexp.freetarg);
669 	(void)printf("%9u target inactive pages\n", uvmexp.inactarg);
670 	(void)printf("%9u maximum wired pages\n", uvmexp.wiredmax);
671 
672 	(void)printf("%9u swap devices\n", uvmexp.nswapdev);
673 	(void)printf("%9u swap pages\n", uvmexp.swpages);
674 	(void)printf("%9u swap pages in use\n", uvmexp.swpginuse);
675 	(void)printf("%9u swap allocations\n", uvmexp.nswget);
676 	(void)printf("%9u anons\n", uvmexp.nanon);
677 	(void)printf("%9u free anons\n", uvmexp.nfreeanon);
678 
679 	(void)printf("%9u total faults taken\n", uvmexp.faults);
680 	(void)printf("%9u traps\n", uvmexp.traps);
681 	(void)printf("%9u device interrupts\n", uvmexp.intrs);
682 	(void)printf("%9u CPU context switches\n", uvmexp.swtch);
683 	(void)printf("%9u software interrupts\n", uvmexp.softs);
684 	(void)printf("%9u system calls\n", uvmexp.syscalls);
685 	(void)printf("%9u pagein requests\n", uvmexp.pageins);
686 	(void)printf("%9u pageout requests\n", uvmexp.pdpageouts);
687 	(void)printf("%9u swap ins\n", uvmexp.swapins);
688 	(void)printf("%9u swap outs\n", uvmexp.swapouts);
689 	(void)printf("%9u pages swapped in\n", uvmexp.pgswapin);
690 	(void)printf("%9u pages swapped out\n", uvmexp.pgswapout);
691 	(void)printf("%9u forks total\n", uvmexp.forks);
692 	(void)printf("%9u forks blocked parent\n", uvmexp.forks_ppwait);
693 	(void)printf("%9u forks shared address space with parent\n",
694 	    uvmexp.forks_sharevm);
695 	(void)printf("%9u pagealloc zero wanted and avail\n",
696 	    uvmexp.pga_zerohit);
697 	(void)printf("%9u pagealloc zero wanted and not avail\n",
698 	    uvmexp.pga_zeromiss);
699 	(void)printf("%9u aborts of idle page zeroing\n",
700 	    uvmexp.zeroaborts);
701 	(void)printf("%9u pagealloc desired color avail\n",
702 	    uvmexp.colorhit);
703 	(void)printf("%9u pagealloc desired color not avail\n",
704 	    uvmexp.colormiss);
705 
706 	(void)printf("%9u faults with no memory\n", uvmexp.fltnoram);
707 	(void)printf("%9u faults with no anons\n", uvmexp.fltnoanon);
708 	(void)printf("%9u faults had to wait on pages\n", uvmexp.fltpgwait);
709 	(void)printf("%9u faults found released page\n", uvmexp.fltpgrele);
710 	(void)printf("%9u faults relock (%u ok)\n", uvmexp.fltrelck,
711 	    uvmexp.fltrelckok);
712 	(void)printf("%9u anon page faults\n", uvmexp.fltanget);
713 	(void)printf("%9u anon retry faults\n", uvmexp.fltanretry);
714 	(void)printf("%9u amap copy faults\n", uvmexp.fltamcopy);
715 	(void)printf("%9u neighbour anon page faults\n", uvmexp.fltnamap);
716 	(void)printf("%9u neighbour object page faults\n", uvmexp.fltnomap);
717 	(void)printf("%9u locked pager get faults\n", uvmexp.fltlget);
718 	(void)printf("%9u unlocked pager get faults\n", uvmexp.fltget);
719 	(void)printf("%9u anon faults\n", uvmexp.flt_anon);
720 	(void)printf("%9u anon copy on write faults\n", uvmexp.flt_acow);
721 	(void)printf("%9u object faults\n", uvmexp.flt_obj);
722 	(void)printf("%9u promote copy faults\n", uvmexp.flt_prcopy);
723 	(void)printf("%9u promote zero fill faults\n", uvmexp.flt_przero);
724 
725 	(void)printf("%9u times daemon wokeup\n",uvmexp.pdwoke);
726 	(void)printf("%9u revolutions of the clock hand\n", uvmexp.pdrevs);
727 	(void)printf("%9u times daemon attempted swapout\n", uvmexp.pdswout);
728 	(void)printf("%9u pages freed by daemon\n", uvmexp.pdfreed);
729 	(void)printf("%9u pages scanned by daemon\n", uvmexp.pdscans);
730 	(void)printf("%9u anonymous pages scanned by daemon\n",
731 	    uvmexp.pdanscan);
732 	(void)printf("%9u object pages scanned by daemon\n", uvmexp.pdobscan);
733 	(void)printf("%9u pages reactivated\n", uvmexp.pdreact);
734 	(void)printf("%9u pages found busy by daemon\n", uvmexp.pdbusy);
735 	(void)printf("%9u total pending pageouts\n", uvmexp.pdpending);
736 	(void)printf("%9u pages deactivated\n", uvmexp.pddeact);
737 	kread(X_NCHSTATS, &nchstats, sizeof(nchstats));
738 	nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
739 	    nchstats.ncs_badhits + nchstats.ncs_falsehits +
740 	    nchstats.ncs_miss + nchstats.ncs_long;
741 	(void)printf("%9ld total name lookups\n", nchtotal);
742 	(void)printf(
743 	    "%9s cache hits (%d%% pos + %d%% neg) system %d%% per-process\n",
744 	    "", PCT(nchstats.ncs_goodhits, nchtotal),
745 	    PCT(nchstats.ncs_neghits, nchtotal),
746 	    PCT(nchstats.ncs_pass2, nchtotal));
747 	(void)printf("%9s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
748 	    PCT(nchstats.ncs_badhits, nchtotal),
749 	    PCT(nchstats.ncs_falsehits, nchtotal),
750 	    PCT(nchstats.ncs_long, nchtotal));
751 }
752 
753 void
754 doforkst(void)
755 {
756 
757 	kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
758 
759 	(void)printf("%u forks total\n", uvmexp.forks);
760 	(void)printf("%u forks blocked parent\n", uvmexp.forks_ppwait);
761 	(void)printf("%u forks shared address space with parent\n",
762 	    uvmexp.forks_sharevm);
763 }
764 
765 void
766 dkstats(void)
767 {
768 	int dn;
769 	double etime;
770 
771 	/* Calculate disk stat deltas. */
772 	dkswap();
773 	etime = cur.cp_etime;
774 
775 	for (dn = 0; dn < dk_ndrive; ++dn) {
776 		if (!dk_select[dn])
777 			continue;
778 		(void)printf("%2.0f ",
779 		    (cur.dk_rxfer[dn] + cur.dk_wxfer[dn]) / etime);
780 	}
781 }
782 
783 void
784 cpustats(void)
785 {
786 	int state;
787 	double pct, total;
788 	double stat_us, stat_sy, stat_id;
789 
790 	total = 0;
791 	for (state = 0; state < CPUSTATES; ++state)
792 		total += cur.cp_time[state];
793 	if (total)
794 		pct = 100 / total;
795 	else
796 		pct = 0;
797 	stat_us = (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * pct;
798 	stat_sy = (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * pct;
799 	stat_id = cur.cp_time[CP_IDLE] * pct;
800 	(void)printf("%*.0f ", ((stat_sy >= 100) ? 1 : 2), stat_us);
801 	(void)printf("%*.0f ", ((stat_us >= 100 || stat_id >= 100) ? 1 : 2), stat_sy);
802 	(void)printf("%2.0f", stat_id);
803 }
804 
805 void
806 dointr(int verbose)
807 {
808 	unsigned long *intrcnt;
809 	unsigned long long inttotal, uptime;
810 	int nintr, inamlen;
811 	char *intrname;
812 	struct evcntlist allevents;
813 	struct evcnt evcnt, *evptr;
814 	char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
815 
816 	uptime = getuptime();
817 	nintr = namelist[X_EINTRCNT].n_value - namelist[X_INTRCNT].n_value;
818 	inamlen =
819 	    namelist[X_EINTRNAMES].n_value - namelist[X_INTRNAMES].n_value;
820 	intrcnt = malloc((size_t)nintr);
821 	intrname = malloc((size_t)inamlen);
822 	if (intrcnt == NULL || intrname == NULL)
823 		errx(1, "%s", "");
824 	kread(X_INTRCNT, intrcnt, (size_t)nintr);
825 	kread(X_INTRNAMES, intrname, (size_t)inamlen);
826 	(void)printf("%-34s %16s %8s\n", "interrupt", "total", "rate");
827 	inttotal = 0;
828 	nintr /= sizeof(long);
829 	while (--nintr >= 0) {
830 		if (*intrcnt || verbose)
831 			(void)printf("%-34s %16llu %8llu\n", intrname,
832 			    (unsigned long long)*intrcnt,
833 			    (unsigned long long)(*intrcnt / uptime));
834 		intrname += strlen(intrname) + 1;
835 		inttotal += *intrcnt++;
836 	}
837 	kread(X_ALLEVENTS, &allevents, sizeof allevents);
838 	evptr = allevents.tqh_first;
839 	while (evptr) {
840 		deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
841 		evptr = evcnt.ev_list.tqe_next;
842 		if (evcnt.ev_type != EVCNT_TYPE_INTR)
843 			continue;
844 
845 		if (evcnt.ev_count == 0 && !verbose)
846 			continue;
847 
848 		deref_kptr(evcnt.ev_group, evgroup, evcnt.ev_grouplen + 1,
849 		    "event chain trashed");
850 		deref_kptr(evcnt.ev_name, evname, evcnt.ev_namelen + 1,
851 		    "event chain trashed");
852 
853 		(void)printf("%s %s%*s %16llu %8llu\n", evgroup, evname,
854 		    34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
855 		    (unsigned long long)evcnt.ev_count,
856 		    (unsigned long long)(evcnt.ev_count / uptime));
857 
858 		inttotal += evcnt.ev_count++;
859 	}
860 	(void)printf("%-34s %16llu %8llu\n", "Total", inttotal,
861 	    (unsigned long long)(inttotal / uptime));
862 }
863 
864 void
865 doevcnt(int verbose)
866 {
867 	static const char * evtypes [] = { "misc", "intr", "trap" };
868 	unsigned long long uptime;
869 	struct evcntlist allevents;
870 	struct evcnt evcnt, *evptr;
871 	char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
872 
873 	/* XXX should print type! */
874 
875 	uptime = getuptime();
876 	(void)printf("%-34s %16s %8s %s\n", "event", "total", "rate", "type");
877 	kread(X_ALLEVENTS, &allevents, sizeof allevents);
878 	evptr = allevents.tqh_first;
879 	while (evptr) {
880 		deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
881 
882 		evptr = evcnt.ev_list.tqe_next;
883 		if (evcnt.ev_count == 0 && !verbose)
884 			continue;
885 
886 		deref_kptr(evcnt.ev_group, evgroup, evcnt.ev_grouplen + 1,
887 		    "event chain trashed");
888 		deref_kptr(evcnt.ev_name, evname, evcnt.ev_namelen + 1,
889 		    "event chain trashed");
890 
891 		(void)printf("%s %s%*s %16llu %8llu %s\n", evgroup, evname,
892 		    34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
893 		    (unsigned long long)evcnt.ev_count,
894 		    (unsigned long long)(evcnt.ev_count / uptime),
895 		    (evcnt.ev_type < sizeof(evtypes)/sizeof(evtypes[0]) ?
896 			evtypes[evcnt.ev_type] : "?"));
897 	}
898 }
899 
900 static char memname[64];
901 
902 void
903 domem(void)
904 {
905 	struct kmembuckets *kp;
906 	struct malloc_type ks, *ksp;
907 	int i, j;
908 	int len, size, first;
909 	long totuse = 0, totfree = 0, totreq = 0;
910 	struct kmembuckets buckets[MINBUCKET + 16];
911 
912 	kread(X_KMEMBUCKETS, buckets, sizeof(buckets));
913 	for (first = 1, i = MINBUCKET, kp = &buckets[i]; i < MINBUCKET + 16;
914 	    i++, kp++) {
915 		if (kp->kb_calls == 0)
916 			continue;
917 		if (first) {
918 			(void)printf("Memory statistics by bucket size\n");
919 			(void)printf(
920 		 "    Size   In Use   Free   Requests  HighWater  Couldfree\n");
921 			first = 0;
922 		}
923 		size = 1 << i;
924 		(void)printf("%8d %8ld %6ld %10ld %7ld %10ld\n", size,
925 		    kp->kb_total - kp->kb_totalfree,
926 		    kp->kb_totalfree, kp->kb_calls,
927 		    kp->kb_highwat, kp->kb_couldfree);
928 		totfree += size * kp->kb_totalfree;
929 	}
930 
931 	/*
932 	 * If kmem statistics are not being gathered by the kernel,
933 	 * first will still be 1.
934 	 */
935 	if (first) {
936 		warnx("Kmem statistics are not being gathered by the kernel.");
937 		return;
938 	}
939 
940 	(void)printf("\nMemory usage type by bucket size\n");
941 	(void)printf("    Size  Type(s)\n");
942 	kp = &buckets[MINBUCKET];
943 	for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1, kp++) {
944 		if (kp->kb_calls == 0)
945 			continue;
946 		first = 1;
947 		len = 8;
948 		for (kread(X_KMEMSTAT, &ksp, sizeof(ksp));
949 		     ksp != NULL; ksp = ks.ks_next) {
950 			deref_kptr(ksp, &ks, sizeof(ks), "malloc type");
951 			if (ks.ks_calls == 0)
952 				continue;
953 			if ((ks.ks_size & j) == 0)
954 				continue;
955 			deref_kptr(ks.ks_shortdesc, memname,
956 			    sizeof(memname), "malloc type name");
957 			len += 2 + strlen(memname);
958 			if (first)
959 				printf("%8d  %s", j, memname);
960 			else
961 				printf(",");
962 			if (len >= 80) {
963 				printf("\n\t ");
964 				len = 10 + strlen(memname);
965 			}
966 			if (!first)
967 				printf(" %s", memname);
968 			first = 0;
969 		}
970 		putchar('\n');
971 	}
972 
973 	(void)printf(
974 	    "\nMemory statistics by type                           Type  Kern\n");
975 	(void)printf(
976 "         Type  InUse MemUse HighUse  Limit Requests Limit Limit Size(s)\n");
977 	for (kread(X_KMEMSTAT, &ksp, sizeof(ksp));
978 	     ksp != NULL; ksp = ks.ks_next) {
979 		deref_kptr(ksp, &ks, sizeof(ks), "malloc type");
980 		if (ks.ks_calls == 0)
981 			continue;
982 		deref_kptr(ks.ks_shortdesc, memname,
983 		    sizeof(memname), "malloc type name");
984 		(void)printf("%14s%6ld%6ldK%7ldK%6ldK%9ld%5u%6u",
985 		    memname,
986 		    ks.ks_inuse, (ks.ks_memuse + 1023) / 1024,
987 		    (ks.ks_maxused + 1023) / 1024,
988 		    (ks.ks_limit + 1023) / 1024, ks.ks_calls,
989 		    ks.ks_limblocks, ks.ks_mapblocks);
990 		first = 1;
991 		for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
992 			if ((ks.ks_size & j) == 0)
993 				continue;
994 			if (first)
995 				printf("  %d", j);
996 			else
997 				printf(",%d", j);
998 			first = 0;
999 		}
1000 		printf("\n");
1001 		totuse += ks.ks_memuse;
1002 		totreq += ks.ks_calls;
1003 	}
1004 	(void)printf("\nMemory totals:  In Use    Free    Requests\n");
1005 	(void)printf("              %7ldK %6ldK    %8ld\n\n",
1006 	    (totuse + 1023) / 1024, (totfree + 1023) / 1024, totreq);
1007 }
1008 
1009 void
1010 dopool(int verbose)
1011 {
1012 	int first, ovflw;
1013 	void *addr;
1014 	long total = 0, inuse = 0;
1015 	TAILQ_HEAD(,pool) pool_head;
1016 	struct pool pool, *pp = &pool;
1017 	struct pool_allocator pa;
1018 	char name[32], maxp[32];
1019 
1020 	kread(X_POOLHEAD, &pool_head, sizeof(pool_head));
1021 	addr = TAILQ_FIRST(&pool_head);
1022 
1023 	for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
1024 		deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
1025 		deref_kptr(pp->pr_alloc, &pa, sizeof(pa),
1026 		    "pool allocatior trashed");
1027 		deref_kptr(pp->pr_wchan, name, sizeof(name),
1028 		    "pool wait channel trashed");
1029 		name[sizeof(name)-1] = '\0';
1030 
1031 		if (first) {
1032 			(void)printf("Memory resource pool statistics\n");
1033 			(void)printf(
1034 			    "%-11s%5s%9s%5s%9s%6s%6s%6s%6s%6s%6s%5s\n",
1035 			    "Name",
1036 			    "Size",
1037 			    "Requests",
1038 			    "Fail",
1039 			    "Releases",
1040 			    "Pgreq",
1041 			    "Pgrel",
1042 			    "Npage",
1043 			    "Hiwat",
1044 			    "Minpg",
1045 			    "Maxpg",
1046 			    "Idle");
1047 			first = 0;
1048 		}
1049 		if (pp->pr_nget == 0 && !verbose)
1050 			continue;
1051 		if (pp->pr_maxpages == UINT_MAX)
1052 			snprintf(maxp, sizeof(maxp), "inf");
1053 		else
1054 			snprintf(maxp, sizeof(maxp), "%u", pp->pr_maxpages);
1055 /*
1056  * Print single word.  `ovflow' is number of characters didn't fit
1057  * on the last word.  `fmt' is a format string to print this word.
1058  * It must contain asterisk for field width.  `width' is a width
1059  * occupied by this word.  `fixed' is a number of constant chars in
1060  * `fmt'.  `val' is a value to be printed using format string `fmt'.
1061  */
1062 #define	PRWORD(ovflw, fmt, width, fixed, val) do {	\
1063 	(ovflw) += printf((fmt),			\
1064 	    (width) - (fixed) - (ovflw) > 0 ?		\
1065 	    (width) - (fixed) - (ovflw) : 0,		\
1066 	    (val)) - (width);				\
1067 	if ((ovflw) < 0)				\
1068 		(ovflw) = 0;				\
1069 } while (/* CONSTCOND */0)
1070 		ovflw = 0;
1071 		PRWORD(ovflw, "%-*s", 11, 0, name);
1072 		PRWORD(ovflw, " %*u", 5, 1, pp->pr_size);
1073 		PRWORD(ovflw, " %*lu", 9, 1, pp->pr_nget);
1074 		PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nfail);
1075 		PRWORD(ovflw, " %*lu", 9, 1, pp->pr_nput);
1076 		PRWORD(ovflw, " %*lu", 6, 1, pp->pr_npagealloc);
1077 		PRWORD(ovflw, " %*lu", 6, 1, pp->pr_npagefree);
1078 		PRWORD(ovflw, " %*d", 6, 1, pp->pr_npages);
1079 		PRWORD(ovflw, " %*d", 6, 1, pp->pr_hiwat);
1080 		PRWORD(ovflw, " %*d", 6, 1, pp->pr_minpages);
1081 		PRWORD(ovflw, " %*s", 6, 1, maxp);
1082 		PRWORD(ovflw, " %*lu\n", 5, 1, pp->pr_nidle);
1083 
1084 		if (pp->pr_roflags & PR_RECURSIVE) {
1085 			/*
1086 			 * Don't count in-use memory, since it's part
1087 			 * of another pool and will be accounted for
1088 			 * there.
1089 			 */
1090 			total += pp->pr_npages * pa.pa_pagesz -
1091 			     (pp->pr_nget - pp->pr_nput) * pp->pr_size;
1092 		} else {
1093 			inuse += (pp->pr_nget - pp->pr_nput) * pp->pr_size;
1094 			total += pp->pr_npages * pa.pa_pagesz;
1095 		}
1096 		dopoolcache(pp, verbose);
1097 	}
1098 
1099 	inuse /= 1024;
1100 	total /= 1024;
1101 	printf("\nIn use %ldK, total allocated %ldK; utilization %.1f%%\n",
1102 	    inuse, total, (double)(100 * inuse) / total);
1103 }
1104 
1105 void
1106 dopoolcache(struct pool *pp, int verbose)
1107 {
1108 	struct pool_cache pool_cache, *pc = &pool_cache;
1109 	struct pool_cache_group pool_cache_group, *pcg = &pool_cache_group;
1110 	void *addr, *pcg_addr;
1111 	int i;
1112 
1113 	if (verbose < 1)
1114 		return;
1115 
1116 	for (addr = TAILQ_FIRST(&pp->pr_cachelist); addr != NULL;
1117 	    addr = TAILQ_NEXT(pc, pc_poollist)) {
1118 		deref_kptr(addr, pc, sizeof(*pc), "pool cache trashed");
1119 		printf("\tcache %p: allocfrom %p freeto %p\n", addr,
1120 		    pc->pc_allocfrom, pc->pc_freeto);
1121 		printf("\t    hits %lu misses %lu ngroups %lu nitems %lu\n",
1122 		    pc->pc_hits, pc->pc_misses, pc->pc_ngroups, pc->pc_nitems);
1123 		if (verbose < 2)
1124 			continue;
1125 		for (pcg_addr = TAILQ_FIRST(&pc->pc_grouplist);
1126 		    pcg_addr != NULL; pcg_addr = TAILQ_NEXT(pcg, pcg_list)) {
1127 			deref_kptr(pcg_addr, pcg, sizeof(*pcg),
1128 			    "pool cache group trashed");
1129 			printf("\t\tgroup %p: avail %d\n", pcg_addr,
1130 			    pcg->pcg_avail);
1131 			for (i = 0; i < PCG_NOBJECTS; i++) {
1132 				if (pcg->pcg_objects[i].pcgo_pa !=
1133 				    POOL_PADDR_INVALID) {
1134 					printf("\t\t\t%p, 0x%llx\n",
1135 					    pcg->pcg_objects[i].pcgo_va,
1136 					    (unsigned long long)
1137 					    pcg->pcg_objects[i].pcgo_pa);
1138 				} else {
1139 					printf("\t\t\t%p\n",
1140 					    pcg->pcg_objects[i].pcgo_va);
1141 				}
1142 			}
1143 		}
1144 	}
1145 
1146 }
1147 
1148 enum hashtype {			/* from <sys/systm.h> */
1149 	HASH_LIST,
1150 	HASH_TAILQ
1151 };
1152 
1153 struct uidinfo {		/* XXX: no kernel header file */
1154 	LIST_ENTRY(uidinfo) ui_hash;
1155 	uid_t	ui_uid;
1156 	long	ui_proccnt;
1157 };
1158 
1159 struct kernel_hash {
1160 	const char *	description;	/* description */
1161 	int		hashsize;	/* nlist index for hash size */
1162 	int		hashtbl;	/* nlist index for hash table */
1163 	enum hashtype	type;		/* type of hash table */
1164 	size_t		offset;		/* offset of {LIST,TAILQ}_NEXT */
1165 } khashes[] =
1166 {
1167 	{
1168 		"buffer hash",
1169 		X_BUFHASH, X_BUFHASHTBL,
1170 		HASH_LIST, offsetof(struct buf, b_hash)
1171 	}, {
1172 		"inode cache (ihash)",
1173 		X_IHASH, X_IHASHTBL,
1174 		HASH_LIST, offsetof(struct inode, i_hash)
1175 	}, {
1176 		"ipv4 address -> interface hash",
1177 		X_IFADDRHASH, X_IFADDRHASHTBL,
1178 		HASH_LIST, offsetof(struct in_ifaddr, ia_hash),
1179 	}, {
1180 		"name cache hash",
1181 		X_NCHASH, X_NCHASHTBL,
1182 		HASH_LIST, offsetof(struct namecache, nc_hash),
1183 	}, {
1184 		"name cache directory hash",
1185 		X_NCVHASH, X_NCVHASHTBL,
1186 		HASH_LIST, offsetof(struct namecache, nc_vhash),
1187 	}, {
1188 		"nfs client node cache",
1189 		X_NFSNODE, X_NFSNODETBL,
1190 		HASH_LIST, offsetof(struct nfsnode, n_hash)
1191 	}, {
1192 		"user info (uid -> used processes) hash",
1193 		X_UIHASH, X_UIHASHTBL,
1194 		HASH_LIST, offsetof(struct uidinfo, ui_hash),
1195 	}, {
1196 		NULL, -1, -1, 0, 0,
1197 	}
1198 };
1199 
1200 void
1201 dohashstat(int verbose, int todo, const char *hashname)
1202 {
1203 	LIST_HEAD(, generic)	*hashtbl_list;
1204 	TAILQ_HEAD(, generic)	*hashtbl_tailq;
1205 	struct kernel_hash	*curhash;
1206 	void	*hashaddr, *hashbuf, *nhashbuf, *nextaddr;
1207 	size_t	elemsize, hashbufsize, thissize;
1208 	u_long	hashsize;
1209 	int	i, used, items, chain, maxchain;
1210 
1211 	hashbuf = NULL;
1212 	hashbufsize = 0;
1213 
1214 	if (todo & HASHLIST) {
1215 		printf("Supported hashes:\n");
1216 		for (curhash = khashes; curhash->description; curhash++) {
1217 			if (hashnl[curhash->hashsize].n_value == 0 ||
1218 			    hashnl[curhash->hashtbl].n_value == 0)
1219 				continue;
1220 			printf("\t%-16s%s\n",
1221 			    hashnl[curhash->hashsize].n_name + 1,
1222 			    curhash->description);
1223 		}
1224 		return;
1225 	}
1226 
1227 	if (hashname != NULL) {
1228 		for (curhash = khashes; curhash->description; curhash++) {
1229 			if (strcmp(hashnl[curhash->hashsize].n_name + 1,
1230 			    hashname) == 0 &&
1231 			    hashnl[curhash->hashsize].n_value != 0 &&
1232 			    hashnl[curhash->hashtbl].n_value != 0)
1233 				break;
1234 		}
1235 		if (curhash->description == NULL) {
1236 			warnx("%s: no such hash", hashname);
1237 			return;
1238 		}
1239 	}
1240 
1241 	printf(
1242 	    "%-16s %8s %8s %8s %8s %8s %8s\n"
1243 	    "%-16s %8s %8s %8s %8s %8s %8s\n",
1244 	    "", "total", "used", "util", "num", "average", "maximum",
1245 	    "hash table", "buckets", "buckets", "%", "items", "chain",
1246 	    "chain");
1247 
1248 	for (curhash = khashes; curhash->description; curhash++) {
1249 		if (hashnl[curhash->hashsize].n_value == 0 ||
1250 		    hashnl[curhash->hashtbl].n_value == 0)
1251 			continue;
1252 		if (hashname != NULL &&
1253 		    strcmp(hashnl[curhash->hashsize].n_name + 1, hashname))
1254 			continue;
1255 		elemsize = curhash->type == HASH_LIST ?
1256 		    sizeof(*hashtbl_list) : sizeof(*hashtbl_tailq);
1257 		deref_kptr((void *)hashnl[curhash->hashsize].n_value,
1258 		    &hashsize, sizeof(hashsize),
1259 		    hashnl[curhash->hashsize].n_name);
1260 		hashsize++;
1261 		deref_kptr((void *)hashnl[curhash->hashtbl].n_value,
1262 		    &hashaddr, sizeof(hashaddr),
1263 		    hashnl[curhash->hashtbl].n_name);
1264 		if (verbose)
1265 			printf("%s %lu, %s %p, offset %ld, elemsize %llu\n",
1266 			    hashnl[curhash->hashsize].n_name + 1, hashsize,
1267 			    hashnl[curhash->hashtbl].n_name + 1, hashaddr,
1268 			    (long)curhash->offset,
1269 			    (unsigned long long)elemsize);
1270 		thissize = hashsize * elemsize;
1271 		if (thissize > hashbufsize) {
1272 			if ((nhashbuf = realloc(hashbuf, thissize)) == NULL)
1273 				errx(1, "malloc hashbuf %llu",
1274 				    (unsigned long long)hashbufsize);
1275 			hashbuf = nhashbuf;
1276 			hashbufsize = thissize;
1277 		}
1278 		deref_kptr(hashaddr, hashbuf, thissize,
1279 		    hashnl[curhash->hashtbl].n_name);
1280 		used = 0;
1281 		items = maxchain = 0;
1282 		if (curhash->type == HASH_LIST)
1283 			hashtbl_list = hashbuf;
1284 		else
1285 			hashtbl_tailq = hashbuf;
1286 		for (i = 0; i < hashsize; i++) {
1287 			if (curhash->type == HASH_LIST)
1288 				nextaddr = LIST_FIRST(&hashtbl_list[i]);
1289 			else
1290 				nextaddr = TAILQ_FIRST(&hashtbl_tailq[i]);
1291 			if (nextaddr == NULL)
1292 				continue;
1293 			if (verbose)
1294 				printf("%5d: %p\n", i, nextaddr);
1295 			used++;
1296 			chain = 0;
1297 			do {
1298 				chain++;
1299 				deref_kptr((char *)nextaddr + curhash->offset,
1300 				    &nextaddr, sizeof(void *),
1301 				    "hash chain corrupted");
1302 				if (verbose > 1)
1303 					printf("got nextaddr as %p\n",
1304 					    nextaddr);
1305 			} while (nextaddr != NULL);
1306 			items += chain;
1307 			if (verbose && chain > 1)
1308 				printf("\tchain = %d\n", chain);
1309 			if (chain > maxchain)
1310 				maxchain = chain;
1311 		}
1312 		printf("%-16s %8ld %8d %8.2f %8d %8.2f %8d\n",
1313 		    hashnl[curhash->hashsize].n_name + 1,
1314 		    hashsize, used, used * 100.0 / hashsize,
1315 		    items, used ? (double)items / used : 0.0, maxchain);
1316 	}
1317 }
1318 
1319 /*
1320  * kread reads something from the kernel, given its nlist index in namelist[].
1321  */
1322 void
1323 kread(int nlx, void *addr, size_t size)
1324 {
1325 	const char *sym;
1326 
1327 	sym = namelist[nlx].n_name;
1328 	if (*sym == '_')
1329 		++sym;
1330 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0)
1331 		errx(1, "symbol %s not defined", sym);
1332 	deref_kptr((void *)namelist[nlx].n_value, addr, size, sym);
1333 }
1334 
1335 /*
1336  * Dereference the kernel pointer `kptr' and fill in the local copy
1337  * pointed to by `ptr'.  The storage space must be pre-allocated,
1338  * and the size of the copy passed in `len'.
1339  */
1340 void
1341 deref_kptr(const void *kptr, void *ptr, size_t len, const char *msg)
1342 {
1343 
1344 	if (*msg == '_')
1345 		msg++;
1346 	if (kvm_read(kd, (u_long)kptr, (char *)ptr, len) != len)
1347 		errx(1, "kptr %lx: %s: %s", (u_long)kptr, msg, kvm_geterr(kd));
1348 }
1349 
1350 /*
1351  * Traverse the UVM history buffers, performing the requested action.
1352  *
1353  * Note, we assume that if we're not listing, we're dumping.
1354  */
1355 void
1356 hist_traverse(int todo, const char *histname)
1357 {
1358 	struct uvm_history_head histhead;
1359 	struct uvm_history hist, *histkva;
1360 	char *name = NULL;
1361 	size_t namelen = 0;
1362 
1363 	if (histnl[0].n_value == 0) {
1364 		warnx("UVM history is not compiled into the kernel.");
1365 		return;
1366 	}
1367 
1368 	deref_kptr((void *)histnl[X_UVM_HISTORIES].n_value, &histhead,
1369 	    sizeof(histhead), histnl[X_UVM_HISTORIES].n_name);
1370 
1371 	if (histhead.lh_first == NULL) {
1372 		warnx("No active UVM history logs.");
1373 		return;
1374 	}
1375 
1376 	if (todo & HISTLIST)
1377 		printf("Active UVM histories:");
1378 
1379 	for (histkva = LIST_FIRST(&histhead); histkva != NULL;
1380 	    histkva = LIST_NEXT(&hist, list)) {
1381 		deref_kptr(histkva, &hist, sizeof(hist), "histkva");
1382 		if (hist.namelen > namelen) {
1383 			if (name != NULL)
1384 				free(name);
1385 			namelen = hist.namelen;
1386 			if ((name = malloc(namelen + 1)) == NULL)
1387 				err(1, "malloc history name");
1388 		}
1389 
1390 		deref_kptr(hist.name, name, namelen, "history name");
1391 		name[namelen] = '\0';
1392 		if (todo & HISTLIST)
1393 			printf(" %s", name);
1394 		else {
1395 			/*
1396 			 * If we're dumping all histories, do it, else
1397 			 * check to see if this is the one we want.
1398 			 */
1399 			if (histname == NULL || strcmp(histname, name) == 0) {
1400 				if (histname == NULL)
1401 					printf("\nUVM history `%s':\n", name);
1402 				hist_dodump(&hist);
1403 			}
1404 		}
1405 	}
1406 
1407 	if (todo & HISTLIST)
1408 		putchar('\n');
1409 
1410 	if (name != NULL)
1411 		free(name);
1412 }
1413 
1414 /*
1415  * Actually dump the history buffer at the specified KVA.
1416  */
1417 void
1418 hist_dodump(struct uvm_history *histp)
1419 {
1420 	struct uvm_history_ent *histents, *e;
1421 	size_t histsize;
1422 	char *fmt = NULL, *fn = NULL;
1423 	size_t fmtlen = 0, fnlen = 0;
1424 	int i;
1425 
1426 	histsize = sizeof(struct uvm_history_ent) * histp->n;
1427 
1428 	if ((histents = malloc(histsize)) == NULL)
1429 		err(1, "malloc history entries");
1430 
1431 	memset(histents, 0, histsize);
1432 
1433 	deref_kptr(histp->e, histents, histsize, "history entries");
1434 	i = histp->f;
1435 	do {
1436 		e = &histents[i];
1437 		if (e->fmt != NULL) {
1438 			if (e->fmtlen > fmtlen) {
1439 				if (fmt != NULL)
1440 					free(fmt);
1441 				fmtlen = e->fmtlen;
1442 				if ((fmt = malloc(fmtlen + 1)) == NULL)
1443 					err(1, "malloc printf format");
1444 			}
1445 			if (e->fnlen > fnlen) {
1446 				if (fn != NULL)
1447 					free(fn);
1448 				fnlen = e->fnlen;
1449 				if ((fn = malloc(fnlen + 1)) == NULL)
1450 					err(1, "malloc function name");
1451 			}
1452 
1453 			deref_kptr(e->fmt, fmt, fmtlen, "printf format");
1454 			fmt[fmtlen] = '\0';
1455 
1456 			deref_kptr(e->fn, fn, fnlen, "function name");
1457 			fn[fnlen] = '\0';
1458 
1459 			printf("%06ld.%06ld ", (long int)e->tv.tv_sec,
1460 			    (long int)e->tv.tv_usec);
1461 			printf("%s#%ld: ", fn, e->call);
1462 			printf(fmt, e->v[0], e->v[1], e->v[2], e->v[3]);
1463 			putchar('\n');
1464 		}
1465 		i = (i + 1) % histp->n;
1466 	} while (i != histp->f);
1467 
1468 	free(histents);
1469 	if (fmt != NULL)
1470 		free(fmt);
1471 	if (fn != NULL)
1472 		free(fn);
1473 }
1474 
1475 void
1476 usage(void)
1477 {
1478 
1479 	(void)fprintf(stderr,
1480 	    "usage: %s [-efHilmsUv] [-h hashname] [-u histname] [-c count]\n"
1481 	    "\t\t[-M core] [-N system] [-w wait] [disks]\n", getprogname());
1482 	exit(1);
1483 }
1484