xref: /dragonfly/usr.bin/vmstat/vmstat.c (revision 2cd2d2b5)
1 /*
2  * Copyright (c) 1980, 1986, 1991, 1993
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * @(#) Copyright (c) 1980, 1986, 1991, 1993 The Regents of the University of California.  All rights reserved.
34  * @(#)vmstat.c	8.1 (Berkeley) 6/6/93
35  * $FreeBSD: src/usr.bin/vmstat/vmstat.c,v 1.38.2.4 2001/07/31 19:52:41 tmm Exp $
36  * $DragonFly: src/usr.bin/vmstat/vmstat.c,v 1.12 2004/06/27 17:39:05 dillon Exp $
37  */
38 
39 #define _KERNEL_STRUCTURES
40 
41 #include <sys/param.h>
42 #include <sys/time.h>
43 #include <sys/user.h>
44 #include <sys/dkstat.h>
45 #include <sys/uio.h>
46 #include <sys/namei.h>
47 #include <sys/malloc.h>
48 #include <sys/signal.h>
49 #include <sys/fcntl.h>
50 #include <sys/ioctl.h>
51 #include <sys/sysctl.h>
52 #include <sys/vmmeter.h>
53 
54 #include <vm/vm_param.h>
55 
56 #include <ctype.h>
57 #include <err.h>
58 #include <errno.h>
59 #include <kvm.h>
60 #include <limits.h>
61 #include <nlist.h>
62 #include <paths.h>
63 #include <stdio.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <sysexits.h>
67 #include <time.h>
68 #include <unistd.h>
69 #include <devstat.h>
70 
71 static struct nlist namelist[] = {
72 #define	X_CPTIME	0
73 	{ "_cp_time" },
74 #define	X_BOOTTIME	1
75 	{ "_boottime" },
76 #define X_HZ		2
77 	{ "_hz" },
78 #define X_STATHZ	3
79 	{ "_stathz" },
80 #define X_NCHSTATS	4
81 	{ "_nchstats" },
82 #define	X_INTRNAMES	5
83 	{ "_intrnames" },
84 #define	X_EINTRNAMES	6
85 	{ "_eintrnames" },
86 #define	X_INTRCNT	7
87 	{ "_intrcnt" },
88 #define	X_EINTRCNT	8
89 	{ "_eintrcnt" },
90 #define	X_KMEMSTATISTICS	9
91 	{ "_kmemstatistics" },
92 #define	X_ZLIST		10
93 	{ "_zlist" },
94 #ifdef notyet
95 #define	X_DEFICIT	11
96 	{ "_deficit" },
97 #define	X_FORKSTAT	12
98 	{ "_forkstat" },
99 #define X_REC		13
100 	{ "_rectime" },
101 #define X_PGIN		14
102 	{ "_pgintime" },
103 #define	X_XSTATS	15
104 	{ "_xstats" },
105 #define X_END		16
106 #else
107 #define X_END		11
108 #endif
109 	{ "" },
110 };
111 
112 struct statinfo cur, last;
113 int num_devices, maxshowdevs;
114 long generation;
115 struct device_selection *dev_select;
116 int num_selected;
117 struct devstat_match *matches;
118 int num_matches = 0;
119 int num_devices_specified, num_selections;
120 long select_generation;
121 char **specified_devices;
122 devstat_select_mode select_mode;
123 
124 struct	vmmeter vmm, ovmm;
125 struct	vmstats vms, ovms;
126 
127 int	winlines = 20;
128 int	nflag = 0;
129 
130 kvm_t *kd;
131 
132 #define	FORKSTAT	0x01
133 #define	INTRSTAT	0x02
134 #define	MEMSTAT		0x04
135 #define	SUMSTAT		0x08
136 #define	TIMESTAT	0x10
137 #define	VMSTAT		0x20
138 #define ZMEMSTAT	0x40
139 
140 void	cpustats(), dointr(), domem(), dosum(), dozmem();
141 void	dovmstat(), kread(), usage();
142 #ifdef notyet
143 void	dotimes(), doforkst();
144 #endif
145 void printhdr(void);
146 static void devstats();
147 
148 int
149 main(register int argc, register char **argv)
150 {
151 	register int c, todo;
152 	u_int interval;
153 	int reps;
154 	char *memf, *nlistf;
155 	char errbuf[_POSIX2_LINE_MAX];
156 
157 	memf = nlistf = NULL;
158 	interval = reps = todo = 0;
159 	maxshowdevs = 2;
160 	while ((c = getopt(argc, argv, "c:fiM:mN:n:p:stw:z")) != -1) {
161 		switch (c) {
162 		case 'c':
163 			reps = atoi(optarg);
164 			break;
165 		case 'f':
166 #ifdef notyet
167 			todo |= FORKSTAT;
168 #else
169 			errx(EX_USAGE, "sorry, -f is not (re)implemented yet");
170 #endif
171 			break;
172 		case 'i':
173 			todo |= INTRSTAT;
174 			break;
175 		case 'M':
176 			memf = optarg;
177 			break;
178 		case 'm':
179 			todo |= MEMSTAT;
180 			break;
181 		case 'N':
182 			nlistf = optarg;
183 			break;
184 		case 'n':
185 			nflag = 1;
186 			maxshowdevs = atoi(optarg);
187 			if (maxshowdevs < 0)
188 				errx(1, "number of devices %d is < 0",
189 				     maxshowdevs);
190 			break;
191 		case 'p':
192 			if (buildmatch(optarg, &matches, &num_matches) != 0)
193 				errx(1, "%s", devstat_errbuf);
194 			break;
195 		case 's':
196 			todo |= SUMSTAT;
197 			break;
198 		case 't':
199 #ifdef notyet
200 			todo |= TIMESTAT;
201 #else
202 			errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
203 #endif
204 			break;
205 		case 'w':
206 			interval = atoi(optarg);
207 			break;
208 		case 'z':
209 			todo |= ZMEMSTAT;
210 			break;
211 		case '?':
212 		default:
213 			usage();
214 		}
215 	}
216 	argc -= optind;
217 	argv += optind;
218 
219 	if (todo == 0)
220 		todo = VMSTAT;
221 
222 	/*
223 	 * Discard setgid privileges if not the running kernel so that bad
224 	 * guys can't print interesting stuff from kernel memory.
225 	 */
226 	if (nlistf != NULL || memf != NULL)
227 		setgid(getgid());
228 
229 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
230 	if (kd == 0)
231 		errx(1, "kvm_openfiles: %s", errbuf);
232 
233 	if ((c = kvm_nlist(kd, namelist)) != 0) {
234 		if (c > 0) {
235 			warnx("undefined symbols:");
236 			for (c = 0;
237 			    c < sizeof(namelist)/sizeof(namelist[0]); c++)
238 				if (namelist[c].n_type == 0)
239 					fprintf(stderr, " %s",
240 					    namelist[c].n_name);
241 			(void)fputc('\n', stderr);
242 		} else
243 			warnx("kvm_nlist: %s", kvm_geterr(kd));
244 		exit(1);
245 	}
246 
247 	if (todo & VMSTAT) {
248 		char **getdrivedata();
249 		struct winsize winsize;
250 
251 		/*
252 		 * Make sure that the userland devstat version matches the
253 		 * kernel devstat version.  If not, exit and print a
254 		 * message informing the user of his mistake.
255 		 */
256 		if (checkversion() < 0)
257 			errx(1, "%s", devstat_errbuf);
258 
259 
260 		argv = getdrivedata(argv);
261 		winsize.ws_row = 0;
262 		(void) ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
263 		if (winsize.ws_row > 0)
264 			winlines = winsize.ws_row;
265 
266 	}
267 
268 #define	BACKWARD_COMPATIBILITY
269 #ifdef	BACKWARD_COMPATIBILITY
270 	if (*argv) {
271 		interval = atoi(*argv);
272 		if (*++argv)
273 			reps = atoi(*argv);
274 	}
275 #endif
276 
277 	if (interval) {
278 		if (!reps)
279 			reps = -1;
280 	} else if (reps)
281 		interval = 1;
282 
283 #ifdef notyet
284 	if (todo & FORKSTAT)
285 		doforkst();
286 #endif
287 	if (todo & MEMSTAT)
288 		domem();
289 	if (todo & ZMEMSTAT)
290 		dozmem();
291 	if (todo & SUMSTAT)
292 		dosum();
293 #ifdef notyet
294 	if (todo & TIMESTAT)
295 		dotimes();
296 #endif
297 	if (todo & INTRSTAT)
298 		dointr();
299 	if (todo & VMSTAT)
300 		dovmstat(interval, reps);
301 	exit(0);
302 }
303 
304 char **
305 getdrivedata(char **argv)
306 {
307 	if ((num_devices = getnumdevs()) < 0)
308 		errx(1, "%s", devstat_errbuf);
309 
310 	cur.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
311 	last.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
312 	bzero(cur.dinfo, sizeof(struct devinfo));
313 	bzero(last.dinfo, sizeof(struct devinfo));
314 
315 	if (getdevs(&cur) == -1)
316 		errx(1, "%s", devstat_errbuf);
317 
318 	num_devices = cur.dinfo->numdevs;
319 	generation = cur.dinfo->generation;
320 
321 	specified_devices = (char **)malloc(sizeof(char *));
322 	for (num_devices_specified = 0; *argv; ++argv) {
323 		if (isdigit(**argv))
324 			break;
325 		num_devices_specified++;
326 		specified_devices = (char **)realloc(specified_devices,
327 						     sizeof(char *) *
328 						     num_devices_specified);
329 		specified_devices[num_devices_specified - 1] = *argv;
330 	}
331 	dev_select = NULL;
332 
333 	if (nflag == 0 && maxshowdevs < num_devices_specified)
334 			maxshowdevs = num_devices_specified;
335 
336 	/*
337 	 * People are generally only interested in disk statistics when
338 	 * they're running vmstat.  So, that's what we're going to give
339 	 * them if they don't specify anything by default.  We'll also give
340 	 * them any other random devices in the system so that we get to
341 	 * maxshowdevs devices, if that many devices exist.  If the user
342 	 * specifies devices on the command line, either through a pattern
343 	 * match or by naming them explicitly, we will give the user only
344 	 * those devices.
345 	 */
346 	if ((num_devices_specified == 0) && (num_matches == 0)) {
347 		if (buildmatch("da", &matches, &num_matches) != 0)
348 			errx(1, "%s", devstat_errbuf);
349 
350 		select_mode = DS_SELECT_ADD;
351 	} else
352 		select_mode = DS_SELECT_ONLY;
353 
354 	/*
355 	 * At this point, selectdevs will almost surely indicate that the
356 	 * device list has changed, so we don't look for return values of 0
357 	 * or 1.  If we get back -1, though, there is an error.
358 	 */
359 	if (selectdevs(&dev_select, &num_selected, &num_selections,
360 		       &select_generation, generation, cur.dinfo->devices,
361 		       num_devices, matches, num_matches, specified_devices,
362 		       num_devices_specified, select_mode,
363 		       maxshowdevs, 0) == -1)
364 		errx(1, "%s", devstat_errbuf);
365 
366 	return(argv);
367 }
368 
369 long
370 getuptime(void)
371 {
372 	static time_t now, boottime;
373 	time_t uptime;
374 
375 	if (boottime == 0)
376 		kread(X_BOOTTIME, &boottime, sizeof(boottime));
377 	(void)time(&now);
378 	uptime = now - boottime;
379 	if (uptime <= 0 || uptime > 60*60*24*365*10)
380 		errx(1, "time makes no sense; namelist must be wrong");
381 	return(uptime);
382 }
383 
384 int	hz, hdrcnt;
385 
386 void
387 dovmstat(u_int interval, int reps)
388 {
389 	struct vmtotal total;
390 	time_t uptime, halfuptime;
391 	struct devinfo *tmp_dinfo;
392 	void needhdr();
393 	int vmm_size = sizeof(vmm);
394 	int vms_size = sizeof(vms);
395 	int vmt_size = sizeof(total);
396 
397 	uptime = getuptime();
398 	halfuptime = uptime / 2;
399 	(void)signal(SIGCONT, needhdr);
400 
401 	if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
402 		kread(X_STATHZ, &hz, sizeof(hz));
403 	if (!hz)
404 		kread(X_HZ, &hz, sizeof(hz));
405 
406 	for (hdrcnt = 1;;) {
407 		if (!--hdrcnt)
408 			printhdr();
409 		kread(X_CPTIME, cur.cp_time, sizeof(cur.cp_time));
410 
411 		tmp_dinfo = last.dinfo;
412 		last.dinfo = cur.dinfo;
413 		cur.dinfo = tmp_dinfo;
414 		last.busy_time = cur.busy_time;
415 
416 		/*
417 		 * Here what we want to do is refresh our device stats.
418 		 * getdevs() returns 1 when the device list has changed.
419 		 * If the device list has changed, we want to go through
420 		 * the selection process again, in case a device that we
421 		 * were previously displaying has gone away.
422 		 */
423 		switch (getdevs(&cur)) {
424 		case -1:
425 			errx(1, "%s", devstat_errbuf);
426 			break;
427 		case 1: {
428 			int retval;
429 
430 			num_devices = cur.dinfo->numdevs;
431 			generation = cur.dinfo->generation;
432 
433 			retval = selectdevs(&dev_select, &num_selected,
434 					    &num_selections, &select_generation,
435 					    generation, cur.dinfo->devices,
436 					    num_devices, matches, num_matches,
437 					    specified_devices,
438 					    num_devices_specified, select_mode,
439 					    maxshowdevs, 0);
440 			switch (retval) {
441 			case -1:
442 				errx(1, "%s", devstat_errbuf);
443 				break;
444 			case 1:
445 				printhdr();
446 				break;
447 			default:
448 				break;
449 			}
450 		}
451 		default:
452 			break;
453 		}
454 
455 		if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
456 			perror("sysctlbyname: vm.vmstats");
457 			exit(1);
458 		}
459 		if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
460 			perror("sysctlbyname: vm.vmmeter");
461 			exit(1);
462 		}
463 		if (sysctlbyname("vm.vmtotal", &total, &vmt_size, NULL, 0)) {
464 			perror("sysctlbyname: vm.vmtotal");
465 			exit(1);
466 		}
467 		(void)printf("%2d %1d %1d",
468 		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
469 #define vmstat_pgtok(a) ((a) * vms.v_page_size >> 10)
470 #define	rate(x)	(((x) + halfuptime) / uptime)	/* round */
471 		(void)printf(" %7ld %6ld ",
472 		    (long)vmstat_pgtok(total.t_avm), (long)vmstat_pgtok(total.t_free));
473 		(void)printf("%4lu ",
474 		    (u_long)rate(vmm.v_vm_faults - ovmm.v_vm_faults));
475 		(void)printf("%3lu ",
476 		    (u_long)rate(vmm.v_reactivated - ovmm.v_reactivated));
477 		(void)printf("%3lu ",
478 		    (u_long)rate(vmm.v_swapin + vmm.v_vnodein -
479 		    (ovmm.v_swapin + ovmm.v_vnodein)));
480 		(void)printf("%3lu ",
481 		    (u_long)rate(vmm.v_swapout + vmm.v_vnodeout -
482 		    (ovmm.v_swapout + ovmm.v_vnodeout)));
483 		(void)printf("%3lu ",
484 		    (u_long)rate(vmm.v_tfree - ovmm.v_tfree));
485 		(void)printf("%3lu ",
486 		    (u_long)rate(vmm.v_pdpages - ovmm.v_pdpages));
487 		devstats();
488 		(void)printf("%4lu %4lu %3lu ",
489 		    (u_long)rate(vmm.v_intr - ovmm.v_intr),
490 		    (u_long)rate(vmm.v_syscall - ovmm.v_syscall),
491 		    (u_long)rate(vmm.v_swtch - ovmm.v_swtch));
492 		cpustats();
493 		(void)printf("\n");
494 		(void)fflush(stdout);
495 		if (reps >= 0 && --reps <= 0)
496 			break;
497 		ovmm = vmm;
498 		uptime = interval;
499 		/*
500 		 * We round upward to avoid losing low-frequency events
501 		 * (i.e., >= 1 per interval but < 1 per second).
502 		 */
503 		if (interval != 1)
504 			halfuptime = (uptime + 1) / 2;
505 		else
506 			halfuptime = 0;
507 		(void)sleep(interval);
508 	}
509 }
510 
511 void
512 printhdr(void)
513 {
514 	int i, num_shown;
515 
516 	num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
517 	(void)printf(" procs      memory      page%*s", 19, "");
518 	if (num_shown > 1)
519 		(void)printf(" disks %*s", num_shown * 4 - 7, "");
520 	else if (num_shown == 1)
521 		(void)printf("disk");
522 	(void)printf("   faults      cpu\n");
523 	(void)printf(" r b w     avm    fre  flt  re  pi  po  fr  sr ");
524 	for (i = 0; i < num_devices; i++)
525 		if ((dev_select[i].selected)
526 		 && (dev_select[i].selected <= maxshowdevs))
527 			(void)printf("%c%c%d ", dev_select[i].device_name[0],
528 				     dev_select[i].device_name[1],
529 				     dev_select[i].unit_number);
530 	(void)printf("  in   sy  cs us sy id\n");
531 	hdrcnt = winlines - 2;
532 }
533 
534 /*
535  * Force a header to be prepended to the next output.
536  */
537 void
538 needhdr(void)
539 {
540 
541 	hdrcnt = 1;
542 }
543 
544 long
545 pct(long top, long bot)
546 {
547 	long ans;
548 
549 	if (bot == 0)
550 		return(0);
551 	ans = (quad_t)top * 100 / bot;
552 	return (ans);
553 }
554 
555 #define	PCT(top, bot) pct((long)(top), (long)(bot))
556 
557 void
558 dosum(void)
559 {
560 	struct nchstats *nch_tmp, nchstats;
561 	int vms_size = sizeof(vms);
562 	int vmm_size = sizeof(vmm);
563 	int cpucnt;
564 	u_long nchtotal;
565 	size_t nch_size = sizeof(struct nchstats) * SMP_MAXCPU;
566 
567 	if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
568 		perror("sysctlbyname: vm.vmstats");
569 		exit(1);
570 	}
571 	if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
572 		perror("sysctlbyname: vm.vmstats");
573 		exit(1);
574 	}
575 	(void)printf("%9u cpu context switches\n", vmm.v_swtch);
576 	(void)printf("%9u device interrupts\n", vmm.v_intr);
577 	(void)printf("%9u software interrupts\n", vmm.v_soft);
578 	(void)printf("%9u traps\n", vmm.v_trap);
579 	(void)printf("%9u system calls\n", vmm.v_syscall);
580 	(void)printf("%9u kernel threads created\n", vmm.v_kthreads);
581 	(void)printf("%9u  fork() calls\n", vmm.v_forks);
582 	(void)printf("%9u vfork() calls\n", vmm.v_vforks);
583 	(void)printf("%9u rfork() calls\n", vmm.v_rforks);
584 	(void)printf("%9u exec() calls\n", vmm.v_exec);
585 	(void)printf("%9u swap pager pageins\n", vmm.v_swapin);
586 	(void)printf("%9u swap pager pages paged in\n", vmm.v_swappgsin);
587 	(void)printf("%9u swap pager pageouts\n", vmm.v_swapout);
588 	(void)printf("%9u swap pager pages paged out\n", vmm.v_swappgsout);
589 	(void)printf("%9u vnode pager pageins\n", vmm.v_vnodein);
590 	(void)printf("%9u vnode pager pages paged in\n", vmm.v_vnodepgsin);
591 	(void)printf("%9u vnode pager pageouts\n", vmm.v_vnodeout);
592 	(void)printf("%9u vnode pager pages paged out\n", vmm.v_vnodepgsout);
593 	(void)printf("%9u page daemon wakeups\n", vmm.v_pdwakeups);
594 	(void)printf("%9u pages examined by the page daemon\n", vmm.v_pdpages);
595 	(void)printf("%9u pages reactivated\n", vmm.v_reactivated);
596 	(void)printf("%9u copy-on-write faults\n", vmm.v_cow_faults);
597 	(void)printf("%9u copy-on-write optimized faults\n", vmm.v_cow_optim);
598 	(void)printf("%9u zero fill pages zeroed\n", vmm.v_zfod);
599 	(void)printf("%9u zero fill pages prezeroed\n", vmm.v_ozfod);
600 	(void)printf("%9u intransit blocking page faults\n", vmm.v_intrans);
601 	(void)printf("%9u total VM faults taken\n", vmm.v_vm_faults);
602 	(void)printf("%9u pages affected by kernel thread creation\n", vmm.v_kthreadpages);
603 	(void)printf("%9u pages affected by  fork()\n", vmm.v_forkpages);
604 	(void)printf("%9u pages affected by vfork()\n", vmm.v_vforkpages);
605 	(void)printf("%9u pages affected by rfork()\n", vmm.v_rforkpages);
606 	(void)printf("%9u pages freed\n", vmm.v_tfree);
607 	(void)printf("%9u pages freed by daemon\n", vmm.v_dfree);
608 	(void)printf("%9u pages freed by exiting processes\n", vmm.v_pfree);
609 	(void)printf("%9u pages active\n", vms.v_active_count);
610 	(void)printf("%9u pages inactive\n", vms.v_inactive_count);
611 	(void)printf("%9u pages in VM cache\n", vms.v_cache_count);
612 	(void)printf("%9u pages wired down\n", vms.v_wire_count);
613 	(void)printf("%9u pages free\n", vms.v_free_count);
614 	(void)printf("%9u bytes per page\n", vms.v_page_size);
615 
616 	if ((nch_tmp = malloc(nch_size)) == NULL) {
617 		perror("malloc");
618 		exit(1);
619 	} else {
620 		if (sysctlbyname("vfs.cache.nchstats", nch_tmp, &nch_size, NULL, 0)) {
621 			perror("sysctlbyname vfs.cache.nchstats");
622 			free(nch_tmp);
623 			exit(1);
624 		} else {
625 			if ((nch_tmp = realloc(nch_tmp, nch_size)) == NULL) {
626 				perror("realloc");
627 				exit(1);
628 			}
629 		}
630 	}
631 
632 	cpucnt = nch_size / sizeof(struct nchstats);
633 	kvm_nch_cpuagg(nch_tmp, &nchstats, cpucnt);
634 
635 	nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
636 	    nchstats.ncs_badhits + nchstats.ncs_falsehits +
637 	    nchstats.ncs_miss + nchstats.ncs_long;
638 	(void)printf("%9ld total name lookups\n", nchtotal);
639 	(void)printf(
640 	    "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
641 	    "", PCT(nchstats.ncs_goodhits, nchtotal),
642 	    PCT(nchstats.ncs_neghits, nchtotal),
643 	    PCT(nchstats.ncs_pass2, nchtotal));
644 	(void)printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
645 	    PCT(nchstats.ncs_badhits, nchtotal),
646 	    PCT(nchstats.ncs_falsehits, nchtotal),
647 	    PCT(nchstats.ncs_long, nchtotal));
648 	free(nch_tmp);
649 }
650 
651 #ifdef notyet
652 void
653 doforkst(void)
654 {
655 	struct forkstat fks;
656 
657 	kread(X_FORKSTAT, &fks, sizeof(struct forkstat));
658 	(void)printf("%d forks, %d pages, average %.2f\n",
659 	    fks.cntfork, fks.sizfork, (double)fks.sizfork / fks.cntfork);
660 	(void)printf("%d vforks, %d pages, average %.2f\n",
661 	    fks.cntvfork, fks.sizvfork, (double)fks.sizvfork / fks.cntvfork);
662 }
663 #endif
664 
665 static void
666 devstats(void)
667 {
668 	register int dn, state;
669 	long double transfers_per_second;
670 	long double busy_seconds;
671 	long tmp;
672 
673 	for (state = 0; state < CPUSTATES; ++state) {
674 		tmp = cur.cp_time[state];
675 		cur.cp_time[state] -= last.cp_time[state];
676 		last.cp_time[state] = tmp;
677 	}
678 
679 	busy_seconds = compute_etime(cur.busy_time, last.busy_time);
680 
681 	for (dn = 0; dn < num_devices; dn++) {
682 		int di;
683 
684 		if ((dev_select[dn].selected == 0)
685 		 || (dev_select[dn].selected > maxshowdevs))
686 			continue;
687 
688 		di = dev_select[dn].position;
689 
690 		if (compute_stats(&cur.dinfo->devices[di],
691 				  &last.dinfo->devices[di], busy_seconds,
692 				  NULL, NULL, NULL,
693 				  NULL, &transfers_per_second, NULL,
694 				  NULL, NULL) != 0)
695 			errx(1, "%s", devstat_errbuf);
696 
697 		printf("%3.0Lf ", transfers_per_second);
698 	}
699 }
700 
701 void
702 cpustats(void)
703 {
704 	register int state;
705 	double pct, total;
706 
707 	total = 0;
708 	for (state = 0; state < CPUSTATES; ++state)
709 		total += cur.cp_time[state];
710 	if (total)
711 		pct = 100 / total;
712 	else
713 		pct = 0;
714 	(void)printf("%2.0f ", (cur.cp_time[CP_USER] +
715 				cur.cp_time[CP_NICE]) * pct);
716 	(void)printf("%2.0f ", (cur.cp_time[CP_SYS] +
717 				cur.cp_time[CP_INTR]) * pct);
718 	(void)printf("%2.0f", cur.cp_time[CP_IDLE] * pct);
719 }
720 
721 void
722 dointr(void)
723 {
724 	register u_long *intrcnt, uptime;
725 	register u_int64_t inttotal;
726 	register int nintr, inamlen;
727 	register char *intrname;
728 
729 	uptime = getuptime();
730 	nintr = namelist[X_EINTRCNT].n_value - namelist[X_INTRCNT].n_value;
731 	inamlen =
732 	    namelist[X_EINTRNAMES].n_value - namelist[X_INTRNAMES].n_value;
733 	intrcnt = malloc((size_t)nintr);
734 	intrname = malloc((size_t)inamlen);
735 	if (intrcnt == NULL || intrname == NULL)
736 		errx(1, "malloc");
737 	kread(X_INTRCNT, intrcnt, (size_t)nintr);
738 	kread(X_INTRNAMES, intrname, (size_t)inamlen);
739 	(void)printf("interrupt                   total       rate\n");
740 	inttotal = 0;
741 	nintr /= sizeof(long);
742 	while (--nintr >= 0) {
743 		if (intrname[0] || *intrcnt) {
744 		    printf("%-12s %20lu %10lu\n", intrname,
745 			    *intrcnt, *intrcnt / uptime);
746 		}
747 		intrname += strlen(intrname) + 1;
748 		inttotal += *intrcnt++;
749 	}
750 	(void)printf("Total        %20llu %10llu\n", inttotal,
751 			inttotal / (u_int64_t) uptime);
752 }
753 
754 #define	MAX_KMSTATS	200
755 
756 static
757 long
758 cpuagg(long *ary)
759 {
760     int i;
761     long ttl;
762 
763     for (i = ttl = 0; i < SMP_MAXCPU; ++i)
764 	ttl += ary[i];
765     return(ttl);
766 }
767 
768 void
769 domem(void)
770 {
771 	register struct malloc_type *ks;
772 	register int i, j;
773 	int first, nkms;
774 	long totuse = 0, totfree = 0, totreq = 0;
775 	struct malloc_type kmemstats[MAX_KMSTATS], *kmsp;
776 	char buf[1024];
777 
778 	kread(X_KMEMSTATISTICS, &kmsp, sizeof(kmsp));
779 	for (nkms = 0; nkms < MAX_KMSTATS && kmsp != NULL; nkms++) {
780 		if (sizeof(kmemstats[0]) != kvm_read(kd, (u_long)kmsp,
781 		    &kmemstats[nkms], sizeof(kmemstats[0])))
782 			err(1, "kvm_read(%p)", (void *)kmsp);
783 		if (sizeof(buf) !=  kvm_read(kd,
784 	            (u_long)kmemstats[nkms].ks_shortdesc, buf, sizeof(buf)))
785 			err(1, "kvm_read(%p)",
786 			    (void *)kmemstats[nkms].ks_shortdesc);
787 		buf[sizeof(buf) - 1] = '\0';
788 		kmemstats[nkms].ks_shortdesc = strdup(buf);
789 		kmsp = kmemstats[nkms].ks_next;
790 	}
791 	if (kmsp != NULL)
792 		warnx("truncated to the first %d memory types", nkms);
793 
794 	(void)printf(
795 	    "\nMemory statistics by type                          Type  Kern\n");
796 	(void)printf(
797 "        Type  InUse MemUse HighUse  Limit Requests Limit Limit Size(s)\n");
798 	for (i = 0, ks = &kmemstats[0]; i < nkms; i++, ks++) {
799 		if (ks->ks_calls == 0)
800 			continue;
801 		(void)printf("%13s%6ld%6ldK%7ldK%6ldK%9lld%5u%6u",
802 		    ks->ks_shortdesc,
803 		    cpuagg(ks->ks_inuse), (cpuagg(ks->ks_memuse) + 1023) / 1024,
804 		    (ks->ks_maxused + 1023) / 1024,
805 		    (ks->ks_limit + 1023) / 1024, ks->ks_calls,
806 		    ks->ks_limblocks, ks->ks_mapblocks);
807 		first = 1;
808 		for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
809 			if ((ks->ks_size & j) == 0)
810 				continue;
811 			if (first)
812 				printf("  ");
813 			else
814 				printf(",");
815 			if(j<1024)
816 				printf("%d",j);
817 			else
818 				printf("%dK",j>>10);
819 			first = 0;
820 		}
821 		printf("\n");
822 		totuse += cpuagg(ks->ks_memuse);
823 		totreq += ks->ks_calls;
824 	}
825 	(void)printf("\nMemory Totals:  In Use    Free    Requests\n");
826 	(void)printf("              %7ldK %6ldK    %8ld\n",
827 	     (totuse + 1023) / 1024, (totfree + 1023) / 1024, totreq);
828 }
829 
830 void
831 dozmem(void)
832 {
833 	char *buf;
834 	size_t bufsize;
835 
836 	buf = NULL;
837 	bufsize = 1024;
838 	for (;;) {
839 		if ((buf = realloc(buf, bufsize)) == NULL)
840 			err(1, "realloc()");
841 		if (sysctlbyname("vm.zone", buf, &bufsize, 0, NULL) == 0)
842 			break;
843 		if (errno != ENOMEM)
844 			err(1, "sysctl()");
845 		bufsize *= 2;
846 	}
847 	buf[bufsize] = '\0'; /* play it safe */
848 	(void)printf("%s\n\n", buf);
849 	free(buf);
850 }
851 
852 /*
853  * kread reads something from the kernel, given its nlist index.
854  */
855 void
856 kread(int nlx, void *addr, size_t size)
857 {
858 	char *sym;
859 
860 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
861 		sym = namelist[nlx].n_name;
862 		if (*sym == '_')
863 			++sym;
864 		errx(1, "symbol %s not defined", sym);
865 	}
866 	if (kvm_read(kd, namelist[nlx].n_value, addr, size) != size) {
867 		sym = namelist[nlx].n_name;
868 		if (*sym == '_')
869 			++sym;
870 		errx(1, "%s: %s", sym, kvm_geterr(kd));
871 	}
872 }
873 
874 void
875 usage(void)
876 {
877 	(void)fprintf(stderr, "%s%s",
878 		"usage: vmstat [-imsz] [-c count] [-M core] [-N system] [-w wait]\n",
879 		"              [-n devs] [disks]\n");
880 	exit(1);
881 }
882