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