xref: /freebsd/usr.bin/vmstat/vmstat.c (revision c98323078dede7579020518ec84cdcb478e5c142)
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 #if 0
41 #ifndef lint
42 static char sccsid[] = "@(#)vmstat.c	8.1 (Berkeley) 6/6/93";
43 #endif /* not lint */
44 #endif
45 
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include <sys/param.h>
50 #include <sys/time.h>
51 #include <sys/proc.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/resource.h>
59 #include <sys/sysctl.h>
60 #include <sys/vmmeter.h>
61 
62 #include <vm/vm_param.h>
63 
64 #include <ctype.h>
65 #include <devstat.h>
66 #include <err.h>
67 #include <errno.h>
68 #include <kvm.h>
69 #include <limits.h>
70 #include <nlist.h>
71 #include <paths.h>
72 #include <stdio.h>
73 #include <stdlib.h>
74 #include <string.h>
75 #include <sysexits.h>
76 #include <time.h>
77 #include <unistd.h>
78 
79 static char da[] = "da";
80 
81 static struct nlist namelist[] = {
82 #define	X_CPTIME	0
83 	{ "_cp_time" },
84 #define X_SUM		1
85 	{ "_cnt" },
86 #define	X_BOOTTIME	2
87 	{ "_boottime" },
88 #define X_HZ		3
89 	{ "_hz" },
90 #define X_STATHZ	4
91 	{ "_stathz" },
92 #define X_NCHSTATS	5
93 	{ "_nchstats" },
94 #define	X_INTRNAMES	6
95 	{ "_intrnames" },
96 #define	X_EINTRNAMES	7
97 	{ "_eintrnames" },
98 #define	X_INTRCNT	8
99 	{ "_intrcnt" },
100 #define	X_EINTRCNT	9
101 	{ "_eintrcnt" },
102 #define	X_KMEMSTATS	10
103 	{ "_kmemstatistics" },
104 #define	X_KMEMZONES	11
105 	{ "_kmemzones" },
106 #ifdef notyet
107 #define	X_DEFICIT	XXX
108 	{ "_deficit" },
109 #define X_REC		XXX
110 	{ "_rectime" },
111 #define X_PGIN		XXX
112 	{ "_pgintime" },
113 #define	X_XSTATS	XXX
114 	{ "_xstats" },
115 #define X_END		XXX
116 #else
117 #define X_END		12
118 #endif
119 	{ "" },
120 };
121 
122 static struct statinfo cur, last;
123 static int num_devices, maxshowdevs;
124 static long generation;
125 static struct device_selection *dev_select;
126 static int num_selected;
127 static struct devstat_match *matches;
128 static int num_matches = 0;
129 static int num_devices_specified, num_selections;
130 static long select_generation;
131 static char **specified_devices;
132 static devstat_select_mode select_mode;
133 
134 static struct	vmmeter sum, osum;
135 
136 static int	winlines = 20;
137 static int	aflag;
138 static int	nflag;
139 
140 static 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 static void	cpustats(void);
151 static void	devstats(void);
152 static void	doforkst(void);
153 static void	domem(void);
154 static void	dointr(void);
155 static void	dosum(void);
156 static void	dosysctl(const char *);
157 static void	dovmstat(unsigned int, int);
158 static void	dozmem(void);
159 static void	kread(int, void *, size_t);
160 static void	kreado(int, void *, size_t, size_t);
161 static char    *kgetstr(const char *);
162 static void	needhdr(int);
163 static void	printhdr(void);
164 static void	usage(void);
165 
166 static long	pct(long, long);
167 static long	getuptime(void);
168 
169 static char   **getdrivedata(char **);
170 
171 int
172 main(int argc, char *argv[])
173 {
174 	int c, todo;
175 	unsigned int interval;
176 	int reps;
177 	char *memf, *nlistf;
178 	char errbuf[_POSIX2_LINE_MAX];
179 
180 	memf = nlistf = NULL;
181 	interval = reps = todo = 0;
182 	maxshowdevs = 2;
183 	while ((c = getopt(argc, argv, "ac:fiM:mN:n:p:stw:z")) != -1) {
184 		switch (c) {
185 		case 'a':
186 			aflag++;
187 			break;
188 		case 'c':
189 			reps = atoi(optarg);
190 			break;
191 		case 'f':
192 			todo |= FORKSTAT;
193 			break;
194 		case 'i':
195 			todo |= INTRSTAT;
196 			break;
197 		case 'M':
198 			memf = optarg;
199 			break;
200 		case 'm':
201 			todo |= MEMSTAT;
202 			break;
203 		case 'N':
204 			nlistf = optarg;
205 			break;
206 		case 'n':
207 			nflag = 1;
208 			maxshowdevs = atoi(optarg);
209 			if (maxshowdevs < 0)
210 				errx(1, "number of devices %d is < 0",
211 				     maxshowdevs);
212 			break;
213 		case 'p':
214 			if (devstat_buildmatch(optarg, &matches, &num_matches) != 0)
215 				errx(1, "%s", devstat_errbuf);
216 			break;
217 		case 's':
218 			todo |= SUMSTAT;
219 			break;
220 		case 't':
221 #ifdef notyet
222 			todo |= TIMESTAT;
223 #else
224 			errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
225 #endif
226 			break;
227 		case 'w':
228 			interval = atoi(optarg);
229 			break;
230 		case 'z':
231 			todo |= ZMEMSTAT;
232 			break;
233 		case '?':
234 		default:
235 			usage();
236 		}
237 	}
238 	argc -= optind;
239 	argv += optind;
240 
241 	if (todo == 0)
242 		todo = VMSTAT;
243 
244 	if (memf != NULL) {
245 		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
246 		if (kd == NULL)
247 			errx(1, "kvm_openfiles: %s", errbuf);
248 	}
249 
250 	if (kd != NULL && (c = kvm_nlist(kd, namelist)) != 0) {
251 		if (c > 0) {
252 			warnx("undefined symbols:");
253 			for (c = 0;
254 			     c < (int)(sizeof(namelist)/sizeof(namelist[0]));
255 			     c++)
256 				if (namelist[c].n_type == 0)
257 					(void)fprintf(stderr, " %s",
258 					    namelist[c].n_name);
259 			(void)fputc('\n', stderr);
260 		} else
261 			warnx("kvm_nlist: %s", kvm_geterr(kd));
262 		exit(1);
263 	}
264 
265 	if (todo & VMSTAT) {
266 		struct winsize winsize;
267 
268 		/*
269 		 * Make sure that the userland devstat version matches the
270 		 * kernel devstat version.  If not, exit and print a
271 		 * message informing the user of his mistake.
272 		 */
273 		if (devstat_checkversion(NULL) < 0)
274 			errx(1, "%s", devstat_errbuf);
275 
276 
277 		argv = getdrivedata(argv);
278 		winsize.ws_row = 0;
279 		(void) ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
280 		if (winsize.ws_row > 0)
281 			winlines = winsize.ws_row;
282 
283 	}
284 
285 #define	BACKWARD_COMPATIBILITY
286 #ifdef	BACKWARD_COMPATIBILITY
287 	if (*argv) {
288 		interval = atoi(*argv);
289 		if (*++argv)
290 			reps = atoi(*argv);
291 	}
292 #endif
293 
294 	if (interval) {
295 		if (!reps)
296 			reps = -1;
297 	} else if (reps)
298 		interval = 1;
299 
300 	if (todo & FORKSTAT)
301 		doforkst();
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 static int
320 mysysctl(const char *name, void *oldp, size_t *oldlenp,
321     void *newp, size_t newlen)
322 {
323 	int error;
324 
325 	error = sysctlbyname(name, oldp, oldlenp, newp, newlen);
326 	if (error != 0 && errno != ENOMEM)
327 		err(1, "sysctl(%s)", name);
328 	return (error);
329 }
330 
331 static char **
332 getdrivedata(char **argv)
333 {
334 	if ((num_devices = devstat_getnumdevs(NULL)) < 0)
335 		errx(1, "%s", devstat_errbuf);
336 
337 	cur.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
338 	last.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
339 	bzero(cur.dinfo, sizeof(struct devinfo));
340 	bzero(last.dinfo, sizeof(struct devinfo));
341 
342 	if (devstat_getdevs(NULL, &cur) == -1)
343 		errx(1, "%s", devstat_errbuf);
344 
345 	num_devices = cur.dinfo->numdevs;
346 	generation = cur.dinfo->generation;
347 
348 	specified_devices = (char **)malloc(sizeof(char *));
349 	for (num_devices_specified = 0; *argv; ++argv) {
350 		if (isdigit(**argv))
351 			break;
352 		num_devices_specified++;
353 		specified_devices = (char **)realloc(specified_devices,
354 						     sizeof(char *) *
355 						     num_devices_specified);
356 		specified_devices[num_devices_specified - 1] = *argv;
357 	}
358 	dev_select = NULL;
359 
360 	if (nflag == 0 && maxshowdevs < num_devices_specified)
361 			maxshowdevs = num_devices_specified;
362 
363 	/*
364 	 * People are generally only interested in disk statistics when
365 	 * they're running vmstat.  So, that's what we're going to give
366 	 * them if they don't specify anything by default.  We'll also give
367 	 * them any other random devices in the system so that we get to
368 	 * maxshowdevs devices, if that many devices exist.  If the user
369 	 * specifies devices on the command line, either through a pattern
370 	 * match or by naming them explicitly, we will give the user only
371 	 * those devices.
372 	 */
373 	if ((num_devices_specified == 0) && (num_matches == 0)) {
374 		if (devstat_buildmatch(da, &matches, &num_matches) != 0)
375 			errx(1, "%s", devstat_errbuf);
376 
377 		select_mode = DS_SELECT_ADD;
378 	} else
379 		select_mode = DS_SELECT_ONLY;
380 
381 	/*
382 	 * At this point, selectdevs will almost surely indicate that the
383 	 * device list has changed, so we don't look for return values of 0
384 	 * or 1.  If we get back -1, though, there is an error.
385 	 */
386 	if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
387 		       &select_generation, generation, cur.dinfo->devices,
388 		       num_devices, matches, num_matches, specified_devices,
389 		       num_devices_specified, select_mode,
390 		       maxshowdevs, 0) == -1)
391 		errx(1, "%s", devstat_errbuf);
392 
393 	return(argv);
394 }
395 
396 static long
397 getuptime(void)
398 {
399 	static struct timeval boottime;
400 	static time_t now;
401 	time_t uptime;
402 
403 	if (boottime.tv_sec == 0) {
404 		if (kd != NULL) {
405 			kread(X_BOOTTIME, &boottime, sizeof(boottime));
406 		} else {
407 			size_t size;
408 
409 			size = sizeof(boottime);
410 			mysysctl("kern.boottime", &boottime, &size, NULL, 0);
411 			if (size != sizeof(boottime))
412 				errx(1, "kern.boottime size mismatch");
413 		}
414 	}
415 	(void)time(&now);
416 	uptime = now - boottime.tv_sec;
417 	if (uptime <= 0 || uptime > 60*60*24*365*10)
418 		errx(1, "time makes no sense; namelist must be wrong");
419 	return(uptime);
420 }
421 
422 static void
423 fill_vmmeter(struct vmmeter *vmmp)
424 {
425 	if (kd != NULL) {
426 		kread(X_SUM, vmmp, sizeof(*vmmp));
427 	} else {
428 		size_t size = sizeof(unsigned int);
429 #define GET_VM_STATS(cat, name) \
430 	mysysctl("vm.stats." #cat "." #name, &vmmp->name, &size, NULL, 0)
431 		/* sys */
432 		GET_VM_STATS(sys, v_swtch);
433 		GET_VM_STATS(sys, v_trap);
434 		GET_VM_STATS(sys, v_syscall);
435 		GET_VM_STATS(sys, v_intr);
436 		GET_VM_STATS(sys, v_soft);
437 
438 		/* vm */
439 		GET_VM_STATS(vm, v_vm_faults);
440 		GET_VM_STATS(vm, v_cow_faults);
441 		GET_VM_STATS(vm, v_cow_optim);
442 		GET_VM_STATS(vm, v_zfod);
443 		GET_VM_STATS(vm, v_ozfod);
444 		GET_VM_STATS(vm, v_swapin);
445 		GET_VM_STATS(vm, v_swapout);
446 		GET_VM_STATS(vm, v_swappgsin);
447 		GET_VM_STATS(vm, v_swappgsout);
448 		GET_VM_STATS(vm, v_vnodein);
449 		GET_VM_STATS(vm, v_vnodeout);
450 		GET_VM_STATS(vm, v_vnodepgsin);
451 		GET_VM_STATS(vm, v_vnodepgsout);
452 		GET_VM_STATS(vm, v_intrans);
453 		GET_VM_STATS(vm, v_reactivated);
454 		GET_VM_STATS(vm, v_pdwakeups);
455 		GET_VM_STATS(vm, v_pdpages);
456 		GET_VM_STATS(vm, v_dfree);
457 		GET_VM_STATS(vm, v_pfree);
458 		GET_VM_STATS(vm, v_tfree);
459 		GET_VM_STATS(vm, v_page_size);
460 		GET_VM_STATS(vm, v_page_count);
461 		GET_VM_STATS(vm, v_free_reserved);
462 		GET_VM_STATS(vm, v_free_target);
463 		GET_VM_STATS(vm, v_free_min);
464 		GET_VM_STATS(vm, v_free_count);
465 		GET_VM_STATS(vm, v_wire_count);
466 		GET_VM_STATS(vm, v_active_count);
467 		GET_VM_STATS(vm, v_inactive_target);
468 		GET_VM_STATS(vm, v_inactive_count);
469 		GET_VM_STATS(vm, v_cache_count);
470 		GET_VM_STATS(vm, v_cache_min);
471 		GET_VM_STATS(vm, v_cache_max);
472 		GET_VM_STATS(vm, v_pageout_free_min);
473 		GET_VM_STATS(vm, v_interrupt_free_min);
474 		/*GET_VM_STATS(vm, v_free_severe);*/
475 		GET_VM_STATS(vm, v_forks);
476 		GET_VM_STATS(vm, v_vforks);
477 		GET_VM_STATS(vm, v_rforks);
478 		GET_VM_STATS(vm, v_kthreads);
479 		GET_VM_STATS(vm, v_forkpages);
480 		GET_VM_STATS(vm, v_vforkpages);
481 		GET_VM_STATS(vm, v_rforkpages);
482 		GET_VM_STATS(vm, v_kthreadpages);
483 #undef GET_VM_STATS
484 	}
485 }
486 
487 static void
488 fill_vmtotal(struct vmtotal *vmtp)
489 {
490 	if (kd != NULL) {
491 		/* XXX fill vmtp */
492 		errx(1, "not implemented");
493 	} else {
494 		size_t size = sizeof(*vmtp);
495 		mysysctl("vm.vmtotal", vmtp, &size, NULL, 0);
496 		if (size != sizeof(*vmtp))
497 			errx(1, "vm.total size mismatch");
498 	}
499 }
500 
501 static int hz, hdrcnt;
502 
503 static void
504 dovmstat(unsigned int interval, int reps)
505 {
506 	struct vmtotal total;
507 	time_t uptime, halfuptime;
508 	struct devinfo *tmp_dinfo;
509 	size_t size;
510 
511 	uptime = getuptime();
512 	halfuptime = uptime / 2;
513 	(void)signal(SIGCONT, needhdr);
514 
515 	if (kd != NULL) {
516 		if (namelist[X_STATHZ].n_type != 0 &&
517 		    namelist[X_STATHZ].n_value != 0)
518 			kread(X_STATHZ, &hz, sizeof(hz));
519 		if (!hz)
520 			kread(X_HZ, &hz, sizeof(hz));
521 	} else {
522 		struct clockinfo clockrate;
523 
524 		size = sizeof(clockrate);
525 		mysysctl("kern.clockrate", &clockrate, &size, NULL, 0);
526 		if (size != sizeof(clockrate))
527 			errx(1, "clockrate size mismatch");
528 		hz = clockrate.hz;
529 	}
530 
531 	for (hdrcnt = 1;;) {
532 		if (!--hdrcnt)
533 			printhdr();
534 		if (kd != NULL) {
535 			kread(X_CPTIME, cur.cp_time, sizeof(cur.cp_time));
536 		} else {
537 			size = sizeof(cur.cp_time);
538 			mysysctl("kern.cp_time", &cur.cp_time, &size, NULL, 0);
539 			if (size != sizeof(cur.cp_time))
540 				errx(1, "cp_time size mismatch");
541 		}
542 
543 		tmp_dinfo = last.dinfo;
544 		last.dinfo = cur.dinfo;
545 		cur.dinfo = tmp_dinfo;
546 		last.snap_time = cur.snap_time;
547 
548 		/*
549 		 * Here what we want to do is refresh our device stats.
550 		 * getdevs() returns 1 when the device list has changed.
551 		 * If the device list has changed, we want to go through
552 		 * the selection process again, in case a device that we
553 		 * were previously displaying has gone away.
554 		 */
555 		switch (devstat_getdevs(NULL, &cur)) {
556 		case -1:
557 			errx(1, "%s", devstat_errbuf);
558 			break;
559 		case 1: {
560 			int retval;
561 
562 			num_devices = cur.dinfo->numdevs;
563 			generation = cur.dinfo->generation;
564 
565 			retval = devstat_selectdevs(&dev_select, &num_selected,
566 					    &num_selections, &select_generation,
567 					    generation, cur.dinfo->devices,
568 					    num_devices, matches, num_matches,
569 					    specified_devices,
570 					    num_devices_specified, select_mode,
571 					    maxshowdevs, 0);
572 			switch (retval) {
573 			case -1:
574 				errx(1, "%s", devstat_errbuf);
575 				break;
576 			case 1:
577 				printhdr();
578 				break;
579 			default:
580 				break;
581 			}
582 		}
583 		default:
584 			break;
585 		}
586 
587 		fill_vmmeter(&sum);
588 		fill_vmtotal(&total);
589 		(void)printf("%2d %1d %1d",
590 		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
591 #define vmstat_pgtok(a) ((a) * sum.v_page_size >> 10)
592 #define	rate(x)	(((x) + halfuptime) / uptime)	/* round */
593 		(void)printf(" %7ld %6ld ", (long)vmstat_pgtok(total.t_avm),
594 			     (long)vmstat_pgtok(total.t_free));
595 		(void)printf("%4lu ",
596 		    (unsigned long)rate(sum.v_vm_faults - osum.v_vm_faults));
597 		(void)printf("%3lu ",
598 		    (unsigned long)rate(sum.v_reactivated - osum.v_reactivated));
599 		(void)printf("%3lu ",
600 		    (unsigned long)rate(sum.v_swapin + sum.v_vnodein -
601 		    (osum.v_swapin + osum.v_vnodein)));
602 		(void)printf("%3lu ",
603 		    (unsigned long)rate(sum.v_swapout + sum.v_vnodeout -
604 		    (osum.v_swapout + osum.v_vnodeout)));
605 		(void)printf("%3lu ",
606 		    (unsigned long)rate(sum.v_tfree - osum.v_tfree));
607 		(void)printf("%3lu ",
608 		    (unsigned long)rate(sum.v_pdpages - osum.v_pdpages));
609 		devstats();
610 		(void)printf("%4lu %4lu %3lu ",
611 		    (unsigned long)rate(sum.v_intr - osum.v_intr),
612 		    (unsigned long)rate(sum.v_syscall - osum.v_syscall),
613 		    (unsigned long)rate(sum.v_swtch - osum.v_swtch));
614 		cpustats();
615 		(void)printf("\n");
616 		(void)fflush(stdout);
617 		if (reps >= 0 && --reps <= 0)
618 			break;
619 		osum = sum;
620 		uptime = interval;
621 		/*
622 		 * We round upward to avoid losing low-frequency events
623 		 * (i.e., >= 1 per interval but < 1 per second).
624 		 */
625 		if (interval != 1)
626 			halfuptime = (uptime + 1) / 2;
627 		else
628 			halfuptime = 0;
629 		(void)sleep(interval);
630 	}
631 }
632 
633 static void
634 printhdr(void)
635 {
636 	int i, num_shown;
637 
638 	num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
639 	(void)printf(" procs      memory      page%*s", 19, "");
640 	if (num_shown > 1)
641 		(void)printf(" disks %*s", num_shown * 4 - 7, "");
642 	else if (num_shown == 1)
643 		(void)printf("disk");
644 	(void)printf("   faults      cpu\n");
645 	(void)printf(" r b w     avm    fre  flt  re  pi  po  fr  sr ");
646 	for (i = 0; i < num_devices; i++)
647 		if ((dev_select[i].selected)
648 		 && (dev_select[i].selected <= maxshowdevs))
649 			(void)printf("%c%c%d ", dev_select[i].device_name[0],
650 				     dev_select[i].device_name[1],
651 				     dev_select[i].unit_number);
652 	(void)printf("  in   sy  cs us sy id\n");
653 	hdrcnt = winlines - 2;
654 }
655 
656 /*
657  * Force a header to be prepended to the next output.
658  */
659 static void
660 needhdr(int dummy __unused)
661 {
662 
663 	hdrcnt = 1;
664 }
665 
666 #ifdef notyet
667 static void
668 dotimes(void)
669 {
670 	unsigned int pgintime, rectime;
671 
672 	kread(X_REC, &rectime, sizeof(rectime));
673 	kread(X_PGIN, &pgintime, sizeof(pgintime));
674 	kread(X_SUM, &sum, sizeof(sum));
675 	(void)printf("%u reclaims, %u total time (usec)\n",
676 	    sum.v_pgrec, rectime);
677 	(void)printf("average: %u usec / reclaim\n", rectime / sum.v_pgrec);
678 	(void)printf("\n");
679 	(void)printf("%u page ins, %u total time (msec)\n",
680 	    sum.v_pgin, pgintime / 10);
681 	(void)printf("average: %8.1f msec / page in\n",
682 	    pgintime / (sum.v_pgin * 10.0));
683 }
684 #endif
685 
686 static long
687 pct(long top, long bot)
688 {
689 	long ans;
690 
691 	if (bot == 0)
692 		return(0);
693 	ans = (quad_t)top * 100 / bot;
694 	return (ans);
695 }
696 
697 #define	PCT(top, bot) pct((long)(top), (long)(bot))
698 
699 static void
700 dosum(void)
701 {
702 	struct nchstats lnchstats;
703 	long nchtotal;
704 
705 	fill_vmmeter(&sum);
706 	(void)printf("%9u cpu context switches\n", sum.v_swtch);
707 	(void)printf("%9u device interrupts\n", sum.v_intr);
708 	(void)printf("%9u software interrupts\n", sum.v_soft);
709 	(void)printf("%9u traps\n", sum.v_trap);
710 	(void)printf("%9u system calls\n", sum.v_syscall);
711 	(void)printf("%9u kernel threads created\n", sum.v_kthreads);
712 	(void)printf("%9u  fork() calls\n", sum.v_forks);
713 	(void)printf("%9u vfork() calls\n", sum.v_vforks);
714 	(void)printf("%9u rfork() calls\n", sum.v_rforks);
715 	(void)printf("%9u swap pager pageins\n", sum.v_swapin);
716 	(void)printf("%9u swap pager pages paged in\n", sum.v_swappgsin);
717 	(void)printf("%9u swap pager pageouts\n", sum.v_swapout);
718 	(void)printf("%9u swap pager pages paged out\n", sum.v_swappgsout);
719 	(void)printf("%9u vnode pager pageins\n", sum.v_vnodein);
720 	(void)printf("%9u vnode pager pages paged in\n", sum.v_vnodepgsin);
721 	(void)printf("%9u vnode pager pageouts\n", sum.v_vnodeout);
722 	(void)printf("%9u vnode pager pages paged out\n", sum.v_vnodepgsout);
723 	(void)printf("%9u page daemon wakeups\n", sum.v_pdwakeups);
724 	(void)printf("%9u pages examined by the page daemon\n", sum.v_pdpages);
725 	(void)printf("%9u pages reactivated\n", sum.v_reactivated);
726 	(void)printf("%9u copy-on-write faults\n", sum.v_cow_faults);
727 	(void)printf("%9u copy-on-write optimized faults\n", sum.v_cow_optim);
728 	(void)printf("%9u zero fill pages zeroed\n", sum.v_zfod);
729 	(void)printf("%9u zero fill pages prezeroed\n", sum.v_ozfod);
730 	(void)printf("%9u intransit blocking page faults\n", sum.v_intrans);
731 	(void)printf("%9u total VM faults taken\n", sum.v_vm_faults);
732 	(void)printf("%9u pages affected by kernel thread creation\n", sum.v_kthreadpages);
733 	(void)printf("%9u pages affected by  fork()\n", sum.v_forkpages);
734 	(void)printf("%9u pages affected by vfork()\n", sum.v_vforkpages);
735 	(void)printf("%9u pages affected by rfork()\n", sum.v_rforkpages);
736 	(void)printf("%9u pages freed\n", sum.v_tfree);
737 	(void)printf("%9u pages freed by daemon\n", sum.v_dfree);
738 	(void)printf("%9u pages freed by exiting processes\n", sum.v_pfree);
739 	(void)printf("%9u pages active\n", sum.v_active_count);
740 	(void)printf("%9u pages inactive\n", sum.v_inactive_count);
741 	(void)printf("%9u pages in VM cache\n", sum.v_cache_count);
742 	(void)printf("%9u pages wired down\n", sum.v_wire_count);
743 	(void)printf("%9u pages free\n", sum.v_free_count);
744 	(void)printf("%9u bytes per page\n", sum.v_page_size);
745 	if (kd != NULL) {
746 		kread(X_NCHSTATS, &lnchstats, sizeof(lnchstats));
747 	} else {
748 		size_t size = sizeof(lnchstats);
749 		mysysctl("vfs.cache.nchstats", &lnchstats, &size, NULL, 0);
750 		if (size != sizeof(lnchstats))
751 			errx(1, "vfs.cache.nchstats size mismatch");
752 	}
753 	nchtotal = lnchstats.ncs_goodhits + lnchstats.ncs_neghits +
754 	    lnchstats.ncs_badhits + lnchstats.ncs_falsehits +
755 	    lnchstats.ncs_miss + lnchstats.ncs_long;
756 	(void)printf("%9ld total name lookups\n", nchtotal);
757 	(void)printf(
758 	    "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
759 	    "", PCT(lnchstats.ncs_goodhits, nchtotal),
760 	    PCT(lnchstats.ncs_neghits, nchtotal),
761 	    PCT(lnchstats.ncs_pass2, nchtotal));
762 	(void)printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
763 	    PCT(lnchstats.ncs_badhits, nchtotal),
764 	    PCT(lnchstats.ncs_falsehits, nchtotal),
765 	    PCT(lnchstats.ncs_long, nchtotal));
766 }
767 
768 static void
769 doforkst(void)
770 {
771 	fill_vmmeter(&sum);
772 	(void)printf("%u forks, %u pages, average %.2f\n",
773 	    sum.v_forks, sum.v_forkpages,
774 	    sum.v_forks == 0 ? 0.0 :
775 	    (double)sum.v_forkpages / sum.v_forks);
776 	(void)printf("%u vforks, %u pages, average %.2f\n",
777 	    sum.v_vforks, sum.v_vforkpages,
778 	    sum.v_vforks == 0 ? 0.0 :
779 	    (double)sum.v_vforkpages / sum.v_vforks);
780 	(void)printf("%u rforks, %u pages, average %.2f\n",
781 	    sum.v_rforks, sum.v_rforkpages,
782 	    sum.v_rforks == 0 ? 0.0 :
783 	    (double)sum.v_rforkpages / sum.v_rforks);
784 }
785 
786 static void
787 devstats(void)
788 {
789 	int dn, state;
790 	long double transfers_per_second;
791 	long double busy_seconds;
792 	long tmp;
793 
794 	for (state = 0; state < CPUSTATES; ++state) {
795 		tmp = cur.cp_time[state];
796 		cur.cp_time[state] -= last.cp_time[state];
797 		last.cp_time[state] = tmp;
798 	}
799 
800 	busy_seconds = cur.snap_time - last.snap_time;
801 
802 	for (dn = 0; dn < num_devices; dn++) {
803 		int di;
804 
805 		if ((dev_select[dn].selected == 0)
806 		 || (dev_select[dn].selected > maxshowdevs))
807 			continue;
808 
809 		di = dev_select[dn].position;
810 
811 		if (devstat_compute_statistics(&cur.dinfo->devices[di],
812 		    &last.dinfo->devices[di], busy_seconds,
813 		    DSM_TRANSFERS_PER_SECOND, &transfers_per_second,
814 		    DSM_NONE) != 0)
815 			errx(1, "%s", devstat_errbuf);
816 
817 		(void)printf("%3.0Lf ", transfers_per_second);
818 	}
819 }
820 
821 static void
822 cpustats(void)
823 {
824 	int state;
825 	double lpct, total;
826 
827 	total = 0;
828 	for (state = 0; state < CPUSTATES; ++state)
829 		total += cur.cp_time[state];
830 	if (total)
831 		lpct = 100.0 / total;
832 	else
833 		lpct = 0.0;
834 	(void)printf("%2.0f ", (cur.cp_time[CP_USER] +
835 				cur.cp_time[CP_NICE]) * lpct);
836 	(void)printf("%2.0f ", (cur.cp_time[CP_SYS] +
837 				cur.cp_time[CP_INTR]) * lpct);
838 	(void)printf("%2.0f", cur.cp_time[CP_IDLE] * lpct);
839 }
840 
841 static void
842 dointr(void)
843 {
844 	unsigned long *intrcnt, uptime;
845 	uint64_t inttotal;
846 	size_t clen, inamlen, intrcntlen, istrnamlen;
847 	unsigned int i, nintr;
848 	char *intrname, *tintrname;
849 
850 	uptime = getuptime();
851 	if (kd != NULL) {
852 		intrcntlen = namelist[X_EINTRCNT].n_value -
853 		    namelist[X_INTRCNT].n_value;
854 		inamlen = namelist[X_EINTRNAMES].n_value -
855 		    namelist[X_INTRNAMES].n_value;
856 		if ((intrcnt = malloc(intrcntlen)) == NULL ||
857 		    (intrname = malloc(inamlen)) == NULL)
858 			err(1, "malloc()");
859 		kread(X_INTRCNT, intrcnt, intrcntlen);
860 		kread(X_INTRNAMES, intrname, inamlen);
861 	} else {
862 		for (intrcnt = NULL, intrcntlen = 1024; ; intrcntlen *= 2) {
863 			if ((intrcnt = reallocf(intrcnt, intrcntlen)) == NULL)
864 				err(1, "reallocf()");
865 			if (mysysctl("hw.intrcnt",
866 			    intrcnt, &intrcntlen, NULL, 0) == 0)
867 				break;
868 		}
869 		for (intrname = NULL, inamlen = 1024; ; inamlen *= 2) {
870 			if ((intrname = reallocf(intrname, inamlen)) == NULL)
871 				err(1, "reallocf()");
872 			if (mysysctl("hw.intrnames",
873 			    intrname, &inamlen, NULL, 0) == 0)
874 				break;
875 		}
876 	}
877 	nintr = intrcntlen / sizeof(unsigned long);
878 	tintrname = intrname;
879 	istrnamlen = strlen("interrupt");
880 	for (i = 0; i < nintr; i++) {
881 		clen = strlen(tintrname);
882 		if (clen > istrnamlen)
883 			istrnamlen = clen;
884 		tintrname += clen + 1;
885 	}
886 	(void)printf("%-*s %20s %10s\n", istrnamlen, "interrupt", "total",
887 	    "rate");
888 	inttotal = 0;
889 	for (i = 0; i < nintr; i++) {
890 		if (intrname[0] != '\0' && (*intrcnt != 0 || aflag))
891 			(void)printf("%-*s %20lu %10lu\n", istrnamlen, intrname,
892 			    *intrcnt, *intrcnt / uptime);
893 		intrname += strlen(intrname) + 1;
894 		inttotal += *intrcnt++;
895 	}
896 	(void)printf("%-*s %20llu %10llu\n", istrnamlen, "Total",
897 	    (long long)inttotal, (long long)(inttotal / uptime));
898 }
899 
900 static void
901 domem(void)
902 {
903 	struct malloc_type type;
904 
905 	if (kd == NULL) {
906 		dosysctl("kern.malloc");
907 		return;
908 	}
909 	kread(X_KMEMSTATS, &type.ks_next, sizeof(type.ks_next));
910 	(void)printf("\n        Type  InUse MemUse HighUse Requests"
911 	    "  Size(s)\n");
912 	do {
913 		/* XXX this should be exported in sys/malloc.h */
914 		struct {
915 			int kz_size;
916 			char *kz_name;
917 			/* uma_zone_t */ void *kz_zone;
918 		} kz;
919 		size_t kmemzonenum;
920 		char *str;
921 		int first;
922 
923 		if (kvm_read(kd, (u_long)type.ks_next, &type, sizeof(type)) !=
924 		    sizeof(type))
925 			errx(1, "%s: %p: %s", __func__, type.ks_next,
926 			    kvm_geterr(kd));
927 		if (type.ks_calls == 0)
928 			continue;
929 		str = kgetstr(type.ks_shortdesc);
930 		(void)printf("%13s%6lu%6luK%7luK%9llu",
931 		    str,
932 		    type.ks_inuse,
933 		    (type.ks_memuse + 1023) / 1024,
934 		    (type.ks_maxused + 1023) / 1024,
935 		    (long long unsigned)type.ks_calls);
936 		free(str);
937 		for (kmemzonenum = 0, first = 1; ; kmemzonenum++) {
938 			kreado(X_KMEMZONES, &kz, sizeof(kz),
939 			    kmemzonenum * sizeof(kz));
940 			if (kz.kz_name == NULL) {
941 				(void)printf("\n");
942 				break;
943 			}
944 			if (!(type.ks_size & (1 << kmemzonenum)))
945 				continue;
946 			if (first)
947 				(void)printf("  ");
948 			else
949 				(void)printf(",");
950 			first = 0;
951 			str = kgetstr(kz.kz_name);
952 			(void)printf("%s", str);
953 			free(str);
954 		}
955 	} while (type.ks_next != NULL);
956 }
957 
958 static void
959 dozmem(void)
960 {
961 	if (kd != NULL)
962 		errx(1, "not implemented");
963 	dosysctl("vm.zone");
964 }
965 
966 static void
967 dosysctl(const char *name)
968 {
969 	char *buf;
970 	size_t bufsize;
971 
972 	for (buf = NULL, bufsize = 1024; ; bufsize *= 2) {
973 		if ((buf = realloc(buf, bufsize)) == NULL)
974 			err(1, "realloc()");
975 		bufsize--;	/* Leave space for the kern.malloc fixup. */
976 		if (mysysctl(name, buf, &bufsize, NULL, 0) == 0)
977 			break;
978 	}
979 	buf[bufsize] = '\0';	/* Fix up kern.malloc not returning a string. */
980 	(void)printf("%s", buf);
981 	free(buf);
982 }
983 
984 /*
985  * kread reads something from the kernel, given its nlist index.
986  */
987 static void
988 kreado(int nlx, void *addr, size_t size, size_t offset)
989 {
990 	const char *sym;
991 
992 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
993 		sym = namelist[nlx].n_name;
994 		if (*sym == '_')
995 			++sym;
996 		errx(1, "symbol %s not defined", sym);
997 	}
998 	if ((size_t)kvm_read(kd, namelist[nlx].n_value + offset, addr,
999 	    size) != size) {
1000 		sym = namelist[nlx].n_name;
1001 		if (*sym == '_')
1002 			++sym;
1003 		errx(1, "%s: %s", sym, kvm_geterr(kd));
1004 	}
1005 }
1006 
1007 static void
1008 kread(int nlx, void *addr, size_t size)
1009 {
1010 	kreado(nlx, addr, size, 0);
1011 }
1012 
1013 static char *
1014 kgetstr(const char *strp)
1015 {
1016 	int n = 0, size = 1;
1017 	char *ret = NULL;
1018 
1019 	do {
1020 		if (size == n + 1) {
1021 			ret = realloc(ret, size);
1022 			if (ret == NULL)
1023 				err(1, "%s: realloc", __func__);
1024 			size *= 2;
1025 		}
1026 		if (kvm_read(kd, (u_long)strp + n, &ret[n], 1) != 1)
1027 			errx(1, "%s: %s", __func__, kvm_geterr(kd));
1028 	} while (ret[n++] != '\0');
1029 	return (ret);
1030 }
1031 
1032 static void
1033 usage(void)
1034 {
1035 	(void)fprintf(stderr, "%s%s",
1036 		"usage: vmstat [-aimsz] [-c count] [-M core [-N system]] [-w wait]\n",
1037 		"              [-n devs] [disks]\n");
1038 	exit(1);
1039 }
1040