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