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