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