xref: /freebsd/usr.bin/vmstat/vmstat.c (revision 7660b554bc59a07be0431c17e0e33815818baa69)
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 #include <sys/cdefs.h>
35 
36 __FBSDID("$FreeBSD$");
37 
38 #ifndef lint
39 static const char copyright[] =
40 "@(#) Copyright (c) 1980, 1986, 1991, 1993\n\
41 	The Regents of the University of California.  All rights reserved.\n";
42 #endif
43 
44 #ifndef lint
45 static const char sccsid[] = "@(#)vmstat.c	8.1 (Berkeley) 6/6/93";
46 #endif
47 
48 #include <sys/param.h>
49 #include <sys/time.h>
50 #include <sys/proc.h>
51 #include <sys/uio.h>
52 #include <sys/namei.h>
53 #include <sys/malloc.h>
54 #include <sys/signal.h>
55 #include <sys/fcntl.h>
56 #include <sys/ioctl.h>
57 #include <sys/resource.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 <devstat.h>
65 #include <err.h>
66 #include <errno.h>
67 #include <kvm.h>
68 #include <limits.h>
69 #include <nlist.h>
70 #include <paths.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <sysexits.h>
75 #include <time.h>
76 #include <unistd.h>
77 
78 static char da[] = "da";
79 
80 static struct nlist namelist[] = {
81 #define	X_CPTIME	0
82 	{ "_cp_time" },
83 #define X_SUM		1
84 	{ "_cnt" },
85 #define	X_BOOTTIME	2
86 	{ "_boottime" },
87 #define X_HZ		3
88 	{ "_hz" },
89 #define X_STATHZ	4
90 	{ "_stathz" },
91 #define X_NCHSTATS	5
92 	{ "_nchstats" },
93 #define	X_INTRNAMES	6
94 	{ "_intrnames" },
95 #define	X_EINTRNAMES	7
96 	{ "_eintrnames" },
97 #define	X_INTRCNT	8
98 	{ "_intrcnt" },
99 #define	X_EINTRCNT	9
100 	{ "_eintrcnt" },
101 #ifdef notyet
102 #define	X_DEFICIT	10
103 	{ "_deficit" },
104 #define X_REC		11
105 	{ "_rectime" },
106 #define X_PGIN		12
107 	{ "_pgintime" },
108 #define	X_XSTATS	13
109 	{ "_xstats" },
110 #define X_END		14
111 #else
112 #define X_END		10
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 sum, osum;
130 
131 int	winlines = 20;
132 int	nflag = 0;
133 
134 kvm_t *kd;
135 
136 #define	FORKSTAT	0x01
137 #define	INTRSTAT	0x02
138 #define	MEMSTAT		0x04
139 #define	SUMSTAT		0x08
140 #define	TIMESTAT	0x10
141 #define	VMSTAT		0x20
142 #define ZMEMSTAT	0x40
143 
144 static void	cpustats(void);
145 static void	devstats(void);
146 static void	dosysctl(char *);
147 static void	domem(void);
148 static void	dointr(void);
149 static void	dosum(void);
150 static void	doforkst(void);
151 static void	dovmstat(u_int, int);
152 static void	dozmem(void);
153 static void	kread(int, void *, size_t);
154 static void	needhdr(int);
155 static void	printhdr(void);
156 static void	usage(void);
157 
158 static long	pct(long, long);
159 static long	getuptime(void);
160 
161 char **getdrivedata(char **);
162 
163 int
164 main(argc, argv)
165 	int argc;
166 	char **argv;
167 {
168 	int c, todo;
169 	u_int interval;
170 	int reps;
171 	char *memf, *nlistf;
172 	char errbuf[_POSIX2_LINE_MAX];
173 
174 	memf = nlistf = NULL;
175 	interval = reps = todo = 0;
176 	maxshowdevs = 2;
177 	while ((c = getopt(argc, argv, "c:fiM:mN:n:p:stw:z")) != -1) {
178 		switch (c) {
179 		case 'c':
180 			reps = atoi(optarg);
181 			break;
182 		case 'f':
183 			todo |= FORKSTAT;
184 			break;
185 		case 'i':
186 			todo |= INTRSTAT;
187 			break;
188 		case 'M':
189 			memf = optarg;
190 			break;
191 		case 'm':
192 			todo |= MEMSTAT;
193 			break;
194 		case 'N':
195 			nlistf = optarg;
196 			break;
197 		case 'n':
198 			nflag = 1;
199 			maxshowdevs = atoi(optarg);
200 			if (maxshowdevs < 0)
201 				errx(1, "number of devices %d is < 0",
202 				     maxshowdevs);
203 			break;
204 		case 'p':
205 			if (devstat_buildmatch(optarg, &matches, &num_matches) != 0)
206 				errx(1, "%s", devstat_errbuf);
207 			break;
208 		case 's':
209 			todo |= SUMSTAT;
210 			break;
211 		case 't':
212 #ifdef notyet
213 			todo |= TIMESTAT;
214 #else
215 			errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
216 #endif
217 			break;
218 		case 'w':
219 			interval = atoi(optarg);
220 			break;
221 		case 'z':
222 			todo |= ZMEMSTAT;
223 			break;
224 		case '?':
225 		default:
226 			usage();
227 		}
228 	}
229 	argc -= optind;
230 	argv += optind;
231 
232 	if (todo == 0)
233 		todo = VMSTAT;
234 
235 	/*
236 	 * Discard setgid privileges if not the running kernel so that bad
237 	 * guys can't print interesting stuff from kernel memory.
238 	 */
239 	if (nlistf != NULL || memf != NULL)
240 		setgid(getgid());
241 
242 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
243 	if (kd == 0)
244 		errx(1, "kvm_openfiles: %s", errbuf);
245 	setgid(getgid());
246 
247 	if ((c = kvm_nlist(kd, namelist)) != 0) {
248 		if (c > 0) {
249 			warnx("undefined symbols:");
250 			for (c = 0;
251 			    c < (int)(sizeof(namelist)/sizeof(namelist[0]));
252 			    c++)
253 				if (namelist[c].n_type == 0)
254 					(void)fprintf(stderr, " %s",
255 					    namelist[c].n_name);
256 			(void)fputc('\n', stderr);
257 		} else
258 			warnx("kvm_nlist: %s", kvm_geterr(kd));
259 		exit(1);
260 	}
261 
262 	if (todo & VMSTAT) {
263 		struct winsize winsize;
264 
265 		/*
266 		 * Make sure that the userland devstat version matches the
267 		 * kernel devstat version.  If not, exit and print a
268 		 * message informing the user of his mistake.
269 		 */
270 		if (devstat_checkversion(NULL) < 0)
271 			errx(1, "%s", devstat_errbuf);
272 
273 
274 		argv = getdrivedata(argv);
275 		winsize.ws_row = 0;
276 		(void) ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
277 		if (winsize.ws_row > 0)
278 			winlines = winsize.ws_row;
279 
280 	}
281 
282 #define	BACKWARD_COMPATIBILITY
283 #ifdef	BACKWARD_COMPATIBILITY
284 	if (*argv) {
285 		interval = atoi(*argv);
286 		if (*++argv)
287 			reps = atoi(*argv);
288 	}
289 #endif
290 
291 	if (interval) {
292 		if (!reps)
293 			reps = -1;
294 	} else if (reps)
295 		interval = 1;
296 
297 	if (todo & FORKSTAT)
298 		doforkst();
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 = devstat_getnumdevs(NULL)) < 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 (devstat_getdevs(NULL, &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 (devstat_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 (devstat_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 struct timeval boottime;
386 	static time_t now;
387 	time_t uptime;
388 
389 	if (boottime.tv_sec == 0)
390 		kread(X_BOOTTIME, &boottime, sizeof(boottime));
391 	(void)time(&now);
392 	uptime = now - boottime.tv_sec;
393 	if (uptime <= 0 || uptime > 60*60*24*365*10)
394 		errx(1, "time makes no sense; namelist must be wrong");
395 	return(uptime);
396 }
397 
398 int	hz, hdrcnt;
399 
400 void
401 dovmstat(interval, reps)
402 	u_int interval;
403 	int reps;
404 {
405 	struct vmtotal total;
406 	time_t uptime, halfuptime;
407 	struct devinfo *tmp_dinfo;
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.snap_time = cur.snap_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 (devstat_getdevs(NULL, &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 = devstat_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_TOTAL;
473 		if (sysctl(mib, 2, &total, &size, NULL, 0) < 0) {
474 			(void)printf("Can't get kerninfo: %s\n",
475 				     strerror(errno));
476 			bzero(&total, sizeof(total));
477 		}
478 		(void)printf("%2d %1d %1d",
479 		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
480 #define vmstat_pgtok(a) ((a) * sum.v_page_size >> 10)
481 #define	rate(x)	(((x) + halfuptime) / uptime)	/* round */
482 		(void)printf(" %7ld %6ld ", (long)vmstat_pgtok(total.t_avm),
483 			     (long)vmstat_pgtok(total.t_free));
484 		(void)printf("%4lu ",
485 		    (u_long)rate(sum.v_vm_faults - osum.v_vm_faults));
486 		(void)printf("%3lu ",
487 		    (u_long)rate(sum.v_reactivated - osum.v_reactivated));
488 		(void)printf("%3lu ",
489 		    (u_long)rate(sum.v_swapin + sum.v_vnodein -
490 		    (osum.v_swapin + osum.v_vnodein)));
491 		(void)printf("%3lu ",
492 		    (u_long)rate(sum.v_swapout + sum.v_vnodeout -
493 		    (osum.v_swapout + osum.v_vnodeout)));
494 		(void)printf("%3lu ",
495 		    (u_long)rate(sum.v_tfree - osum.v_tfree));
496 		(void)printf("%3lu ",
497 		    (u_long)rate(sum.v_pdpages - osum.v_pdpages));
498 		devstats();
499 		(void)printf("%4lu %4lu %3lu ",
500 		    (u_long)rate(sum.v_intr - osum.v_intr),
501 		    (u_long)rate(sum.v_syscall - osum.v_syscall),
502 		    (u_long)rate(sum.v_swtch - osum.v_swtch));
503 		cpustats();
504 		(void)printf("\n");
505 		(void)fflush(stdout);
506 		if (reps >= 0 && --reps <= 0)
507 			break;
508 		osum = sum;
509 		uptime = interval;
510 		/*
511 		 * We round upward to avoid losing low-frequency events
512 		 * (i.e., >= 1 per interval but < 1 per second).
513 		 */
514 		if (interval != 1)
515 			halfuptime = (uptime + 1) / 2;
516 		else
517 			halfuptime = 0;
518 		(void)sleep(interval);
519 	}
520 }
521 
522 void
523 printhdr()
524 {
525 	int i, num_shown;
526 
527 	num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
528 	(void)printf(" procs      memory      page%*s", 19, "");
529 	if (num_shown > 1)
530 		(void)printf(" disks %*s", num_shown * 4 - 7, "");
531 	else if (num_shown == 1)
532 		(void)printf("disk");
533 	(void)printf("   faults      cpu\n");
534 	(void)printf(" r b w     avm    fre  flt  re  pi  po  fr  sr ");
535 	for (i = 0; i < num_devices; i++)
536 		if ((dev_select[i].selected)
537 		 && (dev_select[i].selected <= maxshowdevs))
538 			(void)printf("%c%c%d ", dev_select[i].device_name[0],
539 				     dev_select[i].device_name[1],
540 				     dev_select[i].unit_number);
541 	(void)printf("  in   sy  cs us sy id\n");
542 	hdrcnt = winlines - 2;
543 }
544 
545 /*
546  * Force a header to be prepended to the next output.
547  */
548 void
549 needhdr(dummy)
550 	int dummy __unused;
551 {
552 
553 	hdrcnt = 1;
554 }
555 
556 #ifdef notyet
557 void
558 dotimes()
559 {
560 	u_int pgintime, rectime;
561 
562 	kread(X_REC, &rectime, sizeof(rectime));
563 	kread(X_PGIN, &pgintime, sizeof(pgintime));
564 	kread(X_SUM, &sum, sizeof(sum));
565 	(void)printf("%u reclaims, %u total time (usec)\n",
566 	    sum.v_pgrec, rectime);
567 	(void)printf("average: %u usec / reclaim\n", rectime / sum.v_pgrec);
568 	(void)printf("\n");
569 	(void)printf("%u page ins, %u total time (msec)\n",
570 	    sum.v_pgin, pgintime / 10);
571 	(void)printf("average: %8.1f msec / page in\n",
572 	    pgintime / (sum.v_pgin * 10.0));
573 }
574 #endif
575 
576 long
577 pct(top, bot)
578 	long top, bot;
579 {
580 	long ans;
581 
582 	if (bot == 0)
583 		return(0);
584 	ans = (quad_t)top * 100 / bot;
585 	return (ans);
586 }
587 
588 #define	PCT(top, bot) pct((long)(top), (long)(bot))
589 
590 void
591 dosum()
592 {
593 	struct nchstats lnchstats;
594 	long nchtotal;
595 
596 	kread(X_SUM, &sum, sizeof(sum));
597 	(void)printf("%9u cpu context switches\n", sum.v_swtch);
598 	(void)printf("%9u device interrupts\n", sum.v_intr);
599 	(void)printf("%9u software interrupts\n", sum.v_soft);
600 	(void)printf("%9u traps\n", sum.v_trap);
601 	(void)printf("%9u system calls\n", sum.v_syscall);
602 	(void)printf("%9u kernel threads created\n", sum.v_kthreads);
603 	(void)printf("%9u  fork() calls\n", sum.v_forks);
604 	(void)printf("%9u vfork() calls\n", sum.v_vforks);
605 	(void)printf("%9u rfork() calls\n", sum.v_rforks);
606 	(void)printf("%9u swap pager pageins\n", sum.v_swapin);
607 	(void)printf("%9u swap pager pages paged in\n", sum.v_swappgsin);
608 	(void)printf("%9u swap pager pageouts\n", sum.v_swapout);
609 	(void)printf("%9u swap pager pages paged out\n", sum.v_swappgsout);
610 	(void)printf("%9u vnode pager pageins\n", sum.v_vnodein);
611 	(void)printf("%9u vnode pager pages paged in\n", sum.v_vnodepgsin);
612 	(void)printf("%9u vnode pager pageouts\n", sum.v_vnodeout);
613 	(void)printf("%9u vnode pager pages paged out\n", sum.v_vnodepgsout);
614 	(void)printf("%9u page daemon wakeups\n", sum.v_pdwakeups);
615 	(void)printf("%9u pages examined by the page daemon\n", sum.v_pdpages);
616 	(void)printf("%9u pages reactivated\n", sum.v_reactivated);
617 	(void)printf("%9u copy-on-write faults\n", sum.v_cow_faults);
618 	(void)printf("%9u copy-on-write optimized faults\n", sum.v_cow_optim);
619 	(void)printf("%9u zero fill pages zeroed\n", sum.v_zfod);
620 	(void)printf("%9u zero fill pages prezeroed\n", sum.v_ozfod);
621 	(void)printf("%9u intransit blocking page faults\n", sum.v_intrans);
622 	(void)printf("%9u total VM faults taken\n", sum.v_vm_faults);
623 	(void)printf("%9u pages affected by kernel thread creation\n", sum.v_kthreadpages);
624 	(void)printf("%9u pages affected by  fork()\n", sum.v_forkpages);
625 	(void)printf("%9u pages affected by vfork()\n", sum.v_vforkpages);
626 	(void)printf("%9u pages affected by rfork()\n", sum.v_rforkpages);
627 	(void)printf("%9u pages freed\n", sum.v_tfree);
628 	(void)printf("%9u pages freed by daemon\n", sum.v_dfree);
629 	(void)printf("%9u pages freed by exiting processes\n", sum.v_pfree);
630 	(void)printf("%9u pages active\n", sum.v_active_count);
631 	(void)printf("%9u pages inactive\n", sum.v_inactive_count);
632 	(void)printf("%9u pages in VM cache\n", sum.v_cache_count);
633 	(void)printf("%9u pages wired down\n", sum.v_wire_count);
634 	(void)printf("%9u pages free\n", sum.v_free_count);
635 	(void)printf("%9u bytes per page\n", sum.v_page_size);
636 	kread(X_NCHSTATS, &lnchstats, sizeof(lnchstats));
637 	nchtotal = lnchstats.ncs_goodhits + lnchstats.ncs_neghits +
638 	    lnchstats.ncs_badhits + lnchstats.ncs_falsehits +
639 	    lnchstats.ncs_miss + lnchstats.ncs_long;
640 	(void)printf("%9ld total name lookups\n", nchtotal);
641 	(void)printf(
642 	    "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
643 	    "", PCT(lnchstats.ncs_goodhits, nchtotal),
644 	    PCT(lnchstats.ncs_neghits, nchtotal),
645 	    PCT(lnchstats.ncs_pass2, nchtotal));
646 	(void)printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
647 	    PCT(lnchstats.ncs_badhits, nchtotal),
648 	    PCT(lnchstats.ncs_falsehits, nchtotal),
649 	    PCT(lnchstats.ncs_long, nchtotal));
650 }
651 
652 void
653 doforkst()
654 {
655 
656 	kread(X_SUM, &sum, sizeof(sum));
657 	(void)printf("%d forks, %d pages, average %.2f\n",
658 	    sum.v_forks, sum.v_forkpages,
659 	    sum.v_forks == 0 ? 0.0 :
660 	    (double)sum.v_forkpages / sum.v_forks);
661 	(void)printf("%d vforks, %d pages, average %.2f\n",
662 	    sum.v_vforks, sum.v_vforkpages,
663 	    sum.v_vforks == 0 ? 0.0 :
664 	    (double)sum.v_vforkpages / sum.v_vforks);
665 	(void)printf("%d rforks, %d pages, average %.2f\n",
666 	    sum.v_rforks, sum.v_rforkpages,
667 	    sum.v_rforks == 0 ? 0.0 :
668 	    (double)sum.v_rforkpages / sum.v_rforks);
669 }
670 
671 static void
672 devstats()
673 {
674 	int dn, state;
675 	long double transfers_per_second;
676 	long double busy_seconds;
677 	long tmp;
678 
679 	for (state = 0; state < CPUSTATES; ++state) {
680 		tmp = cur.cp_time[state];
681 		cur.cp_time[state] -= last.cp_time[state];
682 		last.cp_time[state] = tmp;
683 	}
684 
685 	busy_seconds = cur.snap_time - last.snap_time;
686 
687 	for (dn = 0; dn < num_devices; dn++) {
688 		int di;
689 
690 		if ((dev_select[dn].selected == 0)
691 		 || (dev_select[dn].selected > maxshowdevs))
692 			continue;
693 
694 		di = dev_select[dn].position;
695 
696 		if (devstat_compute_statistics(&cur.dinfo->devices[di],
697 		    &last.dinfo->devices[di], busy_seconds,
698 		    DSM_TRANSFERS_PER_SECOND, &transfers_per_second,
699 		    DSM_NONE) != 0)
700 			errx(1, "%s", devstat_errbuf);
701 
702 		(void)printf("%3.0Lf ", transfers_per_second);
703 	}
704 }
705 
706 void
707 cpustats()
708 {
709 	int state;
710 	double lpct, total;
711 
712 	total = 0;
713 	for (state = 0; state < CPUSTATES; ++state)
714 		total += cur.cp_time[state];
715 	if (total)
716 		lpct = 100.0 / total;
717 	else
718 		lpct = 0.0;
719 	(void)printf("%2.0f ", (cur.cp_time[CP_USER] +
720 				cur.cp_time[CP_NICE]) * lpct);
721 	(void)printf("%2.0f ", (cur.cp_time[CP_SYS] +
722 				cur.cp_time[CP_INTR]) * lpct);
723 	(void)printf("%2.0f", cur.cp_time[CP_IDLE] * lpct);
724 }
725 
726 void
727 dointr()
728 {
729 	u_long *intrcnt, uptime;
730 	u_int64_t inttotal;
731 	int nintr, inamlen;
732 	char *intrname;
733 
734 	uptime = getuptime();
735 	nintr = namelist[X_EINTRCNT].n_value - namelist[X_INTRCNT].n_value;
736 	inamlen =
737 	    namelist[X_EINTRNAMES].n_value - namelist[X_INTRNAMES].n_value;
738 	intrcnt = malloc((size_t)nintr);
739 	intrname = malloc((size_t)inamlen);
740 	if (intrcnt == NULL || intrname == NULL)
741 		errx(1, "malloc");
742 	kread(X_INTRCNT, intrcnt, (size_t)nintr);
743 	kread(X_INTRNAMES, intrname, (size_t)inamlen);
744 	(void)printf("%-14s %20s %10s\n", "interrupt", "total", "rate");
745 	inttotal = 0;
746 	nintr /= sizeof(long);
747 	while (--nintr >= 0) {
748 		if (*intrcnt)
749 			(void)printf("%-14s %20lu %10lu\n", intrname,
750 			    *intrcnt, *intrcnt / uptime);
751 		intrname += strlen(intrname) + 1;
752 		inttotal += *intrcnt++;
753 	}
754 	(void)printf("%-14s %20llu %10llu\n", "Total", inttotal,
755 			inttotal / (u_int64_t) uptime);
756 }
757 
758 void
759 domem(void)
760 {
761 	dosysctl("kern.malloc");
762 }
763 
764 void
765 dozmem(void)
766 {
767 	dosysctl("vm.zone");
768 }
769 
770 void
771 dosysctl(char *name)
772 {
773 	char *buf;
774 	size_t bufsize;
775 
776 	buf = NULL;
777 	bufsize = 1024;
778 	for (;;) {
779 		if ((buf = realloc(buf, bufsize)) == NULL)
780 			err(1, "realloc()");
781 		if (sysctlbyname(name, buf, &bufsize, 0, NULL) == 0)
782 			break;
783 		if (errno != ENOMEM)
784 			err(1, "sysctl()");
785 		bufsize *= 2;
786 	}
787 	buf[bufsize] = '\0'; /* play it safe */
788 	(void)printf("%s\n\n", buf);
789 	free(buf);
790 }
791 
792 /*
793  * kread reads something from the kernel, given its nlist index.
794  */
795 void
796 kread(nlx, addr, size)
797 	int nlx;
798 	void *addr;
799 	size_t size;
800 {
801 	char *sym;
802 
803 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
804 		sym = namelist[nlx].n_name;
805 		if (*sym == '_')
806 			++sym;
807 		errx(1, "symbol %s not defined", sym);
808 	}
809 	if (kvm_read(kd, namelist[nlx].n_value, addr, size) != (int)size) {
810 		sym = namelist[nlx].n_name;
811 		if (*sym == '_')
812 			++sym;
813 		errx(1, "%s: %s", sym, kvm_geterr(kd));
814 	}
815 }
816 
817 void
818 usage()
819 {
820 	(void)fprintf(stderr, "%s%s",
821 		"usage: vmstat [-imsz] [-c count] [-M core] [-N system] [-w wait]\n",
822 		"              [-n devs] [disks]\n");
823 	exit(1);
824 }
825