xref: /freebsd/usr.bin/vmstat/vmstat.c (revision 5dcd9c10612684d1c823670cbb5b4715028784e7)
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/time.h>
47 #include <sys/proc.h>
48 #include <sys/uio.h>
49 #include <sys/namei.h>
50 #include <sys/malloc.h>
51 #include <sys/signal.h>
52 #include <sys/fcntl.h>
53 #include <sys/ioctl.h>
54 #include <sys/resource.h>
55 #include <sys/sysctl.h>
56 #include <sys/time.h>
57 #include <sys/vmmeter.h>
58 #include <sys/pcpu.h>
59 
60 #include <vm/vm_param.h>
61 
62 #include <ctype.h>
63 #include <devstat.h>
64 #include <err.h>
65 #include <errno.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 	{ "_cnt" },
84 #define	X_BOOTTIME	1
85 	{ "_boottime" },
86 #define X_HZ		2
87 	{ "_hz" },
88 #define X_STATHZ	3
89 	{ "_stathz" },
90 #define X_NCHSTATS	4
91 	{ "_nchstats" },
92 #define	X_INTRNAMES	5
93 	{ "_intrnames" },
94 #define	X_EINTRNAMES	6
95 	{ "_eintrnames" },
96 #define	X_INTRCNT	7
97 	{ "_intrcnt" },
98 #define	X_EINTRCNT	8
99 	{ "_eintrcnt" },
100 #define	X_KMEMSTATS	9
101 	{ "_kmemstatistics" },
102 #define	X_KMEMZONES	10
103 	{ "_kmemzones" },
104 #ifdef notyet
105 #define	X_DEFICIT	XXX
106 	{ "_deficit" },
107 #define X_REC		XXX
108 	{ "_rectime" },
109 #define X_PGIN		XXX
110 	{ "_pgintime" },
111 #define	X_XSTATS	XXX
112 	{ "_xstats" },
113 #define X_END		XXX
114 #else
115 #define X_END		11
116 #endif
117 	{ "" },
118 };
119 
120 static struct statinfo cur, last;
121 static int num_devices, maxshowdevs;
122 static long generation;
123 static struct device_selection *dev_select;
124 static int num_selected;
125 static struct devstat_match *matches;
126 static int num_matches = 0;
127 static int num_devices_specified, num_selections;
128 static long select_generation;
129 static char **specified_devices;
130 static devstat_select_mode select_mode;
131 
132 static struct	vmmeter sum, osum;
133 
134 #define	VMSTAT_DEFAULT_LINES	20	/* Default number of `winlines'. */
135 volatile sig_atomic_t wresized;		/* Tty resized, when non-zero. */
136 static int winlines = VMSTAT_DEFAULT_LINES; /* Current number of tty rows. */
137 
138 static int	aflag;
139 static int	nflag;
140 static int	Pflag;
141 static int	hflag;
142 
143 static kvm_t   *kd;
144 
145 #define	FORKSTAT	0x01
146 #define	INTRSTAT	0x02
147 #define	MEMSTAT		0x04
148 #define	SUMSTAT		0x08
149 #define	TIMESTAT	0x10
150 #define	VMSTAT		0x20
151 #define ZMEMSTAT	0x40
152 
153 static void	cpustats(void);
154 static void	pcpustats(int, u_long, int);
155 static void	devstats(void);
156 static void	doforkst(void);
157 static void	dointr(void);
158 static void	dosum(void);
159 static void	dovmstat(unsigned int, int);
160 static void	domemstat_malloc(void);
161 static void	domemstat_zone(void);
162 static void	kread(int, void *, size_t);
163 static void	kreado(int, void *, size_t, size_t);
164 static char    *kgetstr(const char *);
165 static void	needhdr(int);
166 static void	needresize(int);
167 static void	doresize(void);
168 static void	printhdr(int, u_long);
169 static void	usage(void);
170 
171 static long	pct(long, long);
172 static long	getuptime(void);
173 
174 static char   **getdrivedata(char **);
175 
176 int
177 main(int argc, char *argv[])
178 {
179 	int c, todo;
180 	unsigned int interval;
181 	float f;
182 	int reps;
183 	char *memf, *nlistf;
184 	char errbuf[_POSIX2_LINE_MAX];
185 
186 	memf = nlistf = NULL;
187 	interval = reps = todo = 0;
188 	maxshowdevs = 2;
189 	hflag = isatty(1);
190 	while ((c = getopt(argc, argv, "ac:fhHiM:mN:n:Pp:stw:z")) != -1) {
191 		switch (c) {
192 		case 'a':
193 			aflag++;
194 			break;
195 		case 'c':
196 			reps = atoi(optarg);
197 			break;
198 		case 'P':
199 			Pflag++;
200 			break;
201 		case 'f':
202 			todo |= FORKSTAT;
203 			break;
204 		case 'h':
205 			hflag = 1;
206 			break;
207 		case 'H':
208 			hflag = 0;
209 			break;
210 		case 'i':
211 			todo |= INTRSTAT;
212 			break;
213 		case 'M':
214 			memf = optarg;
215 			break;
216 		case 'm':
217 			todo |= MEMSTAT;
218 			break;
219 		case 'N':
220 			nlistf = optarg;
221 			break;
222 		case 'n':
223 			nflag = 1;
224 			maxshowdevs = atoi(optarg);
225 			if (maxshowdevs < 0)
226 				errx(1, "number of devices %d is < 0",
227 				     maxshowdevs);
228 			break;
229 		case 'p':
230 			if (devstat_buildmatch(optarg, &matches, &num_matches) != 0)
231 				errx(1, "%s", devstat_errbuf);
232 			break;
233 		case 's':
234 			todo |= SUMSTAT;
235 			break;
236 		case 't':
237 #ifdef notyet
238 			todo |= TIMESTAT;
239 #else
240 			errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
241 #endif
242 			break;
243 		case 'w':
244 			/* Convert to milliseconds. */
245 			f = atof(optarg);
246 			interval = f * 1000;
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 		f = atof(*argv);
302 		interval = f * 1000;
303 		if (*++argv)
304 			reps = atoi(*argv);
305 	}
306 #endif
307 
308 	if (interval) {
309 		if (!reps)
310 			reps = -1;
311 	} else if (reps)
312 		interval = 1 * 1000;
313 
314 	if (todo & FORKSTAT)
315 		doforkst();
316 	if (todo & MEMSTAT)
317 		domemstat_malloc();
318 	if (todo & ZMEMSTAT)
319 		domemstat_zone();
320 	if (todo & SUMSTAT)
321 		dosum();
322 #ifdef notyet
323 	if (todo & TIMESTAT)
324 		dotimes();
325 #endif
326 	if (todo & INTRSTAT)
327 		dointr();
328 	if (todo & VMSTAT)
329 		dovmstat(interval, reps);
330 	exit(0);
331 }
332 
333 static int
334 mysysctl(const char *name, void *oldp, size_t *oldlenp,
335     void *newp, size_t newlen)
336 {
337 	int error;
338 
339 	error = sysctlbyname(name, oldp, oldlenp, newp, newlen);
340 	if (error != 0 && errno != ENOMEM)
341 		err(1, "sysctl(%s)", name);
342 	return (error);
343 }
344 
345 static char **
346 getdrivedata(char **argv)
347 {
348 	if ((num_devices = devstat_getnumdevs(NULL)) < 0)
349 		errx(1, "%s", devstat_errbuf);
350 
351 	cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
352 	last.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
353 
354 	if (devstat_getdevs(NULL, &cur) == -1)
355 		errx(1, "%s", devstat_errbuf);
356 
357 	num_devices = cur.dinfo->numdevs;
358 	generation = cur.dinfo->generation;
359 
360 	specified_devices = (char **)malloc(sizeof(char *));
361 	for (num_devices_specified = 0; *argv; ++argv) {
362 		if (isdigit(**argv))
363 			break;
364 		num_devices_specified++;
365 		specified_devices = (char **)realloc(specified_devices,
366 						     sizeof(char *) *
367 						     num_devices_specified);
368 		specified_devices[num_devices_specified - 1] = *argv;
369 	}
370 	dev_select = NULL;
371 
372 	if (nflag == 0 && maxshowdevs < num_devices_specified)
373 			maxshowdevs = num_devices_specified;
374 
375 	/*
376 	 * People are generally only interested in disk statistics when
377 	 * they're running vmstat.  So, that's what we're going to give
378 	 * them if they don't specify anything by default.  We'll also give
379 	 * them any other random devices in the system so that we get to
380 	 * maxshowdevs devices, if that many devices exist.  If the user
381 	 * specifies devices on the command line, either through a pattern
382 	 * match or by naming them explicitly, we will give the user only
383 	 * those devices.
384 	 */
385 	if ((num_devices_specified == 0) && (num_matches == 0)) {
386 		if (devstat_buildmatch(da, &matches, &num_matches) != 0)
387 			errx(1, "%s", devstat_errbuf);
388 
389 		select_mode = DS_SELECT_ADD;
390 	} else
391 		select_mode = DS_SELECT_ONLY;
392 
393 	/*
394 	 * At this point, selectdevs will almost surely indicate that the
395 	 * device list has changed, so we don't look for return values of 0
396 	 * or 1.  If we get back -1, though, there is an error.
397 	 */
398 	if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
399 		       &select_generation, generation, cur.dinfo->devices,
400 		       num_devices, matches, num_matches, specified_devices,
401 		       num_devices_specified, select_mode,
402 		       maxshowdevs, 0) == -1)
403 		errx(1, "%s", devstat_errbuf);
404 
405 	return(argv);
406 }
407 
408 static long
409 getuptime(void)
410 {
411 	struct timespec sp;
412 	time_t uptime;
413 
414 	(void)clock_gettime(CLOCK_MONOTONIC, &sp);
415 	uptime = sp.tv_sec;
416 	if (uptime <= 0 || uptime > 60*60*24*365*10)
417 		errx(1, "time makes no sense; namelist must be wrong");
418 
419 	return(uptime);
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_cow_faults);
483 			ADD_FROM_PCPU(i, v_cow_optim);
484 			ADD_FROM_PCPU(i, v_zfod);
485 			ADD_FROM_PCPU(i, v_ozfod);
486 			ADD_FROM_PCPU(i, v_swapin);
487 			ADD_FROM_PCPU(i, v_swapout);
488 			ADD_FROM_PCPU(i, v_swappgsin);
489 			ADD_FROM_PCPU(i, v_swappgsout);
490 			ADD_FROM_PCPU(i, v_vnodein);
491 			ADD_FROM_PCPU(i, v_vnodeout);
492 			ADD_FROM_PCPU(i, v_vnodepgsin);
493 			ADD_FROM_PCPU(i, v_vnodepgsout);
494 			ADD_FROM_PCPU(i, v_intrans);
495 			ADD_FROM_PCPU(i, v_tfree);
496 			ADD_FROM_PCPU(i, v_forks);
497 			ADD_FROM_PCPU(i, v_vforks);
498 			ADD_FROM_PCPU(i, v_rforks);
499 			ADD_FROM_PCPU(i, v_kthreads);
500 			ADD_FROM_PCPU(i, v_forkpages);
501 			ADD_FROM_PCPU(i, v_vforkpages);
502 			ADD_FROM_PCPU(i, v_rforkpages);
503 			ADD_FROM_PCPU(i, v_kthreadpages);
504 #undef ADD_FROM_PCPU
505 		}
506 		free_pcpu(pcpu, maxcpu);
507 	} else {
508 		size_t size = sizeof(unsigned int);
509 #define GET_VM_STATS(cat, name) \
510 	mysysctl("vm.stats." #cat "." #name, &vmmp->name, &size, NULL, 0)
511 		/* sys */
512 		GET_VM_STATS(sys, v_swtch);
513 		GET_VM_STATS(sys, v_trap);
514 		GET_VM_STATS(sys, v_syscall);
515 		GET_VM_STATS(sys, v_intr);
516 		GET_VM_STATS(sys, v_soft);
517 
518 		/* vm */
519 		GET_VM_STATS(vm, v_vm_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();
659 	halfuptime = uptime / 2;
660 	rate_adj = 1;
661 
662 	/*
663 	 * If the user stops the program (control-Z) and then resumes it,
664 	 * print out the header again.
665 	 */
666 	(void)signal(SIGCONT, needhdr);
667 
668 	/*
669 	 * If our standard output is a tty, then install a SIGWINCH handler
670 	 * and set wresized so that our first iteration through the main
671 	 * vmstat loop will peek at the terminal's current rows to find out
672 	 * how many lines can fit in a screenful of output.
673 	 */
674 	if (isatty(fileno(stdout)) != 0) {
675 		wresized = 1;
676 		(void)signal(SIGWINCH, needresize);
677 	} else {
678 		wresized = 0;
679 		winlines = VMSTAT_DEFAULT_LINES;
680 	}
681 
682 	if (kd != NULL) {
683 		if (namelist[X_STATHZ].n_type != 0 &&
684 		    namelist[X_STATHZ].n_value != 0)
685 			kread(X_STATHZ, &hz, sizeof(hz));
686 		if (!hz)
687 			kread(X_HZ, &hz, sizeof(hz));
688 	} else {
689 		struct clockinfo clockrate;
690 
691 		size = sizeof(clockrate);
692 		mysysctl("kern.clockrate", &clockrate, &size, NULL, 0);
693 		if (size != sizeof(clockrate))
694 			errx(1, "clockrate size mismatch");
695 		hz = clockrate.hz;
696 	}
697 
698 	if (Pflag) {
699 		ncpus = getcpuinfo(&cpumask, &maxid);
700 		size_cp_times = sizeof(long) * (maxid + 1) * CPUSTATES;
701 		cur_cp_times = calloc(1, size_cp_times);
702 		last_cp_times = calloc(1, size_cp_times);
703 	}
704 	for (hdrcnt = 1;;) {
705 		if (!--hdrcnt)
706 			printhdr(ncpus, cpumask);
707 		if (kd != NULL) {
708 			if (kvm_getcptime(kd, cur.cp_time) < 0)
709 				errx(1, "kvm_getcptime: %s", kvm_geterr(kd));
710 		} else {
711 			size = sizeof(cur.cp_time);
712 			mysysctl("kern.cp_time", &cur.cp_time, &size, NULL, 0);
713 			if (size != sizeof(cur.cp_time))
714 				errx(1, "cp_time size mismatch");
715 		}
716 		if (Pflag) {
717 			size = size_cp_times;
718 			mysysctl("kern.cp_times", cur_cp_times, &size, NULL, 0);
719 			if (size != size_cp_times)
720 				errx(1, "cp_times mismatch");
721 		}
722 
723 		tmp_dinfo = last.dinfo;
724 		last.dinfo = cur.dinfo;
725 		cur.dinfo = tmp_dinfo;
726 		last.snap_time = cur.snap_time;
727 
728 		/*
729 		 * Here what we want to do is refresh our device stats.
730 		 * getdevs() returns 1 when the device list has changed.
731 		 * If the device list has changed, we want to go through
732 		 * the selection process again, in case a device that we
733 		 * were previously displaying has gone away.
734 		 */
735 		switch (devstat_getdevs(NULL, &cur)) {
736 		case -1:
737 			errx(1, "%s", devstat_errbuf);
738 			break;
739 		case 1: {
740 			int retval;
741 
742 			num_devices = cur.dinfo->numdevs;
743 			generation = cur.dinfo->generation;
744 
745 			retval = devstat_selectdevs(&dev_select, &num_selected,
746 					    &num_selections, &select_generation,
747 					    generation, cur.dinfo->devices,
748 					    num_devices, matches, num_matches,
749 					    specified_devices,
750 					    num_devices_specified, select_mode,
751 					    maxshowdevs, 0);
752 			switch (retval) {
753 			case -1:
754 				errx(1, "%s", devstat_errbuf);
755 				break;
756 			case 1:
757 				printhdr(ncpus, cpumask);
758 				break;
759 			default:
760 				break;
761 			}
762 		}
763 		default:
764 			break;
765 		}
766 
767 		fill_vmmeter(&sum);
768 		fill_vmtotal(&total);
769 		(void)printf("%2d %1d %1d",
770 		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
771 #define vmstat_pgtok(a) ((a) * (sum.v_page_size >> 10))
772 #define	rate(x)	(((x) * rate_adj + halfuptime) / uptime)	/* round */
773 		if (hflag) {
774 			printf(" ");
775 			prthuman(total.t_avm * (u_int64_t)sum.v_page_size, 7);
776 			printf(" ");
777 			prthuman(total.t_free * (u_int64_t)sum.v_page_size, 6);
778 			printf(" ");
779 		} else {
780 			printf(" %7d ", vmstat_pgtok(total.t_avm));
781 			printf(" %6d ", vmstat_pgtok(total.t_free));
782 		}
783 		(void)printf("%5lu ",
784 		    (unsigned long)rate(sum.v_vm_faults - osum.v_vm_faults));
785 		(void)printf("%3lu ",
786 		    (unsigned long)rate(sum.v_reactivated - osum.v_reactivated));
787 		(void)printf("%3lu ",
788 		    (unsigned long)rate(sum.v_swapin + sum.v_vnodein -
789 		    (osum.v_swapin + osum.v_vnodein)));
790 		(void)printf("%3lu ",
791 		    (unsigned long)rate(sum.v_swapout + sum.v_vnodeout -
792 		    (osum.v_swapout + osum.v_vnodeout)));
793 		(void)printf("%5lu ",
794 		    (unsigned long)rate(sum.v_tfree - osum.v_tfree));
795 		(void)printf("%3lu ",
796 		    (unsigned long)rate(sum.v_pdpages - osum.v_pdpages));
797 		devstats();
798 		(void)printf("%4lu %4lu %4lu",
799 		    (unsigned long)rate(sum.v_intr - osum.v_intr),
800 		    (unsigned long)rate(sum.v_syscall - osum.v_syscall),
801 		    (unsigned long)rate(sum.v_swtch - osum.v_swtch));
802 		if (Pflag)
803 			pcpustats(ncpus, cpumask, maxid);
804 		else
805 			cpustats();
806 		(void)printf("\n");
807 		(void)fflush(stdout);
808 		if (reps >= 0 && --reps <= 0)
809 			break;
810 		osum = sum;
811 		uptime = interval;
812 		rate_adj = 1000;
813 		/*
814 		 * We round upward to avoid losing low-frequency events
815 		 * (i.e., >= 1 per interval but < 1 per millisecond).
816 		 */
817 		if (interval != 1)
818 			halfuptime = (uptime + 1) / 2;
819 		else
820 			halfuptime = 0;
821 		(void)usleep(interval * 1000);
822 	}
823 }
824 
825 static void
826 printhdr(int ncpus, u_long cpumask)
827 {
828 	int i, num_shown;
829 
830 	num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
831 	(void)printf(" procs      memory      page%*s", 19, "");
832 	if (num_shown > 1)
833 		(void)printf(" disks %*s", num_shown * 4 - 7, "");
834 	else if (num_shown == 1)
835 		(void)printf("disk");
836 	(void)printf("   faults         ");
837 	if (Pflag) {
838 		for (i = 0; i < ncpus; i++) {
839 			if (cpumask & (1ul << i))
840 				printf("cpu%-2d    ", i);
841 		}
842 		printf("\n");
843 	} else
844 		printf("cpu\n");
845 	(void)printf(" r b w     avm    fre   flt  re  pi  po    fr  sr ");
846 	for (i = 0; i < num_devices; i++)
847 		if ((dev_select[i].selected)
848 		 && (dev_select[i].selected <= maxshowdevs))
849 			(void)printf("%c%c%d ", dev_select[i].device_name[0],
850 				     dev_select[i].device_name[1],
851 				     dev_select[i].unit_number);
852 	(void)printf("  in   sy   cs");
853 	if (Pflag) {
854 		for (i = 0; i < ncpus; i++)
855 			printf(" us sy id");
856 		printf("\n");
857 	} else
858 		printf(" us sy id\n");
859 	if (wresized != 0)
860 		doresize();
861 	hdrcnt = winlines;
862 }
863 
864 /*
865  * Force a header to be prepended to the next output.
866  */
867 static void
868 needhdr(int dummy __unused)
869 {
870 
871 	hdrcnt = 1;
872 }
873 
874 /*
875  * When the terminal is resized, force an update of the maximum number of rows
876  * printed between each header repetition.  Then force a new header to be
877  * prepended to the next output.
878  */
879 void
880 needresize(int signo)
881 {
882 
883 	wresized = 1;
884 	hdrcnt = 1;
885 }
886 
887 /*
888  * Update the global `winlines' count of terminal rows.
889  */
890 void
891 doresize(void)
892 {
893 	int status;
894 	struct winsize w;
895 
896 	for (;;) {
897 		status = ioctl(fileno(stdout), TIOCGWINSZ, &w);
898 		if (status == -1 && errno == EINTR)
899 			continue;
900 		else if (status == -1)
901 			err(1, "ioctl");
902 		if (w.ws_row > 3)
903 			winlines = w.ws_row - 3;
904 		else
905 			winlines = VMSTAT_DEFAULT_LINES;
906 		break;
907 	}
908 
909 	/*
910 	 * Inhibit doresize() calls until we are rescheduled by SIGWINCH.
911 	 */
912 	wresized = 0;
913 }
914 
915 #ifdef notyet
916 static void
917 dotimes(void)
918 {
919 	unsigned int pgintime, rectime;
920 
921 	kread(X_REC, &rectime, sizeof(rectime));
922 	kread(X_PGIN, &pgintime, sizeof(pgintime));
923 	kread(X_SUM, &sum, sizeof(sum));
924 	(void)printf("%u reclaims, %u total time (usec)\n",
925 	    sum.v_pgrec, rectime);
926 	(void)printf("average: %u usec / reclaim\n", rectime / sum.v_pgrec);
927 	(void)printf("\n");
928 	(void)printf("%u page ins, %u total time (msec)\n",
929 	    sum.v_pgin, pgintime / 10);
930 	(void)printf("average: %8.1f msec / page in\n",
931 	    pgintime / (sum.v_pgin * 10.0));
932 }
933 #endif
934 
935 static long
936 pct(long top, long bot)
937 {
938 	long ans;
939 
940 	if (bot == 0)
941 		return(0);
942 	ans = (quad_t)top * 100 / bot;
943 	return (ans);
944 }
945 
946 #define	PCT(top, bot) pct((long)(top), (long)(bot))
947 
948 static void
949 dosum(void)
950 {
951 	struct nchstats lnchstats;
952 	long nchtotal;
953 
954 	fill_vmmeter(&sum);
955 	(void)printf("%9u cpu context switches\n", sum.v_swtch);
956 	(void)printf("%9u device interrupts\n", sum.v_intr);
957 	(void)printf("%9u software interrupts\n", sum.v_soft);
958 	(void)printf("%9u traps\n", sum.v_trap);
959 	(void)printf("%9u system calls\n", sum.v_syscall);
960 	(void)printf("%9u kernel threads created\n", sum.v_kthreads);
961 	(void)printf("%9u  fork() calls\n", sum.v_forks);
962 	(void)printf("%9u vfork() calls\n", sum.v_vforks);
963 	(void)printf("%9u rfork() calls\n", sum.v_rforks);
964 	(void)printf("%9u swap pager pageins\n", sum.v_swapin);
965 	(void)printf("%9u swap pager pages paged in\n", sum.v_swappgsin);
966 	(void)printf("%9u swap pager pageouts\n", sum.v_swapout);
967 	(void)printf("%9u swap pager pages paged out\n", sum.v_swappgsout);
968 	(void)printf("%9u vnode pager pageins\n", sum.v_vnodein);
969 	(void)printf("%9u vnode pager pages paged in\n", sum.v_vnodepgsin);
970 	(void)printf("%9u vnode pager pageouts\n", sum.v_vnodeout);
971 	(void)printf("%9u vnode pager pages paged out\n", sum.v_vnodepgsout);
972 	(void)printf("%9u page daemon wakeups\n", sum.v_pdwakeups);
973 	(void)printf("%9u pages examined by the page daemon\n", sum.v_pdpages);
974 	(void)printf("%9u pages reactivated\n", sum.v_reactivated);
975 	(void)printf("%9u copy-on-write faults\n", sum.v_cow_faults);
976 	(void)printf("%9u copy-on-write optimized faults\n", sum.v_cow_optim);
977 	(void)printf("%9u zero fill pages zeroed\n", sum.v_zfod);
978 	(void)printf("%9u zero fill pages prezeroed\n", sum.v_ozfod);
979 	(void)printf("%9u intransit blocking page faults\n", sum.v_intrans);
980 	(void)printf("%9u total VM faults taken\n", sum.v_vm_faults);
981 	(void)printf("%9u pages affected by kernel thread creation\n", sum.v_kthreadpages);
982 	(void)printf("%9u pages affected by  fork()\n", sum.v_forkpages);
983 	(void)printf("%9u pages affected by vfork()\n", sum.v_vforkpages);
984 	(void)printf("%9u pages affected by rfork()\n", sum.v_rforkpages);
985 	(void)printf("%9u pages cached\n", sum.v_tcached);
986 	(void)printf("%9u pages freed\n", sum.v_tfree);
987 	(void)printf("%9u pages freed by daemon\n", sum.v_dfree);
988 	(void)printf("%9u pages freed by exiting processes\n", sum.v_pfree);
989 	(void)printf("%9u pages active\n", sum.v_active_count);
990 	(void)printf("%9u pages inactive\n", sum.v_inactive_count);
991 	(void)printf("%9u pages in VM cache\n", sum.v_cache_count);
992 	(void)printf("%9u pages wired down\n", sum.v_wire_count);
993 	(void)printf("%9u pages free\n", sum.v_free_count);
994 	(void)printf("%9u bytes per page\n", sum.v_page_size);
995 	if (kd != NULL) {
996 		kread(X_NCHSTATS, &lnchstats, sizeof(lnchstats));
997 	} else {
998 		size_t size = sizeof(lnchstats);
999 		mysysctl("vfs.cache.nchstats", &lnchstats, &size, NULL, 0);
1000 		if (size != sizeof(lnchstats))
1001 			errx(1, "vfs.cache.nchstats size mismatch");
1002 	}
1003 	nchtotal = lnchstats.ncs_goodhits + lnchstats.ncs_neghits +
1004 	    lnchstats.ncs_badhits + lnchstats.ncs_falsehits +
1005 	    lnchstats.ncs_miss + lnchstats.ncs_long;
1006 	(void)printf("%9ld total name lookups\n", nchtotal);
1007 	(void)printf(
1008 	    "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
1009 	    "", PCT(lnchstats.ncs_goodhits, nchtotal),
1010 	    PCT(lnchstats.ncs_neghits, nchtotal),
1011 	    PCT(lnchstats.ncs_pass2, nchtotal));
1012 	(void)printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
1013 	    PCT(lnchstats.ncs_badhits, nchtotal),
1014 	    PCT(lnchstats.ncs_falsehits, nchtotal),
1015 	    PCT(lnchstats.ncs_long, nchtotal));
1016 }
1017 
1018 static void
1019 doforkst(void)
1020 {
1021 	fill_vmmeter(&sum);
1022 	(void)printf("%u forks, %u pages, average %.2f\n",
1023 	    sum.v_forks, sum.v_forkpages,
1024 	    sum.v_forks == 0 ? 0.0 :
1025 	    (double)sum.v_forkpages / sum.v_forks);
1026 	(void)printf("%u vforks, %u pages, average %.2f\n",
1027 	    sum.v_vforks, sum.v_vforkpages,
1028 	    sum.v_vforks == 0 ? 0.0 :
1029 	    (double)sum.v_vforkpages / sum.v_vforks);
1030 	(void)printf("%u rforks, %u pages, average %.2f\n",
1031 	    sum.v_rforks, sum.v_rforkpages,
1032 	    sum.v_rforks == 0 ? 0.0 :
1033 	    (double)sum.v_rforkpages / sum.v_rforks);
1034 }
1035 
1036 static void
1037 devstats(void)
1038 {
1039 	int dn, state;
1040 	long double transfers_per_second;
1041 	long double busy_seconds;
1042 	long tmp;
1043 
1044 	for (state = 0; state < CPUSTATES; ++state) {
1045 		tmp = cur.cp_time[state];
1046 		cur.cp_time[state] -= last.cp_time[state];
1047 		last.cp_time[state] = tmp;
1048 	}
1049 
1050 	busy_seconds = cur.snap_time - last.snap_time;
1051 
1052 	for (dn = 0; dn < num_devices; dn++) {
1053 		int di;
1054 
1055 		if ((dev_select[dn].selected == 0)
1056 		 || (dev_select[dn].selected > maxshowdevs))
1057 			continue;
1058 
1059 		di = dev_select[dn].position;
1060 
1061 		if (devstat_compute_statistics(&cur.dinfo->devices[di],
1062 		    &last.dinfo->devices[di], busy_seconds,
1063 		    DSM_TRANSFERS_PER_SECOND, &transfers_per_second,
1064 		    DSM_NONE) != 0)
1065 			errx(1, "%s", devstat_errbuf);
1066 
1067 		(void)printf("%3.0Lf ", transfers_per_second);
1068 	}
1069 }
1070 
1071 static void
1072 percent(double pct, int *over)
1073 {
1074 	char buf[10];
1075 	int l;
1076 
1077 	l = snprintf(buf, sizeof(buf), "%.0f", pct);
1078 	if (l == 1 && *over) {
1079 		printf("%s",  buf);
1080 		(*over)--;
1081 	} else
1082 		printf("%2s", buf);
1083 	if (l > 2)
1084 		(*over)++;
1085 }
1086 
1087 static void
1088 cpustats(void)
1089 {
1090 	int state, over;
1091 	double lpct, total;
1092 
1093 	total = 0;
1094 	for (state = 0; state < CPUSTATES; ++state)
1095 		total += cur.cp_time[state];
1096 	if (total)
1097 		lpct = 100.0 / total;
1098 	else
1099 		lpct = 0.0;
1100 	over = 0;
1101 	printf(" ");
1102 	percent((cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * lpct, &over);
1103 	printf(" ");
1104 	percent((cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * lpct, &over);
1105 	printf(" ");
1106 	percent(cur.cp_time[CP_IDLE] * lpct, &over);
1107 }
1108 
1109 static void
1110 pcpustats(int ncpus, u_long cpumask, int maxid)
1111 {
1112 	int state, i;
1113 	double lpct, total;
1114 	long tmp;
1115 	int over;
1116 
1117 	/* devstats does this for cp_time */
1118 	for (i = 0; i <= maxid; i++) {
1119 		if ((cpumask & (1ul << i)) == 0)
1120 			continue;
1121 		for (state = 0; state < CPUSTATES; ++state) {
1122 			tmp = cur_cp_times[i * CPUSTATES + state];
1123 			cur_cp_times[i * CPUSTATES + state] -= last_cp_times[i * CPUSTATES + state];
1124 			last_cp_times[i * CPUSTATES + state] = tmp;
1125 		}
1126 	}
1127 
1128 	over = 0;
1129 	for (i = 0; i <= maxid; i++) {
1130 		if ((cpumask & (1ul << i)) == 0)
1131 			continue;
1132 		total = 0;
1133 		for (state = 0; state < CPUSTATES; ++state)
1134 			total += cur_cp_times[i * CPUSTATES + state];
1135 		if (total)
1136 			lpct = 100.0 / total;
1137 		else
1138 			lpct = 0.0;
1139 		printf(" ");
1140 		percent((cur_cp_times[i * CPUSTATES + CP_USER] +
1141 			 cur_cp_times[i * CPUSTATES + CP_NICE]) * lpct, &over);
1142 		printf(" ");
1143 		percent((cur_cp_times[i * CPUSTATES + CP_SYS] +
1144 			 cur_cp_times[i * CPUSTATES + CP_INTR]) * lpct, &over);
1145 		printf(" ");
1146 		percent(cur_cp_times[i * CPUSTATES + CP_IDLE] * lpct, &over);
1147 	}
1148 }
1149 
1150 static void
1151 dointr(void)
1152 {
1153 	unsigned long *intrcnt, uptime;
1154 	uint64_t inttotal;
1155 	size_t clen, inamlen, intrcntlen, istrnamlen;
1156 	unsigned int i, nintr;
1157 	char *intrname, *tintrname;
1158 
1159 	uptime = getuptime();
1160 	if (kd != NULL) {
1161 		intrcntlen = namelist[X_EINTRCNT].n_value -
1162 		    namelist[X_INTRCNT].n_value;
1163 		inamlen = namelist[X_EINTRNAMES].n_value -
1164 		    namelist[X_INTRNAMES].n_value;
1165 		if ((intrcnt = malloc(intrcntlen)) == NULL ||
1166 		    (intrname = malloc(inamlen)) == NULL)
1167 			err(1, "malloc()");
1168 		kread(X_INTRCNT, intrcnt, intrcntlen);
1169 		kread(X_INTRNAMES, intrname, inamlen);
1170 	} else {
1171 		for (intrcnt = NULL, intrcntlen = 1024; ; intrcntlen *= 2) {
1172 			if ((intrcnt = reallocf(intrcnt, intrcntlen)) == NULL)
1173 				err(1, "reallocf()");
1174 			if (mysysctl("hw.intrcnt",
1175 			    intrcnt, &intrcntlen, NULL, 0) == 0)
1176 				break;
1177 		}
1178 		for (intrname = NULL, inamlen = 1024; ; inamlen *= 2) {
1179 			if ((intrname = reallocf(intrname, inamlen)) == NULL)
1180 				err(1, "reallocf()");
1181 			if (mysysctl("hw.intrnames",
1182 			    intrname, &inamlen, NULL, 0) == 0)
1183 				break;
1184 		}
1185 	}
1186 	nintr = intrcntlen / sizeof(unsigned long);
1187 	tintrname = intrname;
1188 	istrnamlen = strlen("interrupt");
1189 	for (i = 0; i < nintr; i++) {
1190 		clen = strlen(tintrname);
1191 		if (clen > istrnamlen)
1192 			istrnamlen = clen;
1193 		tintrname += clen + 1;
1194 	}
1195 	(void)printf("%-*s %20s %10s\n", istrnamlen, "interrupt", "total",
1196 	    "rate");
1197 	inttotal = 0;
1198 	for (i = 0; i < nintr; i++) {
1199 		if (intrname[0] != '\0' && (*intrcnt != 0 || aflag))
1200 			(void)printf("%-*s %20lu %10lu\n", istrnamlen, intrname,
1201 			    *intrcnt, *intrcnt / uptime);
1202 		intrname += strlen(intrname) + 1;
1203 		inttotal += *intrcnt++;
1204 	}
1205 	(void)printf("%-*s %20llu %10llu\n", istrnamlen, "Total",
1206 	    (long long)inttotal, (long long)(inttotal / uptime));
1207 }
1208 
1209 static void
1210 domemstat_malloc(void)
1211 {
1212 	struct memory_type_list *mtlp;
1213 	struct memory_type *mtp;
1214 	int error, first, i;
1215 
1216 	mtlp = memstat_mtl_alloc();
1217 	if (mtlp == NULL) {
1218 		warn("memstat_mtl_alloc");
1219 		return;
1220 	}
1221 	if (kd == NULL) {
1222 		if (memstat_sysctl_malloc(mtlp, 0) < 0) {
1223 			warnx("memstat_sysctl_malloc: %s",
1224 			    memstat_strerror(memstat_mtl_geterror(mtlp)));
1225 			return;
1226 		}
1227 	} else {
1228 		if (memstat_kvm_malloc(mtlp, kd) < 0) {
1229 			error = memstat_mtl_geterror(mtlp);
1230 			if (error == MEMSTAT_ERROR_KVM)
1231 				warnx("memstat_kvm_malloc: %s",
1232 				    kvm_geterr(kd));
1233 			else
1234 				warnx("memstat_kvm_malloc: %s",
1235 				    memstat_strerror(error));
1236 		}
1237 	}
1238 	printf("%13s %5s %6s %7s %8s  Size(s)\n", "Type", "InUse", "MemUse",
1239 	    "HighUse", "Requests");
1240 	for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
1241 	    mtp = memstat_mtl_next(mtp)) {
1242 		if (memstat_get_numallocs(mtp) == 0 &&
1243 		    memstat_get_count(mtp) == 0)
1244 			continue;
1245 		printf("%13s %5lld %5lldK %7s %8lld  ",
1246 		    memstat_get_name(mtp), memstat_get_count(mtp),
1247 		    ((int64_t)memstat_get_bytes(mtp) + 1023) / 1024, "-",
1248 		    memstat_get_numallocs(mtp));
1249 		first = 1;
1250 		for (i = 0; i < 32; i++) {
1251 			if (memstat_get_sizemask(mtp) & (1 << i)) {
1252 				if (!first)
1253 					printf(",");
1254 				printf("%d", 1 << (i + 4));
1255 				first = 0;
1256 			}
1257 		}
1258 		printf("\n");
1259 	}
1260 	memstat_mtl_free(mtlp);
1261 }
1262 
1263 static void
1264 domemstat_zone(void)
1265 {
1266 	struct memory_type_list *mtlp;
1267 	struct memory_type *mtp;
1268 	char name[MEMTYPE_MAXNAME + 1];
1269 	int error;
1270 
1271 	mtlp = memstat_mtl_alloc();
1272 	if (mtlp == NULL) {
1273 		warn("memstat_mtl_alloc");
1274 		return;
1275 	}
1276 	if (kd == NULL) {
1277 		if (memstat_sysctl_uma(mtlp, 0) < 0) {
1278 			warnx("memstat_sysctl_uma: %s",
1279 			    memstat_strerror(memstat_mtl_geterror(mtlp)));
1280 			return;
1281 		}
1282 	} else {
1283 		if (memstat_kvm_uma(mtlp, kd) < 0) {
1284 			error = memstat_mtl_geterror(mtlp);
1285 			if (error == MEMSTAT_ERROR_KVM)
1286 				warnx("memstat_kvm_uma: %s",
1287 				    kvm_geterr(kd));
1288 			else
1289 				warnx("memstat_kvm_uma: %s",
1290 				    memstat_strerror(error));
1291 		}
1292 	}
1293 	printf("%-20s %6s %6s %8s %8s %8s %4s %4s\n\n", "ITEM", "SIZE",
1294 	    "LIMIT", "USED", "FREE", "REQ", "FAIL", "SLEEP");
1295 	for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
1296 	    mtp = memstat_mtl_next(mtp)) {
1297 		strlcpy(name, memstat_get_name(mtp), MEMTYPE_MAXNAME);
1298 		strcat(name, ":");
1299 		printf("%-20s %6llu, %6llu,%8llu,%8llu,%8llu,%4llu,%4llu\n",name,
1300 		    memstat_get_size(mtp), memstat_get_countlimit(mtp),
1301 		    memstat_get_count(mtp), memstat_get_free(mtp),
1302 		    memstat_get_numallocs(mtp), memstat_get_failures(mtp),
1303 		    memstat_get_sleeps(mtp));
1304 	}
1305 	memstat_mtl_free(mtlp);
1306 	printf("\n");
1307 }
1308 
1309 /*
1310  * kread reads something from the kernel, given its nlist index.
1311  */
1312 static void
1313 kreado(int nlx, void *addr, size_t size, size_t offset)
1314 {
1315 	const char *sym;
1316 
1317 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
1318 		sym = namelist[nlx].n_name;
1319 		if (*sym == '_')
1320 			++sym;
1321 		errx(1, "symbol %s not defined", sym);
1322 	}
1323 	if ((size_t)kvm_read(kd, namelist[nlx].n_value + offset, addr,
1324 	    size) != size) {
1325 		sym = namelist[nlx].n_name;
1326 		if (*sym == '_')
1327 			++sym;
1328 		errx(1, "%s: %s", sym, kvm_geterr(kd));
1329 	}
1330 }
1331 
1332 static void
1333 kread(int nlx, void *addr, size_t size)
1334 {
1335 	kreado(nlx, addr, size, 0);
1336 }
1337 
1338 static char *
1339 kgetstr(const char *strp)
1340 {
1341 	int n = 0, size = 1;
1342 	char *ret = NULL;
1343 
1344 	do {
1345 		if (size == n + 1) {
1346 			ret = realloc(ret, size);
1347 			if (ret == NULL)
1348 				err(1, "%s: realloc", __func__);
1349 			size *= 2;
1350 		}
1351 		if (kvm_read(kd, (u_long)strp + n, &ret[n], 1) != 1)
1352 			errx(1, "%s: %s", __func__, kvm_geterr(kd));
1353 	} while (ret[n++] != '\0');
1354 	return (ret);
1355 }
1356 
1357 static void
1358 usage(void)
1359 {
1360 	(void)fprintf(stderr, "%s%s",
1361 		"usage: vmstat [-afHhimPsz] [-c count] [-M core [-N system]] [-w wait]\n",
1362 		"              [-n devs] [-p type,if,pass] [disks]\n");
1363 	exit(1);
1364 }
1365