xref: /netbsd-src/usr.bin/vmstat/vmstat.c (revision 274254cdae52594c1aa480a736aef78313d15c9c)
1 /* $NetBSD: vmstat.c,v 1.165 2009/01/18 07:20:00 lukem 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.165 2009/01/18 07:20:00 lukem 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 sw");
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 		(void)printf("%2d ", total.t_sw);
629 
630 		(void)printf("%9d ", total.t_vm);
631 		(void)printf("%9d ", total.t_avm);
632 		(void)printf("%9d ", total.t_arm);
633 		(void)printf("%5d ", total.t_vmshr);
634 		(void)printf("%6d ", total.t_avmshr);
635 		(void)printf("%5d ", total.t_rmshr);
636 		(void)printf("%6d ", total.t_armshr);
637 		(void)printf("%5d",  total.t_free);
638 
639 		(void)putchar('\n');
640 
641 		(void)fflush(stdout);
642 		if (reps >= 0 && --reps <= 0)
643 			break;
644 
645 		(void)nanosleep(interval, NULL);
646 	}
647 }
648 
649 void
650 dovmstat(struct timespec *interval, int reps)
651 {
652 	struct vmtotal total;
653 	time_t uptime, halfuptime;
654 	int mib[2];
655 	size_t size;
656 	int pagesize = getpagesize();
657 	int ovflw;
658 
659 	uptime = getuptime();
660 	halfuptime = uptime / 2;
661 	(void)signal(SIGCONT, needhdr);
662 
663 	if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
664 		kread(namelist, X_STATHZ, &hz, sizeof(hz));
665 	if (!hz)
666 		kread(namelist, X_HZ, &hz, sizeof(hz));
667 
668 	for (hdrcnt = 1;;) {
669 		if (!--hdrcnt)
670 			printhdr();
671 		/* Read new disk statistics */
672 		cpureadstats();
673 		drvreadstats();
674 		tkreadstats();
675 		kread(namelist, X_UVMEXP, &uvmexp, sizeof(uvmexp));
676 		if (memf != NULL) {
677 			/*
678 			 * XXX Can't do this if we're reading a crash
679 			 * XXX dump because they're lazily-calculated.
680 			 */
681 			(void)printf(
682 			    "Unable to get vmtotals from crash dump.\n");
683 			(void)memset(&total, 0, sizeof(total));
684 		} else {
685 			size = sizeof(total);
686 			mib[0] = CTL_VM;
687 			mib[1] = VM_METER;
688 			if (sysctl(mib, 2, &total, &size, NULL, 0) < 0) {
689 				(void)printf("Can't get vmtotals: %s\n",
690 				    strerror(errno));
691 				(void)memset(&total, 0, sizeof(total));
692 			}
693 		}
694 		ovflw = 0;
695 		PRWORD(ovflw, " %*d", 2, 1, total.t_rq - 1);
696 		PRWORD(ovflw, " %*d", 2, 1, total.t_dw + total.t_pw);
697 		PRWORD(ovflw, " %*d", 2, 1, total.t_sw);
698 #define	pgtok(a) (long)((a) * ((uint32_t)pagesize >> 10))
699 #define	rate(x)	(u_long)(((x) + halfuptime) / uptime)	/* round */
700 		PRWORD(ovflw, " %*ld", 7, 1, pgtok(total.t_avm));
701 		PRWORD(ovflw, " %*ld", 7, 1, pgtok(total.t_free));
702 		PRWORD(ovflw, " %*ld", 5, 1,
703 		    rate(uvmexp.faults - ouvmexp.faults));
704 		PRWORD(ovflw, " %*ld", 4, 1,
705 		    rate(uvmexp.pdreact - ouvmexp.pdreact));
706 		PRWORD(ovflw, " %*ld", 4, 1,
707 		    rate(uvmexp.pageins - ouvmexp.pageins));
708 		PRWORD(ovflw, " %*ld", 5, 1,
709 		    rate(uvmexp.pgswapout - ouvmexp.pgswapout));
710 		PRWORD(ovflw, " %*ld", 5, 1,
711 		    rate(uvmexp.pdfreed - ouvmexp.pdfreed));
712 		PRWORD(ovflw, " %*ld", 6, 2,
713 		    rate(uvmexp.pdscans - ouvmexp.pdscans));
714 		drvstats(&ovflw);
715 		PRWORD(ovflw, " %*ld", 5, 1,
716 		    rate(uvmexp.intrs - ouvmexp.intrs));
717 		PRWORD(ovflw, " %*ld", 5, 1,
718 		    rate(uvmexp.syscalls - ouvmexp.syscalls));
719 		PRWORD(ovflw, " %*ld", 4, 1,
720 		    rate(uvmexp.swtch - ouvmexp.swtch));
721 		cpustats(&ovflw);
722 		(void)putchar('\n');
723 		(void)fflush(stdout);
724 		if (reps >= 0 && --reps <= 0)
725 			break;
726 		ouvmexp = uvmexp;
727 		uptime = interval->tv_sec;
728 		/*
729 		 * We round upward to avoid losing low-frequency events
730 		 * (i.e., >= 1 per interval but < 1 per second).
731 		 */
732 		halfuptime = uptime == 1 ? 0 : (uptime + 1) / 2;
733 		(void)nanosleep(interval, NULL);
734 	}
735 }
736 
737 void
738 printhdr(void)
739 {
740 	size_t i;
741 
742 	(void)printf(" procs    memory      page%*s", 23, "");
743 	if (ndrives > 0)
744 		(void)printf("%s %*sfaults      cpu\n",
745 		    ((ndrives > 1) ? "disks" : "disk"),
746 		    ((ndrives > 1) ? ndrives * 3 - 4 : 0), "");
747 	else
748 		(void)printf("%*s  faults   cpu\n",
749 		    ndrives * 3, "");
750 
751 	(void)printf(" r b w    avm    fre  flt  re  pi   po   fr   sr ");
752 	for (i = 0; i < ndrive; i++)
753 		if (drv_select[i])
754 			(void)printf("%c%c ", dr_name[i][0],
755 			    dr_name[i][strlen(dr_name[i]) - 1]);
756 	(void)printf("  in   sy  cs us sy id\n");
757 	hdrcnt = winlines - 2;
758 }
759 
760 /*
761  * Force a header to be prepended to the next output.
762  */
763 void
764 /*ARGSUSED*/
765 needhdr(int dummy)
766 {
767 
768 	hdrcnt = 1;
769 }
770 
771 long
772 pct(long top, long bot)
773 {
774 	long ans;
775 
776 	if (bot == 0)
777 		return (0);
778 	ans = (long)((quad_t)top * 100 / bot);
779 	return (ans);
780 }
781 
782 #define	PCT(top, bot) (int)pct((long)(top), (long)(bot))
783 
784 void
785 dosum(void)
786 {
787 	struct nchstats nchstats;
788 	u_long nchtotal;
789 	int mib[2];
790 	struct uvmexp_sysctl uvmexp2;
791 	size_t ssize;
792 	int active_kernel;
793 
794 	/*
795 	 * The "active" and "inactive" variables
796 	 * are now estimated by the kernel and sadly
797 	 * can not easily be dug out of a crash dump.
798 	 */
799 	ssize = sizeof(uvmexp2);
800 	memset(&uvmexp2, 0, ssize);
801 	active_kernel = (memf == NULL);
802 	if (active_kernel) {
803 		/* only on active kernel */
804 		mib[0] = CTL_VM;
805 		mib[1] = VM_UVMEXP2;
806 		if (sysctl(mib, 2, &uvmexp2, &ssize, NULL, 0) < 0)
807 			fprintf(stderr, "%s: sysctl vm.uvmexp2 failed: %s",
808 				getprogname(), strerror(errno));
809 	}
810 
811 	kread(namelist, X_UVMEXP, &uvmexp, sizeof(uvmexp));
812 
813 	(void)printf("%9u bytes per page\n", uvmexp.pagesize);
814 
815 	(void)printf("%9u page color%s\n",
816 	    uvmexp.ncolors, uvmexp.ncolors == 1 ? "" : "s");
817 
818 	(void)printf("%9u pages managed\n", uvmexp.npages);
819 	(void)printf("%9u pages free\n", uvmexp.free);
820 	if (active_kernel) {
821 		(void)printf("%9" PRIu64 " pages active\n", uvmexp2.active);
822 		(void)printf("%9" PRIu64 " pages inactive\n", uvmexp2.inactive);
823 	}
824 	(void)printf("%9u pages paging\n", uvmexp.paging);
825 	(void)printf("%9u pages wired\n", uvmexp.wired);
826 	(void)printf("%9u zero pages\n", uvmexp.zeropages);
827 	(void)printf("%9u reserve pagedaemon pages\n",
828 	    uvmexp.reserve_pagedaemon);
829 	(void)printf("%9u reserve kernel pages\n", uvmexp.reserve_kernel);
830 	(void)printf("%9u anonymous pages\n", uvmexp.anonpages);
831 	(void)printf("%9u cached file pages\n", uvmexp.filepages);
832 	(void)printf("%9u cached executable pages\n", uvmexp.execpages);
833 
834 	(void)printf("%9u minimum free pages\n", uvmexp.freemin);
835 	(void)printf("%9u target free pages\n", uvmexp.freetarg);
836 	(void)printf("%9u maximum wired pages\n", uvmexp.wiredmax);
837 
838 	(void)printf("%9u swap devices\n", uvmexp.nswapdev);
839 	(void)printf("%9u swap pages\n", uvmexp.swpages);
840 	(void)printf("%9u swap pages in use\n", uvmexp.swpginuse);
841 	(void)printf("%9u swap allocations\n", uvmexp.nswget);
842 
843 	(void)printf("%9u total faults taken\n", uvmexp.faults);
844 	(void)printf("%9u traps\n", uvmexp.traps);
845 	(void)printf("%9u device interrupts\n", uvmexp.intrs);
846 	(void)printf("%9u CPU context switches\n", uvmexp.swtch);
847 	(void)printf("%9u software interrupts\n", uvmexp.softs);
848 	(void)printf("%9u system calls\n", uvmexp.syscalls);
849 	(void)printf("%9u pagein requests\n", uvmexp.pageins);
850 	(void)printf("%9u pageout requests\n", uvmexp.pdpageouts);
851 	(void)printf("%9u swap ins\n", uvmexp.swapins);
852 	(void)printf("%9u swap outs\n", uvmexp.swapouts);
853 	(void)printf("%9u pages swapped in\n", uvmexp.pgswapin);
854 	(void)printf("%9u pages swapped out\n", uvmexp.pgswapout);
855 	(void)printf("%9u forks total\n", uvmexp.forks);
856 	(void)printf("%9u forks blocked parent\n", uvmexp.forks_ppwait);
857 	(void)printf("%9u forks shared address space with parent\n",
858 	    uvmexp.forks_sharevm);
859 	(void)printf("%9u pagealloc zero wanted and avail\n",
860 	    uvmexp.pga_zerohit);
861 	(void)printf("%9u pagealloc zero wanted and not avail\n",
862 	    uvmexp.pga_zeromiss);
863 	(void)printf("%9u aborts of idle page zeroing\n",
864 	    uvmexp.zeroaborts);
865 	(void)printf("%9u pagealloc desired color avail\n",
866 	    uvmexp.colorhit);
867 	(void)printf("%9u pagealloc desired color not avail\n",
868 	    uvmexp.colormiss);
869 	(void)printf("%9u pagealloc local cpu avail\n",
870 	    uvmexp.cpuhit);
871 	(void)printf("%9u pagealloc local cpu not avail\n",
872 	    uvmexp.cpumiss);
873 
874 	(void)printf("%9u faults with no memory\n", uvmexp.fltnoram);
875 	(void)printf("%9u faults with no anons\n", uvmexp.fltnoanon);
876 	(void)printf("%9u faults had to wait on pages\n", uvmexp.fltpgwait);
877 	(void)printf("%9u faults found released page\n", uvmexp.fltpgrele);
878 	(void)printf("%9u faults relock (%u ok)\n", uvmexp.fltrelck,
879 	    uvmexp.fltrelckok);
880 	(void)printf("%9u anon page faults\n", uvmexp.fltanget);
881 	(void)printf("%9u anon retry faults\n", uvmexp.fltanretry);
882 	(void)printf("%9u amap copy faults\n", uvmexp.fltamcopy);
883 	(void)printf("%9u neighbour anon page faults\n", uvmexp.fltnamap);
884 	(void)printf("%9u neighbour object page faults\n", uvmexp.fltnomap);
885 	(void)printf("%9u locked pager get faults\n", uvmexp.fltlget);
886 	(void)printf("%9u unlocked pager get faults\n", uvmexp.fltget);
887 	(void)printf("%9u anon faults\n", uvmexp.flt_anon);
888 	(void)printf("%9u anon copy on write faults\n", uvmexp.flt_acow);
889 	(void)printf("%9u object faults\n", uvmexp.flt_obj);
890 	(void)printf("%9u promote copy faults\n", uvmexp.flt_prcopy);
891 	(void)printf("%9u promote zero fill faults\n", uvmexp.flt_przero);
892 
893 	(void)printf("%9u times daemon wokeup\n",uvmexp.pdwoke);
894 	(void)printf("%9u revolutions of the clock hand\n", uvmexp.pdrevs);
895 	(void)printf("%9u times daemon attempted swapout\n", uvmexp.pdswout);
896 	(void)printf("%9u pages freed by daemon\n", uvmexp.pdfreed);
897 	(void)printf("%9u pages scanned by daemon\n", uvmexp.pdscans);
898 	(void)printf("%9u anonymous pages scanned by daemon\n",
899 	    uvmexp.pdanscan);
900 	(void)printf("%9u object pages scanned by daemon\n", uvmexp.pdobscan);
901 	(void)printf("%9u pages reactivated\n", uvmexp.pdreact);
902 	(void)printf("%9u pages found busy by daemon\n", uvmexp.pdbusy);
903 	(void)printf("%9u total pending pageouts\n", uvmexp.pdpending);
904 	(void)printf("%9u pages deactivated\n", uvmexp.pddeact);
905 
906 	kread(namelist, X_NCHSTATS, &nchstats, sizeof(nchstats));
907 	nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
908 	    nchstats.ncs_badhits + nchstats.ncs_falsehits +
909 	    nchstats.ncs_miss + nchstats.ncs_long;
910 	(void)printf("%9lu total name lookups\n", nchtotal);
911 	(void)printf("%9lu good hits\n", nchstats.ncs_goodhits);
912 	(void)printf("%9lu negative hits\n", nchstats.ncs_neghits);
913 	(void)printf("%9lu bad hits\n", nchstats.ncs_badhits);
914 	(void)printf("%9lu false hits\n", nchstats.ncs_falsehits);
915 	(void)printf("%9lu miss\n", nchstats.ncs_miss);
916 	(void)printf("%9lu too long\n", nchstats.ncs_long);
917 	(void)printf("%9lu pass2 hits\n", nchstats.ncs_pass2);
918 	(void)printf("%9lu 2passes\n", nchstats.ncs_2passes);
919 	(void)printf(
920 	    "%9s cache hits (%d%% pos + %d%% neg) system %d%% per-process\n",
921 	    "", PCT(nchstats.ncs_goodhits, nchtotal),
922 	    PCT(nchstats.ncs_neghits, nchtotal),
923 	    PCT(nchstats.ncs_pass2, nchtotal));
924 	(void)printf("%9s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
925 	    PCT(nchstats.ncs_badhits, nchtotal),
926 	    PCT(nchstats.ncs_falsehits, nchtotal),
927 	    PCT(nchstats.ncs_long, nchtotal));
928 }
929 
930 void
931 doforkst(void)
932 {
933 
934 	kread(namelist, X_UVMEXP, &uvmexp, sizeof(uvmexp));
935 
936 	(void)printf("%u forks total\n", uvmexp.forks);
937 	(void)printf("%u forks blocked parent\n", uvmexp.forks_ppwait);
938 	(void)printf("%u forks shared address space with parent\n",
939 	    uvmexp.forks_sharevm);
940 }
941 
942 void
943 drvstats(int *ovflwp)
944 {
945 	size_t dn;
946 	double etime;
947 	int ovflw = *ovflwp;
948 
949 	/* Calculate disk stat deltas. */
950 	cpuswap();
951 	drvswap();
952 	tkswap();
953 	etime = cur.cp_etime;
954 
955 	for (dn = 0; dn < ndrive; ++dn) {
956 		if (!drv_select[dn])
957 	 		continue;
958 		PRWORD(ovflw, " %*.0f", 3, 1,
959 		    (cur.rxfer[dn] + cur.wxfer[dn]) / etime);
960 	}
961 	*ovflwp = ovflw;
962 }
963 
964 void
965 cpustats(int *ovflwp)
966 {
967 	int state;
968 	double pcnt, total;
969 	double stat_us, stat_sy, stat_id;
970 	int ovflw = *ovflwp;
971 
972 	total = 0;
973 	for (state = 0; state < CPUSTATES; ++state)
974 		total += cur.cp_time[state];
975 	if (total)
976 		pcnt = 100 / total;
977 	else
978 		pcnt = 0;
979 	stat_us = (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * pcnt;
980 	stat_sy = (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * pcnt;
981 	stat_id = cur.cp_time[CP_IDLE] * pcnt;
982 	PRWORD(ovflw, " %*.0f", ((stat_sy >= 100) ? 2 : 3), 1, stat_us);
983 	PRWORD(ovflw, " %*.0f", ((stat_us >= 100 || stat_id >= 100) ? 2 : 3), 1,
984 	    stat_sy);
985 	PRWORD(ovflw, " %*.0f", 3, 1, stat_id);
986 	*ovflwp = ovflw;
987 }
988 
989 void
990 dointr(int verbose)
991 {
992 	unsigned long *intrcnt, *ointrcnt;
993 	unsigned long long inttotal, uptime;
994 	int nintr, inamlen;
995 	char *intrname, *ointrname;
996 	struct evcntlist allevents;
997 	struct evcnt evcnt, *evptr;
998 	char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
999 
1000 	inttotal = 0;
1001 	uptime = getuptime();
1002 	(void)printf("%-34s %16s %8s\n", "interrupt", "total", "rate");
1003 	nintr = intrnl[X_EINTRCNT].n_value - intrnl[X_INTRCNT].n_value;
1004 	inamlen = intrnl[X_EINTRNAMES].n_value - intrnl[X_INTRNAMES].n_value;
1005 	if (nintr != 0 && inamlen != 0) {
1006 		ointrcnt = intrcnt = malloc((size_t)nintr);
1007 		ointrname = intrname = malloc((size_t)inamlen);
1008 		if (intrcnt == NULL || intrname == NULL)
1009 			errx(1, "%s", "");
1010 		kread(intrnl, X_INTRCNT, intrcnt, (size_t)nintr);
1011 		kread(intrnl, X_INTRNAMES, intrname, (size_t)inamlen);
1012 		nintr /= sizeof(long);
1013 		while (--nintr >= 0) {
1014 			if (*intrcnt || verbose)
1015 				(void)printf("%-34s %16llu %8llu\n", intrname,
1016 					     (unsigned long long)*intrcnt,
1017 					     (unsigned long long)
1018 					     (*intrcnt / uptime));
1019 			intrname += strlen(intrname) + 1;
1020 			inttotal += *intrcnt++;
1021 		}
1022 		free(ointrcnt);
1023 		free(ointrname);
1024 	}
1025 
1026 	kread(namelist, X_ALLEVENTS, &allevents, sizeof allevents);
1027 	evptr = TAILQ_FIRST(&allevents);
1028 	while (evptr) {
1029 		deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
1030 		evptr = TAILQ_NEXT(&evcnt, ev_list);
1031 		if (evcnt.ev_type != EVCNT_TYPE_INTR)
1032 			continue;
1033 
1034 		if (evcnt.ev_count == 0 && !verbose)
1035 			continue;
1036 
1037 		deref_kptr(evcnt.ev_group, evgroup,
1038 		    (size_t)evcnt.ev_grouplen + 1, "event chain trashed");
1039 		deref_kptr(evcnt.ev_name, evname,
1040 		    (size_t)evcnt.ev_namelen + 1, "event chain trashed");
1041 
1042 		(void)printf("%s %s%*s %16llu %8llu\n", evgroup, evname,
1043 		    34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
1044 		    (unsigned long long)evcnt.ev_count,
1045 		    (unsigned long long)(evcnt.ev_count / uptime));
1046 
1047 		inttotal += evcnt.ev_count++;
1048 	}
1049 	(void)printf("%-34s %16llu %8llu\n", "Total", inttotal,
1050 	    (unsigned long long)(inttotal / uptime));
1051 }
1052 
1053 void
1054 doevcnt(int verbose)
1055 {
1056 	static const char * evtypes [] = { "misc", "intr", "trap" };
1057 	unsigned long long uptime;
1058 	struct evcntlist allevents;
1059 	struct evcnt evcnt, *evptr;
1060 	char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
1061 
1062 	/* XXX should print type! */
1063 
1064 	uptime = getuptime();
1065 	(void)printf("%-34s %16s %8s %s\n", "event", "total", "rate", "type");
1066 	kread(namelist, X_ALLEVENTS, &allevents, sizeof allevents);
1067 	evptr = TAILQ_FIRST(&allevents);
1068 	while (evptr) {
1069 		deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
1070 
1071 		evptr = TAILQ_NEXT(&evcnt, ev_list);
1072 		if (evcnt.ev_count == 0 && !verbose)
1073 			continue;
1074 
1075 		deref_kptr(evcnt.ev_group, evgroup,
1076 		    (size_t)evcnt.ev_grouplen + 1, "event chain trashed");
1077 		deref_kptr(evcnt.ev_name, evname,
1078 		    (size_t)evcnt.ev_namelen + 1, "event chain trashed");
1079 
1080 		(void)printf("%s %s%*s %16llu %8llu %s\n", evgroup, evname,
1081 		    34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
1082 		    (unsigned long long)evcnt.ev_count,
1083 		    (unsigned long long)(evcnt.ev_count / uptime),
1084 		    (evcnt.ev_type < sizeof(evtypes)/sizeof(evtypes[0]) ?
1085 			evtypes[evcnt.ev_type] : "?"));
1086 	}
1087 }
1088 
1089 static char memname[64];
1090 
1091 void
1092 domem(void)
1093 {
1094 	struct kmembuckets *kp;
1095 	struct malloc_type ks, *ksp;
1096 	int i, j;
1097 	int len, size, first;
1098 	long totuse = 0, totfree = 0, totreq = 0;
1099 	struct kmembuckets buckets[MINBUCKET + 16];
1100 
1101 	kread(namelist, X_KMEMBUCKETS, buckets, sizeof(buckets));
1102 	for (first = 1, i = MINBUCKET, kp = &buckets[i]; i < MINBUCKET + 16;
1103 	    i++, kp++) {
1104 		if (kp->kb_calls == 0)
1105 			continue;
1106 		if (first) {
1107 			(void)printf("Memory statistics by bucket size\n");
1108 			(void)printf(
1109 		 "    Size   In Use   Free   Requests  HighWater  Couldfree\n");
1110 			first = 0;
1111 		}
1112 		size = 1 << i;
1113 		(void)printf("%8d %8ld %6ld %10ld %7ld %10ld\n", size,
1114 		    kp->kb_total - kp->kb_totalfree,
1115 		    kp->kb_totalfree, kp->kb_calls,
1116 		    kp->kb_highwat, kp->kb_couldfree);
1117 		totfree += size * kp->kb_totalfree;
1118 	}
1119 
1120 	/*
1121 	 * If kmem statistics are not being gathered by the kernel,
1122 	 * first will still be 1.
1123 	 */
1124 	if (first) {
1125 		warnx("Kmem statistics are not being gathered by the kernel.");
1126 		return;
1127 	}
1128 
1129 	(void)printf("\nMemory usage type by bucket size\n");
1130 	(void)printf("    Size  Type(s)\n");
1131 	kp = &buckets[MINBUCKET];
1132 	for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1, kp++) {
1133 		if (kp->kb_calls == 0)
1134 			continue;
1135 		first = 1;
1136 		len = 8;
1137 		for (kread(namelist, X_KMEMSTAT, &ksp, sizeof(ksp));
1138 		     ksp != NULL; ksp = ks.ks_next) {
1139 			deref_kptr(ksp, &ks, sizeof(ks), "malloc type");
1140 			if (ks.ks_calls == 0)
1141 				continue;
1142 			if ((ks.ks_size & j) == 0)
1143 				continue;
1144 			deref_kptr(ks.ks_shortdesc, memname,
1145 			    sizeof(memname), "malloc type name");
1146 			len += 2 + strlen(memname);
1147 			if (first)
1148 				(void)printf("%8d  %s", j, memname);
1149 			else
1150 				(void)printf(",");
1151 			if (len >= 80) {
1152 				(void)printf("\n\t ");
1153 				len = 10 + strlen(memname);
1154 			}
1155 			if (!first)
1156 				(void)printf(" %s", memname);
1157 			first = 0;
1158 		}
1159 		(void)putchar('\n');
1160 	}
1161 
1162 	(void)printf(
1163 	    "\nMemory statistics by type                                Type  Kern\n");
1164 	(void)printf(
1165 "           Type InUse  MemUse HighUse   Limit   Requests Limit Limit Size(s)\n");
1166 	for (kread(namelist, X_KMEMSTAT, &ksp, sizeof(ksp));
1167 	     ksp != NULL; ksp = ks.ks_next) {
1168 		deref_kptr(ksp, &ks, sizeof(ks), "malloc type");
1169 		if (ks.ks_calls == 0)
1170 			continue;
1171 		deref_kptr(ks.ks_shortdesc, memname,
1172 		    sizeof(memname), "malloc type name");
1173 		(void)printf("%15s %5ld %6ldK %6ldK %6ldK %10ld %5u %5u",
1174 		    memname,
1175 		    ks.ks_inuse, howmany(ks.ks_memuse, KILO),
1176 		    howmany(ks.ks_maxused, KILO),
1177 		    howmany(ks.ks_limit, KILO), ks.ks_calls,
1178 		    ks.ks_limblocks, ks.ks_mapblocks);
1179 		first = 1;
1180 		for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
1181 			if ((ks.ks_size & j) == 0)
1182 				continue;
1183 			if (first)
1184 				(void)printf(" %d", j);
1185 			else
1186 				(void)printf(",%d", j);
1187 			first = 0;
1188 		}
1189 		(void)printf("\n");
1190 		totuse += ks.ks_memuse;
1191 		totreq += ks.ks_calls;
1192 	}
1193 	(void)printf("\nMemory totals:  In Use    Free    Requests\n");
1194 	(void)printf("              %7ldK %6ldK    %8ld\n\n",
1195 	    howmany(totuse, KILO), howmany(totfree, KILO), totreq);
1196 }
1197 
1198 void
1199 dopool(int verbose, int wide)
1200 {
1201 	int first, ovflw;
1202 	void *addr;
1203 	long total, inuse, this_total, this_inuse;
1204 	TAILQ_HEAD(,pool) pool_head;
1205 	struct pool pool, *pp = &pool;
1206 	struct pool_allocator pa;
1207 	char name[32], maxp[32];
1208 
1209 	kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
1210 	addr = TAILQ_FIRST(&pool_head);
1211 
1212 	total = inuse = 0;
1213 
1214 	for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
1215 		deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
1216 		deref_kptr(pp->pr_alloc, &pa, sizeof(pa),
1217 		    "pool allocator trashed");
1218 		deref_kptr(pp->pr_wchan, name, sizeof(name),
1219 		    "pool wait channel trashed");
1220 		name[sizeof(name)-1] = '\0';
1221 
1222 		if (first) {
1223 			(void)printf("Memory resource pool statistics\n");
1224 			(void)printf(
1225 			    "%-*s%*s%*s%5s%*s%s%s%*s%*s%6s%s%6s%6s%6s%5s%s%s\n",
1226 			    wide ? 16 : 11, "Name",
1227 			    wide ? 6 : 5, "Size",
1228 			    wide ? 12 : 9, "Requests",
1229 			    "Fail",
1230 			    wide ? 12 : 9, "Releases",
1231 			    wide ? "  InUse" : "",
1232 			    wide ? " Avail" : "",
1233 			    wide ? 7 : 6, "Pgreq",
1234 			    wide ? 7 : 6, "Pgrel",
1235 			    "Npage",
1236 			    wide ? " PageSz" : "",
1237 			    "Hiwat",
1238 			    "Minpg",
1239 			    "Maxpg",
1240 			    "Idle",
1241 			    wide ? " Flags" : "",
1242 			    wide ? "   Util" : "");
1243 			first = 0;
1244 		}
1245 		if (pp->pr_nget == 0 && !verbose)
1246 			continue;
1247 		if (pp->pr_maxpages == UINT_MAX)
1248 			(void)snprintf(maxp, sizeof(maxp), "inf");
1249 		else
1250 			(void)snprintf(maxp, sizeof(maxp), "%u",
1251 			    pp->pr_maxpages);
1252 		ovflw = 0;
1253 		PRWORD(ovflw, "%-*s", wide ? 16 : 11, 0, name);
1254 		PRWORD(ovflw, " %*u", wide ? 6 : 5, 1, pp->pr_size);
1255 		PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nget);
1256 		PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nfail);
1257 		PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nput);
1258 		if (wide)
1259 			PRWORD(ovflw, " %*u", 7, 1, pp->pr_nout);
1260 		if (wide)
1261 			PRWORD(ovflw, " %*u", 6, 1, pp->pr_nitems);
1262 		PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagealloc);
1263 		PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagefree);
1264 		PRWORD(ovflw, " %*u", 6, 1, pp->pr_npages);
1265 		if (wide)
1266 			PRWORD(ovflw, " %*u", 7, 1, pa.pa_pagesz);
1267 		PRWORD(ovflw, " %*u", 6, 1, pp->pr_hiwat);
1268 		PRWORD(ovflw, " %*u", 6, 1, pp->pr_minpages);
1269 		PRWORD(ovflw, " %*s", 6, 1, maxp);
1270 		PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nidle);
1271 		if (wide)
1272 			PRWORD(ovflw, " 0x%0*x", 4, 1,
1273 			    pp->pr_flags | pp->pr_roflags);
1274 
1275 		this_inuse = pp->pr_nout * pp->pr_size;
1276 		this_total = pp->pr_npages * pa.pa_pagesz;
1277 		if (pp->pr_roflags & PR_RECURSIVE) {
1278 			/*
1279 			 * Don't count in-use memory, since it's part
1280 			 * of another pool and will be accounted for
1281 			 * there.
1282 			 */
1283 			total += (this_total - this_inuse);
1284 		} else {
1285 			inuse += this_inuse;
1286 			total += this_total;
1287 		}
1288 		if (wide) {
1289 			if (this_total == 0)
1290 				(void)printf("   ---");
1291 			else
1292 				(void)printf(" %5.1f%%",
1293 				    (100.0 * this_inuse) / this_total);
1294 		}
1295 		(void)printf("\n");
1296 	}
1297 
1298 	inuse /= KILO;
1299 	total /= KILO;
1300 	(void)printf(
1301 	    "\nIn use %ldK, total allocated %ldK; utilization %.1f%%\n",
1302 	    inuse, total, (100.0 * inuse) / total);
1303 }
1304 
1305 void
1306 dopoolcache(void)
1307 {
1308 	struct pool_cache pool_cache, *pc = &pool_cache;
1309 	pool_cache_cpu_t cache_cpu, *cc = &cache_cpu;
1310 	TAILQ_HEAD(,pool) pool_head;
1311 	struct pool pool, *pp = &pool;
1312 	char name[32];
1313 	uint64_t cpuhit, cpumiss, tot;
1314 	void *addr;
1315 	int first, ovflw;
1316 	size_t i;
1317 	double p;
1318 
1319 	kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
1320 	addr = TAILQ_FIRST(&pool_head);
1321 
1322 	for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
1323 		deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
1324 		if (pp->pr_cache == NULL)
1325 			continue;
1326 		deref_kptr(pp->pr_wchan, name, sizeof(name),
1327 		    "pool wait channel trashed");
1328 		deref_kptr(pp->pr_cache, pc, sizeof(*pc), "pool cache trashed");
1329 		name[sizeof(name)-1] = '\0';
1330 
1331 		cpuhit = 0;
1332 		cpumiss = 0;
1333 		for (i = 0; i < sizeof(pc->pc_cpus) / sizeof(pc->pc_cpus[0]);
1334 		    i++) {
1335 		    	if ((addr = pc->pc_cpus[i]) == NULL)
1336 		    		continue;
1337 			deref_kptr(addr, cc, sizeof(*cc),
1338 			    "pool cache cpu trashed");
1339 			cpuhit += cc->cc_hits;
1340 			cpumiss += cc->cc_misses;
1341 		}
1342 
1343 		if (first) {
1344 			(void)printf("Pool cache statistics.\n");
1345 			(void)printf("%-*s%*s%*s%*s%*s%*s%*s%*s%*s%*s\n",
1346 			    12, "Name",
1347 			    6, "Spin",
1348 			    6, "GrpSz",
1349 			    5, "Full",
1350 			    5, "Emty",
1351 			    10, "PoolLayer",
1352 			    11, "CacheLayer",
1353 			    6, "Hit%",
1354 			    12, "CpuLayer",
1355 			    6, "Hit%"
1356 			);
1357 			first = 0;
1358 		}
1359 
1360 		ovflw = 0;
1361 		PRWORD(ovflw, "%-*s", 13, 1, name);
1362 		PRWORD(ovflw, " %*llu", 6, 1, (long long)pc->pc_contended);
1363 		PRWORD(ovflw, " %*u", 6, 1, pc->pc_pcgsize);
1364 		PRWORD(ovflw, " %*u", 5, 1, pc->pc_nfull);
1365 		PRWORD(ovflw, " %*u", 5, 1, pc->pc_nempty);
1366 		PRWORD(ovflw, " %*llu", 10, 1, (long long)pc->pc_misses);
1367 
1368 		tot = pc->pc_hits + pc->pc_misses;
1369 		p = pc->pc_hits * 100.0 / (tot);
1370 		PRWORD(ovflw, " %*llu", 11, 1, (long long)tot);
1371 		PRWORD(ovflw, " %*.1f", 6, 1, p);
1372 
1373 		tot = cpuhit + cpumiss;
1374 		p = cpuhit * 100.0 / (tot);
1375 		PRWORD(ovflw, " %*llu", 12, 1, (long long)tot);
1376 		PRWORD(ovflw, " %*.1f", 6, 1, p);
1377 		printf("\n");
1378 	}
1379 }
1380 
1381 enum hashtype {			/* from <sys/systm.h> */
1382 	HASH_LIST,
1383 	HASH_TAILQ
1384 };
1385 
1386 struct uidinfo {		/* XXX: no kernel header file */
1387 	LIST_ENTRY(uidinfo) ui_hash;
1388 	uid_t	ui_uid;
1389 	long	ui_proccnt;
1390 };
1391 
1392 struct kernel_hash {
1393 	const char *	description;	/* description */
1394 	int		hashsize;	/* nlist index for hash size */
1395 	int		hashtbl;	/* nlist index for hash table */
1396 	enum hashtype	type;		/* type of hash table */
1397 	size_t		offset;		/* offset of {LIST,TAILQ}_NEXT */
1398 } khashes[] =
1399 {
1400 	{
1401 		"buffer hash",
1402 		X_BUFHASH, X_BUFHASHTBL,
1403 		HASH_LIST, offsetof(struct buf, b_hash)
1404 	}, {
1405 		"inode cache (ihash)",
1406 		X_IHASH, X_IHASHTBL,
1407 		HASH_LIST, offsetof(struct inode, i_hash)
1408 	}, {
1409 		"ipv4 address -> interface hash",
1410 		X_IFADDRHASH, X_IFADDRHASHTBL,
1411 		HASH_LIST, offsetof(struct in_ifaddr, ia_hash),
1412 	}, {
1413 		"name cache hash",
1414 		X_NCHASH, X_NCHASHTBL,
1415 		HASH_LIST, offsetof(struct namecache, nc_hash),
1416 	}, {
1417 		"name cache directory hash",
1418 		X_NCVHASH, X_NCVHASHTBL,
1419 		HASH_LIST, offsetof(struct namecache, nc_vhash),
1420 	}, {
1421 		"user info (uid -> used processes) hash",
1422 		X_UIHASH, X_UIHASHTBL,
1423 		HASH_LIST, offsetof(struct uidinfo, ui_hash),
1424 	}, {
1425 		NULL, -1, -1, 0, 0,
1426 	}
1427 };
1428 
1429 void
1430 dohashstat(int verbose, int todo, const char *hashname)
1431 {
1432 	LIST_HEAD(, generic)	*hashtbl_list;
1433 	TAILQ_HEAD(, generic)	*hashtbl_tailq;
1434 	struct kernel_hash	*curhash;
1435 	void	*hashaddr, *hashbuf, *nhashbuf, *nextaddr;
1436 	size_t	elemsize, hashbufsize, thissize;
1437 	u_long	hashsize, i;
1438 	int	used, items, chain, maxchain;
1439 
1440 	hashbuf = NULL;
1441 	hashbufsize = 0;
1442 
1443 	if (todo & HASHLIST) {
1444 		(void)printf("Supported hashes:\n");
1445 		for (curhash = khashes; curhash->description; curhash++) {
1446 			if (hashnl[curhash->hashsize].n_value == 0 ||
1447 			    hashnl[curhash->hashtbl].n_value == 0)
1448 				continue;
1449 			(void)printf("\t%-16s%s\n",
1450 			    hashnl[curhash->hashsize].n_name + 1,
1451 			    curhash->description);
1452 		}
1453 		return;
1454 	}
1455 
1456 	if (hashname != NULL) {
1457 		for (curhash = khashes; curhash->description; curhash++) {
1458 			if (strcmp(hashnl[curhash->hashsize].n_name + 1,
1459 			    hashname) == 0 &&
1460 			    hashnl[curhash->hashsize].n_value != 0 &&
1461 			    hashnl[curhash->hashtbl].n_value != 0)
1462 				break;
1463 		}
1464 		if (curhash->description == NULL) {
1465 			warnx("%s: no such hash", hashname);
1466 			return;
1467 		}
1468 	}
1469 
1470 	(void)printf(
1471 	    "%-16s %8s %8s %8s %8s %8s %8s\n"
1472 	    "%-16s %8s %8s %8s %8s %8s %8s\n",
1473 	    "", "total", "used", "util", "num", "average", "maximum",
1474 	    "hash table", "buckets", "buckets", "%", "items", "chain",
1475 	    "chain");
1476 
1477 	for (curhash = khashes; curhash->description; curhash++) {
1478 		if (hashnl[curhash->hashsize].n_value == 0 ||
1479 		    hashnl[curhash->hashtbl].n_value == 0)
1480 			continue;
1481 		if (hashname != NULL &&
1482 		    strcmp(hashnl[curhash->hashsize].n_name + 1, hashname))
1483 			continue;
1484 		elemsize = curhash->type == HASH_LIST ?
1485 		    sizeof(*hashtbl_list) : sizeof(*hashtbl_tailq);
1486 		deref_kptr((void *)hashnl[curhash->hashsize].n_value,
1487 		    &hashsize, sizeof(hashsize),
1488 		    hashnl[curhash->hashsize].n_name);
1489 		hashsize++;
1490 		deref_kptr((void *)hashnl[curhash->hashtbl].n_value,
1491 		    &hashaddr, sizeof(hashaddr),
1492 		    hashnl[curhash->hashtbl].n_name);
1493 		if (verbose)
1494 			(void)printf(
1495 			    "%s %lu, %s %p, offset %ld, elemsize %llu\n",
1496 			    hashnl[curhash->hashsize].n_name + 1, hashsize,
1497 			    hashnl[curhash->hashtbl].n_name + 1, hashaddr,
1498 			    (long)curhash->offset,
1499 			    (unsigned long long)elemsize);
1500 		thissize = hashsize * elemsize;
1501 		if (hashbuf == NULL || thissize > hashbufsize) {
1502 			if ((nhashbuf = realloc(hashbuf, thissize)) == NULL)
1503 				errx(1, "malloc hashbuf %llu",
1504 				    (unsigned long long)hashbufsize);
1505 			hashbuf = nhashbuf;
1506 			hashbufsize = thissize;
1507 		}
1508 		deref_kptr(hashaddr, hashbuf, thissize,
1509 		    hashnl[curhash->hashtbl].n_name);
1510 		used = 0;
1511 		items = maxchain = 0;
1512 		if (curhash->type == HASH_LIST) {
1513 			hashtbl_list = hashbuf;
1514 			hashtbl_tailq = NULL;
1515 		} else {
1516 			hashtbl_list = NULL;
1517 			hashtbl_tailq = hashbuf;
1518 		}
1519 		for (i = 0; i < hashsize; i++) {
1520 			if (curhash->type == HASH_LIST)
1521 				nextaddr = LIST_FIRST(&hashtbl_list[i]);
1522 			else
1523 				nextaddr = TAILQ_FIRST(&hashtbl_tailq[i]);
1524 			if (nextaddr == NULL)
1525 				continue;
1526 			if (verbose)
1527 				(void)printf("%5lu: %p\n", i, nextaddr);
1528 			used++;
1529 			chain = 0;
1530 			do {
1531 				chain++;
1532 				deref_kptr((char *)nextaddr + curhash->offset,
1533 				    &nextaddr, sizeof(void *),
1534 				    "hash chain corrupted");
1535 				if (verbose > 1)
1536 					(void)printf("got nextaddr as %p\n",
1537 					    nextaddr);
1538 			} while (nextaddr != NULL);
1539 			items += chain;
1540 			if (verbose && chain > 1)
1541 				(void)printf("\tchain = %d\n", chain);
1542 			if (chain > maxchain)
1543 				maxchain = chain;
1544 		}
1545 		(void)printf("%-16s %8ld %8d %8.2f %8d %8.2f %8d\n",
1546 		    hashnl[curhash->hashsize].n_name + 1,
1547 		    hashsize, used, used * 100.0 / hashsize,
1548 		    items, used ? (double)items / used : 0.0, maxchain);
1549 	}
1550 }
1551 
1552 /*
1553  * kreadc like kread but returns 1 if sucessful, 0 otherwise
1554  */
1555 int
1556 kreadc(struct nlist *nl, int nlx, void *addr, size_t size)
1557 {
1558 	const char *sym;
1559 
1560 	sym = nl[nlx].n_name;
1561 	if (*sym == '_')
1562 		++sym;
1563 	if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
1564 		return 0;
1565 	deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
1566 	return 1;
1567 }
1568 
1569 /*
1570  * kread reads something from the kernel, given its nlist index in namelist[].
1571  */
1572 void
1573 kread(struct nlist *nl, int nlx, void *addr, size_t size)
1574 {
1575 	const char *sym;
1576 
1577 	sym = nl[nlx].n_name;
1578 	if (*sym == '_')
1579 		++sym;
1580 	if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
1581 		errx(1, "symbol %s not defined", sym);
1582 	deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
1583 }
1584 
1585 /*
1586  * Dereference the kernel pointer `kptr' and fill in the local copy
1587  * pointed to by `ptr'.  The storage space must be pre-allocated,
1588  * and the size of the copy passed in `len'.
1589  */
1590 void
1591 deref_kptr(const void *kptr, void *ptr, size_t len, const char *msg)
1592 {
1593 
1594 	if (*msg == '_')
1595 		msg++;
1596 	if ((size_t)kvm_read(kd, (u_long)kptr, (char *)ptr, len) != len)
1597 		errx(1, "kptr %lx: %s: %s", (u_long)kptr, msg, kvm_geterr(kd));
1598 }
1599 
1600 /*
1601  * Traverse the UVM history buffers, performing the requested action.
1602  *
1603  * Note, we assume that if we're not listing, we're dumping.
1604  */
1605 void
1606 hist_traverse(int todo, const char *histname)
1607 {
1608 	struct uvm_history_head histhead;
1609 	struct uvm_history hist, *histkva;
1610 	char *name = NULL;
1611 	size_t namelen = 0;
1612 
1613 	if (histnl[0].n_value == 0) {
1614 		warnx("UVM history is not compiled into the kernel.");
1615 		return;
1616 	}
1617 
1618 	deref_kptr((void *)histnl[X_UVM_HISTORIES].n_value, &histhead,
1619 	    sizeof(histhead), histnl[X_UVM_HISTORIES].n_name);
1620 
1621 	if (histhead.lh_first == NULL) {
1622 		warnx("No active UVM history logs.");
1623 		return;
1624 	}
1625 
1626 	if (todo & HISTLIST)
1627 		(void)printf("Active UVM histories:");
1628 
1629 	for (histkva = LIST_FIRST(&histhead); histkva != NULL;
1630 	    histkva = LIST_NEXT(&hist, list)) {
1631 		deref_kptr(histkva, &hist, sizeof(hist), "histkva");
1632 		if (name == NULL || hist.namelen > namelen) {
1633 			if (name != NULL)
1634 				free(name);
1635 			namelen = hist.namelen;
1636 			if ((name = malloc(namelen + 1)) == NULL)
1637 				err(1, "malloc history name");
1638 		}
1639 
1640 		deref_kptr(hist.name, name, namelen, "history name");
1641 		name[namelen] = '\0';
1642 		if (todo & HISTLIST)
1643 			(void)printf(" %s", name);
1644 		else {
1645 			/*
1646 			 * If we're dumping all histories, do it, else
1647 			 * check to see if this is the one we want.
1648 			 */
1649 			if (histname == NULL || strcmp(histname, name) == 0) {
1650 				if (histname == NULL)
1651 					(void)printf(
1652 					    "\nUVM history `%s':\n", name);
1653 				hist_dodump(&hist);
1654 			}
1655 		}
1656 	}
1657 
1658 	if (todo & HISTLIST)
1659 		(void)putchar('\n');
1660 
1661 	if (name != NULL)
1662 		free(name);
1663 }
1664 
1665 /*
1666  * Actually dump the history buffer at the specified KVA.
1667  */
1668 void
1669 hist_dodump(struct uvm_history *histp)
1670 {
1671 	struct uvm_history_ent *histents, *e;
1672 	size_t histsize;
1673 	char *fmt = NULL, *fn = NULL;
1674 	size_t fmtlen = 0, fnlen = 0;
1675 	int i;
1676 
1677 	histsize = sizeof(struct uvm_history_ent) * histp->n;
1678 
1679 	if ((histents = malloc(histsize)) == NULL)
1680 		err(1, "malloc history entries");
1681 
1682 	(void)memset(histents, 0, histsize);
1683 
1684 	deref_kptr(histp->e, histents, histsize, "history entries");
1685 	i = histp->f;
1686 	do {
1687 		e = &histents[i];
1688 		if (e->fmt != NULL) {
1689 			if (fmt == NULL || e->fmtlen > fmtlen) {
1690 				if (fmt != NULL)
1691 					free(fmt);
1692 				fmtlen = e->fmtlen;
1693 				if ((fmt = malloc(fmtlen + 1)) == NULL)
1694 					err(1, "malloc printf format");
1695 			}
1696 			if (fn == NULL || e->fnlen > fnlen) {
1697 				if (fn != NULL)
1698 					free(fn);
1699 				fnlen = e->fnlen;
1700 				if ((fn = malloc(fnlen + 1)) == NULL)
1701 					err(1, "malloc function name");
1702 			}
1703 
1704 			deref_kptr(e->fmt, fmt, fmtlen, "printf format");
1705 			fmt[fmtlen] = '\0';
1706 
1707 			deref_kptr(e->fn, fn, fnlen, "function name");
1708 			fn[fnlen] = '\0';
1709 
1710 			(void)printf("%06ld.%06ld ", (long int)e->tv.tv_sec,
1711 			    (long int)e->tv.tv_usec);
1712 			(void)printf("%s#%ld: ", fn, e->call);
1713 			(void)printf(fmt, e->v[0], e->v[1], e->v[2], e->v[3]);
1714 			(void)putchar('\n');
1715 		}
1716 		i = (i + 1) % histp->n;
1717 	} while (i != histp->f);
1718 
1719 	free(histents);
1720 	if (fmt != NULL)
1721 		free(fmt);
1722 	if (fn != NULL)
1723 		free(fn);
1724 }
1725 
1726 void
1727 usage(void)
1728 {
1729 
1730 	(void)fprintf(stderr,
1731 	    "usage: %s [-CefHiLlmstUvW] [-c count] [-h hashname] [-M core] [-N system]\n"
1732 	    "\t\t[-u histname] [-w wait] [disks]\n", getprogname());
1733 	exit(1);
1734 }
1735