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