xref: /freebsd/usr.bin/vmstat/vmstat.c (revision 2b15cb3d0922bd70ea592f0da9b4a5b167f4d53f)
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  * 4. 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 
30 #ifndef lint
31 static const char copyright[] =
32 "@(#) Copyright (c) 1980, 1986, 1991, 1993\n\
33 	The Regents of the University of California.  All rights reserved.\n";
34 #endif /* not lint */
35 
36 #if 0
37 #ifndef lint
38 static char sccsid[] = "@(#)vmstat.c	8.1 (Berkeley) 6/6/93";
39 #endif /* not lint */
40 #endif
41 
42 #include <sys/cdefs.h>
43 __FBSDID("$FreeBSD$");
44 
45 #include <sys/param.h>
46 #include <sys/proc.h>
47 #include <sys/uio.h>
48 #include <sys/namei.h>
49 #include <sys/malloc.h>
50 #include <sys/signal.h>
51 #include <sys/fcntl.h>
52 #include <sys/ioctl.h>
53 #include <sys/resource.h>
54 #include <sys/sysctl.h>
55 #include <sys/time.h>
56 #include <sys/vmmeter.h>
57 #include <sys/pcpu.h>
58 
59 #include <vm/vm_param.h>
60 
61 #include <ctype.h>
62 #include <devstat.h>
63 #include <err.h>
64 #include <errno.h>
65 #include <inttypes.h>
66 #include <kvm.h>
67 #include <limits.h>
68 #include <memstat.h>
69 #include <nlist.h>
70 #include <paths.h>
71 #include <stdio.h>
72 #include <stdlib.h>
73 #include <string.h>
74 #include <sysexits.h>
75 #include <time.h>
76 #include <unistd.h>
77 #include <libutil.h>
78 
79 static char da[] = "da";
80 
81 static struct nlist namelist[] = {
82 #define X_SUM		0
83 	{ "_vm_cnt" },
84 #define X_HZ		1
85 	{ "_hz" },
86 #define X_STATHZ	2
87 	{ "_stathz" },
88 #define X_NCHSTATS	3
89 	{ "_nchstats" },
90 #define	X_INTRNAMES	4
91 	{ "_intrnames" },
92 #define	X_SINTRNAMES	5
93 	{ "_sintrnames" },
94 #define	X_INTRCNT	6
95 	{ "_intrcnt" },
96 #define	X_SINTRCNT	7
97 	{ "_sintrcnt" },
98 #ifdef notyet
99 #define	X_DEFICIT	XXX
100 	{ "_deficit" },
101 #define X_REC		XXX
102 	{ "_rectime" },
103 #define X_PGIN		XXX
104 	{ "_pgintime" },
105 #define	X_XSTATS	XXX
106 	{ "_xstats" },
107 #define X_END		XXX
108 #else
109 #define X_END		8
110 #endif
111 	{ "" },
112 };
113 
114 static struct statinfo cur, last;
115 static int num_devices, maxshowdevs;
116 static long generation;
117 static struct device_selection *dev_select;
118 static int num_selected;
119 static struct devstat_match *matches;
120 static int num_matches = 0;
121 static int num_devices_specified, num_selections;
122 static long select_generation;
123 static char **specified_devices;
124 static devstat_select_mode select_mode;
125 
126 static struct	vmmeter sum, osum;
127 
128 #define	VMSTAT_DEFAULT_LINES	20	/* Default number of `winlines'. */
129 volatile sig_atomic_t wresized;		/* Tty resized, when non-zero. */
130 static int winlines = VMSTAT_DEFAULT_LINES; /* Current number of tty rows. */
131 
132 static int	aflag;
133 static int	nflag;
134 static int	Pflag;
135 static int	hflag;
136 
137 static kvm_t   *kd;
138 
139 #define	FORKSTAT	0x01
140 #define	INTRSTAT	0x02
141 #define	MEMSTAT		0x04
142 #define	SUMSTAT		0x08
143 #define	TIMESTAT	0x10
144 #define	VMSTAT		0x20
145 #define ZMEMSTAT	0x40
146 
147 static void	cpustats(void);
148 static void	pcpustats(int, u_long, int);
149 static void	devstats(void);
150 static void	doforkst(void);
151 static void	dointr(unsigned int, int);
152 static void	dosum(void);
153 static void	dovmstat(unsigned int, int);
154 static void	domemstat_malloc(void);
155 static void	domemstat_zone(void);
156 static void	kread(int, void *, size_t);
157 static void	kreado(int, void *, size_t, size_t);
158 static char    *kgetstr(const char *);
159 static void	needhdr(int);
160 static void	needresize(int);
161 static void	doresize(void);
162 static void	printhdr(int, u_long);
163 static void	usage(void);
164 
165 static long	pct(long, long);
166 static long long	getuptime(void);
167 
168 static char   **getdrivedata(char **);
169 
170 int
171 main(int argc, char *argv[])
172 {
173 	int c, todo;
174 	unsigned int interval;
175 	float f;
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 	hflag = isatty(1);
184 	while ((c = getopt(argc, argv, "ac:fhHiM:mN:n:Pp:stw:z")) != -1) {
185 		switch (c) {
186 		case 'a':
187 			aflag++;
188 			break;
189 		case 'c':
190 			reps = atoi(optarg);
191 			break;
192 		case 'P':
193 			Pflag++;
194 			break;
195 		case 'f':
196 			todo |= FORKSTAT;
197 			break;
198 		case 'h':
199 			hflag = 1;
200 			break;
201 		case 'H':
202 			hflag = 0;
203 			break;
204 		case 'i':
205 			todo |= INTRSTAT;
206 			break;
207 		case 'M':
208 			memf = optarg;
209 			break;
210 		case 'm':
211 			todo |= MEMSTAT;
212 			break;
213 		case 'N':
214 			nlistf = optarg;
215 			break;
216 		case 'n':
217 			nflag = 1;
218 			maxshowdevs = atoi(optarg);
219 			if (maxshowdevs < 0)
220 				errx(1, "number of devices %d is < 0",
221 				     maxshowdevs);
222 			break;
223 		case 'p':
224 			if (devstat_buildmatch(optarg, &matches, &num_matches) != 0)
225 				errx(1, "%s", devstat_errbuf);
226 			break;
227 		case 's':
228 			todo |= SUMSTAT;
229 			break;
230 		case 't':
231 #ifdef notyet
232 			todo |= TIMESTAT;
233 #else
234 			errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
235 #endif
236 			break;
237 		case 'w':
238 			/* Convert to milliseconds. */
239 			f = atof(optarg);
240 			interval = f * 1000;
241 			break;
242 		case 'z':
243 			todo |= ZMEMSTAT;
244 			break;
245 		case '?':
246 		default:
247 			usage();
248 		}
249 	}
250 	argc -= optind;
251 	argv += optind;
252 
253 	if (todo == 0)
254 		todo = VMSTAT;
255 
256 	if (memf != NULL) {
257 		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
258 		if (kd == NULL)
259 			errx(1, "kvm_openfiles: %s", errbuf);
260 	}
261 
262 retry_nlist:
263 	if (kd != NULL && (c = kvm_nlist(kd, namelist)) != 0) {
264 		if (c > 0) {
265 			/*
266 			 * 'cnt' was renamed to 'vm_cnt'. If 'vm_cnt' is not
267 			 * found try looking up older 'cnt' symbol.
268 			 * */
269 			if (namelist[X_SUM].n_type == 0 &&
270 			    strcmp(namelist[X_SUM].n_name, "_vm_cnt") == 0) {
271 				namelist[X_SUM].n_name = "_cnt";
272 				goto retry_nlist;
273 			}
274 			warnx("undefined symbols:");
275 			for (c = 0;
276 			     c < (int)(sizeof(namelist)/sizeof(namelist[0]));
277 			     c++)
278 				if (namelist[c].n_type == 0)
279 					(void)fprintf(stderr, " %s",
280 					    namelist[c].n_name);
281 			(void)fputc('\n', stderr);
282 		} else
283 			warnx("kvm_nlist: %s", kvm_geterr(kd));
284 		exit(1);
285 	}
286 	if (kd && Pflag)
287 		errx(1, "Cannot use -P with crash dumps");
288 
289 	if (todo & VMSTAT) {
290 		/*
291 		 * Make sure that the userland devstat version matches the
292 		 * kernel devstat version.  If not, exit and print a
293 		 * message informing the user of his mistake.
294 		 */
295 		if (devstat_checkversion(NULL) < 0)
296 			errx(1, "%s", devstat_errbuf);
297 
298 
299 		argv = getdrivedata(argv);
300 	}
301 
302 	if (*argv) {
303 		f = atof(*argv);
304 		interval = f * 1000;
305 		if (*++argv)
306 			reps = atoi(*argv);
307 	}
308 
309 	if (interval) {
310 		if (!reps)
311 			reps = -1;
312 	} else if (reps)
313 		interval = 1 * 1000;
314 
315 	if (todo & FORKSTAT)
316 		doforkst();
317 	if (todo & MEMSTAT)
318 		domemstat_malloc();
319 	if (todo & ZMEMSTAT)
320 		domemstat_zone();
321 	if (todo & SUMSTAT)
322 		dosum();
323 #ifdef notyet
324 	if (todo & TIMESTAT)
325 		dotimes();
326 #endif
327 	if (todo & INTRSTAT)
328 		dointr(interval, reps);
329 	if (todo & VMSTAT)
330 		dovmstat(interval, reps);
331 	exit(0);
332 }
333 
334 static int
335 mysysctl(const char *name, void *oldp, size_t *oldlenp,
336     void *newp, size_t newlen)
337 {
338 	int error;
339 
340 	error = sysctlbyname(name, oldp, oldlenp, newp, newlen);
341 	if (error != 0 && errno != ENOMEM)
342 		err(1, "sysctl(%s)", name);
343 	return (error);
344 }
345 
346 static char **
347 getdrivedata(char **argv)
348 {
349 	if ((num_devices = devstat_getnumdevs(NULL)) < 0)
350 		errx(1, "%s", devstat_errbuf);
351 
352 	cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
353 	last.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
354 
355 	if (devstat_getdevs(NULL, &cur) == -1)
356 		errx(1, "%s", devstat_errbuf);
357 
358 	num_devices = cur.dinfo->numdevs;
359 	generation = cur.dinfo->generation;
360 
361 	specified_devices = (char **)malloc(sizeof(char *));
362 	for (num_devices_specified = 0; *argv; ++argv) {
363 		if (isdigit(**argv))
364 			break;
365 		num_devices_specified++;
366 		specified_devices = (char **)realloc(specified_devices,
367 						     sizeof(char *) *
368 						     num_devices_specified);
369 		specified_devices[num_devices_specified - 1] = *argv;
370 	}
371 	dev_select = NULL;
372 
373 	if (nflag == 0 && maxshowdevs < num_devices_specified)
374 			maxshowdevs = num_devices_specified;
375 
376 	/*
377 	 * People are generally only interested in disk statistics when
378 	 * they're running vmstat.  So, that's what we're going to give
379 	 * them if they don't specify anything by default.  We'll also give
380 	 * them any other random devices in the system so that we get to
381 	 * maxshowdevs devices, if that many devices exist.  If the user
382 	 * specifies devices on the command line, either through a pattern
383 	 * match or by naming them explicitly, we will give the user only
384 	 * those devices.
385 	 */
386 	if ((num_devices_specified == 0) && (num_matches == 0)) {
387 		if (devstat_buildmatch(da, &matches, &num_matches) != 0)
388 			errx(1, "%s", devstat_errbuf);
389 
390 		select_mode = DS_SELECT_ADD;
391 	} else
392 		select_mode = DS_SELECT_ONLY;
393 
394 	/*
395 	 * At this point, selectdevs will almost surely indicate that the
396 	 * device list has changed, so we don't look for return values of 0
397 	 * or 1.  If we get back -1, though, there is an error.
398 	 */
399 	if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
400 		       &select_generation, generation, cur.dinfo->devices,
401 		       num_devices, matches, num_matches, specified_devices,
402 		       num_devices_specified, select_mode,
403 		       maxshowdevs, 0) == -1)
404 		errx(1, "%s", devstat_errbuf);
405 
406 	return(argv);
407 }
408 
409 /* Return system uptime in nanoseconds */
410 static long long
411 getuptime(void)
412 {
413 	struct timespec sp;
414 
415 	(void)clock_gettime(CLOCK_UPTIME, &sp);
416 
417 	return((long long)sp.tv_sec * 1000000000LL + sp.tv_nsec);
418 }
419 
420 static void
421 fill_pcpu(struct pcpu ***pcpup, int* maxcpup)
422 {
423 	struct pcpu **pcpu;
424 
425 	int maxcpu, i;
426 
427 	*pcpup = NULL;
428 
429 	if (kd == NULL)
430 		return;
431 
432 	maxcpu = kvm_getmaxcpu(kd);
433 	if (maxcpu < 0)
434 		errx(1, "kvm_getmaxcpu: %s", kvm_geterr(kd));
435 
436 	pcpu = calloc(maxcpu, sizeof(struct pcpu *));
437 	if (pcpu == NULL)
438 		err(1, "calloc");
439 
440 	for (i = 0; i < maxcpu; i++) {
441 		pcpu[i] = kvm_getpcpu(kd, i);
442 		if (pcpu[i] == (struct pcpu *)-1)
443 			errx(1, "kvm_getpcpu: %s", kvm_geterr(kd));
444 	}
445 
446 	*maxcpup = maxcpu;
447 	*pcpup = pcpu;
448 }
449 
450 static void
451 free_pcpu(struct pcpu **pcpu, int maxcpu)
452 {
453 	int i;
454 
455 	for (i = 0; i < maxcpu; i++)
456 		free(pcpu[i]);
457 	free(pcpu);
458 }
459 
460 static void
461 fill_vmmeter(struct vmmeter *vmmp)
462 {
463 	struct pcpu **pcpu;
464 	int maxcpu, i;
465 
466 	if (kd != NULL) {
467 		kread(X_SUM, vmmp, sizeof(*vmmp));
468 		fill_pcpu(&pcpu, &maxcpu);
469 		for (i = 0; i < maxcpu; i++) {
470 			if (pcpu[i] == NULL)
471 				continue;
472 #define ADD_FROM_PCPU(i, name) \
473 			vmmp->name += pcpu[i]->pc_cnt.name
474 			ADD_FROM_PCPU(i, v_swtch);
475 			ADD_FROM_PCPU(i, v_trap);
476 			ADD_FROM_PCPU(i, v_syscall);
477 			ADD_FROM_PCPU(i, v_intr);
478 			ADD_FROM_PCPU(i, v_soft);
479 			ADD_FROM_PCPU(i, v_vm_faults);
480 			ADD_FROM_PCPU(i, v_io_faults);
481 			ADD_FROM_PCPU(i, v_cow_faults);
482 			ADD_FROM_PCPU(i, v_cow_optim);
483 			ADD_FROM_PCPU(i, v_zfod);
484 			ADD_FROM_PCPU(i, v_ozfod);
485 			ADD_FROM_PCPU(i, v_swapin);
486 			ADD_FROM_PCPU(i, v_swapout);
487 			ADD_FROM_PCPU(i, v_swappgsin);
488 			ADD_FROM_PCPU(i, v_swappgsout);
489 			ADD_FROM_PCPU(i, v_vnodein);
490 			ADD_FROM_PCPU(i, v_vnodeout);
491 			ADD_FROM_PCPU(i, v_vnodepgsin);
492 			ADD_FROM_PCPU(i, v_vnodepgsout);
493 			ADD_FROM_PCPU(i, v_intrans);
494 			ADD_FROM_PCPU(i, v_tfree);
495 			ADD_FROM_PCPU(i, v_forks);
496 			ADD_FROM_PCPU(i, v_vforks);
497 			ADD_FROM_PCPU(i, v_rforks);
498 			ADD_FROM_PCPU(i, v_kthreads);
499 			ADD_FROM_PCPU(i, v_forkpages);
500 			ADD_FROM_PCPU(i, v_vforkpages);
501 			ADD_FROM_PCPU(i, v_rforkpages);
502 			ADD_FROM_PCPU(i, v_kthreadpages);
503 #undef ADD_FROM_PCPU
504 		}
505 		free_pcpu(pcpu, maxcpu);
506 	} else {
507 		size_t size = sizeof(unsigned int);
508 #define GET_VM_STATS(cat, name) \
509 	mysysctl("vm.stats." #cat "." #name, &vmmp->name, &size, NULL, 0)
510 		/* sys */
511 		GET_VM_STATS(sys, v_swtch);
512 		GET_VM_STATS(sys, v_trap);
513 		GET_VM_STATS(sys, v_syscall);
514 		GET_VM_STATS(sys, v_intr);
515 		GET_VM_STATS(sys, v_soft);
516 
517 		/* vm */
518 		GET_VM_STATS(vm, v_vm_faults);
519 		GET_VM_STATS(vm, v_io_faults);
520 		GET_VM_STATS(vm, v_cow_faults);
521 		GET_VM_STATS(vm, v_cow_optim);
522 		GET_VM_STATS(vm, v_zfod);
523 		GET_VM_STATS(vm, v_ozfod);
524 		GET_VM_STATS(vm, v_swapin);
525 		GET_VM_STATS(vm, v_swapout);
526 		GET_VM_STATS(vm, v_swappgsin);
527 		GET_VM_STATS(vm, v_swappgsout);
528 		GET_VM_STATS(vm, v_vnodein);
529 		GET_VM_STATS(vm, v_vnodeout);
530 		GET_VM_STATS(vm, v_vnodepgsin);
531 		GET_VM_STATS(vm, v_vnodepgsout);
532 		GET_VM_STATS(vm, v_intrans);
533 		GET_VM_STATS(vm, v_reactivated);
534 		GET_VM_STATS(vm, v_pdwakeups);
535 		GET_VM_STATS(vm, v_pdpages);
536 		GET_VM_STATS(vm, v_tcached);
537 		GET_VM_STATS(vm, v_dfree);
538 		GET_VM_STATS(vm, v_pfree);
539 		GET_VM_STATS(vm, v_tfree);
540 		GET_VM_STATS(vm, v_page_size);
541 		GET_VM_STATS(vm, v_page_count);
542 		GET_VM_STATS(vm, v_free_reserved);
543 		GET_VM_STATS(vm, v_free_target);
544 		GET_VM_STATS(vm, v_free_min);
545 		GET_VM_STATS(vm, v_free_count);
546 		GET_VM_STATS(vm, v_wire_count);
547 		GET_VM_STATS(vm, v_active_count);
548 		GET_VM_STATS(vm, v_inactive_target);
549 		GET_VM_STATS(vm, v_inactive_count);
550 		GET_VM_STATS(vm, v_cache_count);
551 		GET_VM_STATS(vm, v_cache_min);
552 		GET_VM_STATS(vm, v_cache_max);
553 		GET_VM_STATS(vm, v_pageout_free_min);
554 		GET_VM_STATS(vm, v_interrupt_free_min);
555 		/*GET_VM_STATS(vm, v_free_severe);*/
556 		GET_VM_STATS(vm, v_forks);
557 		GET_VM_STATS(vm, v_vforks);
558 		GET_VM_STATS(vm, v_rforks);
559 		GET_VM_STATS(vm, v_kthreads);
560 		GET_VM_STATS(vm, v_forkpages);
561 		GET_VM_STATS(vm, v_vforkpages);
562 		GET_VM_STATS(vm, v_rforkpages);
563 		GET_VM_STATS(vm, v_kthreadpages);
564 #undef GET_VM_STATS
565 	}
566 }
567 
568 static void
569 fill_vmtotal(struct vmtotal *vmtp)
570 {
571 	if (kd != NULL) {
572 		/* XXX fill vmtp */
573 		errx(1, "not implemented");
574 	} else {
575 		size_t size = sizeof(*vmtp);
576 		mysysctl("vm.vmtotal", vmtp, &size, NULL, 0);
577 		if (size != sizeof(*vmtp))
578 			errx(1, "vm.total size mismatch");
579 	}
580 }
581 
582 /* Determine how many cpu columns, and what index they are in kern.cp_times */
583 static int
584 getcpuinfo(u_long *maskp, int *maxidp)
585 {
586 	int maxcpu;
587 	int maxid;
588 	int ncpus;
589 	int i, j;
590 	int empty;
591 	size_t size;
592 	long *times;
593 	u_long mask;
594 
595 	if (kd != NULL)
596 		errx(1, "not implemented");
597 	mask = 0;
598 	ncpus = 0;
599 	size = sizeof(maxcpu);
600 	mysysctl("kern.smp.maxcpus", &maxcpu, &size, NULL, 0);
601 	if (size != sizeof(maxcpu))
602 		errx(1, "sysctl kern.smp.maxcpus");
603 	size = sizeof(long) * maxcpu * CPUSTATES;
604 	times = malloc(size);
605 	if (times == NULL)
606 		err(1, "malloc %zd bytes", size);
607 	mysysctl("kern.cp_times", times, &size, NULL, 0);
608 	maxid = (size / CPUSTATES / sizeof(long)) - 1;
609 	for (i = 0; i <= maxid; i++) {
610 		empty = 1;
611 		for (j = 0; empty && j < CPUSTATES; j++) {
612 			if (times[i * CPUSTATES + j] != 0)
613 				empty = 0;
614 		}
615 		if (!empty) {
616 			mask |= (1ul << i);
617 			ncpus++;
618 		}
619 	}
620 	if (maskp)
621 		*maskp = mask;
622 	if (maxidp)
623 		*maxidp = maxid;
624 	return (ncpus);
625 }
626 
627 
628 static void
629 prthuman(u_int64_t val, int size)
630 {
631 	char buf[10];
632 	int flags;
633 
634 	if (size < 5 || size > 9)
635 		errx(1, "doofus");
636 	flags = HN_B | HN_NOSPACE | HN_DECIMAL;
637 	humanize_number(buf, size, val, "", HN_AUTOSCALE, flags);
638 	printf("%*s", size, buf);
639 }
640 
641 static int hz, hdrcnt;
642 
643 static long *cur_cp_times;
644 static long *last_cp_times;
645 static size_t size_cp_times;
646 
647 static void
648 dovmstat(unsigned int interval, int reps)
649 {
650 	struct vmtotal total;
651 	time_t uptime, halfuptime;
652 	struct devinfo *tmp_dinfo;
653 	size_t size;
654 	int ncpus, maxid;
655 	u_long cpumask;
656 	int rate_adj;
657 
658 	uptime = getuptime() / 1000000000LL;
659 	halfuptime = uptime / 2;
660 	rate_adj = 1;
661 	ncpus = 1;
662 	maxid = 0;
663 
664 	/*
665 	 * If the user stops the program (control-Z) and then resumes it,
666 	 * print out the header again.
667 	 */
668 	(void)signal(SIGCONT, needhdr);
669 
670 	/*
671 	 * If our standard output is a tty, then install a SIGWINCH handler
672 	 * and set wresized so that our first iteration through the main
673 	 * vmstat loop will peek at the terminal's current rows to find out
674 	 * how many lines can fit in a screenful of output.
675 	 */
676 	if (isatty(fileno(stdout)) != 0) {
677 		wresized = 1;
678 		(void)signal(SIGWINCH, needresize);
679 	} else {
680 		wresized = 0;
681 		winlines = VMSTAT_DEFAULT_LINES;
682 	}
683 
684 	if (kd != NULL) {
685 		if (namelist[X_STATHZ].n_type != 0 &&
686 		    namelist[X_STATHZ].n_value != 0)
687 			kread(X_STATHZ, &hz, sizeof(hz));
688 		if (!hz)
689 			kread(X_HZ, &hz, sizeof(hz));
690 	} else {
691 		struct clockinfo clockrate;
692 
693 		size = sizeof(clockrate);
694 		mysysctl("kern.clockrate", &clockrate, &size, NULL, 0);
695 		if (size != sizeof(clockrate))
696 			errx(1, "clockrate size mismatch");
697 		hz = clockrate.hz;
698 	}
699 
700 	if (Pflag) {
701 		ncpus = getcpuinfo(&cpumask, &maxid);
702 		size_cp_times = sizeof(long) * (maxid + 1) * CPUSTATES;
703 		cur_cp_times = calloc(1, size_cp_times);
704 		last_cp_times = calloc(1, size_cp_times);
705 	}
706 	for (hdrcnt = 1;;) {
707 		if (!--hdrcnt)
708 			printhdr(maxid, cpumask);
709 		if (kd != NULL) {
710 			if (kvm_getcptime(kd, cur.cp_time) < 0)
711 				errx(1, "kvm_getcptime: %s", kvm_geterr(kd));
712 		} else {
713 			size = sizeof(cur.cp_time);
714 			mysysctl("kern.cp_time", &cur.cp_time, &size, NULL, 0);
715 			if (size != sizeof(cur.cp_time))
716 				errx(1, "cp_time size mismatch");
717 		}
718 		if (Pflag) {
719 			size = size_cp_times;
720 			mysysctl("kern.cp_times", cur_cp_times, &size, NULL, 0);
721 			if (size != size_cp_times)
722 				errx(1, "cp_times mismatch");
723 		}
724 
725 		tmp_dinfo = last.dinfo;
726 		last.dinfo = cur.dinfo;
727 		cur.dinfo = tmp_dinfo;
728 		last.snap_time = cur.snap_time;
729 
730 		/*
731 		 * Here what we want to do is refresh our device stats.
732 		 * getdevs() returns 1 when the device list has changed.
733 		 * If the device list has changed, we want to go through
734 		 * the selection process again, in case a device that we
735 		 * were previously displaying has gone away.
736 		 */
737 		switch (devstat_getdevs(NULL, &cur)) {
738 		case -1:
739 			errx(1, "%s", devstat_errbuf);
740 			break;
741 		case 1: {
742 			int retval;
743 
744 			num_devices = cur.dinfo->numdevs;
745 			generation = cur.dinfo->generation;
746 
747 			retval = devstat_selectdevs(&dev_select, &num_selected,
748 					    &num_selections, &select_generation,
749 					    generation, cur.dinfo->devices,
750 					    num_devices, matches, num_matches,
751 					    specified_devices,
752 					    num_devices_specified, select_mode,
753 					    maxshowdevs, 0);
754 			switch (retval) {
755 			case -1:
756 				errx(1, "%s", devstat_errbuf);
757 				break;
758 			case 1:
759 				printhdr(maxid, cpumask);
760 				break;
761 			default:
762 				break;
763 			}
764 		}
765 		default:
766 			break;
767 		}
768 
769 		fill_vmmeter(&sum);
770 		fill_vmtotal(&total);
771 		(void)printf("%1d %1d %1d",
772 		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
773 #define vmstat_pgtok(a) ((a) * (sum.v_page_size >> 10))
774 #define	rate(x)	(((x) * rate_adj + halfuptime) / uptime)	/* round */
775 		if (hflag) {
776 			printf("");
777 			prthuman(total.t_avm * (u_int64_t)sum.v_page_size, 5);
778 			printf(" ");
779 			prthuman(total.t_free * (u_int64_t)sum.v_page_size, 5);
780 			printf(" ");
781 			(void)printf("%5lu ",
782 			    (unsigned long)rate(sum.v_vm_faults -
783 			    osum.v_vm_faults));
784 		} else {
785 			printf(" %7d", vmstat_pgtok(total.t_avm));
786 			printf(" %7d ", vmstat_pgtok(total.t_free));
787 			(void)printf("%4lu ",
788 			    (unsigned long)rate(sum.v_vm_faults -
789 			    osum.v_vm_faults));
790 		}
791 		(void)printf("%3lu ",
792 		    (unsigned long)rate(sum.v_reactivated - osum.v_reactivated));
793 		(void)printf("%3lu ",
794 		    (unsigned long)rate(sum.v_swapin + sum.v_vnodein -
795 		    (osum.v_swapin + osum.v_vnodein)));
796 		(void)printf("%3lu ",
797 		    (unsigned long)rate(sum.v_swapout + sum.v_vnodeout -
798 		    (osum.v_swapout + osum.v_vnodeout)));
799 		(void)printf("%5lu ",
800 		    (unsigned long)rate(sum.v_tfree - osum.v_tfree));
801 		(void)printf("%4lu ",
802 		    (unsigned long)rate(sum.v_pdpages - osum.v_pdpages));
803 		devstats();
804 		(void)printf("%4lu %5lu %5lu",
805 		    (unsigned long)rate(sum.v_intr - osum.v_intr),
806 		    (unsigned long)rate(sum.v_syscall - osum.v_syscall),
807 		    (unsigned long)rate(sum.v_swtch - osum.v_swtch));
808 		if (Pflag)
809 			pcpustats(ncpus, cpumask, maxid);
810 		else
811 			cpustats();
812 		(void)printf("\n");
813 		(void)fflush(stdout);
814 		if (reps >= 0 && --reps <= 0)
815 			break;
816 		osum = sum;
817 		uptime = interval;
818 		rate_adj = 1000;
819 		/*
820 		 * We round upward to avoid losing low-frequency events
821 		 * (i.e., >= 1 per interval but < 1 per millisecond).
822 		 */
823 		if (interval != 1)
824 			halfuptime = (uptime + 1) / 2;
825 		else
826 			halfuptime = 0;
827 		(void)usleep(interval * 1000);
828 	}
829 }
830 
831 static void
832 printhdr(int maxid, u_long cpumask)
833 {
834 	int i, num_shown;
835 
836 	num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
837 	if (hflag) {
838 		(void)printf("procs  memory      page%*s ", 19, "");
839 	} else {
840 		(void)printf("procs     memory       page%*s ", 19, "");
841 	}
842 	if (num_shown > 1)
843 		(void)printf("   disks %*s", num_shown * 4 - 7, "");
844 	else if (num_shown == 1)
845 		(void)printf("   disk");
846 	(void)printf("   faults      ");
847 	if (Pflag) {
848 		for (i = 0; i <= maxid; i++) {
849 			if (cpumask & (1ul << i))
850 				printf("  cpu%d   ", i);
851 		}
852 		printf("\n");
853 	} else
854 		printf("   cpu\n");
855 	if (hflag) {
856 		(void)printf("r b w  avm   fre   flt  re  pi  po    fr   sr ");
857 	} else {
858 		(void)printf("r b w     avm     fre  flt  re  pi  po    fr   sr ");
859 	}
860 	for (i = 0; i < num_devices; i++)
861 		if ((dev_select[i].selected)
862 		 && (dev_select[i].selected <= maxshowdevs))
863 			(void)printf("%c%c%d ", dev_select[i].device_name[0],
864 				     dev_select[i].device_name[1],
865 				     dev_select[i].unit_number);
866 	(void)printf("  in    sy    cs");
867 	if (Pflag) {
868 		for (i = 0; i <= maxid; i++) {
869 			if (cpumask & (1ul << i))
870 				printf(" us sy id");
871 		}
872 		printf("\n");
873 	} else
874 		printf(" us sy id\n");
875 	if (wresized != 0)
876 		doresize();
877 	hdrcnt = winlines;
878 }
879 
880 /*
881  * Force a header to be prepended to the next output.
882  */
883 static void
884 needhdr(int dummy __unused)
885 {
886 
887 	hdrcnt = 1;
888 }
889 
890 /*
891  * When the terminal is resized, force an update of the maximum number of rows
892  * printed between each header repetition.  Then force a new header to be
893  * prepended to the next output.
894  */
895 void
896 needresize(int signo)
897 {
898 
899 	wresized = 1;
900 	hdrcnt = 1;
901 }
902 
903 /*
904  * Update the global `winlines' count of terminal rows.
905  */
906 void
907 doresize(void)
908 {
909 	int status;
910 	struct winsize w;
911 
912 	for (;;) {
913 		status = ioctl(fileno(stdout), TIOCGWINSZ, &w);
914 		if (status == -1 && errno == EINTR)
915 			continue;
916 		else if (status == -1)
917 			err(1, "ioctl");
918 		if (w.ws_row > 3)
919 			winlines = w.ws_row - 3;
920 		else
921 			winlines = VMSTAT_DEFAULT_LINES;
922 		break;
923 	}
924 
925 	/*
926 	 * Inhibit doresize() calls until we are rescheduled by SIGWINCH.
927 	 */
928 	wresized = 0;
929 }
930 
931 #ifdef notyet
932 static void
933 dotimes(void)
934 {
935 	unsigned int pgintime, rectime;
936 
937 	kread(X_REC, &rectime, sizeof(rectime));
938 	kread(X_PGIN, &pgintime, sizeof(pgintime));
939 	kread(X_SUM, &sum, sizeof(sum));
940 	(void)printf("%u reclaims, %u total time (usec)\n",
941 	    sum.v_pgrec, rectime);
942 	(void)printf("average: %u usec / reclaim\n", rectime / sum.v_pgrec);
943 	(void)printf("\n");
944 	(void)printf("%u page ins, %u total time (msec)\n",
945 	    sum.v_pgin, pgintime / 10);
946 	(void)printf("average: %8.1f msec / page in\n",
947 	    pgintime / (sum.v_pgin * 10.0));
948 }
949 #endif
950 
951 static long
952 pct(long top, long bot)
953 {
954 	long ans;
955 
956 	if (bot == 0)
957 		return(0);
958 	ans = (quad_t)top * 100 / bot;
959 	return (ans);
960 }
961 
962 #define	PCT(top, bot) pct((long)(top), (long)(bot))
963 
964 static void
965 dosum(void)
966 {
967 	struct nchstats lnchstats;
968 	long nchtotal;
969 
970 	fill_vmmeter(&sum);
971 	(void)printf("%9u cpu context switches\n", sum.v_swtch);
972 	(void)printf("%9u device interrupts\n", sum.v_intr);
973 	(void)printf("%9u software interrupts\n", sum.v_soft);
974 	(void)printf("%9u traps\n", sum.v_trap);
975 	(void)printf("%9u system calls\n", sum.v_syscall);
976 	(void)printf("%9u kernel threads created\n", sum.v_kthreads);
977 	(void)printf("%9u  fork() calls\n", sum.v_forks);
978 	(void)printf("%9u vfork() calls\n", sum.v_vforks);
979 	(void)printf("%9u rfork() calls\n", sum.v_rforks);
980 	(void)printf("%9u swap pager pageins\n", sum.v_swapin);
981 	(void)printf("%9u swap pager pages paged in\n", sum.v_swappgsin);
982 	(void)printf("%9u swap pager pageouts\n", sum.v_swapout);
983 	(void)printf("%9u swap pager pages paged out\n", sum.v_swappgsout);
984 	(void)printf("%9u vnode pager pageins\n", sum.v_vnodein);
985 	(void)printf("%9u vnode pager pages paged in\n", sum.v_vnodepgsin);
986 	(void)printf("%9u vnode pager pageouts\n", sum.v_vnodeout);
987 	(void)printf("%9u vnode pager pages paged out\n", sum.v_vnodepgsout);
988 	(void)printf("%9u page daemon wakeups\n", sum.v_pdwakeups);
989 	(void)printf("%9u pages examined by the page daemon\n", sum.v_pdpages);
990 	(void)printf("%9u pages reactivated\n", sum.v_reactivated);
991 	(void)printf("%9u copy-on-write faults\n", sum.v_cow_faults);
992 	(void)printf("%9u copy-on-write optimized faults\n", sum.v_cow_optim);
993 	(void)printf("%9u zero fill pages zeroed\n", sum.v_zfod);
994 	(void)printf("%9u zero fill pages prezeroed\n", sum.v_ozfod);
995 	(void)printf("%9u intransit blocking page faults\n", sum.v_intrans);
996 	(void)printf("%9u total VM faults taken\n", sum.v_vm_faults);
997 	(void)printf("%9u page faults requiring I/O\n", sum.v_io_faults);
998 	(void)printf("%9u pages affected by kernel thread creation\n",
999 	    sum.v_kthreadpages);
1000 	(void)printf("%9u pages affected by  fork()\n", sum.v_forkpages);
1001 	(void)printf("%9u pages affected by vfork()\n", sum.v_vforkpages);
1002 	(void)printf("%9u pages affected by rfork()\n", sum.v_rforkpages);
1003 	(void)printf("%9u pages cached\n", sum.v_tcached);
1004 	(void)printf("%9u pages freed\n", sum.v_tfree);
1005 	(void)printf("%9u pages freed by daemon\n", sum.v_dfree);
1006 	(void)printf("%9u pages freed by exiting processes\n", sum.v_pfree);
1007 	(void)printf("%9u pages active\n", sum.v_active_count);
1008 	(void)printf("%9u pages inactive\n", sum.v_inactive_count);
1009 	(void)printf("%9u pages in VM cache\n", sum.v_cache_count);
1010 	(void)printf("%9u pages wired down\n", sum.v_wire_count);
1011 	(void)printf("%9u pages free\n", sum.v_free_count);
1012 	(void)printf("%9u bytes per page\n", sum.v_page_size);
1013 	if (kd != NULL) {
1014 		kread(X_NCHSTATS, &lnchstats, sizeof(lnchstats));
1015 	} else {
1016 		size_t size = sizeof(lnchstats);
1017 		mysysctl("vfs.cache.nchstats", &lnchstats, &size, NULL, 0);
1018 		if (size != sizeof(lnchstats))
1019 			errx(1, "vfs.cache.nchstats size mismatch");
1020 	}
1021 	nchtotal = lnchstats.ncs_goodhits + lnchstats.ncs_neghits +
1022 	    lnchstats.ncs_badhits + lnchstats.ncs_falsehits +
1023 	    lnchstats.ncs_miss + lnchstats.ncs_long;
1024 	(void)printf("%9ld total name lookups\n", nchtotal);
1025 	(void)printf(
1026 	    "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
1027 	    "", PCT(lnchstats.ncs_goodhits, nchtotal),
1028 	    PCT(lnchstats.ncs_neghits, nchtotal),
1029 	    PCT(lnchstats.ncs_pass2, nchtotal));
1030 	(void)printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
1031 	    PCT(lnchstats.ncs_badhits, nchtotal),
1032 	    PCT(lnchstats.ncs_falsehits, nchtotal),
1033 	    PCT(lnchstats.ncs_long, nchtotal));
1034 }
1035 
1036 static void
1037 doforkst(void)
1038 {
1039 	fill_vmmeter(&sum);
1040 	(void)printf("%u forks, %u pages, average %.2f\n",
1041 	    sum.v_forks, sum.v_forkpages,
1042 	    sum.v_forks == 0 ? 0.0 :
1043 	    (double)sum.v_forkpages / sum.v_forks);
1044 	(void)printf("%u vforks, %u pages, average %.2f\n",
1045 	    sum.v_vforks, sum.v_vforkpages,
1046 	    sum.v_vforks == 0 ? 0.0 :
1047 	    (double)sum.v_vforkpages / sum.v_vforks);
1048 	(void)printf("%u rforks, %u pages, average %.2f\n",
1049 	    sum.v_rforks, sum.v_rforkpages,
1050 	    sum.v_rforks == 0 ? 0.0 :
1051 	    (double)sum.v_rforkpages / sum.v_rforks);
1052 }
1053 
1054 static void
1055 devstats(void)
1056 {
1057 	int dn, state;
1058 	long double transfers_per_second;
1059 	long double busy_seconds;
1060 	long tmp;
1061 
1062 	for (state = 0; state < CPUSTATES; ++state) {
1063 		tmp = cur.cp_time[state];
1064 		cur.cp_time[state] -= last.cp_time[state];
1065 		last.cp_time[state] = tmp;
1066 	}
1067 
1068 	busy_seconds = cur.snap_time - last.snap_time;
1069 
1070 	for (dn = 0; dn < num_devices; dn++) {
1071 		int di;
1072 
1073 		if ((dev_select[dn].selected == 0)
1074 		 || (dev_select[dn].selected > maxshowdevs))
1075 			continue;
1076 
1077 		di = dev_select[dn].position;
1078 
1079 		if (devstat_compute_statistics(&cur.dinfo->devices[di],
1080 		    &last.dinfo->devices[di], busy_seconds,
1081 		    DSM_TRANSFERS_PER_SECOND, &transfers_per_second,
1082 		    DSM_NONE) != 0)
1083 			errx(1, "%s", devstat_errbuf);
1084 
1085 		(void)printf("%3.0Lf ", transfers_per_second);
1086 	}
1087 }
1088 
1089 static void
1090 percent(double pct, int *over)
1091 {
1092 	char buf[10];
1093 	int l;
1094 
1095 	l = snprintf(buf, sizeof(buf), "%.0f", pct);
1096 	if (l == 1 && *over) {
1097 		printf("%s",  buf);
1098 		(*over)--;
1099 	} else
1100 		printf("%2s", buf);
1101 	if (l > 2)
1102 		(*over)++;
1103 }
1104 
1105 static void
1106 cpustats(void)
1107 {
1108 	int state, over;
1109 	double lpct, total;
1110 
1111 	total = 0;
1112 	for (state = 0; state < CPUSTATES; ++state)
1113 		total += cur.cp_time[state];
1114 	if (total)
1115 		lpct = 100.0 / total;
1116 	else
1117 		lpct = 0.0;
1118 	over = 0;
1119 	printf(" ");
1120 	percent((cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * lpct, &over);
1121 	printf(" ");
1122 	percent((cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * lpct, &over);
1123 	printf(" ");
1124 	percent(cur.cp_time[CP_IDLE] * lpct, &over);
1125 }
1126 
1127 static void
1128 pcpustats(int ncpus, u_long cpumask, int maxid)
1129 {
1130 	int state, i;
1131 	double lpct, total;
1132 	long tmp;
1133 	int over;
1134 
1135 	/* devstats does this for cp_time */
1136 	for (i = 0; i <= maxid; i++) {
1137 		if ((cpumask & (1ul << i)) == 0)
1138 			continue;
1139 		for (state = 0; state < CPUSTATES; ++state) {
1140 			tmp = cur_cp_times[i * CPUSTATES + state];
1141 			cur_cp_times[i * CPUSTATES + state] -= last_cp_times[i *
1142 			    CPUSTATES + state];
1143 			last_cp_times[i * CPUSTATES + state] = tmp;
1144 		}
1145 	}
1146 
1147 	over = 0;
1148 	for (i = 0; i <= maxid; i++) {
1149 		if ((cpumask & (1ul << i)) == 0)
1150 			continue;
1151 		total = 0;
1152 		for (state = 0; state < CPUSTATES; ++state)
1153 			total += cur_cp_times[i * CPUSTATES + state];
1154 		if (total)
1155 			lpct = 100.0 / total;
1156 		else
1157 			lpct = 0.0;
1158 		printf(" ");
1159 		percent((cur_cp_times[i * CPUSTATES + CP_USER] +
1160 			 cur_cp_times[i * CPUSTATES + CP_NICE]) * lpct, &over);
1161 		printf(" ");
1162 		percent((cur_cp_times[i * CPUSTATES + CP_SYS] +
1163 			 cur_cp_times[i * CPUSTATES + CP_INTR]) * lpct, &over);
1164 		printf(" ");
1165 		percent(cur_cp_times[i * CPUSTATES + CP_IDLE] * lpct, &over);
1166 	}
1167 }
1168 
1169 static unsigned int
1170 read_intrcnts(unsigned long **intrcnts)
1171 {
1172 	size_t intrcntlen;
1173 
1174 	if (kd != NULL) {
1175 		kread(X_SINTRCNT, &intrcntlen, sizeof(intrcntlen));
1176 		if ((*intrcnts = malloc(intrcntlen)) == NULL)
1177 			err(1, "malloc()");
1178 		kread(X_INTRCNT, *intrcnts, intrcntlen);
1179 	} else {
1180 		for (*intrcnts = NULL, intrcntlen = 1024; ; intrcntlen *= 2) {
1181 			*intrcnts = reallocf(*intrcnts, intrcntlen);
1182 			if (*intrcnts == NULL)
1183 				err(1, "reallocf()");
1184 			if (mysysctl("hw.intrcnt",
1185 			    *intrcnts, &intrcntlen, NULL, 0) == 0)
1186 				break;
1187 		}
1188 	}
1189 
1190 	return (intrcntlen / sizeof(unsigned long));
1191 }
1192 
1193 static void
1194 print_intrcnts(unsigned long *intrcnts, unsigned long *old_intrcnts,
1195 		char *intrnames, unsigned int nintr,
1196 		size_t istrnamlen, long long period_ms)
1197 {
1198 	unsigned long *intrcnt, *old_intrcnt;
1199 	uint64_t inttotal, old_inttotal, total_count, total_rate;
1200 	char* intrname;
1201 	unsigned int i;
1202 
1203 	inttotal = 0;
1204 	old_inttotal = 0;
1205 	intrname = intrnames;
1206 	for (i = 0, intrcnt=intrcnts, old_intrcnt=old_intrcnts; i < nintr; i++) {
1207 		if (intrname[0] != '\0' && (*intrcnt != 0 || aflag)) {
1208 			unsigned long count, rate;
1209 
1210 			count = *intrcnt - *old_intrcnt;
1211 			rate = (count * 1000 + period_ms / 2) / period_ms;
1212 			(void)printf("%-*s %20lu %10lu\n", (int)istrnamlen,
1213 			    intrname, count, rate);
1214 		}
1215 		intrname += strlen(intrname) + 1;
1216 		inttotal += *intrcnt++;
1217 		old_inttotal += *old_intrcnt++;
1218 	}
1219 	total_count = inttotal - old_inttotal;
1220 	total_rate = (total_count * 1000 + period_ms / 2) / period_ms;
1221 	(void)printf("%-*s %20" PRIu64 " %10" PRIu64 "\n", (int)istrnamlen,
1222 	    "Total", total_count, total_rate);
1223 }
1224 
1225 static void
1226 dointr(unsigned int interval, int reps)
1227 {
1228 	unsigned long *intrcnts;
1229 	long long uptime, period_ms;
1230 	unsigned long *old_intrcnts = NULL;
1231 	size_t clen, inamlen, istrnamlen;
1232 	char *intrnames, *intrname;
1233 
1234 	uptime = getuptime();
1235 
1236 	/* Get the names of each interrupt source */
1237 	if (kd != NULL) {
1238 		kread(X_SINTRNAMES, &inamlen, sizeof(inamlen));
1239 		if ((intrnames = malloc(inamlen)) == NULL)
1240 			err(1, "malloc()");
1241 		kread(X_INTRNAMES, intrnames, inamlen);
1242 	} else {
1243 		for (intrnames = NULL, inamlen = 1024; ; inamlen *= 2) {
1244 			if ((intrnames = reallocf(intrnames, inamlen)) == NULL)
1245 				err(1, "reallocf()");
1246 			if (mysysctl("hw.intrnames",
1247 			    intrnames, &inamlen, NULL, 0) == 0)
1248 				break;
1249 		}
1250 	}
1251 
1252 	/* Determine the length of the longest interrupt name */
1253 	intrname = intrnames;
1254 	istrnamlen = strlen("interrupt");
1255 	while(*intrname != '\0') {
1256 		clen = strlen(intrname);
1257 		if (clen > istrnamlen)
1258 			istrnamlen = clen;
1259 		intrname += strlen(intrname) + 1;
1260 	}
1261 	(void)printf("%-*s %20s %10s\n", (int)istrnamlen, "interrupt", "total",
1262 	    "rate");
1263 
1264 	/*
1265 	 * Loop reps times printing differential interrupt counts.  If reps is
1266 	 * zero, then run just once, printing total counts
1267 	 */
1268 	period_ms = uptime / 1000000;
1269 	while(1) {
1270 		unsigned int nintr;
1271 		long long old_uptime;
1272 
1273 		nintr = read_intrcnts(&intrcnts);
1274 		/*
1275 		 * Initialize old_intrcnts to 0 for the first pass, so
1276 		 * print_intrcnts will print total interrupts since boot
1277 		 */
1278 		if (old_intrcnts == NULL) {
1279 			old_intrcnts = calloc(nintr, sizeof(unsigned long));
1280 			if (old_intrcnts == NULL)
1281 				err(1, "calloc()");
1282 		}
1283 
1284 		print_intrcnts(intrcnts, old_intrcnts, intrnames, nintr,
1285 		    istrnamlen, period_ms);
1286 
1287 		free(old_intrcnts);
1288 		old_intrcnts = intrcnts;
1289 		if (reps >= 0 && --reps <= 0)
1290 			break;
1291 		usleep(interval * 1000);
1292 		old_uptime = uptime;
1293 		uptime = getuptime();
1294 		period_ms = (uptime - old_uptime) / 1000000;
1295 	}
1296 }
1297 
1298 static void
1299 domemstat_malloc(void)
1300 {
1301 	struct memory_type_list *mtlp;
1302 	struct memory_type *mtp;
1303 	int error, first, i;
1304 
1305 	mtlp = memstat_mtl_alloc();
1306 	if (mtlp == NULL) {
1307 		warn("memstat_mtl_alloc");
1308 		return;
1309 	}
1310 	if (kd == NULL) {
1311 		if (memstat_sysctl_malloc(mtlp, 0) < 0) {
1312 			warnx("memstat_sysctl_malloc: %s",
1313 			    memstat_strerror(memstat_mtl_geterror(mtlp)));
1314 			return;
1315 		}
1316 	} else {
1317 		if (memstat_kvm_malloc(mtlp, kd) < 0) {
1318 			error = memstat_mtl_geterror(mtlp);
1319 			if (error == MEMSTAT_ERROR_KVM)
1320 				warnx("memstat_kvm_malloc: %s",
1321 				    kvm_geterr(kd));
1322 			else
1323 				warnx("memstat_kvm_malloc: %s",
1324 				    memstat_strerror(error));
1325 		}
1326 	}
1327 	printf("%13s %5s %6s %7s %8s  Size(s)\n", "Type", "InUse", "MemUse",
1328 	    "HighUse", "Requests");
1329 	for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
1330 	    mtp = memstat_mtl_next(mtp)) {
1331 		if (memstat_get_numallocs(mtp) == 0 &&
1332 		    memstat_get_count(mtp) == 0)
1333 			continue;
1334 		printf("%13s %5" PRIu64 " %5" PRIu64 "K %7s %8" PRIu64 "  ",
1335 		    memstat_get_name(mtp), memstat_get_count(mtp),
1336 		    (memstat_get_bytes(mtp) + 1023) / 1024, "-",
1337 		    memstat_get_numallocs(mtp));
1338 		first = 1;
1339 		for (i = 0; i < 32; i++) {
1340 			if (memstat_get_sizemask(mtp) & (1 << i)) {
1341 				if (!first)
1342 					printf(",");
1343 				printf("%d", 1 << (i + 4));
1344 				first = 0;
1345 			}
1346 		}
1347 		printf("\n");
1348 	}
1349 	memstat_mtl_free(mtlp);
1350 }
1351 
1352 static void
1353 domemstat_zone(void)
1354 {
1355 	struct memory_type_list *mtlp;
1356 	struct memory_type *mtp;
1357 	char name[MEMTYPE_MAXNAME + 1];
1358 	int error;
1359 
1360 	mtlp = memstat_mtl_alloc();
1361 	if (mtlp == NULL) {
1362 		warn("memstat_mtl_alloc");
1363 		return;
1364 	}
1365 	if (kd == NULL) {
1366 		if (memstat_sysctl_uma(mtlp, 0) < 0) {
1367 			warnx("memstat_sysctl_uma: %s",
1368 			    memstat_strerror(memstat_mtl_geterror(mtlp)));
1369 			return;
1370 		}
1371 	} else {
1372 		if (memstat_kvm_uma(mtlp, kd) < 0) {
1373 			error = memstat_mtl_geterror(mtlp);
1374 			if (error == MEMSTAT_ERROR_KVM)
1375 				warnx("memstat_kvm_uma: %s",
1376 				    kvm_geterr(kd));
1377 			else
1378 				warnx("memstat_kvm_uma: %s",
1379 				    memstat_strerror(error));
1380 		}
1381 	}
1382 	printf("%-20s %6s %6s %8s %8s %8s %4s %4s\n\n", "ITEM", "SIZE",
1383 	    "LIMIT", "USED", "FREE", "REQ", "FAIL", "SLEEP");
1384 	for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
1385 	    mtp = memstat_mtl_next(mtp)) {
1386 		strlcpy(name, memstat_get_name(mtp), MEMTYPE_MAXNAME);
1387 		strcat(name, ":");
1388 		printf("%-20s %6" PRIu64 ", %6" PRIu64 ",%8" PRIu64 ",%8" PRIu64
1389 		    ",%8" PRIu64 ",%4" PRIu64 ",%4" PRIu64 "\n", name,
1390 		    memstat_get_size(mtp), memstat_get_countlimit(mtp),
1391 		    memstat_get_count(mtp), memstat_get_free(mtp),
1392 		    memstat_get_numallocs(mtp), memstat_get_failures(mtp),
1393 		    memstat_get_sleeps(mtp));
1394 	}
1395 	memstat_mtl_free(mtlp);
1396 	printf("\n");
1397 }
1398 
1399 /*
1400  * kread reads something from the kernel, given its nlist index.
1401  */
1402 static void
1403 kreado(int nlx, void *addr, size_t size, size_t offset)
1404 {
1405 	const char *sym;
1406 
1407 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
1408 		sym = namelist[nlx].n_name;
1409 		if (*sym == '_')
1410 			++sym;
1411 		errx(1, "symbol %s not defined", sym);
1412 	}
1413 	if ((size_t)kvm_read(kd, namelist[nlx].n_value + offset, addr,
1414 	    size) != size) {
1415 		sym = namelist[nlx].n_name;
1416 		if (*sym == '_')
1417 			++sym;
1418 		errx(1, "%s: %s", sym, kvm_geterr(kd));
1419 	}
1420 }
1421 
1422 static void
1423 kread(int nlx, void *addr, size_t size)
1424 {
1425 	kreado(nlx, addr, size, 0);
1426 }
1427 
1428 static char *
1429 kgetstr(const char *strp)
1430 {
1431 	int n = 0, size = 1;
1432 	char *ret = NULL;
1433 
1434 	do {
1435 		if (size == n + 1) {
1436 			ret = realloc(ret, size);
1437 			if (ret == NULL)
1438 				err(1, "%s: realloc", __func__);
1439 			size *= 2;
1440 		}
1441 		if (kvm_read(kd, (u_long)strp + n, &ret[n], 1) != 1)
1442 			errx(1, "%s: %s", __func__, kvm_geterr(kd));
1443 	} while (ret[n++] != '\0');
1444 	return (ret);
1445 }
1446 
1447 static void
1448 usage(void)
1449 {
1450 	(void)fprintf(stderr, "%s%s",
1451 		"usage: vmstat [-afHhimPsz] [-M core [-N system]] [-c count] [-n devs]\n",
1452 		"              [-p type,if,pass] [-w wait] [disks] [wait [count]]\n");
1453 	exit(1);
1454 }
1455