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