xref: /netbsd-src/usr.bin/vmstat/vmstat.c (revision 89c5a767f8fc7a4633b2d409966e2becbb98ff92)
1 /*	$NetBSD: vmstat.c,v 1.60 1999/12/05 19:02:29 fredb Exp $	*/
2 
3 /*-
4  * Copyright (c) 1998 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9  * NASA Ames Research Center.
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  * 3. All advertising materials mentioning features or use of this software
20  *    must display the following acknowledgement:
21  *	This product includes software developed by the NetBSD
22  *	Foundation, Inc. and its contributors.
23  * 4. Neither the name of The NetBSD Foundation nor the names of its
24  *    contributors may be used to endorse or promote products derived
25  *    from this software without specific prior written permission.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37  * POSSIBILITY OF SUCH DAMAGE.
38  */
39 
40 /*
41  * Copyright (c) 1980, 1986, 1991, 1993
42  *	The Regents of the University of California.  All rights reserved.
43  *
44  * Redistribution and use in source and binary forms, with or without
45  * modification, are permitted provided that the following conditions
46  * are met:
47  * 1. Redistributions of source code must retain the above copyright
48  *    notice, this list of conditions and the following disclaimer.
49  * 2. Redistributions in binary form must reproduce the above copyright
50  *    notice, this list of conditions and the following disclaimer in the
51  *    documentation and/or other materials provided with the distribution.
52  * 3. All advertising materials mentioning features or use of this software
53  *    must display the following acknowledgement:
54  *	This product includes software developed by the University of
55  *	California, Berkeley and its contributors.
56  * 4. Neither the name of the University nor the names of its contributors
57  *    may be used to endorse or promote products derived from this software
58  *    without specific prior written permission.
59  *
60  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
61  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
62  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
63  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
64  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
65  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
66  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
67  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
68  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
69  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
70  * SUCH DAMAGE.
71  */
72 
73 #include <sys/cdefs.h>
74 #ifndef lint
75 __COPYRIGHT("@(#) Copyright (c) 1980, 1986, 1991, 1993\n\
76 	The Regents of the University of California.  All rights reserved.\n");
77 #endif /* not lint */
78 
79 #ifndef lint
80 #if 0
81 static char sccsid[] = "@(#)vmstat.c	8.2 (Berkeley) 3/1/95";
82 #else
83 __RCSID("$NetBSD: vmstat.c,v 1.60 1999/12/05 19:02:29 fredb Exp $");
84 #endif
85 #endif /* not lint */
86 
87 #define	__POOL_EXPOSE
88 
89 #include <sys/param.h>
90 #include <sys/time.h>
91 #include <sys/proc.h>
92 #include <sys/user.h>
93 #include <sys/dkstat.h>
94 #include <sys/buf.h>
95 #include <sys/namei.h>
96 #include <sys/malloc.h>
97 #include <sys/ioctl.h>
98 #include <sys/sysctl.h>
99 #include <sys/device.h>
100 #include <sys/pool.h>
101 #include <vm/vm.h>
102 #include <err.h>
103 #include <fcntl.h>
104 #include <time.h>
105 #include <nlist.h>
106 #include <kvm.h>
107 #include <errno.h>
108 #include <unistd.h>
109 #include <signal.h>
110 #include <stdio.h>
111 #include <ctype.h>
112 #include <stdlib.h>
113 #include <string.h>
114 #include <paths.h>
115 #include <limits.h>
116 #include "dkstats.h"
117 
118 #include <uvm/uvm_stat.h>
119 
120 struct nlist namelist[] = {
121 #define	X_CPTIME	0
122 	{ "_cp_time" },
123 #define	X_BOOTTIME	1
124 	{ "_boottime" },
125 #define X_HZ		2
126 	{ "_hz" },
127 #define X_STATHZ	3
128 	{ "_stathz" },
129 #define X_NCHSTATS	4
130 	{ "_nchstats" },
131 #define	X_INTRNAMES	5
132 	{ "_intrnames" },
133 #define	X_EINTRNAMES	6
134 	{ "_eintrnames" },
135 #define	X_INTRCNT	7
136 	{ "_intrcnt" },
137 #define	X_EINTRCNT	8
138 	{ "_eintrcnt" },
139 #define	X_KMEMSTAT	9
140 	{ "_kmemstats" },
141 #define	X_KMEMBUCKETS	10
142 	{ "_bucket" },
143 #define X_ALLEVENTS	11
144 	{ "_allevents" },
145 #define X_POOLHEAD	12
146 	{ "_pool_head" },
147 #define	X_UVMEXP	13
148 	{ "_uvmexp" },
149 #define X_END		14
150 #if defined(pc532)
151 #define	X_IVT		(X_END)
152 	{ "_ivt" },
153 #endif
154 	{ "" },
155 };
156 
157 /* Objects defined in dkstats.c */
158 extern struct _disk	cur;
159 extern char	**dr_name;
160 extern int	*dk_select, dk_ndrive;
161 
162 struct	uvmexp uvmexp, ouvmexp;
163 int		ndrives;
164 
165 int	winlines = 20;
166 
167 kvm_t *kd;
168 
169 #define	FORKSTAT	0x01
170 #define	INTRSTAT	0x02
171 #define	MEMSTAT		0x04
172 #define	SUMSTAT		0x08
173 #define	VMSTAT		0x20
174 #define	HISTLIST	0x40
175 #define	HISTDUMP	0x80
176 
177 void	cpustats __P((void));
178 void	dkstats __P((void));
179 void	dointr __P((void));
180 void	domem __P((void));
181 void	dopool __P((void));
182 void	dosum __P((void));
183 void	dovmstat __P((u_int, int));
184 void	kread __P((int, void *, size_t));
185 void	needhdr __P((int));
186 long	getuptime __P((void));
187 void	printhdr __P((void));
188 long	pct __P((long, long));
189 void	usage __P((void));
190 void	doforkst __P((void));
191 
192 void	hist_traverse __P((int, const char *));
193 void	hist_dodump __P((struct uvm_history *));
194 
195 int	main __P((int, char **));
196 char	**choosedrives __P((char **));
197 
198 extern int dkinit __P((int, gid_t));
199 extern void dkreadstats __P((void));
200 extern void dkswap __P((void));
201 
202 /* Namelist and memory file names. */
203 char	*nlistf, *memf;
204 
205 /* allow old usage [vmstat 1] */
206 #define	BACKWARD_COMPATIBILITY
207 
208 int
209 main(argc, argv)
210 	int argc;
211 	char **argv;
212 {
213 	extern int optind;
214 	extern char *optarg;
215 	int c, todo;
216 	u_int interval;
217 	int reps;
218         char errbuf[_POSIX2_LINE_MAX];
219 	gid_t	egid = getegid();
220 	const char *histname = NULL;
221 
222 	(void)setegid(getgid());
223 	memf = nlistf = NULL;
224 	interval = reps = todo = 0;
225 	while ((c = getopt(argc, argv, "c:fh:HilM:mN:sw:")) != -1) {
226 		switch (c) {
227 		case 'c':
228 			reps = atoi(optarg);
229 			break;
230 		case 'f':
231 			todo |= FORKSTAT;
232 			break;
233 		case 'h':
234 			histname = optarg;
235 			/* FALLTHROUGH */
236 		case 'H':
237 			todo |= HISTDUMP;
238 			break;
239 		case 'i':
240 			todo |= INTRSTAT;
241 			break;
242 		case 'l':
243 			todo |= HISTLIST;
244 			break;
245 		case 'M':
246 			memf = optarg;
247 			break;
248 		case 'm':
249 			todo |= MEMSTAT;
250 			break;
251 		case 'N':
252 			nlistf = optarg;
253 			break;
254 		case 's':
255 			todo |= SUMSTAT;
256 			break;
257 		case 'w':
258 			interval = atoi(optarg);
259 			break;
260 		case '?':
261 		default:
262 			usage();
263 		}
264 	}
265 	argc -= optind;
266 	argv += optind;
267 
268 	if (todo == 0)
269 		todo = VMSTAT;
270 
271 	/*
272 	 * Discard setgid privileges.  If not the running kernel, we toss
273 	 * them away totally so that bad guys can't print interesting stuff
274 	 * from kernel memory, otherwise switch back to kmem for the
275 	 * duration of the kvm_openfiles() call.
276 	 */
277 	if (nlistf != NULL || memf != NULL)
278 		(void)setgid(getgid());
279 	else
280 		(void)setegid(egid);
281 
282         kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
283 	if (kd == 0)
284 		errx(1, "kvm_openfiles: %s\n", errbuf);
285 
286 	if (nlistf == NULL && memf == NULL) {
287 		if (todo & VMSTAT)
288 			(void)setegid(getgid());	/* XXX: dkinit */
289 		else
290 			(void)setgid(getgid());
291 	}
292 
293 	if ((c = kvm_nlist(kd, namelist)) != 0) {
294 		if (c > 0) {
295 			(void)fprintf(stderr,
296 			    "vmstat: undefined symbols:");
297 			for (c = 0;
298 			    c < sizeof(namelist)/sizeof(namelist[0]); c++)
299 				if (namelist[c].n_type == 0)
300 					fprintf(stderr, " %s",
301 					    namelist[c].n_name);
302 			(void)fputc('\n', stderr);
303 		} else
304 			(void)fprintf(stderr, "vmstat: kvm_nlist: %s\n",
305 			    kvm_geterr(kd));
306 		exit(1);
307 	}
308 
309 	if (todo & VMSTAT) {
310 		struct winsize winsize;
311 
312 		dkinit(0, egid); /* Initialize disk stats, no disks selected. */
313 
314 		(void)setgid(getgid()); /* don't need privs anymore */
315 
316 		argv = choosedrives(argv);	/* Select disks. */
317 		winsize.ws_row = 0;
318 		(void)ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
319 		if (winsize.ws_row > 0)
320 			winlines = winsize.ws_row;
321 
322 	}
323 
324 #ifdef	BACKWARD_COMPATIBILITY
325 	if (*argv) {
326 		interval = atoi(*argv);
327 		if (*++argv)
328 			reps = atoi(*argv);
329 	}
330 #endif
331 
332 	if (interval) {
333 		if (!reps)
334 			reps = -1;
335 	} else if (reps)
336 		interval = 1;
337 
338 	if (todo & (HISTLIST|HISTDUMP)) {
339 		if ((todo & (HISTLIST|HISTDUMP)) == (HISTLIST|HISTDUMP))
340 			errx(1, "you may list or dump, but not both!");
341 		hist_traverse(todo, histname);
342 	}
343 	if (todo & FORKSTAT)
344 		doforkst();
345 	if (todo & MEMSTAT) {
346 		domem();
347 		dopool();
348 	}
349 	if (todo & SUMSTAT)
350 		dosum();
351 	if (todo & INTRSTAT)
352 		dointr();
353 	if (todo & VMSTAT)
354 		dovmstat(interval, reps);
355 	exit(0);
356 }
357 
358 char **
359 choosedrives(argv)
360 	char **argv;
361 {
362 	int i;
363 
364 	/*
365 	 * Choose drives to be displayed.  Priority goes to (in order) drives
366 	 * supplied as arguments, default drives.  If everything isn't filled
367 	 * in and there are drives not taken care of, display the first few
368 	 * that fit.
369 	 */
370 #define BACKWARD_COMPATIBILITY
371 	for (ndrives = 0; *argv; ++argv) {
372 #ifdef	BACKWARD_COMPATIBILITY
373 		if (isdigit(**argv))
374 			break;
375 #endif
376 		for (i = 0; i < dk_ndrive; i++) {
377 			if (strcmp(dr_name[i], *argv))
378 				continue;
379 			dk_select[i] = 1;
380 			++ndrives;
381 			break;
382 		}
383 	}
384 	for (i = 0; i < dk_ndrive && ndrives < 4; i++) {
385 		if (dk_select[i])
386 			continue;
387 		dk_select[i] = 1;
388 		++ndrives;
389 	}
390 	return(argv);
391 }
392 
393 long
394 getuptime()
395 {
396 	static time_t now;
397 	static struct timeval boottime;
398 	time_t uptime;
399 
400 	if (boottime.tv_sec == 0)
401 		kread(X_BOOTTIME, &boottime, sizeof(boottime));
402 	(void)time(&now);
403 	uptime = now - boottime.tv_sec;
404 	if (uptime <= 0 || uptime > 60*60*24*365*10) {
405 		(void)fprintf(stderr,
406 		    "vmstat: time makes no sense; namelist must be wrong.\n");
407 		exit(1);
408 	}
409 	return(uptime);
410 }
411 
412 int	hz, hdrcnt;
413 
414 void
415 dovmstat(interval, reps)
416 	u_int interval;
417 	int reps;
418 {
419 	struct vmtotal total;
420 	time_t uptime, halfuptime;
421 	int mib[2];
422 	size_t size;
423 	int pagesize = getpagesize();
424 
425 	uptime = getuptime();
426 	halfuptime = uptime / 2;
427 	(void)signal(SIGCONT, needhdr);
428 
429 	if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
430 		kread(X_STATHZ, &hz, sizeof(hz));
431 	if (!hz)
432 		kread(X_HZ, &hz, sizeof(hz));
433 
434 	for (hdrcnt = 1;;) {
435 		if (!--hdrcnt)
436 			printhdr();
437 		/* Read new disk statistics */
438 		dkreadstats();
439 		kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
440 		if (memf != NULL) {
441 			/*
442 			 * XXX Can't do this if we're reading a crash
443 			 * XXX dump because they're lazily-calculated.
444 			 */
445 			printf("Unable to get vmtotals from crash dump.\n");
446 			memset(&total, 0, sizeof(total));
447 		} else {
448 			size = sizeof(total);
449 			mib[0] = CTL_VM;
450 			mib[1] = VM_METER;
451 			if (sysctl(mib, 2, &total, &size, NULL, 0) < 0) {
452 				printf("Can't get vmtotals: %s\n",
453 				    strerror(errno));
454 				memset(&total, 0, sizeof(total));
455 			}
456 		}
457 		(void)printf("%2d%2d%2d",
458 		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
459 #define pgtok(a) (long)((a) * (pagesize >> 10))
460 #define	rate(x)	(u_long)(((x) + halfuptime) / uptime)	/* round */
461 		(void)printf("%6ld%6ld ",
462 		    pgtok(total.t_avm), pgtok(total.t_free));
463 		(void)printf("%4lu ", rate(uvmexp.faults - ouvmexp.faults));
464 		(void)printf("%3lu ", rate(uvmexp.pdreact - ouvmexp.pdreact));
465 		(void)printf("%3lu ", rate(uvmexp.pageins - ouvmexp.pageins));
466 		(void)printf("%4lu ",
467 		    rate(uvmexp.pgswapout - ouvmexp.pgswapout));
468 		(void)printf("%4lu ", rate(uvmexp.pdfreed - ouvmexp.pdfreed));
469 		(void)printf("%4lu ", rate(uvmexp.pdscans - ouvmexp.pdscans));
470 		dkstats();
471 		(void)printf("%4lu %4lu %3lu ",
472 		    rate(uvmexp.intrs - ouvmexp.intrs),
473 		    rate(uvmexp.syscalls - ouvmexp.syscalls),
474 		    rate(uvmexp.swtch - ouvmexp.swtch));
475 		cpustats();
476 		(void)printf("\n");
477 		(void)fflush(stdout);
478 		if (reps >= 0 && --reps <= 0)
479 			break;
480 		ouvmexp = uvmexp;
481 		uptime = interval;
482 		/*
483 		 * We round upward to avoid losing low-frequency events
484 		 * (i.e., >= 1 per interval but < 1 per second).
485 		 */
486 		halfuptime = uptime == 1 ? 0 : (uptime + 1) / 2;
487 		(void)sleep(interval);
488 	}
489 }
490 
491 void
492 printhdr()
493 {
494 	int i;
495 
496 	(void)printf(" procs   memory     page%*s", 23, "");
497 	if (ndrives > 0)
498 		(void)printf("%s %*sfaults   cpu\n",
499 		   ((ndrives > 1) ? "disks" : "disk"),
500 		   ((ndrives > 1) ? ndrives * 3 - 4 : 0), "");
501 	else
502 		(void)printf("%*s  faults   cpu\n",
503 		   ndrives * 3, "");
504 
505 	(void)printf(" r b w   avm   fre  flt  re  pi   po   fr   sr ");
506 	for (i = 0; i < dk_ndrive; i++)
507 		if (dk_select[i])
508 			(void)printf("%c%c ", dr_name[i][0],
509 			    dr_name[i][strlen(dr_name[i]) - 1]);
510 	(void)printf("  in   sy  cs us sy id\n");
511 	hdrcnt = winlines - 2;
512 }
513 
514 /*
515  * Force a header to be prepended to the next output.
516  */
517 void
518 needhdr(dummy)
519 	int dummy;
520 {
521 
522 	hdrcnt = 1;
523 }
524 
525 long
526 pct(top, bot)
527 	long top, bot;
528 {
529 	long ans;
530 
531 	if (bot == 0)
532 		return(0);
533 	ans = (quad_t)top * 100 / bot;
534 	return (ans);
535 }
536 
537 #define	PCT(top, bot) (int)pct((long)(top), (long)(bot))
538 
539 void
540 dosum()
541 {
542 	struct nchstats nchstats;
543 	long nchtotal;
544 
545 	kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
546 
547 	(void)printf("%9u bytes per page\n", uvmexp.pagesize);
548 
549 	(void)printf("%9u pages managed\n", uvmexp.npages);
550 	(void)printf("%9u pages free\n", uvmexp.free);
551 	(void)printf("%9u pages active\n", uvmexp.active);
552 	(void)printf("%9u pages inactive\n", uvmexp.inactive);
553 	(void)printf("%9u pages paging\n", uvmexp.paging);
554 	(void)printf("%9u pages wired\n", uvmexp.wired);
555 	(void)printf("%9u reserve pagedaemon pages\n",
556 	    uvmexp.reserve_pagedaemon);
557 	(void)printf("%9u reserve kernel pages\n", uvmexp.reserve_kernel);
558 
559 	(void)printf("%9u minimum free pages\n", uvmexp.freemin);
560 	(void)printf("%9u target free pages\n", uvmexp.freetarg);
561 	(void)printf("%9u target inactive pages\n", uvmexp.inactarg);
562 	(void)printf("%9u maximum wired pages\n", uvmexp.wiredmax);
563 
564 	(void)printf("%9u swap devices\n", uvmexp.nswapdev);
565 	(void)printf("%9u swap pages\n", uvmexp.swpages);
566 	(void)printf("%9u swap pages in use\n", uvmexp.swpginuse);
567 	(void)printf("%9u swap allocations\n", uvmexp.nswget);
568 	(void)printf("%9u anons\n", uvmexp.nanon);
569 	(void)printf("%9u free anons\n", uvmexp.nfreeanon);
570 
571 	(void)printf("%9u total faults taken\n", uvmexp.faults);
572 	(void)printf("%9u traps\n", uvmexp.traps);
573 	(void)printf("%9u device interrupts\n", uvmexp.intrs);
574 	(void)printf("%9u cpu context switches\n", uvmexp.swtch);
575 	(void)printf("%9u software interrupts\n", uvmexp.softs);
576 	(void)printf("%9u system calls\n", uvmexp.syscalls);
577 	(void)printf("%9u pagein requests\n", uvmexp.pageins);
578 	(void)printf("%9u pageout requests\n", uvmexp.pdpageouts);
579 	(void)printf("%9u swap ins\n", uvmexp.swapins);
580 	(void)printf("%9u swap outs\n", uvmexp.swapouts);
581 	(void)printf("%9u pages swapped in\n", uvmexp.pgswapin);
582 	(void)printf("%9u pages swapped out\n", uvmexp.pgswapout);
583 	(void)printf("%9u forks total\n", uvmexp.forks);
584 	(void)printf("%9u forks blocked parent\n", uvmexp.forks_ppwait);
585 	(void)printf("%9u forks shared address space with parent\n",
586 	    uvmexp.forks_sharevm);
587 
588 	(void)printf("%9u faults with no memory\n", uvmexp.fltnoram);
589 	(void)printf("%9u faults with no anons\n", uvmexp.fltnoanon);
590 	(void)printf("%9u faults had to wait on pages\n", uvmexp.fltpgwait);
591 	(void)printf("%9u faults found released page\n", uvmexp.fltpgrele);
592 	(void)printf("%9u faults relock (%u ok)\n", uvmexp.fltrelck,
593 	    uvmexp.fltrelckok);
594 	(void)printf("%9u anon page faults\n", uvmexp.fltanget);
595 	(void)printf("%9u anon retry faults\n", uvmexp.fltanretry);
596 	(void)printf("%9u amap copy faults\n", uvmexp.fltamcopy);
597 	(void)printf("%9u neighbour anon page faults\n", uvmexp.fltnamap);
598 	(void)printf("%9u neighbour object page faults\n", uvmexp.fltnomap);
599 	(void)printf("%9u locked pager get faults\n", uvmexp.fltlget);
600 	(void)printf("%9u unlocked pager get faults\n", uvmexp.fltget);
601 	(void)printf("%9u anon faults\n", uvmexp.flt_anon);
602 	(void)printf("%9u anon copy on write faults\n", uvmexp.flt_acow);
603 	(void)printf("%9u object faults\n", uvmexp.flt_obj);
604 	(void)printf("%9u promote copy faults\n", uvmexp.flt_prcopy);
605 	(void)printf("%9u promote zero fill faults\n", uvmexp.flt_przero);
606 
607 	(void)printf("%9u times daemon wokeup\n",uvmexp.pdwoke);
608 	(void)printf("%9u revolutions of the clock hand\n", uvmexp.pdrevs);
609 	(void)printf("%9u times daemon attempted swapout\n", uvmexp.pdswout);
610 	(void)printf("%9u pages freed by daemon\n", uvmexp.pdfreed);
611 	(void)printf("%9u pages scanned by daemon\n", uvmexp.pdscans);
612 	(void)printf("%9u anonymous pages scanned by daemon\n", uvmexp.pdanscan);
613 	(void)printf("%9u object pages scanned by daemon\n", uvmexp.pdobscan);
614 	(void)printf("%9u pages reactivated\n", uvmexp.pdreact);
615 	(void)printf("%9u pages found busy by daemon\n", uvmexp.pdbusy);
616 	(void)printf("%9u total pending pageouts\n", uvmexp.pdpending);
617 	(void)printf("%9u pages deactivated\n", uvmexp.pddeact);
618 	kread(X_NCHSTATS, &nchstats, sizeof(nchstats));
619 	nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
620 	    nchstats.ncs_badhits + nchstats.ncs_falsehits +
621 	    nchstats.ncs_miss + nchstats.ncs_long;
622 	(void)printf("%9ld total name lookups\n", nchtotal);
623 	(void)printf(
624 	    "%9s cache hits (%d%% pos + %d%% neg) system %d%% per-process\n",
625 	    "", PCT(nchstats.ncs_goodhits, nchtotal),
626 	    PCT(nchstats.ncs_neghits, nchtotal),
627 	    PCT(nchstats.ncs_pass2, nchtotal));
628 	(void)printf("%9s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
629 	    PCT(nchstats.ncs_badhits, nchtotal),
630 	    PCT(nchstats.ncs_falsehits, nchtotal),
631 	    PCT(nchstats.ncs_long, nchtotal));
632 }
633 
634 void
635 doforkst()
636 {
637 
638 	kread(X_UVMEXP, &uvmexp, sizeof(uvmexp));
639 
640 	(void)printf("%u forks total\n", uvmexp.forks);
641 	(void)printf("%u forks blocked parent\n", uvmexp.forks_ppwait);
642 	(void)printf("%u forks shared address space with parent\n",
643 	    uvmexp.forks_sharevm);
644 }
645 
646 void
647 dkstats()
648 {
649 	int dn, state;
650 	double etime;
651 
652 	/* Calculate disk stat deltas. */
653 	dkswap();
654 	etime = 0;
655 	for (state = 0; state < CPUSTATES; ++state) {
656 		etime += cur.cp_time[state];
657 	}
658 	if (etime == 0)
659 		etime = 1;
660 	etime /= hz;
661 	for (dn = 0; dn < dk_ndrive; ++dn) {
662 		if (!dk_select[dn])
663 			continue;
664 		(void)printf("%2.0f ", cur.dk_xfer[dn] / etime);
665 	}
666 }
667 
668 void
669 cpustats()
670 {
671 	int state;
672 	double pct, total;
673 
674 	total = 0;
675 	for (state = 0; state < CPUSTATES; ++state)
676 		total += cur.cp_time[state];
677 	if (total)
678 		pct = 100 / total;
679 	else
680 		pct = 0;
681 	(void)printf("%2.0f ", (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * pct);
682 	(void)printf("%2.0f ", (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * pct);
683 	(void)printf("%2.0f", cur.cp_time[CP_IDLE] * pct);
684 }
685 
686 #if defined(pc532)
687 /* To get struct iv ...*/
688 #define _KERNEL
689 #include <machine/psl.h>
690 #undef _KERNEL
691 void
692 dointr()
693 {
694 	long i, j, inttotal, uptime;
695 	static char iname[64];
696 	struct iv ivt[32], *ivp = ivt;
697 
698 	iname[63] = '\0';
699 	uptime = getuptime();
700 	kread(X_IVT, ivp, sizeof(ivt));
701 
702 	for (i = 0; i < 2; i++) {
703 		(void)printf("%sware interrupts:\n", i ? "\nsoft" : "hard");
704 		(void)printf("interrupt       total     rate\n");
705 		inttotal = 0;
706 		for (j = 0; j < 16; j++, ivp++) {
707 			if (ivp->iv_vec && ivp->iv_use && ivp->iv_cnt) {
708 				if (kvm_read(kd, (u_long)ivp->iv_use, iname, 63) != 63) {
709 					(void)fprintf(stderr, "vmstat: iv_use: %s\n",
710 					    kvm_geterr(kd));
711 					exit(1);
712 				}
713 				(void)printf("%-12s %8ld %8ld\n", iname,
714 				    ivp->iv_cnt, ivp->iv_cnt / uptime);
715 				inttotal += ivp->iv_cnt;
716 			}
717 		}
718 		(void)printf("Total        %8ld %8ld\n",
719 		    inttotal, inttotal / uptime);
720 	}
721 }
722 #else
723 void
724 dointr()
725 {
726 	long *intrcnt, inttotal, uptime;
727 	int nintr, inamlen;
728 	char *intrname;
729 	struct evcntlist allevents;
730 	struct evcnt evcnt, *evptr;
731 	struct device dev;
732 
733 	uptime = getuptime();
734 	nintr = namelist[X_EINTRCNT].n_value - namelist[X_INTRCNT].n_value;
735 	inamlen =
736 	    namelist[X_EINTRNAMES].n_value - namelist[X_INTRNAMES].n_value;
737 	intrcnt = malloc((size_t)nintr);
738 	intrname = malloc((size_t)inamlen);
739 	if (intrcnt == NULL || intrname == NULL) {
740 		(void)fprintf(stderr, "vmstat: %s.\n", strerror(errno));
741 		exit(1);
742 	}
743 	kread(X_INTRCNT, intrcnt, (size_t)nintr);
744 	kread(X_INTRNAMES, intrname, (size_t)inamlen);
745 	(void)printf("interrupt         total     rate\n");
746 	inttotal = 0;
747 	nintr /= sizeof(long);
748 	while (--nintr >= 0) {
749 		if (*intrcnt)
750 			(void)printf("%-14s %8ld %8ld\n", intrname,
751 			    *intrcnt, *intrcnt / uptime);
752 		intrname += strlen(intrname) + 1;
753 		inttotal += *intrcnt++;
754 	}
755 	kread(X_ALLEVENTS, &allevents, sizeof allevents);
756 	evptr = allevents.tqh_first;
757 	while (evptr) {
758 		if (kvm_read(kd, (long)evptr, (void *)&evcnt,
759 		    sizeof evcnt) != sizeof evcnt) {
760 			(void)fprintf(stderr, "vmstat: event chain trashed: %s\n",
761 			    kvm_geterr(kd));
762 			exit(1);
763 		}
764 		if (kvm_read(kd, (long)evcnt.ev_dev, (void *)&dev,
765 		    sizeof dev) != sizeof dev) {
766 			(void)fprintf(stderr, "vmstat: event chain trashed: %s\n",
767 			    kvm_geterr(kd));
768 			exit(1);
769 		}
770 		if (evcnt.ev_count)
771 			(void)printf("%-14s %8ld %8ld\n", dev.dv_xname,
772 			    (long)evcnt.ev_count, evcnt.ev_count / uptime);
773 		inttotal += evcnt.ev_count++;
774 
775 		evptr = evcnt.ev_list.tqe_next;
776 	}
777 	(void)printf("Total          %8ld %8ld\n", inttotal, inttotal / uptime);
778 }
779 #endif
780 
781 /*
782  * These names are defined in <sys/malloc.h>.
783  */
784 char *kmemnames[] = INITKMEMNAMES;
785 
786 void
787 domem()
788 {
789 	struct kmembuckets *kp;
790 	struct kmemstats *ks;
791 	int i, j;
792 	int len, size, first;
793 	long totuse = 0, totfree = 0, totreq = 0;
794 	char *name;
795 	struct kmemstats kmemstats[M_LAST];
796 	struct kmembuckets buckets[MINBUCKET + 16];
797 
798 	kread(X_KMEMBUCKETS, buckets, sizeof(buckets));
799 	for (first = 1, i = MINBUCKET, kp = &buckets[i]; i < MINBUCKET + 16;
800 	    i++, kp++) {
801 		if (kp->kb_calls == 0)
802 			continue;
803 		if (first) {
804 			(void)printf("Memory statistics by bucket size\n");
805 			(void)printf(
806 		 "    Size   In Use   Free   Requests  HighWater  Couldfree\n");
807 			first = 0;
808 		}
809 		size = 1 << i;
810 		(void)printf("%8d %8ld %6ld %10ld %7ld %10ld\n", size,
811 			kp->kb_total - kp->kb_totalfree,
812 			kp->kb_totalfree, kp->kb_calls,
813 			kp->kb_highwat, kp->kb_couldfree);
814 		totfree += size * kp->kb_totalfree;
815 	}
816 
817 	/*
818 	 * If kmem statistics are not being gathered by the kernel,
819 	 * first will still be 1.
820 	 */
821 	if (first) {
822 		printf(
823 		    "Kmem statistics are not being gathered by the kernel.\n");
824 		return;
825 	}
826 
827 	kread(X_KMEMSTAT, kmemstats, sizeof(kmemstats));
828 	(void)printf("\nMemory usage type by bucket size\n");
829 	(void)printf("    Size  Type(s)\n");
830 	kp = &buckets[MINBUCKET];
831 	for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1, kp++) {
832 		if (kp->kb_calls == 0)
833 			continue;
834 		first = 1;
835 		len = 8;
836 		for (i = 0, ks = &kmemstats[0]; i < M_LAST; i++, ks++) {
837 			if (ks->ks_calls == 0)
838 				continue;
839 			if ((ks->ks_size & j) == 0)
840 				continue;
841 			if (kmemnames[i] == 0) {
842 				kmemnames[i] = malloc(10);
843 						/* strlen("undef/")+3+1);*/
844 				snprintf(kmemnames[i], 10, "undef/%d", i);
845 						/* same 10 as above!!! */
846 			}
847 			name = kmemnames[i];
848 			len += 2 + strlen(name);
849 			if (first)
850 				printf("%8d  %s", j, name);
851 			else
852 				printf(",");
853 			if (len >= 80) {
854 				printf("\n\t ");
855 				len = 10 + strlen(name);
856 			}
857 			if (!first)
858 				printf(" %s", name);
859 			first = 0;
860 		}
861 		printf("\n");
862 	}
863 
864 	(void)printf(
865 	    "\nMemory statistics by type                        Type  Kern\n");
866 	(void)printf(
867 "         Type  InUse MemUse HighUse  Limit Requests Limit Limit Size(s)\n");
868 	for (i = 0, ks = &kmemstats[0]; i < M_LAST; i++, ks++) {
869 		if (ks->ks_calls == 0)
870 			continue;
871 		(void)printf("%14s%6ld%6ldK%7ldK%6ldK%9ld%5u%6u",
872 		    kmemnames[i] ? kmemnames[i] : "undefined",
873 		    ks->ks_inuse, (ks->ks_memuse + 1023) / 1024,
874 		    (ks->ks_maxused + 1023) / 1024,
875 		    (ks->ks_limit + 1023) / 1024, ks->ks_calls,
876 		    ks->ks_limblocks, ks->ks_mapblocks);
877 		first = 1;
878 		for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
879 			if ((ks->ks_size & j) == 0)
880 				continue;
881 			if (first)
882 				printf("  %d", j);
883 			else
884 				printf(",%d", j);
885 			first = 0;
886 		}
887 		printf("\n");
888 		totuse += ks->ks_memuse;
889 		totreq += ks->ks_calls;
890 	}
891 	(void)printf("\nMemory Totals:  In Use    Free    Requests\n");
892 	(void)printf("              %7ldK %6ldK    %8ld\n",
893 	     (totuse + 1023) / 1024, (totfree + 1023) / 1024, totreq);
894 }
895 
896 void
897 dopool()
898 {
899 	int first;
900 	long addr;
901 	long total = 0, inuse = 0;
902 	TAILQ_HEAD(,pool) pool_head;
903 	struct pool pool, *pp = &pool;
904 
905 	kread(X_POOLHEAD, &pool_head, sizeof(pool_head));
906 	addr = (long)TAILQ_FIRST(&pool_head);
907 
908 	for (first = 1; addr != 0; ) {
909 		char name[32], maxp[32];
910 		if (kvm_read(kd, addr, (void *)pp, sizeof *pp) != sizeof *pp) {
911 			(void)fprintf(stderr, "vmstat: pool chain trashed: %s\n",
912 			    kvm_geterr(kd));
913 			exit(1);
914 		}
915 		if (kvm_read(kd, (long)pp->pr_wchan, name, sizeof name) < 0) {
916 			(void)fprintf(stderr, "vmstat: pool name trashed: %s\n",
917 			    kvm_geterr(kd));
918 			exit(1);
919 		}
920 		name[31]='\0';
921 
922 		if (first) {
923 			(void)printf("Memory resource pool statistics\n");
924 			(void)printf(
925 			"%-11s%5s%9s%5s%9s%6s%6s%6s%6s%6s%6s%5s\n",
926 		 		"Name",
927 				"Size",
928 				"Requests",
929 				"Fail",
930 				"Releases",
931 				"Pgreq",
932 				"Pgrel",
933 				"Npage",
934 				"Hiwat",
935 				"Minpg",
936 				"Maxpg",
937 				"Idle");
938 			first = 0;
939 		}
940 		if (pp->pr_maxpages == UINT_MAX)
941 			sprintf(maxp, "inf");
942 		else
943 			sprintf(maxp, "%6u", pp->pr_maxpages);
944 		(void)printf(
945 		    "%-11s%5u%9lu%5lu%9lu%6lu%6lu%6d%6d%6d%6s%5lu\n",
946 			name,
947 			pp->pr_size,
948 			pp->pr_nget,
949 			pp->pr_nfail,
950 			pp->pr_nput,
951 			pp->pr_npagealloc,
952 			pp->pr_npagefree,
953 			pp->pr_npages,
954 			pp->pr_hiwat,
955 			pp->pr_minpages,
956 			maxp,
957 			pp->pr_nidle);
958 
959 		inuse += (pp->pr_nget - pp->pr_nput) * pp->pr_size;
960 		total += pp->pr_npages * pp->pr_pagesz;
961 		addr = (long)TAILQ_NEXT(pp, pr_poollist);
962 	}
963 
964 	printf("\nIn use %ldK, total allocated %ldK; utilization %.1f%%\n",
965 		inuse/1024, total/1024, (double)(100 * inuse) / total);
966 
967 }
968 
969 /*
970  * kread reads something from the kernel, given its nlist index.
971  */
972 void
973 kread(nlx, addr, size)
974 	int nlx;
975 	void *addr;
976 	size_t size;
977 {
978 	const char *sym;
979 
980 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
981 		sym = namelist[nlx].n_name;
982 		if (*sym == '_')
983 			++sym;
984 		(void)fprintf(stderr,
985 		    "vmstat: symbol %s not defined\n", sym);
986 		exit(1);
987 	}
988 	if (kvm_read(kd, namelist[nlx].n_value, addr, size) != size) {
989 		sym = namelist[nlx].n_name;
990 		if (*sym == '_')
991 			++sym;
992 		(void)fprintf(stderr, "vmstat: %s: %s\n", sym, kvm_geterr(kd));
993 		exit(1);
994 	}
995 }
996 
997 struct nlist histnl[] = {
998 	{ "_uvm_histories" },
999 #define	X_UVM_HISTORIES		0
1000 	{ NULL },
1001 };
1002 
1003 /*
1004  * Traverse the UVM history buffers, performing the requested action.
1005  *
1006  * Note, we assume that if we're not listing, we're dumping.
1007  */
1008 void
1009 hist_traverse(todo, histname)
1010 	int todo;
1011 	const char *histname;
1012 {
1013 	struct uvm_history_head histhead;
1014 	struct uvm_history hist, *histkva;
1015 	char *name = NULL;
1016 	size_t namelen = 0;
1017 
1018 	if (kvm_nlist(kd, histnl) != 0) {
1019 		printf("UVM history is not compiled into the kernel.\n");
1020 		return;
1021 	}
1022 
1023 	if (kvm_read(kd, histnl[X_UVM_HISTORIES].n_value, &histhead,
1024 	    sizeof(histhead)) != sizeof(histhead)) {
1025 		warnx("unable to read %s: %s",
1026 		    histnl[X_UVM_HISTORIES].n_name, kvm_geterr(kd));
1027 		return;
1028 	}
1029 
1030 	if (histhead.lh_first == NULL) {
1031 		printf("No active UVM history logs.\n");
1032 		return;
1033 	}
1034 
1035 	if (todo & HISTLIST)
1036 		printf("Active UVM histories:");
1037 
1038 	for (histkva = histhead.lh_first; histkva != NULL;
1039 	    histkva = hist.list.le_next) {
1040 		if (kvm_read(kd, (u_long)histkva, &hist, sizeof(hist)) !=
1041 		    sizeof(hist)) {
1042 			warnx("unable to read history at %p: %s",
1043 			    histkva, kvm_geterr(kd));
1044 			goto out;
1045 		}
1046 
1047 		if (hist.namelen > namelen) {
1048 			if (name != NULL)
1049 				free(name);
1050 			namelen = hist.namelen;
1051 			if ((name = malloc(namelen + 1)) == NULL)
1052 				err(1, "malloc history name");
1053 		}
1054 
1055 		if (kvm_read(kd, (u_long)hist.name, name, namelen) !=
1056 		    namelen) {
1057 			warnx("unable to read history name at %p: %s",
1058 			    hist.name, kvm_geterr(kd));
1059 			goto out;
1060 		}
1061 		name[namelen] = '\0';
1062 		if (todo & HISTLIST)
1063 			printf(" %s", name);
1064 		else {
1065 			/*
1066 			 * If we're dumping all histories, do it, else
1067 			 * check to see if this is the one we want.
1068 			 */
1069 			if (histname == NULL || strcmp(histname, name) == 0) {
1070 				if (histname == NULL)
1071 					printf("\nUVM history `%s':\n", name);
1072 				hist_dodump(&hist);
1073 			}
1074 		}
1075 	}
1076 
1077 	if (todo & HISTLIST)
1078 		printf("\n");
1079 
1080  out:
1081 	if (name != NULL)
1082 		free(name);
1083 }
1084 
1085 /*
1086  * Actually dump the history buffer at the specified KVA.
1087  */
1088 void
1089 hist_dodump(histp)
1090 	struct uvm_history *histp;
1091 {
1092 	struct uvm_history_ent *histents, *e;
1093 	size_t histsize;
1094 	char *fmt = NULL, *fn = NULL;
1095 	size_t fmtlen = 0, fnlen = 0;
1096 	int i;
1097 
1098 	histsize = sizeof(struct uvm_history_ent) * histp->n;
1099 
1100 	if ((histents = malloc(histsize)) == NULL)
1101 		err(1, "malloc history entries");
1102 
1103 	memset(histents, 0, histsize);
1104 
1105 	if (kvm_read(kd, (u_long)histp->e, histents, histsize) != histsize) {
1106 		warnx("unable to read history entries at %p: %s",
1107 		    histp->e, kvm_geterr(kd));
1108 		goto out;
1109 	}
1110 
1111 	i = histp->f;
1112 	do {
1113 		e = &histents[i];
1114 		if (e->fmt != NULL) {
1115 			if (e->fmtlen > fmtlen) {
1116 				if (fmt != NULL)
1117 					free(fmt);
1118 				fmtlen = e->fmtlen;
1119 				if ((fmt = malloc(fmtlen + 1)) == NULL)
1120 					err(1, "malloc printf format");
1121 			}
1122 			if (e->fnlen > fnlen) {
1123 				if (fn != NULL)
1124 					free(fn);
1125 				fnlen = e->fnlen;
1126 				if ((fn = malloc(fnlen + 1)) == NULL)
1127 					err(1, "malloc function name");
1128 			}
1129 
1130 			if (kvm_read(kd, (u_long)e->fmt, fmt, fmtlen)
1131 			    != fmtlen) {
1132 				warnx("unable to read printf format "
1133 				    "at %p: %s", e->fmt, kvm_geterr(kd));
1134 				goto out;
1135 			}
1136 			fmt[fmtlen] = '\0';
1137 
1138 			if (kvm_read(kd, (u_long)e->fn, fn, fnlen) != fnlen) {
1139 				warnx("unable to read function name "
1140 				    "at %p: %s", e->fn, kvm_geterr(kd));
1141 				goto out;
1142 			}
1143 			fn[fnlen] = '\0';
1144 
1145 			printf("%06ld.%06ld ", e->tv.tv_sec, e->tv.tv_usec);
1146 			printf("%s#%ld: ", fn, e->call);
1147 			printf(fmt, e->v[0], e->v[1], e->v[2], e->v[3]);
1148 			printf("\n");
1149 		}
1150 		i = (i + 1) % histp->n;
1151 	} while (i != histp->f);
1152 
1153  out:
1154 	free(histents);
1155 	if (fmt != NULL)
1156 		free(fmt);
1157 	if (fn != NULL)
1158 		free(fn);
1159 }
1160 
1161 void
1162 usage()
1163 {
1164 
1165 	(void)fprintf(stderr,
1166 	    "usage: vmstat [-fHilms] [-h histname] [-c count] [-M core] \
1167 [-N system] [-w wait] [disks]\n");
1168 	exit(1);
1169 }
1170