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