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