xref: /freebsd/usr.bin/vmstat/vmstat.c (revision 298f5fdc242b760e70cd3494e3a4f1f50b20664d)
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(void);
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	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 #define	BACKWARD_COMPATIBILITY
303 #ifdef	BACKWARD_COMPATIBILITY
304 	if (*argv) {
305 		f = atof(*argv);
306 		interval = f * 1000;
307 		if (*++argv)
308 			reps = atoi(*argv);
309 	}
310 #endif
311 
312 	if (interval) {
313 		if (!reps)
314 			reps = -1;
315 	} else if (reps)
316 		interval = 1 * 1000;
317 
318 	if (todo & FORKSTAT)
319 		doforkst();
320 	if (todo & MEMSTAT)
321 		domemstat_malloc();
322 	if (todo & ZMEMSTAT)
323 		domemstat_zone();
324 	if (todo & SUMSTAT)
325 		dosum();
326 #ifdef notyet
327 	if (todo & TIMESTAT)
328 		dotimes();
329 #endif
330 	if (todo & INTRSTAT)
331 		dointr();
332 	if (todo & VMSTAT)
333 		dovmstat(interval, reps);
334 	exit(0);
335 }
336 
337 static int
338 mysysctl(const char *name, void *oldp, size_t *oldlenp,
339     void *newp, size_t newlen)
340 {
341 	int error;
342 
343 	error = sysctlbyname(name, oldp, oldlenp, newp, newlen);
344 	if (error != 0 && errno != ENOMEM)
345 		err(1, "sysctl(%s)", name);
346 	return (error);
347 }
348 
349 static char **
350 getdrivedata(char **argv)
351 {
352 	if ((num_devices = devstat_getnumdevs(NULL)) < 0)
353 		errx(1, "%s", devstat_errbuf);
354 
355 	cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
356 	last.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
357 
358 	if (devstat_getdevs(NULL, &cur) == -1)
359 		errx(1, "%s", devstat_errbuf);
360 
361 	num_devices = cur.dinfo->numdevs;
362 	generation = cur.dinfo->generation;
363 
364 	specified_devices = (char **)malloc(sizeof(char *));
365 	for (num_devices_specified = 0; *argv; ++argv) {
366 		if (isdigit(**argv))
367 			break;
368 		num_devices_specified++;
369 		specified_devices = (char **)realloc(specified_devices,
370 						     sizeof(char *) *
371 						     num_devices_specified);
372 		specified_devices[num_devices_specified - 1] = *argv;
373 	}
374 	dev_select = NULL;
375 
376 	if (nflag == 0 && maxshowdevs < num_devices_specified)
377 			maxshowdevs = num_devices_specified;
378 
379 	/*
380 	 * People are generally only interested in disk statistics when
381 	 * they're running vmstat.  So, that's what we're going to give
382 	 * them if they don't specify anything by default.  We'll also give
383 	 * them any other random devices in the system so that we get to
384 	 * maxshowdevs devices, if that many devices exist.  If the user
385 	 * specifies devices on the command line, either through a pattern
386 	 * match or by naming them explicitly, we will give the user only
387 	 * those devices.
388 	 */
389 	if ((num_devices_specified == 0) && (num_matches == 0)) {
390 		if (devstat_buildmatch(da, &matches, &num_matches) != 0)
391 			errx(1, "%s", devstat_errbuf);
392 
393 		select_mode = DS_SELECT_ADD;
394 	} else
395 		select_mode = DS_SELECT_ONLY;
396 
397 	/*
398 	 * At this point, selectdevs will almost surely indicate that the
399 	 * device list has changed, so we don't look for return values of 0
400 	 * or 1.  If we get back -1, though, there is an error.
401 	 */
402 	if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
403 		       &select_generation, generation, cur.dinfo->devices,
404 		       num_devices, matches, num_matches, specified_devices,
405 		       num_devices_specified, select_mode,
406 		       maxshowdevs, 0) == -1)
407 		errx(1, "%s", devstat_errbuf);
408 
409 	return(argv);
410 }
411 
412 static long
413 getuptime(void)
414 {
415 	struct timespec sp;
416 
417 	(void)clock_gettime(CLOCK_MONOTONIC, &sp);
418 
419 	return(sp.tv_sec);
420 }
421 
422 static void
423 fill_pcpu(struct pcpu ***pcpup, int* maxcpup)
424 {
425 	struct pcpu **pcpu;
426 
427 	int maxcpu, i;
428 
429 	*pcpup = NULL;
430 
431 	if (kd == NULL)
432 		return;
433 
434 	maxcpu = kvm_getmaxcpu(kd);
435 	if (maxcpu < 0)
436 		errx(1, "kvm_getmaxcpu: %s", kvm_geterr(kd));
437 
438 	pcpu = calloc(maxcpu, sizeof(struct pcpu *));
439 	if (pcpu == NULL)
440 		err(1, "calloc");
441 
442 	for (i = 0; i < maxcpu; i++) {
443 		pcpu[i] = kvm_getpcpu(kd, i);
444 		if (pcpu[i] == (struct pcpu *)-1)
445 			errx(1, "kvm_getpcpu: %s", kvm_geterr(kd));
446 	}
447 
448 	*maxcpup = maxcpu;
449 	*pcpup = pcpu;
450 }
451 
452 static void
453 free_pcpu(struct pcpu **pcpu, int maxcpu)
454 {
455 	int i;
456 
457 	for (i = 0; i < maxcpu; i++)
458 		free(pcpu[i]);
459 	free(pcpu);
460 }
461 
462 static void
463 fill_vmmeter(struct vmmeter *vmmp)
464 {
465 	struct pcpu **pcpu;
466 	int maxcpu, i;
467 
468 	if (kd != NULL) {
469 		kread(X_SUM, vmmp, sizeof(*vmmp));
470 		fill_pcpu(&pcpu, &maxcpu);
471 		for (i = 0; i < maxcpu; i++) {
472 			if (pcpu[i] == NULL)
473 				continue;
474 #define ADD_FROM_PCPU(i, name) \
475 			vmmp->name += pcpu[i]->pc_cnt.name
476 			ADD_FROM_PCPU(i, v_swtch);
477 			ADD_FROM_PCPU(i, v_trap);
478 			ADD_FROM_PCPU(i, v_syscall);
479 			ADD_FROM_PCPU(i, v_intr);
480 			ADD_FROM_PCPU(i, v_soft);
481 			ADD_FROM_PCPU(i, v_vm_faults);
482 			ADD_FROM_PCPU(i, v_io_faults);
483 			ADD_FROM_PCPU(i, v_cow_faults);
484 			ADD_FROM_PCPU(i, v_cow_optim);
485 			ADD_FROM_PCPU(i, v_zfod);
486 			ADD_FROM_PCPU(i, v_ozfod);
487 			ADD_FROM_PCPU(i, v_swapin);
488 			ADD_FROM_PCPU(i, v_swapout);
489 			ADD_FROM_PCPU(i, v_swappgsin);
490 			ADD_FROM_PCPU(i, v_swappgsout);
491 			ADD_FROM_PCPU(i, v_vnodein);
492 			ADD_FROM_PCPU(i, v_vnodeout);
493 			ADD_FROM_PCPU(i, v_vnodepgsin);
494 			ADD_FROM_PCPU(i, v_vnodepgsout);
495 			ADD_FROM_PCPU(i, v_intrans);
496 			ADD_FROM_PCPU(i, v_tfree);
497 			ADD_FROM_PCPU(i, v_forks);
498 			ADD_FROM_PCPU(i, v_vforks);
499 			ADD_FROM_PCPU(i, v_rforks);
500 			ADD_FROM_PCPU(i, v_kthreads);
501 			ADD_FROM_PCPU(i, v_forkpages);
502 			ADD_FROM_PCPU(i, v_vforkpages);
503 			ADD_FROM_PCPU(i, v_rforkpages);
504 			ADD_FROM_PCPU(i, v_kthreadpages);
505 #undef ADD_FROM_PCPU
506 		}
507 		free_pcpu(pcpu, maxcpu);
508 	} else {
509 		size_t size = sizeof(unsigned int);
510 #define GET_VM_STATS(cat, name) \
511 	mysysctl("vm.stats." #cat "." #name, &vmmp->name, &size, NULL, 0)
512 		/* sys */
513 		GET_VM_STATS(sys, v_swtch);
514 		GET_VM_STATS(sys, v_trap);
515 		GET_VM_STATS(sys, v_syscall);
516 		GET_VM_STATS(sys, v_intr);
517 		GET_VM_STATS(sys, v_soft);
518 
519 		/* vm */
520 		GET_VM_STATS(vm, v_vm_faults);
521 		GET_VM_STATS(vm, v_io_faults);
522 		GET_VM_STATS(vm, v_cow_faults);
523 		GET_VM_STATS(vm, v_cow_optim);
524 		GET_VM_STATS(vm, v_zfod);
525 		GET_VM_STATS(vm, v_ozfod);
526 		GET_VM_STATS(vm, v_swapin);
527 		GET_VM_STATS(vm, v_swapout);
528 		GET_VM_STATS(vm, v_swappgsin);
529 		GET_VM_STATS(vm, v_swappgsout);
530 		GET_VM_STATS(vm, v_vnodein);
531 		GET_VM_STATS(vm, v_vnodeout);
532 		GET_VM_STATS(vm, v_vnodepgsin);
533 		GET_VM_STATS(vm, v_vnodepgsout);
534 		GET_VM_STATS(vm, v_intrans);
535 		GET_VM_STATS(vm, v_reactivated);
536 		GET_VM_STATS(vm, v_pdwakeups);
537 		GET_VM_STATS(vm, v_pdpages);
538 		GET_VM_STATS(vm, v_tcached);
539 		GET_VM_STATS(vm, v_dfree);
540 		GET_VM_STATS(vm, v_pfree);
541 		GET_VM_STATS(vm, v_tfree);
542 		GET_VM_STATS(vm, v_page_size);
543 		GET_VM_STATS(vm, v_page_count);
544 		GET_VM_STATS(vm, v_free_reserved);
545 		GET_VM_STATS(vm, v_free_target);
546 		GET_VM_STATS(vm, v_free_min);
547 		GET_VM_STATS(vm, v_free_count);
548 		GET_VM_STATS(vm, v_wire_count);
549 		GET_VM_STATS(vm, v_active_count);
550 		GET_VM_STATS(vm, v_inactive_target);
551 		GET_VM_STATS(vm, v_inactive_count);
552 		GET_VM_STATS(vm, v_cache_count);
553 		GET_VM_STATS(vm, v_cache_min);
554 		GET_VM_STATS(vm, v_cache_max);
555 		GET_VM_STATS(vm, v_pageout_free_min);
556 		GET_VM_STATS(vm, v_interrupt_free_min);
557 		/*GET_VM_STATS(vm, v_free_severe);*/
558 		GET_VM_STATS(vm, v_forks);
559 		GET_VM_STATS(vm, v_vforks);
560 		GET_VM_STATS(vm, v_rforks);
561 		GET_VM_STATS(vm, v_kthreads);
562 		GET_VM_STATS(vm, v_forkpages);
563 		GET_VM_STATS(vm, v_vforkpages);
564 		GET_VM_STATS(vm, v_rforkpages);
565 		GET_VM_STATS(vm, v_kthreadpages);
566 #undef GET_VM_STATS
567 	}
568 }
569 
570 static void
571 fill_vmtotal(struct vmtotal *vmtp)
572 {
573 	if (kd != NULL) {
574 		/* XXX fill vmtp */
575 		errx(1, "not implemented");
576 	} else {
577 		size_t size = sizeof(*vmtp);
578 		mysysctl("vm.vmtotal", vmtp, &size, NULL, 0);
579 		if (size != sizeof(*vmtp))
580 			errx(1, "vm.total size mismatch");
581 	}
582 }
583 
584 /* Determine how many cpu columns, and what index they are in kern.cp_times */
585 static int
586 getcpuinfo(u_long *maskp, int *maxidp)
587 {
588 	int maxcpu;
589 	int maxid;
590 	int ncpus;
591 	int i, j;
592 	int empty;
593 	size_t size;
594 	long *times;
595 	u_long mask;
596 
597 	if (kd != NULL)
598 		errx(1, "not implemented");
599 	mask = 0;
600 	ncpus = 0;
601 	size = sizeof(maxcpu);
602 	mysysctl("kern.smp.maxcpus", &maxcpu, &size, NULL, 0);
603 	if (size != sizeof(maxcpu))
604 		errx(1, "sysctl kern.smp.maxcpus");
605 	size = sizeof(long) * maxcpu * CPUSTATES;
606 	times = malloc(size);
607 	if (times == NULL)
608 		err(1, "malloc %zd bytes", size);
609 	mysysctl("kern.cp_times", times, &size, NULL, 0);
610 	maxid = (size / CPUSTATES / sizeof(long)) - 1;
611 	for (i = 0; i <= maxid; i++) {
612 		empty = 1;
613 		for (j = 0; empty && j < CPUSTATES; j++) {
614 			if (times[i * CPUSTATES + j] != 0)
615 				empty = 0;
616 		}
617 		if (!empty) {
618 			mask |= (1ul << i);
619 			ncpus++;
620 		}
621 	}
622 	if (maskp)
623 		*maskp = mask;
624 	if (maxidp)
625 		*maxidp = maxid;
626 	return (ncpus);
627 }
628 
629 
630 static void
631 prthuman(u_int64_t val, int size)
632 {
633 	char buf[10];
634 	int flags;
635 
636 	if (size < 5 || size > 9)
637 		errx(1, "doofus");
638 	flags = HN_B | HN_NOSPACE | HN_DECIMAL;
639 	humanize_number(buf, size, val, "", HN_AUTOSCALE, flags);
640 	printf("%*s", size, buf);
641 }
642 
643 static int hz, hdrcnt;
644 
645 static long *cur_cp_times;
646 static long *last_cp_times;
647 static size_t size_cp_times;
648 
649 static void
650 dovmstat(unsigned int interval, int reps)
651 {
652 	struct vmtotal total;
653 	time_t uptime, halfuptime;
654 	struct devinfo *tmp_dinfo;
655 	size_t size;
656 	int ncpus, maxid;
657 	u_long cpumask;
658 	int rate_adj;
659 
660 	uptime = getuptime();
661 	halfuptime = uptime / 2;
662 	rate_adj = 1;
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(ncpus, 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(ncpus, 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("%2d %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, 7);
778 			printf(" ");
779 			prthuman(total.t_free * (u_int64_t)sum.v_page_size, 6);
780 			printf(" ");
781 		} else {
782 			printf(" %7d ", vmstat_pgtok(total.t_avm));
783 			printf(" %6d ", vmstat_pgtok(total.t_free));
784 		}
785 		(void)printf("%5lu ",
786 		    (unsigned long)rate(sum.v_vm_faults - osum.v_vm_faults));
787 		(void)printf("%3lu ",
788 		    (unsigned long)rate(sum.v_reactivated - osum.v_reactivated));
789 		(void)printf("%3lu ",
790 		    (unsigned long)rate(sum.v_swapin + sum.v_vnodein -
791 		    (osum.v_swapin + osum.v_vnodein)));
792 		(void)printf("%3lu ",
793 		    (unsigned long)rate(sum.v_swapout + sum.v_vnodeout -
794 		    (osum.v_swapout + osum.v_vnodeout)));
795 		(void)printf("%5lu ",
796 		    (unsigned long)rate(sum.v_tfree - osum.v_tfree));
797 		(void)printf("%3lu ",
798 		    (unsigned long)rate(sum.v_pdpages - osum.v_pdpages));
799 		devstats();
800 		(void)printf("%4lu %4lu %4lu",
801 		    (unsigned long)rate(sum.v_intr - osum.v_intr),
802 		    (unsigned long)rate(sum.v_syscall - osum.v_syscall),
803 		    (unsigned long)rate(sum.v_swtch - osum.v_swtch));
804 		if (Pflag)
805 			pcpustats(ncpus, cpumask, maxid);
806 		else
807 			cpustats();
808 		(void)printf("\n");
809 		(void)fflush(stdout);
810 		if (reps >= 0 && --reps <= 0)
811 			break;
812 		osum = sum;
813 		uptime = interval;
814 		rate_adj = 1000;
815 		/*
816 		 * We round upward to avoid losing low-frequency events
817 		 * (i.e., >= 1 per interval but < 1 per millisecond).
818 		 */
819 		if (interval != 1)
820 			halfuptime = (uptime + 1) / 2;
821 		else
822 			halfuptime = 0;
823 		(void)usleep(interval * 1000);
824 	}
825 }
826 
827 static void
828 printhdr(int ncpus, u_long cpumask)
829 {
830 	int i, num_shown;
831 
832 	num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
833 	(void)printf(" procs      memory      page%*s", 19, "");
834 	if (num_shown > 1)
835 		(void)printf(" disks %*s", num_shown * 4 - 7, "");
836 	else if (num_shown == 1)
837 		(void)printf("disk");
838 	(void)printf("   faults         ");
839 	if (Pflag) {
840 		for (i = 0; i < ncpus; i++) {
841 			if (cpumask & (1ul << i))
842 				printf("cpu%-2d    ", i);
843 		}
844 		printf("\n");
845 	} else
846 		printf("cpu\n");
847 	(void)printf(" r b w     avm    fre   flt  re  pi  po    fr  sr ");
848 	for (i = 0; i < num_devices; i++)
849 		if ((dev_select[i].selected)
850 		 && (dev_select[i].selected <= maxshowdevs))
851 			(void)printf("%c%c%d ", dev_select[i].device_name[0],
852 				     dev_select[i].device_name[1],
853 				     dev_select[i].unit_number);
854 	(void)printf("  in   sy   cs");
855 	if (Pflag) {
856 		for (i = 0; i < ncpus; i++)
857 			printf(" us sy id");
858 		printf("\n");
859 	} else
860 		printf(" us sy id\n");
861 	if (wresized != 0)
862 		doresize();
863 	hdrcnt = winlines;
864 }
865 
866 /*
867  * Force a header to be prepended to the next output.
868  */
869 static void
870 needhdr(int dummy __unused)
871 {
872 
873 	hdrcnt = 1;
874 }
875 
876 /*
877  * When the terminal is resized, force an update of the maximum number of rows
878  * printed between each header repetition.  Then force a new header to be
879  * prepended to the next output.
880  */
881 void
882 needresize(int signo)
883 {
884 
885 	wresized = 1;
886 	hdrcnt = 1;
887 }
888 
889 /*
890  * Update the global `winlines' count of terminal rows.
891  */
892 void
893 doresize(void)
894 {
895 	int status;
896 	struct winsize w;
897 
898 	for (;;) {
899 		status = ioctl(fileno(stdout), TIOCGWINSZ, &w);
900 		if (status == -1 && errno == EINTR)
901 			continue;
902 		else if (status == -1)
903 			err(1, "ioctl");
904 		if (w.ws_row > 3)
905 			winlines = w.ws_row - 3;
906 		else
907 			winlines = VMSTAT_DEFAULT_LINES;
908 		break;
909 	}
910 
911 	/*
912 	 * Inhibit doresize() calls until we are rescheduled by SIGWINCH.
913 	 */
914 	wresized = 0;
915 }
916 
917 #ifdef notyet
918 static void
919 dotimes(void)
920 {
921 	unsigned int pgintime, rectime;
922 
923 	kread(X_REC, &rectime, sizeof(rectime));
924 	kread(X_PGIN, &pgintime, sizeof(pgintime));
925 	kread(X_SUM, &sum, sizeof(sum));
926 	(void)printf("%u reclaims, %u total time (usec)\n",
927 	    sum.v_pgrec, rectime);
928 	(void)printf("average: %u usec / reclaim\n", rectime / sum.v_pgrec);
929 	(void)printf("\n");
930 	(void)printf("%u page ins, %u total time (msec)\n",
931 	    sum.v_pgin, pgintime / 10);
932 	(void)printf("average: %8.1f msec / page in\n",
933 	    pgintime / (sum.v_pgin * 10.0));
934 }
935 #endif
936 
937 static long
938 pct(long top, long bot)
939 {
940 	long ans;
941 
942 	if (bot == 0)
943 		return(0);
944 	ans = (quad_t)top * 100 / bot;
945 	return (ans);
946 }
947 
948 #define	PCT(top, bot) pct((long)(top), (long)(bot))
949 
950 static void
951 dosum(void)
952 {
953 	struct nchstats lnchstats;
954 	long nchtotal;
955 
956 	fill_vmmeter(&sum);
957 	(void)printf("%9u cpu context switches\n", sum.v_swtch);
958 	(void)printf("%9u device interrupts\n", sum.v_intr);
959 	(void)printf("%9u software interrupts\n", sum.v_soft);
960 	(void)printf("%9u traps\n", sum.v_trap);
961 	(void)printf("%9u system calls\n", sum.v_syscall);
962 	(void)printf("%9u kernel threads created\n", sum.v_kthreads);
963 	(void)printf("%9u  fork() calls\n", sum.v_forks);
964 	(void)printf("%9u vfork() calls\n", sum.v_vforks);
965 	(void)printf("%9u rfork() calls\n", sum.v_rforks);
966 	(void)printf("%9u swap pager pageins\n", sum.v_swapin);
967 	(void)printf("%9u swap pager pages paged in\n", sum.v_swappgsin);
968 	(void)printf("%9u swap pager pageouts\n", sum.v_swapout);
969 	(void)printf("%9u swap pager pages paged out\n", sum.v_swappgsout);
970 	(void)printf("%9u vnode pager pageins\n", sum.v_vnodein);
971 	(void)printf("%9u vnode pager pages paged in\n", sum.v_vnodepgsin);
972 	(void)printf("%9u vnode pager pageouts\n", sum.v_vnodeout);
973 	(void)printf("%9u vnode pager pages paged out\n", sum.v_vnodepgsout);
974 	(void)printf("%9u page daemon wakeups\n", sum.v_pdwakeups);
975 	(void)printf("%9u pages examined by the page daemon\n", sum.v_pdpages);
976 	(void)printf("%9u pages reactivated\n", sum.v_reactivated);
977 	(void)printf("%9u copy-on-write faults\n", sum.v_cow_faults);
978 	(void)printf("%9u copy-on-write optimized faults\n", sum.v_cow_optim);
979 	(void)printf("%9u zero fill pages zeroed\n", sum.v_zfod);
980 	(void)printf("%9u zero fill pages prezeroed\n", sum.v_ozfod);
981 	(void)printf("%9u intransit blocking page faults\n", sum.v_intrans);
982 	(void)printf("%9u total VM faults taken\n", sum.v_vm_faults);
983 	(void)printf("%9u page faults requiring I/O\n", sum.v_io_faults);
984 	(void)printf("%9u pages affected by kernel thread creation\n", sum.v_kthreadpages);
985 	(void)printf("%9u pages affected by  fork()\n", sum.v_forkpages);
986 	(void)printf("%9u pages affected by vfork()\n", sum.v_vforkpages);
987 	(void)printf("%9u pages affected by rfork()\n", sum.v_rforkpages);
988 	(void)printf("%9u pages cached\n", sum.v_tcached);
989 	(void)printf("%9u pages freed\n", sum.v_tfree);
990 	(void)printf("%9u pages freed by daemon\n", sum.v_dfree);
991 	(void)printf("%9u pages freed by exiting processes\n", sum.v_pfree);
992 	(void)printf("%9u pages active\n", sum.v_active_count);
993 	(void)printf("%9u pages inactive\n", sum.v_inactive_count);
994 	(void)printf("%9u pages in VM cache\n", sum.v_cache_count);
995 	(void)printf("%9u pages wired down\n", sum.v_wire_count);
996 	(void)printf("%9u pages free\n", sum.v_free_count);
997 	(void)printf("%9u bytes per page\n", sum.v_page_size);
998 	if (kd != NULL) {
999 		kread(X_NCHSTATS, &lnchstats, sizeof(lnchstats));
1000 	} else {
1001 		size_t size = sizeof(lnchstats);
1002 		mysysctl("vfs.cache.nchstats", &lnchstats, &size, NULL, 0);
1003 		if (size != sizeof(lnchstats))
1004 			errx(1, "vfs.cache.nchstats size mismatch");
1005 	}
1006 	nchtotal = lnchstats.ncs_goodhits + lnchstats.ncs_neghits +
1007 	    lnchstats.ncs_badhits + lnchstats.ncs_falsehits +
1008 	    lnchstats.ncs_miss + lnchstats.ncs_long;
1009 	(void)printf("%9ld total name lookups\n", nchtotal);
1010 	(void)printf(
1011 	    "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
1012 	    "", PCT(lnchstats.ncs_goodhits, nchtotal),
1013 	    PCT(lnchstats.ncs_neghits, nchtotal),
1014 	    PCT(lnchstats.ncs_pass2, nchtotal));
1015 	(void)printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
1016 	    PCT(lnchstats.ncs_badhits, nchtotal),
1017 	    PCT(lnchstats.ncs_falsehits, nchtotal),
1018 	    PCT(lnchstats.ncs_long, nchtotal));
1019 }
1020 
1021 static void
1022 doforkst(void)
1023 {
1024 	fill_vmmeter(&sum);
1025 	(void)printf("%u forks, %u pages, average %.2f\n",
1026 	    sum.v_forks, sum.v_forkpages,
1027 	    sum.v_forks == 0 ? 0.0 :
1028 	    (double)sum.v_forkpages / sum.v_forks);
1029 	(void)printf("%u vforks, %u pages, average %.2f\n",
1030 	    sum.v_vforks, sum.v_vforkpages,
1031 	    sum.v_vforks == 0 ? 0.0 :
1032 	    (double)sum.v_vforkpages / sum.v_vforks);
1033 	(void)printf("%u rforks, %u pages, average %.2f\n",
1034 	    sum.v_rforks, sum.v_rforkpages,
1035 	    sum.v_rforks == 0 ? 0.0 :
1036 	    (double)sum.v_rforkpages / sum.v_rforks);
1037 }
1038 
1039 static void
1040 devstats(void)
1041 {
1042 	int dn, state;
1043 	long double transfers_per_second;
1044 	long double busy_seconds;
1045 	long tmp;
1046 
1047 	for (state = 0; state < CPUSTATES; ++state) {
1048 		tmp = cur.cp_time[state];
1049 		cur.cp_time[state] -= last.cp_time[state];
1050 		last.cp_time[state] = tmp;
1051 	}
1052 
1053 	busy_seconds = cur.snap_time - last.snap_time;
1054 
1055 	for (dn = 0; dn < num_devices; dn++) {
1056 		int di;
1057 
1058 		if ((dev_select[dn].selected == 0)
1059 		 || (dev_select[dn].selected > maxshowdevs))
1060 			continue;
1061 
1062 		di = dev_select[dn].position;
1063 
1064 		if (devstat_compute_statistics(&cur.dinfo->devices[di],
1065 		    &last.dinfo->devices[di], busy_seconds,
1066 		    DSM_TRANSFERS_PER_SECOND, &transfers_per_second,
1067 		    DSM_NONE) != 0)
1068 			errx(1, "%s", devstat_errbuf);
1069 
1070 		(void)printf("%3.0Lf ", transfers_per_second);
1071 	}
1072 }
1073 
1074 static void
1075 percent(double pct, int *over)
1076 {
1077 	char buf[10];
1078 	int l;
1079 
1080 	l = snprintf(buf, sizeof(buf), "%.0f", pct);
1081 	if (l == 1 && *over) {
1082 		printf("%s",  buf);
1083 		(*over)--;
1084 	} else
1085 		printf("%2s", buf);
1086 	if (l > 2)
1087 		(*over)++;
1088 }
1089 
1090 static void
1091 cpustats(void)
1092 {
1093 	int state, over;
1094 	double lpct, total;
1095 
1096 	total = 0;
1097 	for (state = 0; state < CPUSTATES; ++state)
1098 		total += cur.cp_time[state];
1099 	if (total)
1100 		lpct = 100.0 / total;
1101 	else
1102 		lpct = 0.0;
1103 	over = 0;
1104 	printf(" ");
1105 	percent((cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * lpct, &over);
1106 	printf(" ");
1107 	percent((cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * lpct, &over);
1108 	printf(" ");
1109 	percent(cur.cp_time[CP_IDLE] * lpct, &over);
1110 }
1111 
1112 static void
1113 pcpustats(int ncpus, u_long cpumask, int maxid)
1114 {
1115 	int state, i;
1116 	double lpct, total;
1117 	long tmp;
1118 	int over;
1119 
1120 	/* devstats does this for cp_time */
1121 	for (i = 0; i <= maxid; i++) {
1122 		if ((cpumask & (1ul << i)) == 0)
1123 			continue;
1124 		for (state = 0; state < CPUSTATES; ++state) {
1125 			tmp = cur_cp_times[i * CPUSTATES + state];
1126 			cur_cp_times[i * CPUSTATES + state] -= last_cp_times[i * CPUSTATES + state];
1127 			last_cp_times[i * CPUSTATES + state] = tmp;
1128 		}
1129 	}
1130 
1131 	over = 0;
1132 	for (i = 0; i <= maxid; i++) {
1133 		if ((cpumask & (1ul << i)) == 0)
1134 			continue;
1135 		total = 0;
1136 		for (state = 0; state < CPUSTATES; ++state)
1137 			total += cur_cp_times[i * CPUSTATES + state];
1138 		if (total)
1139 			lpct = 100.0 / total;
1140 		else
1141 			lpct = 0.0;
1142 		printf(" ");
1143 		percent((cur_cp_times[i * CPUSTATES + CP_USER] +
1144 			 cur_cp_times[i * CPUSTATES + CP_NICE]) * lpct, &over);
1145 		printf(" ");
1146 		percent((cur_cp_times[i * CPUSTATES + CP_SYS] +
1147 			 cur_cp_times[i * CPUSTATES + CP_INTR]) * lpct, &over);
1148 		printf(" ");
1149 		percent(cur_cp_times[i * CPUSTATES + CP_IDLE] * lpct, &over);
1150 	}
1151 }
1152 
1153 static void
1154 dointr(void)
1155 {
1156 	unsigned long *intrcnt, uptime;
1157 	uint64_t inttotal;
1158 	size_t clen, inamlen, intrcntlen, istrnamlen;
1159 	unsigned int i, nintr;
1160 	char *intrname, *tintrname;
1161 
1162 	uptime = getuptime();
1163 	if (kd != NULL) {
1164 		kread(X_SINTRCNT, &intrcntlen, sizeof(intrcntlen));
1165 		kread(X_SINTRNAMES, &inamlen, sizeof(inamlen));
1166 		if ((intrcnt = malloc(intrcntlen)) == NULL ||
1167 		    (intrname = malloc(inamlen)) == NULL)
1168 			err(1, "malloc()");
1169 		kread(X_INTRCNT, intrcnt, intrcntlen);
1170 		kread(X_INTRNAMES, intrname, inamlen);
1171 	} else {
1172 		for (intrcnt = NULL, intrcntlen = 1024; ; intrcntlen *= 2) {
1173 			if ((intrcnt = reallocf(intrcnt, intrcntlen)) == NULL)
1174 				err(1, "reallocf()");
1175 			if (mysysctl("hw.intrcnt",
1176 			    intrcnt, &intrcntlen, NULL, 0) == 0)
1177 				break;
1178 		}
1179 		for (intrname = NULL, inamlen = 1024; ; inamlen *= 2) {
1180 			if ((intrname = reallocf(intrname, inamlen)) == NULL)
1181 				err(1, "reallocf()");
1182 			if (mysysctl("hw.intrnames",
1183 			    intrname, &inamlen, NULL, 0) == 0)
1184 				break;
1185 		}
1186 	}
1187 	nintr = intrcntlen / sizeof(unsigned long);
1188 	tintrname = intrname;
1189 	istrnamlen = strlen("interrupt");
1190 	for (i = 0; i < nintr; i++) {
1191 		clen = strlen(tintrname);
1192 		if (clen > istrnamlen)
1193 			istrnamlen = clen;
1194 		tintrname += clen + 1;
1195 	}
1196 	(void)printf("%-*s %20s %10s\n", (int)istrnamlen, "interrupt", "total",
1197 	    "rate");
1198 	inttotal = 0;
1199 	for (i = 0; i < nintr; i++) {
1200 		if (intrname[0] != '\0' && (*intrcnt != 0 || aflag))
1201 			(void)printf("%-*s %20lu %10lu\n", (int)istrnamlen,
1202 			    intrname, *intrcnt, *intrcnt / uptime);
1203 		intrname += strlen(intrname) + 1;
1204 		inttotal += *intrcnt++;
1205 	}
1206 	(void)printf("%-*s %20" PRIu64 " %10" PRIu64 "\n", (int)istrnamlen,
1207 	    "Total", inttotal, inttotal / uptime);
1208 }
1209 
1210 static void
1211 domemstat_malloc(void)
1212 {
1213 	struct memory_type_list *mtlp;
1214 	struct memory_type *mtp;
1215 	int error, first, i;
1216 
1217 	mtlp = memstat_mtl_alloc();
1218 	if (mtlp == NULL) {
1219 		warn("memstat_mtl_alloc");
1220 		return;
1221 	}
1222 	if (kd == NULL) {
1223 		if (memstat_sysctl_malloc(mtlp, 0) < 0) {
1224 			warnx("memstat_sysctl_malloc: %s",
1225 			    memstat_strerror(memstat_mtl_geterror(mtlp)));
1226 			return;
1227 		}
1228 	} else {
1229 		if (memstat_kvm_malloc(mtlp, kd) < 0) {
1230 			error = memstat_mtl_geterror(mtlp);
1231 			if (error == MEMSTAT_ERROR_KVM)
1232 				warnx("memstat_kvm_malloc: %s",
1233 				    kvm_geterr(kd));
1234 			else
1235 				warnx("memstat_kvm_malloc: %s",
1236 				    memstat_strerror(error));
1237 		}
1238 	}
1239 	printf("%13s %5s %6s %7s %8s  Size(s)\n", "Type", "InUse", "MemUse",
1240 	    "HighUse", "Requests");
1241 	for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
1242 	    mtp = memstat_mtl_next(mtp)) {
1243 		if (memstat_get_numallocs(mtp) == 0 &&
1244 		    memstat_get_count(mtp) == 0)
1245 			continue;
1246 		printf("%13s %5" PRIu64 " %5" PRIu64 "K %7s %8" PRIu64 "  ",
1247 		    memstat_get_name(mtp), memstat_get_count(mtp),
1248 		    (memstat_get_bytes(mtp) + 1023) / 1024, "-",
1249 		    memstat_get_numallocs(mtp));
1250 		first = 1;
1251 		for (i = 0; i < 32; i++) {
1252 			if (memstat_get_sizemask(mtp) & (1 << i)) {
1253 				if (!first)
1254 					printf(",");
1255 				printf("%d", 1 << (i + 4));
1256 				first = 0;
1257 			}
1258 		}
1259 		printf("\n");
1260 	}
1261 	memstat_mtl_free(mtlp);
1262 }
1263 
1264 static void
1265 domemstat_zone(void)
1266 {
1267 	struct memory_type_list *mtlp;
1268 	struct memory_type *mtp;
1269 	char name[MEMTYPE_MAXNAME + 1];
1270 	int error;
1271 
1272 	mtlp = memstat_mtl_alloc();
1273 	if (mtlp == NULL) {
1274 		warn("memstat_mtl_alloc");
1275 		return;
1276 	}
1277 	if (kd == NULL) {
1278 		if (memstat_sysctl_uma(mtlp, 0) < 0) {
1279 			warnx("memstat_sysctl_uma: %s",
1280 			    memstat_strerror(memstat_mtl_geterror(mtlp)));
1281 			return;
1282 		}
1283 	} else {
1284 		if (memstat_kvm_uma(mtlp, kd) < 0) {
1285 			error = memstat_mtl_geterror(mtlp);
1286 			if (error == MEMSTAT_ERROR_KVM)
1287 				warnx("memstat_kvm_uma: %s",
1288 				    kvm_geterr(kd));
1289 			else
1290 				warnx("memstat_kvm_uma: %s",
1291 				    memstat_strerror(error));
1292 		}
1293 	}
1294 	printf("%-20s %6s %6s %8s %8s %8s %4s %4s\n\n", "ITEM", "SIZE",
1295 	    "LIMIT", "USED", "FREE", "REQ", "FAIL", "SLEEP");
1296 	for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
1297 	    mtp = memstat_mtl_next(mtp)) {
1298 		strlcpy(name, memstat_get_name(mtp), MEMTYPE_MAXNAME);
1299 		strcat(name, ":");
1300 		printf("%-20s %6" PRIu64 ", %6" PRIu64 ",%8" PRIu64 ",%8" PRIu64
1301 		    ",%8" PRIu64 ",%4" PRIu64 ",%4" PRIu64 "\n", name,
1302 		    memstat_get_size(mtp), memstat_get_countlimit(mtp),
1303 		    memstat_get_count(mtp), memstat_get_free(mtp),
1304 		    memstat_get_numallocs(mtp), memstat_get_failures(mtp),
1305 		    memstat_get_sleeps(mtp));
1306 	}
1307 	memstat_mtl_free(mtlp);
1308 	printf("\n");
1309 }
1310 
1311 /*
1312  * kread reads something from the kernel, given its nlist index.
1313  */
1314 static void
1315 kreado(int nlx, void *addr, size_t size, size_t offset)
1316 {
1317 	const char *sym;
1318 
1319 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
1320 		sym = namelist[nlx].n_name;
1321 		if (*sym == '_')
1322 			++sym;
1323 		errx(1, "symbol %s not defined", sym);
1324 	}
1325 	if ((size_t)kvm_read(kd, namelist[nlx].n_value + offset, addr,
1326 	    size) != size) {
1327 		sym = namelist[nlx].n_name;
1328 		if (*sym == '_')
1329 			++sym;
1330 		errx(1, "%s: %s", sym, kvm_geterr(kd));
1331 	}
1332 }
1333 
1334 static void
1335 kread(int nlx, void *addr, size_t size)
1336 {
1337 	kreado(nlx, addr, size, 0);
1338 }
1339 
1340 static char *
1341 kgetstr(const char *strp)
1342 {
1343 	int n = 0, size = 1;
1344 	char *ret = NULL;
1345 
1346 	do {
1347 		if (size == n + 1) {
1348 			ret = realloc(ret, size);
1349 			if (ret == NULL)
1350 				err(1, "%s: realloc", __func__);
1351 			size *= 2;
1352 		}
1353 		if (kvm_read(kd, (u_long)strp + n, &ret[n], 1) != 1)
1354 			errx(1, "%s: %s", __func__, kvm_geterr(kd));
1355 	} while (ret[n++] != '\0');
1356 	return (ret);
1357 }
1358 
1359 static void
1360 usage(void)
1361 {
1362 	(void)fprintf(stderr, "%s%s",
1363 		"usage: vmstat [-afHhimPsz] [-c count] [-M core [-N system]] [-w wait]\n",
1364 		"              [-n devs] [-p type,if,pass] [disks]\n");
1365 	exit(1);
1366 }
1367