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