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