xref: /dflybsd-src/usr.bin/vmstat/vmstat.c (revision 7491e5ac85fbf1e3b9867ca39213d74c8f640ded)
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. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  * @(#) Copyright (c) 1980, 1986, 1991, 1993 The Regents of the University of California.  All rights reserved.
30  * @(#)vmstat.c	8.1 (Berkeley) 6/6/93
31  * $FreeBSD: src/usr.bin/vmstat/vmstat.c,v 1.38.2.4 2001/07/31 19:52:41 tmm Exp $
32  */
33 
34 #include <sys/user.h>
35 #include <sys/param.h>
36 #include <sys/time.h>
37 #include <sys/uio.h>
38 #include <sys/namei.h>
39 #include <sys/objcache.h>
40 #include <sys/signal.h>
41 #include <sys/fcntl.h>
42 #include <sys/ioctl.h>
43 #include <sys/sysctl.h>
44 #include <sys/vmmeter.h>
45 #include <sys/interrupt.h>
46 
47 #include <vm/vm_param.h>
48 #include <vm/vm_zone.h>
49 
50 #include <ctype.h>
51 #include <err.h>
52 #include <errno.h>
53 #include <kinfo.h>
54 #include <kvm.h>
55 #include <limits.h>
56 #include <nlist.h>
57 #include <paths.h>
58 #include <stdio.h>
59 #include <stdlib.h>
60 #include <string.h>
61 #include <sysexits.h>
62 #include <time.h>
63 #include <unistd.h>
64 #include <devstat.h>
65 
66 static struct nlist namelist[] = {
67 #define	X_BOOTTIME	0
68 	{ "_boottime",	0, 0, 0, 0 },
69 #define X_NCHSTATS	1
70 	{ "_nchstats",	0, 0, 0, 0 },
71 #define	X_KMEMSTATISTICS 2
72 	{ "_kmemstatistics",	0, 0, 0, 0 },
73 #define	X_NCPUS		3
74 	{ "_ncpus",	0, 0, 0, 0 },
75 #define	X_ZLIST		4
76 	{ "_zlist",	0, 0, 0, 0 },
77 #ifdef notyet
78 #define	X_DEFICIT	5
79 	{ "_deficit",	0, 0, 0, 0 },
80 #define	X_FORKSTAT	6
81 	{ "_forkstat",	0, 0, 0, 0 },
82 #define X_REC		7
83 	{ "_rectime",	0, 0, 0, 0 },
84 #define X_PGIN		8
85 	{ "_pgintime",	0, 0, 0, 0 },
86 #define	X_XSTATS	9
87 	{ "_xstats",	0, 0, 0, 0 },
88 #define X_END		10
89 #else
90 #define X_END		5
91 #endif
92 	{ "", 0, 0, 0, 0 },
93 };
94 
95 #define ONEMB	(1024L * 1024L)
96 #define ONEKB	(1024L)
97 
98 LIST_HEAD(zlist, vm_zone);
99 
100 struct statinfo cur, last;
101 int num_devices, maxshowdevs;
102 long generation;
103 struct device_selection *dev_select;
104 int num_selected;
105 struct devstat_match *matches;
106 int num_matches = 0;
107 int num_devices_specified, num_selections;
108 long select_generation;
109 char **specified_devices;
110 devstat_select_mode select_mode;
111 
112 struct	vmmeter vmm, ovmm;
113 struct	vmstats vms, ovms;
114 
115 int	winlines = 20;
116 int	nflag = 0;
117 int	verbose = 0;
118 int	unformatted_opt = 0;
119 int	brief_opt = 0;
120 int	ncpus;
121 
122 kvm_t *kd;
123 
124 struct kinfo_cputime cp_time, old_cp_time, diff_cp_time;
125 
126 #define	FORKSTAT	0x01
127 #define	INTRSTAT	0x02
128 #define	MEMSTAT		0x04
129 #define	SUMSTAT		0x08
130 #define	TIMESTAT	0x10
131 #define	VMSTAT		0x20
132 #define ZMEMSTAT	0x40
133 #define OCSTAT		0x80
134 
135 static void cpustats(void);
136 static void dointr(void);
137 static void domem(void);
138 static void dooc(void);
139 static void dosum(void);
140 static void dozmem(u_int interval, int reps);
141 static void dovmstat(u_int, int);
142 static void kread(int, void *, size_t);
143 static void usage(void);
144 static char **getdrivedata(char **);
145 static long getuptime(void);
146 static void needhdr(int);
147 static long pct(long, long);
148 
149 #ifdef notyet
150 static void dotimes(void); /* Not implemented */
151 static void doforkst(void);
152 #endif
153 static void printhdr(void);
154 static const char *formatnum(intmax_t value, int width, int do10s);
155 static void devstats(int dooutput);
156 
157 int
158 main(int argc, char **argv)
159 {
160 	int c, todo;
161 	u_int interval;		/* milliseconds */
162 	int reps;
163 	char *memf, *nlistf;
164 	char errbuf[_POSIX2_LINE_MAX];
165 
166 	memf = nlistf = NULL;
167 	interval = reps = todo = 0;
168 	maxshowdevs = 2;
169 	while ((c = getopt(argc, argv, "bc:fiM:mN:n:op:stuvw:z")) != -1) {
170 		switch (c) {
171 		case 'b':
172 			brief_opt = 1;
173 			break;
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 'o':
204 			todo |= OCSTAT;
205 			break;
206 		case 'p':
207 			if (buildmatch(optarg, &matches, &num_matches) != 0)
208 				errx(1, "%s", devstat_errbuf);
209 			break;
210 		case 's':
211 			todo |= SUMSTAT;
212 			break;
213 		case 't':
214 #ifdef notyet
215 			todo |= TIMESTAT;
216 #else
217 			errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
218 #endif
219 			break;
220 		case 'u':
221 			unformatted_opt = 1;
222 			break;
223 		case 'v':
224 			++verbose;
225 			break;
226 		case 'w':
227 			interval = (u_int)(strtod(optarg, NULL) * 1000.0);
228 			break;
229 		case 'z':
230 			todo |= ZMEMSTAT;
231 			break;
232 		default:
233 			usage();
234 		}
235 	}
236 	argc -= optind;
237 	argv += optind;
238 
239 	if (todo == 0)
240 		todo = VMSTAT;
241 
242 	/*
243 	 * Discard setgid privileges if not the running kernel so that bad
244 	 * guys can't print interesting stuff from kernel memory.
245 	 */
246 	if (nlistf != NULL || memf != NULL) {
247 		setgid(getgid());
248 		if (todo & OCSTAT) {
249 			errx(1, "objcache stats can only be gathered on "
250 			    "the running system");
251 		}
252 	}
253 
254 	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
255 	if (kd == NULL)
256 		errx(1, "kvm_openfiles: %s", errbuf);
257 
258 	if ((c = kvm_nlist(kd, namelist)) != 0) {
259 		if (c > 0) {
260 			warnx("undefined symbols:");
261 			for (c = 0; c < (int)NELEM(namelist); c++)
262 				if (namelist[c].n_type == 0)
263 					fprintf(stderr, " %s",
264 					    namelist[c].n_name);
265 			fputc('\n', stderr);
266 		} else
267 			warnx("kvm_nlist: %s", kvm_geterr(kd));
268 		exit(1);
269 	}
270 
271 	kread(X_NCPUS, &ncpus, sizeof(ncpus));
272 
273 	if (todo & VMSTAT) {
274 		struct winsize winsize;
275 
276 		/*
277 		 * Make sure that the userland devstat version matches the
278 		 * kernel devstat version.  If not, exit and print a
279 		 * message informing the user of his mistake.
280 		 */
281 		if (checkversion() < 0)
282 			errx(1, "%s", devstat_errbuf);
283 
284 
285 		argv = getdrivedata(argv);
286 		winsize.ws_row = 0;
287 		ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
288 		if (winsize.ws_row > 0)
289 			winlines = winsize.ws_row;
290 
291 	}
292 
293 #define	BACKWARD_COMPATIBILITY
294 #ifdef	BACKWARD_COMPATIBILITY
295 	if (*argv) {
296 		interval = (u_int)(strtod(*argv, NULL) * 1000.0);
297 		if (*++argv)
298 			reps = atoi(*argv);
299 	}
300 #endif
301 
302 	if (interval) {
303 		if (!reps)
304 			reps = -1;
305 	} else if (reps) {
306 		interval = 1000;
307 	}
308 
309 #ifdef notyet
310 	if (todo & FORKSTAT)
311 		doforkst();
312 #endif
313 	if (todo & MEMSTAT)
314 		domem();
315 	if (todo & ZMEMSTAT)
316 		dozmem(interval, reps);
317 	if (todo & SUMSTAT)
318 		dosum();
319 #ifdef notyet
320 	if (todo & TIMESTAT)
321 		dotimes();
322 #endif
323 	if (todo & INTRSTAT)
324 		dointr();
325 	if (todo & VMSTAT)
326 		dovmstat(interval, reps);
327 	if (todo & OCSTAT)
328 		dooc();
329 	exit(0);
330 }
331 
332 static char **
333 getdrivedata(char **argv)
334 {
335 	if ((num_devices = getnumdevs()) < 0)
336 		errx(1, "%s", devstat_errbuf);
337 
338 	cur.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
339 	last.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
340 	bzero(cur.dinfo, sizeof(struct devinfo));
341 	bzero(last.dinfo, sizeof(struct devinfo));
342 
343 	if (getdevs(&cur) == -1)
344 		errx(1, "%s", devstat_errbuf);
345 
346 	num_devices = cur.dinfo->numdevs;
347 	generation = cur.dinfo->generation;
348 
349 	specified_devices = (char **)malloc(sizeof(char *));
350 	for (num_devices_specified = 0; *argv; ++argv) {
351 		if (isdigit(**argv))
352 			break;
353 		num_devices_specified++;
354 		specified_devices = (char **)realloc(specified_devices,
355 						     sizeof(char *) *
356 						     num_devices_specified);
357 		specified_devices[num_devices_specified - 1] = *argv;
358 	}
359 	dev_select = NULL;
360 
361 	if (nflag == 0 && maxshowdevs < num_devices_specified)
362 			maxshowdevs = num_devices_specified;
363 
364 	/*
365 	 * People are generally only interested in disk statistics when
366 	 * they're running vmstat.  So, that's what we're going to give
367 	 * them if they don't specify anything by default.  We'll also give
368 	 * them any other random devices in the system so that we get to
369 	 * maxshowdevs devices, if that many devices exist.  If the user
370 	 * specifies devices on the command line, either through a pattern
371 	 * match or by naming them explicitly, we will give the user only
372 	 * those devices.
373 	 */
374 	if ((num_devices_specified == 0) && (num_matches == 0)) {
375 		if (buildmatch("da", &matches, &num_matches) != 0)
376 			errx(1, "%s", devstat_errbuf);
377 
378 		select_mode = DS_SELECT_ADD;
379 	} else
380 		select_mode = DS_SELECT_ONLY;
381 
382 	/*
383 	 * At this point, selectdevs will almost surely indicate that the
384 	 * device list has changed, so we don't look for return values of 0
385 	 * or 1.  If we get back -1, though, there is an error.
386 	 */
387 	if (selectdevs(&dev_select, &num_selected, &num_selections,
388 		       &select_generation, generation, cur.dinfo->devices,
389 		       num_devices, matches, num_matches, specified_devices,
390 		       num_devices_specified, select_mode,
391 		       maxshowdevs, 0) == -1)
392 		errx(1, "%s", devstat_errbuf);
393 
394 	return(argv);
395 }
396 
397 static long
398 getuptime(void)
399 {
400 	static time_t now, boottime;
401 	time_t uptime;
402 
403 	if (boottime == 0)
404 		kread(X_BOOTTIME, &boottime, sizeof(boottime));
405 	time(&now);
406 	uptime = now - boottime;
407 	if (uptime <= 0 || uptime > 60*60*24*365*10)
408 		errx(1, "time makes no sense; namelist must be wrong");
409 	return(uptime);
410 }
411 
412 int	hdrcnt;
413 
414 static void
415 dovmstat(u_int interval, int reps)
416 {
417 	struct vmtotal total;
418 	struct devinfo *tmp_dinfo;
419 	size_t vmm_size = sizeof(vmm);
420 	size_t vms_size = sizeof(vms);
421 	size_t vmt_size = sizeof(total);
422 	int initial = 1;
423 	int dooutput = 1;
424 
425 	signal(SIGCONT, needhdr);
426 	if (reps != 0)
427 		dooutput = 0;
428 
429 	for (hdrcnt = 1;;) {
430 		if (!--hdrcnt)
431 			printhdr();
432 		if (kinfo_get_sched_cputime(&cp_time))
433 			err(1, "kinfo_get_sched_cputime");
434 
435 		tmp_dinfo = last.dinfo;
436 		last.dinfo = cur.dinfo;
437 		cur.dinfo = tmp_dinfo;
438 		last.busy_time = cur.busy_time;
439 
440 		/*
441 		 * Here what we want to do is refresh our device stats.
442 		 * getdevs() returns 1 when the device list has changed.
443 		 * If the device list has changed, we want to go through
444 		 * the selection process again, in case a device that we
445 		 * were previously displaying has gone away.
446 		 */
447 		switch (getdevs(&cur)) {
448 		case -1:
449 			errx(1, "%s", devstat_errbuf);
450 			break;
451 		case 1: {
452 			int retval;
453 
454 			num_devices = cur.dinfo->numdevs;
455 			generation = cur.dinfo->generation;
456 
457 			retval = selectdevs(&dev_select, &num_selected,
458 					    &num_selections, &select_generation,
459 					    generation, cur.dinfo->devices,
460 					    num_devices, matches, num_matches,
461 					    specified_devices,
462 					    num_devices_specified, select_mode,
463 					    maxshowdevs, 0);
464 			switch (retval) {
465 			case -1:
466 				errx(1, "%s", devstat_errbuf);
467 				break;
468 			case 1:
469 				printhdr();
470 				break;
471 			default:
472 				break;
473 			}
474 		}
475 		default:
476 			break;
477 		}
478 
479 		if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
480 			perror("sysctlbyname: vm.vmstats");
481 			exit(1);
482 		}
483 		if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
484 			perror("sysctlbyname: vm.vmmeter");
485 			exit(1);
486 		}
487 		if (sysctlbyname("vm.vmtotal", &total, &vmt_size, NULL, 0)) {
488 			perror("sysctlbyname: vm.vmtotal");
489 			exit(1);
490 		}
491 		if (dooutput) {
492 			printf("%3ld %2ld %2ld",
493 			       total.t_rq - 1,
494 			       total.t_dw + total.t_pw,
495 			       total.t_sw);
496 		}
497 
498 #define rate(x)		\
499 	(intmax_t)(initial ? (x) : ((intmax_t)(x) * 1000 + interval / 2) \
500 				   / interval)
501 
502 		if (dooutput) {
503 			printf(" %s ",
504 			       formatnum((int64_t)total.t_free *
505 					 vms.v_page_size,
506 					 5, 1));
507 			printf("%s ",
508 			       formatnum(rate(vmm.v_vm_faults -
509 					      ovmm.v_vm_faults),
510 					 5, 1));
511 			printf("%s ",
512 			       formatnum(rate(vmm.v_reactivated -
513 					      ovmm.v_reactivated),
514 					 4, 0));
515 			printf("%s ",
516 			       formatnum(rate(vmm.v_swapin + vmm.v_vnodein -
517 					      (ovmm.v_swapin +
518 					       ovmm.v_vnodein)),
519 					 4, 0));
520 			printf("%s ",
521 			       formatnum(rate(vmm.v_swapout + vmm.v_vnodeout -
522 					      (ovmm.v_swapout +
523 					       ovmm.v_vnodeout)),
524 					 4, 0));
525 			printf("%s ",
526 			       formatnum(rate(vmm.v_tfree - ovmm.v_tfree),
527 					 4, 0));
528 		}
529 		devstats(dooutput);
530 		if (dooutput) {
531 			printf("%s ",
532 			       formatnum(rate(vmm.v_intr - ovmm.v_intr),
533 					 5, 1));
534 			printf("%s ",
535 			       formatnum(rate(vmm.v_syscall -
536 					      ovmm.v_syscall),
537 					 5, 1));
538 			printf("%s ",
539 			       formatnum(rate(vmm.v_swtch -
540 					      ovmm.v_swtch),
541 					 5, 1));
542 			cpustats();
543 			printf("\n");
544 			fflush(stdout);
545 		}
546 		if (reps >= 0 && --reps <= 0)
547 			break;
548 		ovmm = vmm;
549 		usleep(interval * 1000);
550 		initial = 0;
551 		dooutput = 1;
552 	}
553 }
554 
555 static const char *
556 formatnum(intmax_t value, int width, int do10s)
557 {
558 	static char buf[16][64];
559 	static int bi;
560 	const char *fmt;
561 	double d;
562 
563 	if (brief_opt)
564 		do10s = 0;
565 
566 	bi = (bi + 1) % 16;
567 
568 	if (unformatted_opt) {
569 		switch(width) {
570 		case 4:
571 			snprintf(buf[bi], sizeof(buf[bi]), "%4jd", value);
572 			break;
573 		case 5:
574 			snprintf(buf[bi], sizeof(buf[bi]), "%5jd", value);
575 			break;
576 		default:
577 			snprintf(buf[bi], sizeof(buf[bi]), "%jd", value);
578 			break;
579 		}
580 		return buf[bi];
581 	}
582 
583 	d = (double)value;
584 	fmt = "n/a";
585 
586 	switch(width) {
587 	case 4:
588 		if (value < 1024) {
589 			fmt = "%4.0f";
590 		} else if (value < 10*1024) {
591 			fmt = "%3.1fK";
592 			d = d / 1024;
593 		} else if (value < 1000*1024) {
594 			fmt = "%3.0fK";
595 			d = d / 1024;
596 		} else if (value < 10*1024*1024) {
597 			fmt = "%3.1fM";
598 			d = d / (1024 * 1024);
599 		} else if (value < 1000*1024*1024) {
600 			fmt = "%3.0fM";
601 			d = d / (1024 * 1024);
602 		} else {
603 			fmt = "%3.1fG";
604 			d = d / (1024.0 * 1024.0 * 1024.0);
605 		}
606 		break;
607 	case 5:
608 		if (value < 1024) {
609 			fmt = "%5.0f";
610 		} else if (value < 10*1024) {
611 			fmt = "%4.2fK";
612 			d = d / 1024;
613 		} else if (value < 100*1024 && do10s) {
614 			fmt = "%4.1fK";
615 			d = d / 1024;
616 		} else if (value < 1000*1024) {
617 			fmt = "%4.0fK";
618 			d = d / 1024;
619 		} else if (value < 10*1024*1024) {
620 			fmt = "%4.2fM";
621 			d = d / (1024 * 1024);
622 		} else if (value < 100*1024*1024 && do10s) {
623 			fmt = "%4.1fM";
624 			d = d / (1024 * 1024);
625 		} else if (value < 1000*1024*1024) {
626 			fmt = "%4.0fM";
627 			d = d / (1024 * 1024);
628 		} else if (value < 10LL*1024*1024*1024) {
629 			fmt = "%4.2fG";
630 			d = d / (1024.0 * 1024.0 * 1024.0);
631 		} else if (value < 100LL*1024*1024*1024 && do10s) {
632 			fmt = "%4.1fG";
633 			d = d / (1024.0 * 1024.0 * 1024.0);
634 		} else if (value < 1000LL*1024*1024*1024) {
635 			fmt = "%4.0fG";
636 			d = d / (1024.0 * 1024.0 * 1024.0);
637 		} else {
638 			fmt = "%4.2fT";
639 			d = d / (1024.0 * 1024.0 * 1024.0 * 1024.0);
640 		}
641 		break;
642 	default:
643 		fprintf(stderr, "formatnum: unsupported width %d\n", width);
644 		exit(1);
645 		break;
646 	}
647 	snprintf(buf[bi], sizeof(buf[bi]), fmt, d);
648 	return buf[bi];
649 }
650 
651 static void
652 printhdr(void)
653 {
654 	int i, num_shown;
655 
656 	num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
657 	printf("--procs-- ---memory-- -------paging------ ");
658 	if (num_shown > 1)
659 		printf("--disks%.*s",
660 		       num_shown * 4 - 6,
661 		       "---------------------------------");
662 	else if (num_shown == 1)
663 		printf("disk");
664 	printf(" -----faults------ ---cpu---\n");
665 	printf("  r  b  w   fre   flt   re   pi   po   fr ");
666 	for (i = 0; i < num_devices; i++)
667 		if ((dev_select[i].selected)
668 		 && (dev_select[i].selected <= maxshowdevs))
669 			printf(" %c%c%d ", dev_select[i].device_name[0],
670 				     dev_select[i].device_name[1],
671 				     dev_select[i].unit_number);
672 	printf("  int   sys   ctx us sy id\n");
673 	hdrcnt = winlines - 2;
674 }
675 
676 /*
677  * Force a header to be prepended to the next output.
678  */
679 static void
680 needhdr(__unused int signo)
681 {
682 
683 	hdrcnt = 1;
684 }
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 *nch_tmp, nchstats;
703 	size_t vms_size = sizeof(vms);
704 	size_t vmm_size = sizeof(vmm);
705 	int cpucnt;
706 	u_long nchtotal;
707 	u_long nchpathtotal;
708 	size_t nch_size = sizeof(struct nchstats) * SMP_MAXCPU;
709 
710 	if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0)) {
711 		perror("sysctlbyname: vm.vmstats");
712 		exit(1);
713 	}
714 	if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0)) {
715 		perror("sysctlbyname: vm.vmstats");
716 		exit(1);
717 	}
718 	printf("%9u cpu context switches\n", vmm.v_swtch);
719 	printf("%9u device interrupts\n", vmm.v_intr);
720 	printf("%9u software interrupts\n", vmm.v_soft);
721 	printf("%9u traps\n", vmm.v_trap);
722 	printf("%9u system calls\n", vmm.v_syscall);
723 	printf("%9u kernel threads created\n", vmm.v_kthreads);
724 	printf("%9u  fork() calls\n", vmm.v_forks);
725 	printf("%9u vfork() calls\n", vmm.v_vforks);
726 	printf("%9u rfork() calls\n", vmm.v_rforks);
727 	printf("%9u exec() calls\n", vmm.v_exec);
728 	printf("%9u swap pager pageins\n", vmm.v_swapin);
729 	printf("%9u swap pager pages paged in\n", vmm.v_swappgsin);
730 	printf("%9u swap pager pageouts\n", vmm.v_swapout);
731 	printf("%9u swap pager pages paged out\n", vmm.v_swappgsout);
732 	printf("%9u vnode pager pageins\n", vmm.v_vnodein);
733 	printf("%9u vnode pager pages paged in\n", vmm.v_vnodepgsin);
734 	printf("%9u vnode pager pageouts\n", vmm.v_vnodeout);
735 	printf("%9u vnode pager pages paged out\n", vmm.v_vnodepgsout);
736 	printf("%9u page daemon wakeups\n", vmm.v_pdwakeups);
737 	printf("%9u pages examined by the page daemon\n", vmm.v_pdpages);
738 	printf("%9u pages reactivated\n", vmm.v_reactivated);
739 	printf("%9u copy-on-write faults\n", vmm.v_cow_faults);
740 	printf("%9u copy-on-write optimized faults\n", vmm.v_cow_optim);
741 	printf("%9u zero fill pages zeroed\n", vmm.v_zfod);
742 	printf("%9u zero fill pages prezeroed\n", vmm.v_ozfod);
743 	printf("%9u intransit blocking page faults\n", vmm.v_intrans);
744 	printf("%9u total VM faults taken\n", vmm.v_vm_faults);
745 	printf("%9u pages affected by kernel thread creation\n", vmm.v_kthreadpages);
746 	printf("%9u pages affected by  fork()\n", vmm.v_forkpages);
747 	printf("%9u pages affected by vfork()\n", vmm.v_vforkpages);
748 	printf("%9u pages affected by rfork()\n", vmm.v_rforkpages);
749 	printf("%9u pages freed\n", vmm.v_tfree);
750 	printf("%9u pages freed by daemon\n", vmm.v_dfree);
751 	printf("%9u pages freed by exiting processes\n", vmm.v_pfree);
752 	printf("%9lu pages active\n", vms.v_active_count);
753 	printf("%9lu pages inactive\n", vms.v_inactive_count);
754 	printf("%9lu pages in VM cache\n", vms.v_cache_count);
755 	printf("%9lu pages wired down\n", vms.v_wire_count);
756 	printf("%9lu pages free\n", vms.v_free_count);
757 	printf("%9u bytes per page\n", vms.v_page_size);
758 	printf("%9u global smp invltlbs\n", vmm.v_smpinvltlb);
759 
760 	if ((nch_tmp = malloc(nch_size)) == NULL) {
761 		perror("malloc");
762 		exit(1);
763 	} else {
764 		if (sysctlbyname("vfs.cache.nchstats", nch_tmp, &nch_size, NULL, 0)) {
765 			perror("sysctlbyname vfs.cache.nchstats");
766 			free(nch_tmp);
767 			exit(1);
768 		} else {
769 			if ((nch_tmp = realloc(nch_tmp, nch_size)) == NULL) {
770 				perror("realloc");
771 				exit(1);
772 			}
773 		}
774 	}
775 
776 	cpucnt = nch_size / sizeof(struct nchstats);
777 	kvm_nch_cpuagg(nch_tmp, &nchstats, cpucnt);
778 
779 	nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
780 	    nchstats.ncs_badhits + nchstats.ncs_falsehits +
781 	    nchstats.ncs_miss;
782 	nchpathtotal = nchstats.ncs_longhits + nchstats.ncs_longmiss;
783 	printf("%9ld total path lookups\n", nchpathtotal);
784 	printf("%9ld total component lookups\n", nchtotal);
785 	printf(
786 	    "%9s cache hits (%ld%% pos + %ld%% neg)\n",
787 	    "", PCT(nchstats.ncs_goodhits, nchtotal),
788 	    PCT(nchstats.ncs_neghits, nchtotal));
789 	printf("%9s deletions %ld%%, falsehits %ld%%\n", "",
790 	    PCT(nchstats.ncs_badhits, nchtotal),
791 	    PCT(nchstats.ncs_falsehits, nchtotal));
792 	free(nch_tmp);
793 }
794 
795 #ifdef notyet
796 void
797 doforkst(void)
798 {
799 	struct forkstat fks;
800 
801 	kread(X_FORKSTAT, &fks, sizeof(struct forkstat));
802 	printf("%d forks, %d pages, average %.2f\n",
803 	    fks.cntfork, fks.sizfork, (double)fks.sizfork / fks.cntfork);
804 	printf("%d vforks, %d pages, average %.2f\n",
805 	    fks.cntvfork, fks.sizvfork, (double)fks.sizvfork / fks.cntvfork);
806 }
807 #endif
808 
809 static void
810 devstats(int dooutput)
811 {
812 	int dn;
813 	long double transfers_per_second;
814 	long double busy_seconds;
815 
816 	diff_cp_time.cp_user = cp_time.cp_user - old_cp_time.cp_user;
817 	diff_cp_time.cp_nice = cp_time.cp_nice - old_cp_time.cp_nice;
818 	diff_cp_time.cp_sys = cp_time.cp_sys - old_cp_time.cp_sys;
819 	diff_cp_time.cp_intr = cp_time.cp_intr - old_cp_time.cp_intr;
820 	diff_cp_time.cp_idle = cp_time.cp_idle - old_cp_time.cp_idle;
821 	old_cp_time = cp_time;
822 
823 	busy_seconds = compute_etime(cur.busy_time, last.busy_time);
824 
825 	for (dn = 0; dn < num_devices; dn++) {
826 		int di;
827 
828 		if ((dev_select[dn].selected == 0)
829 		 || (dev_select[dn].selected > maxshowdevs))
830 			continue;
831 
832 		di = dev_select[dn].position;
833 
834 		if (compute_stats(&cur.dinfo->devices[di],
835 				  &last.dinfo->devices[di], busy_seconds,
836 				  NULL, NULL, NULL,
837 				  NULL, &transfers_per_second, NULL,
838 				  NULL, NULL) != 0)
839 			errx(1, "%s", devstat_errbuf);
840 
841 		if (dooutput)
842 			printf("%s ", formatnum(transfers_per_second, 4, 0));
843 	}
844 }
845 
846 static void
847 cpustats(void)
848 {
849 	uint64_t total;
850 	double totusage;
851 
852 	total = diff_cp_time.cp_user + diff_cp_time.cp_nice +
853 	    diff_cp_time.cp_sys + diff_cp_time.cp_intr + diff_cp_time.cp_idle;
854 
855 	if (total)
856 		totusage = 100.0 / total;
857 	else
858 		totusage = 0;
859 	printf("%2.0f ",
860 	       (diff_cp_time.cp_user + diff_cp_time.cp_nice) * totusage);
861 	printf("%2.0f ",
862 	       (diff_cp_time.cp_sys + diff_cp_time.cp_intr) * totusage);
863 	printf("%2.0f",
864 	       diff_cp_time.cp_idle * totusage);
865 }
866 
867 static void
868 dointr(void)
869 {
870 	u_long *intrcnt, uptime;
871 	u_int64_t inttotal;
872 	size_t nintr, inamlen, i, size;
873 	int nwidth;
874 	char *intrstr;
875 	char **intrname;
876 
877 	uptime = getuptime();
878 	if (sysctlbyname("hw.intrnames", NULL, &inamlen, NULL, 0) != 0)
879 		errx(1, "sysctlbyname");
880 	intrstr = malloc(inamlen);
881 	if (intrstr == NULL)
882 		err(1, "malloc");
883 	sysctlbyname("hw.intrnames", intrstr, &inamlen, NULL, 0);
884 	for (nintr = 0, i = 0; i < inamlen; ++i) {
885 		if (intrstr[i] == 0)
886 			nintr++;
887 	}
888 	intrname = malloc(nintr * sizeof(char *));
889 	for (i = 0; i < nintr; ++i) {
890 		intrname[i] = intrstr;
891 		intrstr += strlen(intrstr) + 1;
892 	}
893 
894 	size = nintr * sizeof(*intrcnt);
895 	intrcnt = calloc(nintr, sizeof(*intrcnt));
896 	if (intrcnt == NULL)
897 		err(1, "malloc");
898 	sysctlbyname("hw.intrcnt", intrcnt, &size, NULL, 0);
899 
900 	nwidth = 21;
901 	for (i = 0; i < nintr; ++i) {
902 		if (nwidth < (int)strlen(intrname[i]))
903 			nwidth = (int)strlen(intrname[i]);
904 	}
905 	if (verbose) nwidth += 12;
906 
907 	printf("%-*.*s %11s %10s\n",
908 		nwidth, nwidth, "interrupt", "total", "rate");
909 	inttotal = 0;
910 	for (i = 0; i < nintr; ++i) {
911 		int named;
912 		char *infop, irqinfo[72];
913 
914 		if ((named = strncmp(intrname[i], "irq", 3)) != 0 ||
915 		    intrcnt[i] > 0) {
916 			infop = intrname[i];
917 			if (verbose) {
918 				ssize_t irq, cpu;
919 
920 				irq = i % MAX_INTS;
921 				cpu = i / MAX_INTS;
922 				if (named) {
923 					snprintf(irqinfo, sizeof(irqinfo),
924 						 "irq%-3zd %3zd: %s",
925 						 irq, cpu, intrname[i]);
926 				} else {
927 					snprintf(irqinfo, sizeof(irqinfo),
928 						 "irq%-3zd %3zd: ", irq, cpu);
929 				}
930 				infop = irqinfo;
931 			}
932 			printf("%-*.*s %11lu %10lu\n",
933 				nwidth, nwidth, infop,
934 				intrcnt[i], intrcnt[i] / uptime);
935 		}
936 		inttotal += intrcnt[i];
937 	}
938 	printf("%-*.*s %11llu %10llu\n",
939 		nwidth, nwidth, "Total",
940 		(long long)inttotal, (long long)(inttotal / uptime));
941 }
942 
943 #define	MAX_KMSTATS	16384
944 
945 enum ksuse { KSINUSE, KSMEMUSE, KSCALLS };
946 
947 static long
948 cpuagg(struct malloc_type *ks, enum ksuse use)
949 {
950     int i;
951     long ttl;
952 
953     ttl = 0;
954 
955     switch(use) {
956     case KSINUSE:
957 	for (i = 0; i < ncpus; ++i)
958 	    ttl += ks->ks_use[i].inuse;
959 	break;
960     case KSMEMUSE:
961 	for (i = 0; i < ncpus; ++i)
962 	    ttl += ks->ks_use[i].memuse;
963 	break;
964     case KSCALLS:
965 	for (i = 0; i < ncpus; ++i)
966 	    ttl += ks->ks_use[i].calls;
967     	break;
968     }
969     return(ttl);
970 }
971 
972 static void
973 domem(void)
974 {
975 	struct malloc_type *ks;
976 	int i;
977 	int nkms;
978 	long totuse = 0, totreq = 0;
979 	struct malloc_type kmemstats[MAX_KMSTATS], *kmsp;
980 	char buf[1024];
981 
982 	kread(X_KMEMSTATISTICS, &kmsp, sizeof(kmsp));
983 	for (nkms = 0; nkms < MAX_KMSTATS && kmsp != NULL; nkms++) {
984 		if (sizeof(kmemstats[0]) != kvm_read(kd, (u_long)kmsp,
985 		    &kmemstats[nkms], sizeof(kmemstats[0])))
986 			err(1, "kvm_read(%p)", (void *)kmsp);
987 		if (sizeof(buf) !=  kvm_read(kd,
988 	            (u_long)kmemstats[nkms].ks_shortdesc, buf, sizeof(buf)))
989 			err(1, "kvm_read(%p)",
990 			    kmemstats[nkms].ks_shortdesc);
991 		buf[sizeof(buf) - 1] = '\0';
992 		kmemstats[nkms].ks_shortdesc = strdup(buf);
993 		if (kmemstats[nkms].ks_use) {
994 			size_t usebytes;
995 			void *use;
996 
997 			usebytes = ncpus * sizeof(kmemstats[nkms].ks_use[0]);
998 			use = malloc(usebytes);
999 			if (kvm_read(kd, (u_long)kmemstats[nkms].ks_use,
1000 				     use, usebytes) != (ssize_t)usebytes) {
1001 				err(1, "kvm_read(%p)", kmemstats[nkms].ks_use);
1002 			}
1003 			kmemstats[nkms].ks_use = use;
1004 		}
1005 		kmsp = kmemstats[nkms].ks_next;
1006 	}
1007 	if (kmsp != NULL)
1008 		warnx("truncated to the first %d memory types", nkms);
1009 
1010 	printf(
1011 	    "\nMemory statistics by type\n");
1012 	printf("               Type   Count  MemUse   Limit Requests\n");
1013 	for (i = 0, ks = &kmemstats[0]; i < nkms; i++, ks++) {
1014 		long ks_inuse;
1015 		long ks_memuse;
1016 		long ks_calls;
1017 
1018 		ks_calls = cpuagg(ks, KSCALLS);
1019 		if (ks_calls == 0 && verbose == 0)
1020 			continue;
1021 
1022 		ks_inuse = cpuagg(ks, KSINUSE);
1023 		ks_memuse = cpuagg(ks, KSMEMUSE);
1024 
1025 		printf("%19s   %s   %s   %s    %s\n",
1026 			ks->ks_shortdesc,
1027 			formatnum(ks_inuse, 5, 1),
1028 			formatnum(ks_memuse, 5, 1),
1029 			formatnum(ks->ks_limit, 5, 1),
1030 			formatnum(ks_calls, 5, 1));
1031 
1032 		totuse += ks_memuse;
1033 		totreq += ks_calls;
1034 	}
1035 	printf("\nMemory Totals:  In Use  Requests\n");
1036 	printf("                 %s  %s\n",
1037 		formatnum(totuse, 5, 1),
1038 		formatnum(totreq, 5, 1));
1039 }
1040 
1041 static void
1042 dooc(void)
1043 {
1044 	struct objcache_stats *stat, *s;
1045 	size_t len, count;
1046 
1047 	if (sysctlbyname("kern.objcache.stats", NULL, &len, NULL, 0) < 0)
1048 		errx(1, "objcache stats sysctl failed\n");
1049 
1050 	/* Add some extra space. */
1051 	stat = malloc(len + (8 * sizeof(*stat)));
1052 	if (sysctlbyname("kern.objcache.stats", stat, &len, NULL, 0) < 0)
1053 		errx(1, "objcache stats sysctl failed\n");
1054 
1055 	printf(
1056 	    "\nObjcache statistics by name\n");
1057 	printf("                 Name    Used  Cached   Limit Requests  Allocs Fails  Exhausts\n");
1058 	for (s = stat, count = 0; count < len; ++s) {
1059 		printf("%21s   %s   %s   %s    %s   %s  %s  %s\n",
1060 		    s->oc_name,
1061 		    formatnum(s->oc_used, 5, 1),
1062 		    formatnum(s->oc_cached, 5, 1),
1063 		    s->oc_limit < OBJCACHE_UNLIMITED ?
1064 		    formatnum(s->oc_limit, 5, 1) : "unlim",
1065 		    formatnum(s->oc_requested, 5, 1),
1066 		    formatnum(s->oc_allocated, 5, 1),
1067 		    formatnum(s->oc_failed, 4, 1),
1068 		    formatnum(s->oc_exhausted, 4, 1));
1069 
1070 		count += sizeof(*s);
1071 	}
1072 	free(stat);
1073 }
1074 
1075 #define MAXSAVE	16
1076 
1077 static void
1078 dozmem(u_int interval, int reps)
1079 {
1080 	struct zlist	zlist;
1081 	struct vm_zone	*kz;
1082 	struct vm_zone	zone;
1083 	struct vm_zone	save[MAXSAVE];
1084 	long zfreecnt_prev;
1085 	long znalloc_prev;
1086 	long zfreecnt_next;
1087 	long znalloc_next;
1088 	char name[64];
1089 	size_t namesz;
1090 	int first = 1;
1091 	int i;
1092 	int n;
1093 
1094 	bzero(save, sizeof(save));
1095 
1096 again:
1097 	kread(X_ZLIST, &zlist, sizeof(zlist));
1098 	kz = LIST_FIRST(&zlist);
1099 	i = 0;
1100 
1101 	while (kz) {
1102 		if (kvm_read(kd, (intptr_t)kz, &zone, sizeof(zone)) !=
1103 		    (ssize_t)sizeof(zone)) {
1104 			perror("kvm_read");
1105 			break;
1106 		}
1107 		zfreecnt_prev = save[i].zfreecnt;
1108 		znalloc_prev = save[i].znalloc;
1109 		for (n = 0; n < ncpus; ++n) {
1110 			zfreecnt_prev += save[i].zpcpu[n].zfreecnt;
1111 			znalloc_prev += save[i].zpcpu[n].znalloc;
1112 		}
1113 
1114 		zfreecnt_next = zone.zfreecnt;
1115 		znalloc_next = zone.znalloc;
1116 		for (n = 0; n < ncpus; ++n) {
1117 			zfreecnt_next += zone.zpcpu[n].zfreecnt;
1118 			znalloc_next += zone.zpcpu[n].znalloc;
1119 		}
1120 		save[i] = zone;
1121 
1122 		namesz = sizeof(name);
1123 		if (kvm_readstr(kd, (intptr_t)zone.zname, name, &namesz) == NULL) {
1124 			perror("kvm_read");
1125 			break;
1126 		}
1127 		if (first && interval) {
1128 			/* do nothing */
1129 		} else if (zone.zmax) {
1130 			printf("%-10s %9ld / %-9ld %5ldM used"
1131 			       " %6.2f%% ",
1132 				name,
1133 				(long)(zone.ztotal - zfreecnt_next),
1134 				(long)zone.zmax,
1135 				(long)zone.zpagecount * 4096 / (1024 * 1024),
1136 				(double)(zone.ztotal - zfreecnt_next) *
1137 					100.0 / (double)zone.zmax);
1138 		} else {
1139 			printf("%-10s %9ld             %5ldM used"
1140 			       "         ",
1141 				name,
1142 				(long)(zone.ztotal - zfreecnt_next),
1143 				(long)(zone.ztotal - zfreecnt_next) *
1144 					zone.zsize / (1024 * 1024));
1145 		}
1146 		if (first == 0) {
1147 			printf("use=%ld\n", znalloc_next - znalloc_prev);
1148 		} else if (interval == 0)
1149 			printf("\n");
1150 
1151 		kz = LIST_NEXT(&zone, zlink);
1152 		++i;
1153 	}
1154 	if (reps) {
1155 		first = 0;
1156 		fflush(stdout);
1157 		usleep(interval * 1000);
1158 		--reps;
1159 		printf("\n");
1160 		goto again;
1161 	}
1162 }
1163 
1164 /*
1165  * kread reads something from the kernel, given its nlist index.
1166  */
1167 static void
1168 kread(int nlx, void *addr, size_t size)
1169 {
1170 	const char *sym;
1171 
1172 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
1173 		sym = namelist[nlx].n_name;
1174 		if (*sym == '_')
1175 			++sym;
1176 		errx(1, "symbol %s not defined", sym);
1177 	}
1178 	if (kvm_read(kd, namelist[nlx].n_value, addr, size) != (ssize_t)size) {
1179 		sym = namelist[nlx].n_name;
1180 		if (*sym == '_')
1181 			++sym;
1182 		errx(1, "%s: %s", sym, kvm_geterr(kd));
1183 	}
1184 }
1185 
1186 static void
1187 usage(void)
1188 {
1189 	fprintf(stderr, "%s%s",
1190 		"usage: vmstat [-imsuvz] [-c count] [-M core] "
1191 		"[-N system] [-w wait]\n",
1192 		"              [-n devs] [disks]\n");
1193 	exit(1);
1194 }
1195