xref: /freebsd/usr.bin/vmstat/vmstat.c (revision fd5aaf2ea0178b03aa93c35245053247e5d3840c)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1980, 1986, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 #ifndef lint
33 static const char copyright[] =
34 "@(#) Copyright (c) 1980, 1986, 1991, 1993\n\
35 	The Regents of the University of California.  All rights reserved.\n";
36 #endif /* not lint */
37 
38 #if 0
39 #ifndef lint
40 static char sccsid[] = "@(#)vmstat.c	8.1 (Berkeley) 6/6/93";
41 #endif /* not lint */
42 #endif
43 
44 #include <sys/cdefs.h>
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/user.h>
57 #define	_WANT_VMMETER
58 #include <sys/vmmeter.h>
59 #include <sys/pcpu.h>
60 
61 #include <vm/vm_param.h>
62 
63 #include <ctype.h>
64 #include <devstat.h>
65 #include <err.h>
66 #include <errno.h>
67 #include <inttypes.h>
68 #include <kvm.h>
69 #include <limits.h>
70 #include <memstat.h>
71 #include <nlist.h>
72 #include <paths.h>
73 #include <stdio.h>
74 #include <stdlib.h>
75 #include <string.h>
76 #include <sysexits.h>
77 #include <time.h>
78 #include <unistd.h>
79 #include <libutil.h>
80 #include <libxo/xo.h>
81 
82 #define VMSTAT_XO_VERSION "1"
83 
84 static char da[] = "da";
85 
86 enum x_stats { X_SUM, X_HZ, X_STATHZ, X_NCHSTATS, X_INTRNAMES, X_SINTRNAMES,
87     X_INTRCNT, X_SINTRCNT, X_NINTRCNT };
88 
89 static struct nlist namelist[] = {
90 	[X_SUM] = { .n_name = "_vm_cnt", },
91 	[X_HZ] = { .n_name = "_hz", },
92 	[X_STATHZ] = { .n_name = "_stathz", },
93 	[X_NCHSTATS] = { .n_name = "_nchstats", },
94 	[X_INTRNAMES] = { .n_name = "_intrnames", },
95 	[X_SINTRNAMES] = { .n_name = "_sintrnames", },
96 	[X_INTRCNT] = { .n_name = "_intrcnt", },
97 	[X_SINTRCNT] = { .n_name = "_sintrcnt", },
98 	[X_NINTRCNT] = { .n_name = "_nintrcnt", },
99 	{ .n_name = NULL, },
100 };
101 
102 static struct devstat_match *matches;
103 static struct device_selection *dev_select;
104 static struct statinfo cur, last;
105 static devstat_select_mode select_mode;
106 static size_t size_cp_times;
107 static long *cur_cp_times, *last_cp_times;
108 static long generation, select_generation;
109 static int hz, hdrcnt, maxshowdevs;
110 static int num_devices, num_devices_specified;
111 static int num_matches, num_selected, num_selections;
112 static char **specified_devices;
113 
114 static struct __vmmeter {
115 	uint64_t v_swtch;
116 	uint64_t v_trap;
117 	uint64_t v_syscall;
118 	uint64_t v_intr;
119 	uint64_t v_soft;
120 	uint64_t v_vm_faults;
121 	uint64_t v_io_faults;
122 	uint64_t v_cow_faults;
123 	uint64_t v_cow_optim;
124 	uint64_t v_zfod;
125 	uint64_t v_ozfod;
126 	uint64_t v_swapin;
127 	uint64_t v_swapout;
128 	uint64_t v_swappgsin;
129 	uint64_t v_swappgsout;
130 	uint64_t v_vnodein;
131 	uint64_t v_vnodeout;
132 	uint64_t v_vnodepgsin;
133 	uint64_t v_vnodepgsout;
134 	uint64_t v_intrans;
135 	uint64_t v_reactivated;
136 	uint64_t v_pdwakeups;
137 	uint64_t v_pdpages;
138 	uint64_t v_pdshortfalls;
139 	uint64_t v_dfree;
140 	uint64_t v_pfree;
141 	uint64_t v_tfree;
142 	uint64_t v_forks;
143 	uint64_t v_vforks;
144 	uint64_t v_rforks;
145 	uint64_t v_kthreads;
146 	uint64_t v_forkpages;
147 	uint64_t v_vforkpages;
148 	uint64_t v_rforkpages;
149 	uint64_t v_kthreadpages;
150 	u_int v_page_size;
151 	u_int v_page_count;
152 	u_int v_free_reserved;
153 	u_int v_free_target;
154 	u_int v_free_min;
155 	u_int v_free_count;
156 	u_int v_wire_count;
157 	u_long v_user_wire_count;
158 	u_int v_active_count;
159 	u_int v_inactive_target;
160 	u_int v_inactive_count;
161 	u_int v_laundry_count;
162 	u_int v_pageout_free_min;
163 	u_int v_interrupt_free_min;
164 	u_int v_free_severe;
165 } sum, osum;
166 
167 #define	VMSTAT_DEFAULT_LINES	20	/* Default number of `winlines'. */
168 static volatile sig_atomic_t wresized;		/* Tty resized when non-zero. */
169 static int winlines = VMSTAT_DEFAULT_LINES; /* Current number of tty rows. */
170 
171 static int	aflag;
172 static int	nflag;
173 static int	Pflag;
174 static int	hflag;
175 
176 static kvm_t	*kd;
177 
178 #define	FORKSTAT	0x01
179 #define	INTRSTAT	0x02
180 #define	MEMSTAT		0x04
181 #define	SUMSTAT		0x08
182 #define	TIMESTAT	0x10
183 #define	VMSTAT		0x20
184 #define	ZMEMSTAT	0x40
185 #define	OBJSTAT		0x80
186 
187 static void	cpustats(void);
188 static void	pcpustats(u_long, int);
189 static void	devstats(void);
190 static void	doforkst(void);
191 static void	dointr(unsigned int, int);
192 static void	doobjstat(void);
193 static void	dosum(void);
194 static void	dovmstat(unsigned int, int);
195 static void	domemstat_malloc(void);
196 static void	domemstat_zone(void);
197 static void	kread(int, void *, size_t);
198 static void	kreado(int, void *, size_t, size_t);
199 static void	kreadptr(uintptr_t, void *, size_t);
200 static void	needhdr(int);
201 static void	needresize(int);
202 static void	doresize(void);
203 static void	printhdr(int, u_long);
204 static void	usage(void);
205 
206 static long	pct(long, long);
207 static long long	getuptime(void);
208 
209 static char	**getdrivedata(char **);
210 
211 int
212 main(int argc, char *argv[])
213 {
214 	char *bp, *buf, *memf, *nlistf;
215 	float f;
216 	int bufsize, c, reps, todo;
217 	size_t len;
218 	unsigned int interval;
219 	char errbuf[_POSIX2_LINE_MAX];
220 
221 	memf = nlistf = NULL;
222 	interval = reps = todo = 0;
223 	maxshowdevs = 2;
224 
225 	argc = xo_parse_args(argc, argv);
226 	if (argc < 0)
227 		return (argc);
228 
229 	hflag = (xo_get_style(NULL) == XO_STYLE_TEXT) && isatty(1);
230 
231 	while ((c = getopt(argc, argv, "ac:fhHiM:mN:n:oPp:sw:z")) != -1) {
232 		switch (c) {
233 		case 'a':
234 			aflag++;
235 			break;
236 		case 'c':
237 			reps = atoi(optarg);
238 			break;
239 		case 'P':
240 			Pflag++;
241 			break;
242 		case 'f':
243 			todo |= FORKSTAT;
244 			break;
245 		case 'h':
246 			hflag = 1;
247 			break;
248 		case 'H':
249 			hflag = 0;
250 			break;
251 		case 'i':
252 			todo |= INTRSTAT;
253 			break;
254 		case 'M':
255 			memf = optarg;
256 			break;
257 		case 'm':
258 			todo |= MEMSTAT;
259 			break;
260 		case 'N':
261 			nlistf = optarg;
262 			break;
263 		case 'n':
264 			nflag = 1;
265 			maxshowdevs = atoi(optarg);
266 			if (maxshowdevs < 0)
267 				xo_errx(1, "number of devices %d is < 0",
268 				    maxshowdevs);
269 			break;
270 		case 'o':
271 			todo |= OBJSTAT;
272 			break;
273 		case 'p':
274 			if (devstat_buildmatch(optarg, &matches, &num_matches)
275 			    != 0)
276 				xo_errx(1, "%s", devstat_errbuf);
277 			break;
278 		case 's':
279 			todo |= SUMSTAT;
280 			break;
281 		case 'w':
282 			/* Convert to milliseconds. */
283 			f = atof(optarg);
284 			interval = f * 1000;
285 			break;
286 		case 'z':
287 			todo |= ZMEMSTAT;
288 			break;
289 		case '?':
290 		default:
291 			usage();
292 		}
293 	}
294 	argc -= optind;
295 	argv += optind;
296 
297 	xo_set_version(VMSTAT_XO_VERSION);
298 	if (todo == 0)
299 		todo = VMSTAT;
300 
301 	if (memf != NULL) {
302 		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
303 		if (kd == NULL)
304 			xo_errx(1, "kvm_openfiles: %s", errbuf);
305 	}
306 
307 retry_nlist:
308 	if (kd != NULL && (c = kvm_nlist(kd, namelist)) != 0) {
309 		if (c > 0) {
310 			bufsize = 0;
311 			len = 0;
312 
313 			/*
314 			 * 'cnt' was renamed to 'vm_cnt'.  If 'vm_cnt' is not
315 			 * found try looking up older 'cnt' symbol.
316 			 * */
317 			if (namelist[X_SUM].n_type == 0 &&
318 			    strcmp(namelist[X_SUM].n_name, "_vm_cnt") == 0) {
319 				namelist[X_SUM].n_name = "_cnt";
320 				goto retry_nlist;
321 			}
322 
323 			/*
324 			 * 'nintrcnt' doesn't exist in older kernels, but
325 			 * that isn't fatal.
326 			 */
327 			if (namelist[X_NINTRCNT].n_type == 0 && c == 1)
328 				goto nlist_ok;
329 
330 			for (c = 0; c < (int)(nitems(namelist)); c++)
331 				if (namelist[c].n_type == 0)
332 					bufsize += strlen(namelist[c].n_name)
333 					    + 1;
334 			bufsize += len + 1;
335 			buf = bp = alloca(bufsize);
336 
337 			for (c = 0; c < (int)(nitems(namelist)); c++)
338 				if (namelist[c].n_type == 0) {
339 					xo_error(" %s",
340 					    namelist[c].n_name);
341 					len = strlen(namelist[c].n_name);
342 					*bp++ = ' ';
343 					memcpy(bp, namelist[c].n_name, len);
344 					bp += len;
345 				}
346 			*bp = '\0';
347 			xo_error("undefined symbols:\n", buf);
348 		} else
349 			xo_warnx("kvm_nlist: %s", kvm_geterr(kd));
350 		xo_finish();
351 		exit(1);
352 	}
353 nlist_ok:
354 	if (kd && Pflag)
355 		xo_errx(1, "Cannot use -P with crash dumps");
356 
357 	if (todo & VMSTAT) {
358 		/*
359 		 * Make sure that the userland devstat version matches the
360 		 * kernel devstat version.  If not, exit and print a
361 		 * message informing the user of his mistake.
362 		 */
363 		if (devstat_checkversion(NULL) < 0)
364 			xo_errx(1, "%s", devstat_errbuf);
365 
366 
367 		argv = getdrivedata(argv);
368 	}
369 
370 	if (*argv) {
371 		f = atof(*argv);
372 		interval = f * 1000;
373 		if (*++argv)
374 			reps = atoi(*argv);
375 	}
376 
377 	if (interval) {
378 		if (!reps)
379 			reps = -1;
380 	} else if (reps)
381 		interval = 1 * 1000;
382 
383 	if (todo & FORKSTAT)
384 		doforkst();
385 	if (todo & MEMSTAT)
386 		domemstat_malloc();
387 	if (todo & ZMEMSTAT)
388 		domemstat_zone();
389 	if (todo & SUMSTAT)
390 		dosum();
391 	if (todo & OBJSTAT)
392 		doobjstat();
393 	if (todo & INTRSTAT)
394 		dointr(interval, reps);
395 	if (todo & VMSTAT)
396 		dovmstat(interval, reps);
397 	xo_finish();
398 	exit(0);
399 }
400 
401 static int
402 mysysctl(const char *name, void *oldp, size_t *oldlenp)
403 {
404 	int error;
405 
406 	error = sysctlbyname(name, oldp, oldlenp, NULL, 0);
407 	if (error != 0 && errno != ENOMEM)
408 		xo_err(1, "sysctl(%s)", name);
409 	return (error);
410 }
411 
412 static char **
413 getdrivedata(char **argv)
414 {
415 
416 	if ((num_devices = devstat_getnumdevs(NULL)) < 0)
417 		xo_errx(1, "%s", devstat_errbuf);
418 
419 	cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
420 	last.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo));
421 
422 	if (devstat_getdevs(NULL, &cur) == -1)
423 		xo_errx(1, "%s", devstat_errbuf);
424 
425 	num_devices = cur.dinfo->numdevs;
426 	generation = cur.dinfo->generation;
427 
428 	specified_devices = malloc(sizeof(char *));
429 	for (num_devices_specified = 0; *argv; ++argv) {
430 		if (isdigit(**argv))
431 			break;
432 		num_devices_specified++;
433 		specified_devices = reallocf(specified_devices,
434 		    sizeof(char *) * num_devices_specified);
435 		if (specified_devices == NULL) {
436 			xo_errx(1, "%s", "reallocf (specified_devices)");
437 		}
438 		specified_devices[num_devices_specified - 1] = *argv;
439 	}
440 	dev_select = NULL;
441 
442 	if (nflag == 0 && maxshowdevs < num_devices_specified)
443 		maxshowdevs = num_devices_specified;
444 
445 	/*
446 	 * People are generally only interested in disk statistics when
447 	 * they're running vmstat.  So, that's what we're going to give
448 	 * them if they don't specify anything by default.  We'll also give
449 	 * them any other random devices in the system so that we get to
450 	 * maxshowdevs devices, if that many devices exist.  If the user
451 	 * specifies devices on the command line, either through a pattern
452 	 * match or by naming them explicitly, we will give the user only
453 	 * those devices.
454 	 */
455 	if ((num_devices_specified == 0) && (num_matches == 0)) {
456 		if (devstat_buildmatch(da, &matches, &num_matches) != 0)
457 			xo_errx(1, "%s", devstat_errbuf);
458 		select_mode = DS_SELECT_ADD;
459 	} else
460 		select_mode = DS_SELECT_ONLY;
461 
462 	/*
463 	 * At this point, selectdevs will almost surely indicate that the
464 	 * device list has changed, so we don't look for return values of 0
465 	 * or 1.  If we get back -1, though, there is an error.
466 	 */
467 	if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
468 	    &select_generation, generation, cur.dinfo->devices,
469 	    num_devices, matches, num_matches, specified_devices,
470 	    num_devices_specified, select_mode,
471 	    maxshowdevs, 0) == -1)
472 		xo_errx(1, "%s", devstat_errbuf);
473 
474 	return(argv);
475 }
476 
477 /* Return system uptime in nanoseconds */
478 static long long
479 getuptime(void)
480 {
481 	struct timespec sp;
482 
483 	(void)clock_gettime(CLOCK_UPTIME, &sp);
484 	return((long long)sp.tv_sec * 1000000000LL + sp.tv_nsec);
485 }
486 
487 static void
488 fill_vmmeter(struct __vmmeter *vmmp)
489 {
490 	struct vmmeter vm_cnt;
491 	size_t size;
492 
493 	if (kd != NULL) {
494 		kread(X_SUM, &vm_cnt, sizeof(vm_cnt));
495 #define	GET_COUNTER(name) \
496 		vmmp->name = kvm_counter_u64_fetch(kd, (u_long)vm_cnt.name)
497 		GET_COUNTER(v_swtch);
498 		GET_COUNTER(v_trap);
499 		GET_COUNTER(v_syscall);
500 		GET_COUNTER(v_intr);
501 		GET_COUNTER(v_soft);
502 		GET_COUNTER(v_vm_faults);
503 		GET_COUNTER(v_io_faults);
504 		GET_COUNTER(v_cow_faults);
505 		GET_COUNTER(v_cow_optim);
506 		GET_COUNTER(v_zfod);
507 		GET_COUNTER(v_ozfod);
508 		GET_COUNTER(v_swapin);
509 		GET_COUNTER(v_swapout);
510 		GET_COUNTER(v_swappgsin);
511 		GET_COUNTER(v_swappgsout);
512 		GET_COUNTER(v_vnodein);
513 		GET_COUNTER(v_vnodeout);
514 		GET_COUNTER(v_vnodepgsin);
515 		GET_COUNTER(v_vnodepgsout);
516 		GET_COUNTER(v_intrans);
517 		GET_COUNTER(v_tfree);
518 		GET_COUNTER(v_forks);
519 		GET_COUNTER(v_vforks);
520 		GET_COUNTER(v_rforks);
521 		GET_COUNTER(v_kthreads);
522 		GET_COUNTER(v_forkpages);
523 		GET_COUNTER(v_vforkpages);
524 		GET_COUNTER(v_rforkpages);
525 		GET_COUNTER(v_kthreadpages);
526 #undef GET_COUNTER
527 	} else {
528 #define GET_VM_STATS(cat, name)	do {					\
529 	size = sizeof(vmmp->name);					\
530 	mysysctl("vm.stats." #cat "." #name, &vmmp->name, &size);	\
531 } while (0)
532 		/* sys */
533 		GET_VM_STATS(sys, v_swtch);
534 		GET_VM_STATS(sys, v_trap);
535 		GET_VM_STATS(sys, v_syscall);
536 		GET_VM_STATS(sys, v_intr);
537 		GET_VM_STATS(sys, v_soft);
538 
539 		/* vm */
540 		GET_VM_STATS(vm, v_vm_faults);
541 		GET_VM_STATS(vm, v_io_faults);
542 		GET_VM_STATS(vm, v_cow_faults);
543 		GET_VM_STATS(vm, v_cow_optim);
544 		GET_VM_STATS(vm, v_zfod);
545 		GET_VM_STATS(vm, v_ozfod);
546 		GET_VM_STATS(vm, v_swapin);
547 		GET_VM_STATS(vm, v_swapout);
548 		GET_VM_STATS(vm, v_swappgsin);
549 		GET_VM_STATS(vm, v_swappgsout);
550 		GET_VM_STATS(vm, v_vnodein);
551 		GET_VM_STATS(vm, v_vnodeout);
552 		GET_VM_STATS(vm, v_vnodepgsin);
553 		GET_VM_STATS(vm, v_vnodepgsout);
554 		GET_VM_STATS(vm, v_intrans);
555 		GET_VM_STATS(vm, v_reactivated);
556 		GET_VM_STATS(vm, v_pdwakeups);
557 		GET_VM_STATS(vm, v_pdpages);
558 		GET_VM_STATS(vm, v_pdshortfalls);
559 		GET_VM_STATS(vm, v_dfree);
560 		GET_VM_STATS(vm, v_pfree);
561 		GET_VM_STATS(vm, v_tfree);
562 		GET_VM_STATS(vm, v_page_size);
563 		GET_VM_STATS(vm, v_page_count);
564 		GET_VM_STATS(vm, v_free_reserved);
565 		GET_VM_STATS(vm, v_free_target);
566 		GET_VM_STATS(vm, v_free_min);
567 		GET_VM_STATS(vm, v_free_count);
568 		GET_VM_STATS(vm, v_wire_count);
569 		GET_VM_STATS(vm, v_user_wire_count);
570 		GET_VM_STATS(vm, v_active_count);
571 		GET_VM_STATS(vm, v_inactive_target);
572 		GET_VM_STATS(vm, v_inactive_count);
573 		GET_VM_STATS(vm, v_laundry_count);
574 		GET_VM_STATS(vm, v_pageout_free_min);
575 		GET_VM_STATS(vm, v_interrupt_free_min);
576 		/*GET_VM_STATS(vm, v_free_severe);*/
577 		GET_VM_STATS(vm, v_forks);
578 		GET_VM_STATS(vm, v_vforks);
579 		GET_VM_STATS(vm, v_rforks);
580 		GET_VM_STATS(vm, v_kthreads);
581 		GET_VM_STATS(vm, v_forkpages);
582 		GET_VM_STATS(vm, v_vforkpages);
583 		GET_VM_STATS(vm, v_rforkpages);
584 		GET_VM_STATS(vm, v_kthreadpages);
585 #undef GET_VM_STATS
586 	}
587 }
588 
589 static void
590 fill_vmtotal(struct vmtotal *vmtp)
591 {
592 	size_t size;
593 
594 	if (kd != NULL) {
595 		/* XXX fill vmtp */
596 		xo_errx(1, "not implemented");
597 	} else {
598 		size = sizeof(*vmtp);
599 		mysysctl("vm.vmtotal", vmtp, &size);
600 		if (size != sizeof(*vmtp))
601 			xo_errx(1, "vm.total size mismatch");
602 	}
603 }
604 
605 /* Determine how many cpu columns, and what index they are in kern.cp_times */
606 static void
607 getcpuinfo(u_long *maskp, int *maxidp)
608 {
609 	long *times;
610 	u_long mask;
611 	size_t size;
612 	int empty, i, j, maxcpu, maxid;
613 
614 	if (kd != NULL)
615 		xo_errx(1, "not implemented");
616 	mask = 0;
617 	size = sizeof(maxcpu);
618 	mysysctl("kern.smp.maxcpus", &maxcpu, &size);
619 	if (size != sizeof(maxcpu))
620 		xo_errx(1, "sysctl kern.smp.maxcpus");
621 	size = sizeof(long) * maxcpu * CPUSTATES;
622 	times = malloc(size);
623 	if (times == NULL)
624 		xo_err(1, "malloc %zd bytes", size);
625 	mysysctl("kern.cp_times", times, &size);
626 	maxid = (size / CPUSTATES / sizeof(long)) - 1;
627 	for (i = 0; i <= maxid; i++) {
628 		empty = 1;
629 		for (j = 0; empty && j < CPUSTATES; j++) {
630 			if (times[i * CPUSTATES + j] != 0)
631 				empty = 0;
632 		}
633 		if (!empty)
634 			mask |= (1ul << i);
635 	}
636 	if (maskp)
637 		*maskp = mask;
638 	if (maxidp)
639 		*maxidp = maxid;
640 }
641 
642 
643 static void
644 prthuman(const char *name, uint64_t val, int size, int flags)
645 {
646 	char buf[10];
647 	char fmt[128];
648 
649 	snprintf(fmt, sizeof(fmt), "{:%s/%%*s}", name);
650 
651 	if (size < 5 || size > 9)
652 		xo_errx(1, "doofus");
653 	flags |= HN_NOSPACE | HN_DECIMAL;
654 	humanize_number(buf, size, val, "", HN_AUTOSCALE, flags);
655 	xo_attr("value", "%ju", (uintmax_t) val);
656 	xo_emit(fmt, size, buf);
657 }
658 
659 static void
660 dovmstat(unsigned int interval, int reps)
661 {
662 	struct clockinfo clockrate;
663 	struct vmtotal total;
664 	struct devinfo *tmp_dinfo;
665 	u_long cpumask;
666 	size_t size;
667 	time_t uptime, halfuptime;
668 	int maxid, rate_adj, retval;
669 
670 	uptime = getuptime() / 1000000000LL;
671 	halfuptime = uptime / 2;
672 	rate_adj = 1;
673 	maxid = 0;
674 	cpumask = 0;
675 
676 	/*
677 	 * If the user stops the program (control-Z) and then resumes it,
678 	 * print out the header again.
679 	 */
680 	(void)signal(SIGCONT, needhdr);
681 
682 	/*
683 	 * If our standard output is a tty, then install a SIGWINCH handler
684 	 * and set wresized so that our first iteration through the main
685 	 * vmstat loop will peek at the terminal's current rows to find out
686 	 * how many lines can fit in a screenful of output.
687 	 */
688 	if (isatty(fileno(stdout)) != 0) {
689 		wresized = 1;
690 		(void)signal(SIGWINCH, needresize);
691 	} else {
692 		wresized = 0;
693 		winlines = VMSTAT_DEFAULT_LINES;
694 	}
695 
696 	if (kd != NULL) {
697 		if (namelist[X_STATHZ].n_type != 0 &&
698 		    namelist[X_STATHZ].n_value != 0)
699 			kread(X_STATHZ, &hz, sizeof(hz));
700 		if (!hz)
701 			kread(X_HZ, &hz, sizeof(hz));
702 	} else {
703 		size = sizeof(clockrate);
704 		mysysctl("kern.clockrate", &clockrate, &size);
705 		if (size != sizeof(clockrate))
706 			xo_errx(1, "clockrate size mismatch");
707 		hz = clockrate.hz;
708 	}
709 
710 	if (Pflag) {
711 		getcpuinfo(&cpumask, &maxid);
712 		size_cp_times = sizeof(long) * (maxid + 1) * CPUSTATES;
713 		cur_cp_times = calloc(1, size_cp_times);
714 		last_cp_times = calloc(1, size_cp_times);
715 	}
716 	for (hdrcnt = 1;;) {
717 		if (!--hdrcnt)
718 			printhdr(maxid, cpumask);
719 		if (kd != NULL) {
720 			if (kvm_getcptime(kd, cur.cp_time) < 0)
721 				xo_errx(1, "kvm_getcptime: %s", kvm_geterr(kd));
722 		} else {
723 			size = sizeof(cur.cp_time);
724 			mysysctl("kern.cp_time", &cur.cp_time, &size);
725 			if (size != sizeof(cur.cp_time))
726 				xo_errx(1, "cp_time size mismatch");
727 		}
728 		if (Pflag) {
729 			size = size_cp_times;
730 			mysysctl("kern.cp_times", cur_cp_times, &size);
731 			if (size != size_cp_times)
732 				xo_errx(1, "cp_times mismatch");
733 		}
734 
735 		tmp_dinfo = last.dinfo;
736 		last.dinfo = cur.dinfo;
737 		cur.dinfo = tmp_dinfo;
738 		last.snap_time = cur.snap_time;
739 
740 		/*
741 		 * Here what we want to do is refresh our device stats.
742 		 * getdevs() returns 1 when the device list has changed.
743 		 * If the device list has changed, we want to go through
744 		 * the selection process again, in case a device that we
745 		 * were previously displaying has gone away.
746 		 */
747 		switch (devstat_getdevs(NULL, &cur)) {
748 		case -1:
749 			xo_errx(1, "%s", devstat_errbuf);
750 			break;
751 		case 1:
752 			num_devices = cur.dinfo->numdevs;
753 			generation = cur.dinfo->generation;
754 
755 			retval = devstat_selectdevs(&dev_select, &num_selected,
756 			    &num_selections, &select_generation,
757 			    generation, cur.dinfo->devices,
758 			    num_devices, matches, num_matches,
759 			    specified_devices,
760 			    num_devices_specified, select_mode,
761 			    maxshowdevs, 0);
762 			switch (retval) {
763 			case -1:
764 				xo_errx(1, "%s", devstat_errbuf);
765 				break;
766 			case 1:
767 				printhdr(maxid, cpumask);
768 				break;
769 			default:
770 				break;
771 			}
772 			break;
773 		default:
774 			break;
775 		}
776 
777 		fill_vmmeter(&sum);
778 		fill_vmtotal(&total);
779 		xo_open_container("processes");
780 		xo_emit("{:runnable/%2d} {:waiting/%2ld} "
781 		    "{:swapped-out/%2ld}", total.t_rq - 1, total.t_dw +
782 		    total.t_pw, total.t_sw);
783 		xo_close_container("processes");
784 		xo_open_container("memory");
785 #define vmstat_pgtok(a) ((uintmax_t)(a) * (sum.v_page_size >> 10))
786 #define	rate(x)	(unsigned long)(((x) * rate_adj + halfuptime) / uptime)
787 		if (hflag) {
788 			prthuman("available-memory",
789 			    total.t_avm * (uint64_t)sum.v_page_size, 5, HN_B);
790 			prthuman("free-memory",
791 			    total.t_free * (uint64_t)sum.v_page_size, 5, HN_B);
792 			prthuman("total-page-faults",
793 			    rate(sum.v_vm_faults - osum.v_vm_faults), 5, 0);
794 			xo_emit(" ");
795 		} else {
796 			xo_emit(" ");
797 			xo_emit("{:available-memory/%7ju}",
798 			    vmstat_pgtok(total.t_avm));
799 			xo_emit(" ");
800 			xo_emit("{:free-memory/%7ju}",
801 			    vmstat_pgtok(total.t_free));
802 			xo_emit(" ");
803 			xo_emit("{:total-page-faults/%5lu} ",
804 			    rate(sum.v_vm_faults - osum.v_vm_faults));
805 		}
806 		xo_close_container("memory");
807 
808 		xo_open_container("paging-rates");
809 		xo_emit("{:page-reactivated/%3lu} ",
810 		    rate(sum.v_reactivated - osum.v_reactivated));
811 		xo_emit("{:paged-in/%3lu} ",
812 		    rate(sum.v_swapin + sum.v_vnodein -
813 		    (osum.v_swapin + osum.v_vnodein)));
814 		xo_emit("{:paged-out/%3lu}",
815 		    rate(sum.v_swapout + sum.v_vnodeout -
816 		    (osum.v_swapout + osum.v_vnodeout)));
817 		if (hflag) {
818 			prthuman("freed",
819 			    rate(sum.v_tfree - osum.v_tfree), 5, 0);
820 			prthuman("scanned",
821 			    rate(sum.v_pdpages - osum.v_pdpages), 5, 0);
822 		} else {
823 			xo_emit(" ");
824 			xo_emit("{:freed/%5lu} ",
825 			    rate(sum.v_tfree - osum.v_tfree));
826 			xo_emit("{:scanned/%4lu}",
827 			    rate(sum.v_pdpages - osum.v_pdpages));
828 		}
829 		xo_close_container("paging-rates");
830 
831 		devstats();
832 		xo_open_container("fault-rates");
833 		if (hflag) {
834 			prthuman("interrupts",
835 			    rate(sum.v_intr - osum.v_intr), 5, 0);
836 			prthuman("system-calls",
837 			    rate(sum.v_syscall - osum.v_syscall), 5, 0);
838 			prthuman("context-switches",
839 			    rate(sum.v_swtch - osum.v_swtch), 5, 0);
840 		} else {
841 			xo_emit(" ");
842 			xo_emit("{:interrupts/%4lu} "
843 			    "{:system-calls/%5lu} "
844 			    "{:context-switches/%5lu}",
845 			    rate(sum.v_intr - osum.v_intr),
846 			    rate(sum.v_syscall - osum.v_syscall),
847 			    rate(sum.v_swtch - osum.v_swtch));
848 		}
849 		xo_close_container("fault-rates");
850 		if (Pflag)
851 			pcpustats(cpumask, maxid);
852 		else
853 			cpustats();
854 		xo_emit("\n");
855 		xo_flush();
856 		if (reps >= 0 && --reps <= 0)
857 			break;
858 		osum = sum;
859 		uptime = interval;
860 		rate_adj = 1000;
861 		/*
862 		 * We round upward to avoid losing low-frequency events
863 		 * (i.e., >= 1 per interval but < 1 per millisecond).
864 		 */
865 		if (interval != 1)
866 			halfuptime = (uptime + 1) / 2;
867 		else
868 			halfuptime = 0;
869 		(void)usleep(interval * 1000);
870 	}
871 }
872 
873 static void
874 printhdr(int maxid, u_long cpumask)
875 {
876 	int i, num_shown;
877 
878 	num_shown = MIN(num_selected, maxshowdevs);
879 	if (hflag)
880 		xo_emit(" {T:procs}    {T:memory}    {T:/page%*s}", 19, "");
881 	else
882 		xo_emit("{T:procs}     {T:memory}       {T:/page%*s}", 19, "");
883 	if (num_shown > 1)
884 		xo_emit("   {T:/disks %*s}  ", num_shown * 5 - 7, "");
885 	else if (num_shown == 1)
886 		xo_emit("   {T:disks} ");
887 	xo_emit(" {T:faults}      ");
888 	if (Pflag) {
889 		for (i = 0; i <= maxid; i++) {
890 			if (cpumask & (1ul << i))
891 				xo_emit("  {T:/cpu%d}   ", i);
892 		}
893 		xo_emit("\n");
894 	} else
895 		xo_emit(" {T:cpu}\n");
896 	if (hflag) {
897 		xo_emit(" {T:r}  {T:b}  {T:w}  {T:avm}  {T:fre}  {T:flt}  {T:re}"
898 		    "  {T:pi}  {T:po}   {T:fr}   {T:sr} ");
899 	} else {
900 		xo_emit("{T:r} {T:b} {T:w}     {T:avm}     {T:fre}  {T:flt}  "
901 		    "{T:re}  {T:pi}  {T:po}    {T:fr}   {T:sr} ");
902 	}
903 	for (i = 0; i < num_devices; i++)
904 		if ((dev_select[i].selected) &&
905 		    (dev_select[i].selected <= maxshowdevs))
906 			xo_emit("{T:/%3.3s%d} ", dev_select[i].device_name,
907 			    dev_select[i].unit_number);
908 	xo_emit("  {T:in}   {T:sy}   {T:cs}");
909 	if (Pflag) {
910 		for (i = 0; i <= maxid; i++) {
911 			if (cpumask & (1ul << i))
912 				xo_emit(" {T:us} {T:sy} {T:id}");
913 		}
914 		xo_emit("\n");
915 	} else
916 		xo_emit(" {T:us} {T:sy} {T:id}\n");
917 	if (wresized != 0)
918 		doresize();
919 	hdrcnt = winlines;
920 }
921 
922 /*
923  * Force a header to be prepended to the next output.
924  */
925 static void
926 needhdr(int dummy __unused)
927 {
928 
929 	hdrcnt = 1;
930 }
931 
932 /*
933  * When the terminal is resized, force an update of the maximum number of rows
934  * printed between each header repetition.  Then force a new header to be
935  * prepended to the next output.
936  */
937 void
938 needresize(int signo __unused)
939 {
940 
941 	wresized = 1;
942 	hdrcnt = 1;
943 }
944 
945 /*
946  * Update the global `winlines' count of terminal rows.
947  */
948 void
949 doresize(void)
950 {
951 	struct winsize w;
952 	int status;
953 
954 	for (;;) {
955 		status = ioctl(fileno(stdout), TIOCGWINSZ, &w);
956 		if (status == -1 && errno == EINTR)
957 			continue;
958 		else if (status == -1)
959 			xo_err(1, "ioctl");
960 		if (w.ws_row > 3)
961 			winlines = w.ws_row - 3;
962 		else
963 			winlines = VMSTAT_DEFAULT_LINES;
964 		break;
965 	}
966 
967 	/*
968 	 * Inhibit doresize() calls until we are rescheduled by SIGWINCH.
969 	 */
970 	wresized = 0;
971 }
972 
973 static long
974 pct(long top, long bot)
975 {
976 	long ans;
977 
978 	if (bot == 0)
979 		return(0);
980 	ans = (quad_t)top * 100 / bot;
981 	return (ans);
982 }
983 
984 #define	PCT(top, bot) pct((long)(top), (long)(bot))
985 
986 static void
987 dosum(void)
988 {
989 	struct nchstats lnchstats;
990 	size_t size;
991 	long nchtotal;
992 
993 	fill_vmmeter(&sum);
994 	xo_open_container("summary-statistics");
995 	xo_emit("{:context-switches/%9u} {N:cpu context switches}\n",
996 	    sum.v_swtch);
997 	xo_emit("{:interrupts/%9u} {N:device interrupts}\n",
998 	    sum.v_intr);
999 	xo_emit("{:software-interrupts/%9u} {N:software interrupts}\n",
1000 	    sum.v_soft);
1001 	xo_emit("{:traps/%9u} {N:traps}\n", sum.v_trap);
1002 	xo_emit("{:system-calls/%9u} {N:system calls}\n",
1003 	    sum.v_syscall);
1004 	xo_emit("{:kernel-threads/%9u} {N:kernel threads created}\n",
1005 	    sum.v_kthreads);
1006 	xo_emit("{:forks/%9u} {N: fork() calls}\n", sum.v_forks);
1007 	xo_emit("{:vforks/%9u} {N:vfork() calls}\n",
1008 	    sum.v_vforks);
1009 	xo_emit("{:rforks/%9u} {N:rfork() calls}\n",
1010 	    sum.v_rforks);
1011 	xo_emit("{:swap-ins/%9u} {N:swap pager pageins}\n",
1012 	    sum.v_swapin);
1013 	xo_emit("{:swap-in-pages/%9u} {N:swap pager pages paged in}\n",
1014 	    sum.v_swappgsin);
1015 	xo_emit("{:swap-outs/%9u} {N:swap pager pageouts}\n",
1016 	    sum.v_swapout);
1017 	xo_emit("{:swap-out-pages/%9u} {N:swap pager pages paged out}\n",
1018 	    sum.v_swappgsout);
1019 	xo_emit("{:vnode-page-ins/%9u} {N:vnode pager pageins}\n",
1020 	    sum.v_vnodein);
1021 	xo_emit("{:vnode-page-in-pages/%9u} {N:vnode pager pages paged in}\n",
1022 	    sum.v_vnodepgsin);
1023 	xo_emit("{:vnode-page-outs/%9u} {N:vnode pager pageouts}\n",
1024 	    sum.v_vnodeout);
1025 	xo_emit("{:vnode-page-out-pages/%9u} {N:vnode pager pages paged out}\n",
1026 	    sum.v_vnodepgsout);
1027 	xo_emit("{:page-daemon-wakeups/%9u} {N:page daemon wakeups}\n",
1028 	    sum.v_pdwakeups);
1029 	xo_emit("{:page-daemon-pages/%9u} {N:pages examined by the page "
1030 	    "daemon}\n", sum.v_pdpages);
1031 	xo_emit("{:page-reclamation-shortfalls/%9u} {N:clean page reclamation "
1032 	    "shortfalls}\n", sum.v_pdshortfalls);
1033 	xo_emit("{:reactivated/%9u} {N:pages reactivated by the page daemon}\n",
1034 	    sum.v_reactivated);
1035 	xo_emit("{:copy-on-write-faults/%9u} {N:copy-on-write faults}\n",
1036 	    sum.v_cow_faults);
1037 	xo_emit("{:copy-on-write-optimized-faults/%9u} {N:copy-on-write "
1038 	    "optimized faults}\n", sum.v_cow_optim);
1039 	xo_emit("{:zero-fill-pages/%9u} {N:zero fill pages zeroed}\n",
1040 	    sum.v_zfod);
1041 	xo_emit("{:zero-fill-prezeroed/%9u} {N:zero fill pages prezeroed}\n",
1042 	    sum.v_ozfod);
1043 	xo_emit("{:intransit-blocking/%9u} {N:intransit blocking page faults}\n",
1044 	    sum.v_intrans);
1045 	xo_emit("{:total-faults/%9u} {N:total VM faults taken}\n",
1046 	    sum.v_vm_faults);
1047 	xo_emit("{:faults-requiring-io/%9u} {N:page faults requiring I\\/O}\n",
1048 	    sum.v_io_faults);
1049 	xo_emit("{:faults-from-thread-creation/%9u} {N:pages affected by "
1050 	    "kernel thread creation}\n", sum.v_kthreadpages);
1051 	xo_emit("{:faults-from-fork/%9u} {N:pages affected by  fork}()\n",
1052 	    sum.v_forkpages);
1053 	xo_emit("{:faults-from-vfork/%9u} {N:pages affected by vfork}()\n",
1054 	    sum.v_vforkpages);
1055 	xo_emit("{:pages-rfork/%9u} {N:pages affected by rfork}()\n",
1056 	    sum.v_rforkpages);
1057 	xo_emit("{:pages-freed/%9u} {N:pages freed}\n",
1058 	    sum.v_tfree);
1059 	xo_emit("{:pages-freed-by-daemon/%9u} {N:pages freed by daemon}\n",
1060 	    sum.v_dfree);
1061 	xo_emit("{:pages-freed-on-exit/%9u} {N:pages freed by exiting processes}\n",
1062 	    sum.v_pfree);
1063 	xo_emit("{:active-pages/%9u} {N:pages active}\n",
1064 	    sum.v_active_count);
1065 	xo_emit("{:inactive-pages/%9u} {N:pages inactive}\n",
1066 	    sum.v_inactive_count);
1067 	xo_emit("{:laundry-pages/%9u} {N:pages in the laundry queue}\n",
1068 	    sum.v_laundry_count);
1069 	xo_emit("{:wired-pages/%9u} {N:pages wired down}\n",
1070 	    sum.v_wire_count);
1071 	xo_emit("{:virtual-user-wired-pages/%9lu} {N:virtual user pages wired "
1072 	    "down}\n", sum.v_user_wire_count);
1073 	xo_emit("{:free-pages/%9u} {N:pages free}\n",
1074 	    sum.v_free_count);
1075 	xo_emit("{:bytes-per-page/%9u} {N:bytes per page}\n", sum.v_page_size);
1076 	if (kd != NULL) {
1077 		kread(X_NCHSTATS, &lnchstats, sizeof(lnchstats));
1078 	} else {
1079 		size = sizeof(lnchstats);
1080 		mysysctl("vfs.cache.nchstats", &lnchstats, &size);
1081 		if (size != sizeof(lnchstats))
1082 			xo_errx(1, "vfs.cache.nchstats size mismatch");
1083 	}
1084 	nchtotal = lnchstats.ncs_goodhits + lnchstats.ncs_neghits +
1085 	    lnchstats.ncs_badhits + lnchstats.ncs_falsehits +
1086 	    lnchstats.ncs_miss + lnchstats.ncs_long;
1087 	xo_emit("{:total-name-lookups/%9ld} {N:total name lookups}\n",
1088 	    nchtotal);
1089 	xo_emit("{P:/%9s} {N:cache hits} "
1090 	    "({:positive-cache-hits/%ld}% pos + "
1091 	    "{:negative-cache-hits/%ld}% {N:neg}) "
1092 	    "system {:cache-hit-percent/%ld}% per-directory\n",
1093 	    "", PCT(lnchstats.ncs_goodhits, nchtotal),
1094 	    PCT(lnchstats.ncs_neghits, nchtotal),
1095 	    PCT(lnchstats.ncs_pass2, nchtotal));
1096 	xo_emit("{P:/%9s} {L:deletions} {:deletions/%ld}%, "
1097 	    "{L:falsehits} {:false-hits/%ld}%, "
1098 	    "{L:toolong} {:too-long/%ld}%\n", "",
1099 	    PCT(lnchstats.ncs_badhits, nchtotal),
1100 	    PCT(lnchstats.ncs_falsehits, nchtotal),
1101 	    PCT(lnchstats.ncs_long, nchtotal));
1102 	xo_close_container("summary-statistics");
1103 }
1104 
1105 static void
1106 doforkst(void)
1107 {
1108 
1109 	fill_vmmeter(&sum);
1110 	xo_open_container("fork-statistics");
1111 	xo_emit("{:fork/%u} {N:forks}, {:fork-pages/%u} {N:pages}, "
1112 	    "{L:average} {:fork-average/%.2f}\n",
1113 	    sum.v_forks, sum.v_forkpages,
1114 	    sum.v_forks == 0 ? 0.0 :
1115 	    (double)sum.v_forkpages / sum.v_forks);
1116 	xo_emit("{:vfork/%u} {N:vforks}, {:vfork-pages/%u} {N:pages}, "
1117 	    "{L:average} {:vfork-average/%.2f}\n",
1118 	    sum.v_vforks, sum.v_vforkpages,
1119 	    sum.v_vforks == 0 ? 0.0 :
1120 	    (double)sum.v_vforkpages / sum.v_vforks);
1121 	xo_emit("{:rfork/%u} {N:rforks}, {:rfork-pages/%u} {N:pages}, "
1122 	    "{L:average} {:rfork-average/%.2f}\n",
1123 	    sum.v_rforks, sum.v_rforkpages,
1124 	    sum.v_rforks == 0 ? 0.0 :
1125 	    (double)sum.v_rforkpages / sum.v_rforks);
1126 	xo_close_container("fork-statistics");
1127 }
1128 
1129 static void
1130 devstats(void)
1131 {
1132 	long double busy_seconds, transfers_per_second;
1133 	long tmp;
1134 	int di, dn, state;
1135 
1136 	for (state = 0; state < CPUSTATES; ++state) {
1137 		tmp = cur.cp_time[state];
1138 		cur.cp_time[state] -= last.cp_time[state];
1139 		last.cp_time[state] = tmp;
1140 	}
1141 
1142 	busy_seconds = cur.snap_time - last.snap_time;
1143 
1144 	xo_open_list("device");
1145 	for (dn = 0; dn < num_devices; dn++) {
1146 		if (dev_select[dn].selected == 0 ||
1147 		    dev_select[dn].selected > maxshowdevs)
1148 			continue;
1149 
1150 		di = dev_select[dn].position;
1151 
1152 		if (devstat_compute_statistics(&cur.dinfo->devices[di],
1153 		    &last.dinfo->devices[di], busy_seconds,
1154 		    DSM_TRANSFERS_PER_SECOND, &transfers_per_second,
1155 		    DSM_NONE) != 0)
1156 			xo_errx(1, "%s", devstat_errbuf);
1157 
1158 		xo_open_instance("device");
1159 		xo_emit("{ekq:name/%s%d}",
1160 		    dev_select[dn].device_name,
1161 		    dev_select[dn].unit_number);
1162 		if (hflag) {
1163 			prthuman("transfers", (uint64_t)transfers_per_second,
1164 			    5, HN_DIVISOR_1000);
1165 		} else {
1166 			xo_emit("{:transfers/%3.0Lf}", transfers_per_second);
1167 		}
1168 		xo_close_instance("device");
1169 	}
1170 	xo_close_list("device");
1171 }
1172 
1173 static void
1174 percent(const char *name, double pctv, int *over)
1175 {
1176 	int l;
1177 	char buf[10];
1178 	char fmt[128];
1179 
1180 	snprintf(fmt, sizeof(fmt), " {:%s/%%*s}", name);
1181 	l = snprintf(buf, sizeof(buf), "%.0f", pctv);
1182 	if (l == 1 && *over) {
1183 		xo_emit(fmt, 1, buf);
1184 		(*over)--;
1185 	} else
1186 		xo_emit(fmt, 2, buf);
1187 	if (l > 2)
1188 		(*over)++;
1189 }
1190 
1191 static void
1192 cpustats(void)
1193 {
1194 	double lpct, total;
1195 	int state, over;
1196 
1197 	total = 0;
1198 	for (state = 0; state < CPUSTATES; ++state)
1199 		total += cur.cp_time[state];
1200 	if (total > 0)
1201 		lpct = 100.0 / total;
1202 	else
1203 		lpct = 0.0;
1204 	over = 0;
1205 	xo_open_container("cpu-statistics");
1206 	percent("user", (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * lpct,
1207 	    &over);
1208 	percent("system", (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * lpct,
1209 	    &over);
1210 	percent("idle", cur.cp_time[CP_IDLE] * lpct, &over);
1211 	xo_close_container("cpu-statistics");
1212 }
1213 
1214 static void
1215 pcpustats(u_long cpumask, int maxid)
1216 {
1217 	double lpct, total;
1218 	long tmp;
1219 	int i, over, state;
1220 
1221 	/* devstats does this for cp_time */
1222 	for (i = 0; i <= maxid; i++) {
1223 		if ((cpumask & (1ul << i)) == 0)
1224 			continue;
1225 		for (state = 0; state < CPUSTATES; ++state) {
1226 			tmp = cur_cp_times[i * CPUSTATES + state];
1227 			cur_cp_times[i * CPUSTATES + state] -= last_cp_times[i *
1228 			    CPUSTATES + state];
1229 			last_cp_times[i * CPUSTATES + state] = tmp;
1230 		}
1231 	}
1232 
1233 	over = 0;
1234 	xo_open_list("cpu");
1235 	for (i = 0; i <= maxid; i++) {
1236 		if ((cpumask & (1ul << i)) == 0)
1237 			continue;
1238 		xo_open_instance("cpu");
1239 		xo_emit("{ke:name/%d}", i);
1240 		total = 0;
1241 		for (state = 0; state < CPUSTATES; ++state)
1242 			total += cur_cp_times[i * CPUSTATES + state];
1243 		if (total)
1244 			lpct = 100.0 / total;
1245 		else
1246 			lpct = 0.0;
1247 		percent("user", (cur_cp_times[i * CPUSTATES + CP_USER] +
1248 		    cur_cp_times[i * CPUSTATES + CP_NICE]) * lpct, &over);
1249 		percent("system", (cur_cp_times[i * CPUSTATES + CP_SYS] +
1250 		    cur_cp_times[i * CPUSTATES + CP_INTR]) * lpct, &over);
1251 		percent("idle", cur_cp_times[i * CPUSTATES + CP_IDLE] * lpct,
1252 		    &over);
1253 		xo_close_instance("cpu");
1254 	}
1255 	xo_close_list("cpu");
1256 }
1257 
1258 static unsigned int
1259 read_intrcnts(unsigned long **intrcnts)
1260 {
1261 	size_t intrcntlen;
1262 	uintptr_t kaddr;
1263 
1264 	if (kd != NULL) {
1265 		kread(X_SINTRCNT, &intrcntlen, sizeof(intrcntlen));
1266 		if ((*intrcnts = malloc(intrcntlen)) == NULL)
1267 			err(1, "malloc()");
1268 		if (namelist[X_NINTRCNT].n_type == 0)
1269 			kread(X_INTRCNT, *intrcnts, intrcntlen);
1270 		else {
1271 			kread(X_INTRCNT, &kaddr, sizeof(kaddr));
1272 			kreadptr(kaddr, *intrcnts, intrcntlen);
1273 		}
1274 	} else {
1275 		for (*intrcnts = NULL, intrcntlen = 1024; ; intrcntlen *= 2) {
1276 			*intrcnts = reallocf(*intrcnts, intrcntlen);
1277 			if (*intrcnts == NULL)
1278 				err(1, "reallocf()");
1279 			if (mysysctl("hw.intrcnt", *intrcnts, &intrcntlen) == 0)
1280 				break;
1281 		}
1282 	}
1283 
1284 	return (intrcntlen / sizeof(unsigned long));
1285 }
1286 
1287 static void
1288 print_intrcnts(unsigned long *intrcnts, unsigned long *old_intrcnts,
1289     char *intrnames, unsigned int nintr, size_t istrnamlen, long long period_ms)
1290 {
1291 	uint64_t inttotal, old_inttotal, total_count, total_rate;
1292 	unsigned long count, rate;
1293 	unsigned int i;
1294 
1295 	inttotal = 0;
1296 	old_inttotal = 0;
1297 	xo_open_list("interrupt");
1298 	for (i = 0; i < nintr; i++) {
1299 		if (intrnames[0] != '\0' && (*intrcnts != 0 || aflag)) {
1300 			count = *intrcnts - *old_intrcnts;
1301 			rate = ((uint64_t)count * 1000 + period_ms / 2) / period_ms;
1302 			xo_open_instance("interrupt");
1303 			xo_emit("{d:name/%-*s}{ket:name/%s} "
1304 			    "{:total/%20lu} {:rate/%10lu}\n",
1305 			    (int)istrnamlen, intrnames, intrnames, count, rate);
1306 			xo_close_instance("interrupt");
1307 		}
1308 		intrnames += strlen(intrnames) + 1;
1309 		inttotal += *intrcnts++;
1310 		old_inttotal += *old_intrcnts++;
1311 	}
1312 	total_count = inttotal - old_inttotal;
1313 	total_rate = (total_count * 1000 + period_ms / 2) / period_ms;
1314 	xo_close_list("interrupt");
1315 	xo_emit("{L:/%-*s} {:total-interrupts/%20ju} "
1316 	    "{:total-rate/%10ju}\n", (int)istrnamlen,
1317 	    "Total", (uintmax_t)total_count, (uintmax_t)total_rate);
1318 }
1319 
1320 static void
1321 dointr(unsigned int interval, int reps)
1322 {
1323 	unsigned long *intrcnts, *old_intrcnts;
1324 	char *intrname, *intrnames;
1325 	long long period_ms, old_uptime, uptime;
1326 	size_t clen, inamlen, istrnamlen;
1327 	uintptr_t kaddr;
1328 	unsigned int nintr;
1329 
1330 	old_intrcnts = NULL;
1331 	uptime = getuptime();
1332 
1333 	/* Get the names of each interrupt source */
1334 	if (kd != NULL) {
1335 		kread(X_SINTRNAMES, &inamlen, sizeof(inamlen));
1336 		if ((intrnames = malloc(inamlen)) == NULL)
1337 			xo_err(1, "malloc()");
1338 		if (namelist[X_NINTRCNT].n_type == 0)
1339 			kread(X_INTRNAMES, intrnames, inamlen);
1340 		else {
1341 			kread(X_INTRNAMES, &kaddr, sizeof(kaddr));
1342 			kreadptr(kaddr, intrnames, inamlen);
1343 		}
1344 	} else {
1345 		for (intrnames = NULL, inamlen = 1024; ; inamlen *= 2) {
1346 			if ((intrnames = reallocf(intrnames, inamlen)) == NULL)
1347 				xo_err(1, "reallocf()");
1348 			if (mysysctl("hw.intrnames", intrnames, &inamlen) == 0)
1349 				break;
1350 		}
1351 	}
1352 
1353 	/* Determine the length of the longest interrupt name */
1354 	intrname = intrnames;
1355 	istrnamlen = strlen("interrupt");
1356 	while (intrname < intrnames + inamlen) {
1357 		clen = strlen(intrname);
1358 		if (clen > istrnamlen)
1359 			istrnamlen = clen;
1360 		intrname += strlen(intrname) + 1;
1361 	}
1362 	xo_emit("{T:/%-*s} {T:/%20s} {T:/%10s}\n",
1363 	    (int)istrnamlen, "interrupt", "total", "rate");
1364 
1365 	/*
1366 	 * Loop reps times printing differential interrupt counts.  If reps is
1367 	 * zero, then run just once, printing total counts
1368 	 */
1369 	xo_open_container("interrupt-statistics");
1370 
1371 	period_ms = uptime / 1000000;
1372 	while(1) {
1373 		nintr = read_intrcnts(&intrcnts);
1374 		/*
1375 		 * Initialize old_intrcnts to 0 for the first pass, so
1376 		 * print_intrcnts will print total interrupts since boot
1377 		 */
1378 		if (old_intrcnts == NULL) {
1379 			old_intrcnts = calloc(nintr, sizeof(unsigned long));
1380 			if (old_intrcnts == NULL)
1381 				xo_err(1, "calloc()");
1382 		}
1383 
1384 		print_intrcnts(intrcnts, old_intrcnts, intrnames, nintr,
1385 		    istrnamlen, period_ms);
1386 		xo_flush();
1387 
1388 		free(old_intrcnts);
1389 		old_intrcnts = intrcnts;
1390 		if (reps >= 0 && --reps <= 0)
1391 			break;
1392 		usleep(interval * 1000);
1393 		old_uptime = uptime;
1394 		uptime = getuptime();
1395 		period_ms = (uptime - old_uptime) / 1000000;
1396 	}
1397 
1398 	xo_close_container("interrupt-statistics");
1399 }
1400 
1401 static void
1402 domemstat_malloc(void)
1403 {
1404 	struct memory_type_list *mtlp;
1405 	struct memory_type *mtp;
1406 	size_t i, zones;
1407 	int error, first;
1408 
1409 	mtlp = memstat_mtl_alloc();
1410 	if (mtlp == NULL) {
1411 		xo_warn("memstat_mtl_alloc");
1412 		return;
1413 	}
1414 	if (kd == NULL) {
1415 		if (memstat_sysctl_malloc(mtlp, 0) < 0) {
1416 			xo_warnx("memstat_sysctl_malloc: %s",
1417 			    memstat_strerror(memstat_mtl_geterror(mtlp)));
1418 			return;
1419 		}
1420 	} else {
1421 		if (memstat_kvm_malloc(mtlp, kd) < 0) {
1422 			error = memstat_mtl_geterror(mtlp);
1423 			if (error == MEMSTAT_ERROR_KVM)
1424 				xo_warnx("memstat_kvm_malloc: %s",
1425 				    kvm_geterr(kd));
1426 			else
1427 				xo_warnx("memstat_kvm_malloc: %s",
1428 				    memstat_strerror(error));
1429 		}
1430 	}
1431 	xo_open_container("malloc-statistics");
1432 	xo_emit("{T:/%13s} {T:/%5s} {T:/%6s} {T:/%8s}  {T:Size(s)}\n",
1433 	    "Type", "InUse", "MemUse", "Requests");
1434 	xo_open_list("memory");
1435 	zones = memstat_malloc_zone_get_count();
1436 	for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
1437 	    mtp = memstat_mtl_next(mtp)) {
1438 		if (memstat_get_numallocs(mtp) == 0 &&
1439 		    memstat_get_count(mtp) == 0)
1440 			continue;
1441 		xo_open_instance("memory");
1442 		xo_emit("{k:type/%13s/%s} {:in-use/%5ju} "
1443 		    "{:memory-use/%5ju}{U:K} {:requests/%8ju}  ",
1444 		    memstat_get_name(mtp), (uintmax_t)memstat_get_count(mtp),
1445 		    ((uintmax_t)memstat_get_bytes(mtp) + 1023) / 1024,
1446 		    (uintmax_t)memstat_get_numallocs(mtp));
1447 		first = 1;
1448 		xo_open_list("size");
1449 		for (i = 0; i < zones; i++) {
1450 			if (memstat_malloc_zone_used(mtp, i)) {
1451 				if (!first)
1452 					xo_emit(",");
1453 				xo_emit("{l:size/%d}", memstat_malloc_zone_get_size(i));
1454 				first = 0;
1455 			}
1456 		}
1457 		xo_close_list("size");
1458 		xo_close_instance("memory");
1459 		xo_emit("\n");
1460 	}
1461 	xo_close_list("memory");
1462 	xo_close_container("malloc-statistics");
1463 	memstat_mtl_free(mtlp);
1464 }
1465 
1466 static void
1467 domemstat_zone(void)
1468 {
1469 	struct memory_type_list *mtlp;
1470 	struct memory_type *mtp;
1471 	int error;
1472 	char name[MEMTYPE_MAXNAME + 1];
1473 
1474 	mtlp = memstat_mtl_alloc();
1475 	if (mtlp == NULL) {
1476 		xo_warn("memstat_mtl_alloc");
1477 		return;
1478 	}
1479 	if (kd == NULL) {
1480 		if (memstat_sysctl_uma(mtlp, 0) < 0) {
1481 			xo_warnx("memstat_sysctl_uma: %s",
1482 			    memstat_strerror(memstat_mtl_geterror(mtlp)));
1483 			return;
1484 		}
1485 	} else {
1486 		if (memstat_kvm_uma(mtlp, kd) < 0) {
1487 			error = memstat_mtl_geterror(mtlp);
1488 			if (error == MEMSTAT_ERROR_KVM)
1489 				xo_warnx("memstat_kvm_uma: %s",
1490 				    kvm_geterr(kd));
1491 			else
1492 				xo_warnx("memstat_kvm_uma: %s",
1493 				    memstat_strerror(error));
1494 		}
1495 	}
1496 	xo_open_container("memory-zone-statistics");
1497 	xo_emit("{T:/%-20s} {T:/%6s} {T:/%6s} {T:/%8s} {T:/%8s} {T:/%8s} {T:/%8s}"
1498 	    "{T:/%4s} {T:/%4s}\n", "ITEM", "SIZE",
1499 	    "LIMIT", "USED", "FREE", "REQ", "FAIL", "SLEEP", "XDOMAIN");
1500 	xo_open_list("zone");
1501 	for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
1502 	    mtp = memstat_mtl_next(mtp)) {
1503 		strlcpy(name, memstat_get_name(mtp), MEMTYPE_MAXNAME);
1504 		strcat(name, ":");
1505 		xo_open_instance("zone");
1506 		xo_emit("{d:name/%-20s}{ke:name/%s} {:size/%6ju}, "
1507 		    "{:limit/%6ju},{:used/%8ju},"
1508 		    "{:free/%8ju},{:requests/%8ju},"
1509 		    "{:fail/%4ju},{:sleep/%4ju},{:xdomain/%4ju}\n", name,
1510 		    memstat_get_name(mtp),
1511 		    (uintmax_t)memstat_get_size(mtp),
1512 		    (uintmax_t)memstat_get_countlimit(mtp),
1513 		    (uintmax_t)memstat_get_count(mtp),
1514 		    (uintmax_t)memstat_get_free(mtp),
1515 		    (uintmax_t)memstat_get_numallocs(mtp),
1516 		    (uintmax_t)memstat_get_failures(mtp),
1517 		    (uintmax_t)memstat_get_sleeps(mtp),
1518 		    (uintmax_t)memstat_get_xdomain(mtp));
1519 		xo_close_instance("zone");
1520 	}
1521 	memstat_mtl_free(mtlp);
1522 	xo_close_list("zone");
1523 	xo_close_container("memory-zone-statistics");
1524 }
1525 
1526 static void
1527 display_object(struct kinfo_vmobject *kvo)
1528 {
1529 	const char *str;
1530 
1531 	xo_open_instance("object");
1532 	xo_emit("{:resident/%5ju} ", (uintmax_t)kvo->kvo_resident);
1533 	xo_emit("{:active/%5ju} ", (uintmax_t)kvo->kvo_active);
1534 	xo_emit("{:inactive/%5ju} ", (uintmax_t)kvo->kvo_inactive);
1535 	xo_emit("{:refcount/%3d} ", kvo->kvo_ref_count);
1536 	xo_emit("{:shadowcount/%3d} ", kvo->kvo_shadow_count);
1537 
1538 #define	MEMATTR_STR(type, val)					\
1539 	if (kvo->kvo_memattr == (type)) {			\
1540 		str = (val);					\
1541 	} else
1542 #ifdef VM_MEMATTR_UNCACHEABLE
1543 	MEMATTR_STR(VM_MEMATTR_UNCACHEABLE, "UC")
1544 #endif
1545 #ifdef VM_MEMATTR_WRITE_COMBINING
1546 	MEMATTR_STR(VM_MEMATTR_WRITE_COMBINING, "WC")
1547 #endif
1548 #ifdef VM_MEMATTR_WRITE_THROUGH
1549 	MEMATTR_STR(VM_MEMATTR_WRITE_THROUGH, "WT")
1550 #endif
1551 #ifdef VM_MEMATTR_WRITE_PROTECTED
1552 	MEMATTR_STR(VM_MEMATTR_WRITE_PROTECTED, "WP")
1553 #endif
1554 #ifdef VM_MEMATTR_WRITE_BACK
1555 	MEMATTR_STR(VM_MEMATTR_WRITE_BACK, "WB")
1556 #endif
1557 #ifdef VM_MEMATTR_WEAK_UNCACHEABLE
1558 	MEMATTR_STR(VM_MEMATTR_WEAK_UNCACHEABLE, "UC-")
1559 #endif
1560 #ifdef VM_MEMATTR_WB_WA
1561 	MEMATTR_STR(VM_MEMATTR_WB_WA, "WB")
1562 #endif
1563 #ifdef VM_MEMATTR_NOCACHE
1564 	MEMATTR_STR(VM_MEMATTR_NOCACHE, "NC")
1565 #endif
1566 #ifdef VM_MEMATTR_DEVICE
1567 	MEMATTR_STR(VM_MEMATTR_DEVICE, "DEV")
1568 #endif
1569 #ifdef VM_MEMATTR_DEVICE_NP
1570 	MEMATTR_STR(VM_MEMATTR_DEVICE, "NP")
1571 #endif
1572 #ifdef VM_MEMATTR_CACHEABLE
1573 	MEMATTR_STR(VM_MEMATTR_CACHEABLE, "C")
1574 #endif
1575 #ifdef VM_MEMATTR_PREFETCHABLE
1576 	MEMATTR_STR(VM_MEMATTR_PREFETCHABLE, "PRE")
1577 #endif
1578 	{
1579 		str = "??";
1580 	}
1581 #undef MEMATTR_STR
1582 	xo_emit("{:attribute/%-3s} ", str);
1583 	switch (kvo->kvo_type) {
1584 	case KVME_TYPE_NONE:
1585 		str = "--";
1586 		break;
1587 	case KVME_TYPE_DEFAULT:
1588 		str = "df";
1589 		break;
1590 	case KVME_TYPE_VNODE:
1591 		str = "vn";
1592 		break;
1593 	case KVME_TYPE_SWAP:
1594 		str = "sw";
1595 		break;
1596 	case KVME_TYPE_DEVICE:
1597 		str = "dv";
1598 		break;
1599 	case KVME_TYPE_PHYS:
1600 		str = "ph";
1601 		break;
1602 	case KVME_TYPE_DEAD:
1603 		str = "dd";
1604 		break;
1605 	case KVME_TYPE_SG:
1606 		str = "sg";
1607 		break;
1608 	case KVME_TYPE_MGTDEVICE:
1609 		str = "md";
1610 		break;
1611 	case KVME_TYPE_UNKNOWN:
1612 	default:
1613 		str = "??";
1614 		break;
1615 	}
1616 	xo_emit("{:type/%-2s} ", str);
1617 	xo_emit("{:path/%-s}\n", kvo->kvo_path);
1618 	xo_close_instance("object");
1619 }
1620 
1621 static void
1622 doobjstat(void)
1623 {
1624 	struct kinfo_vmobject *kvo;
1625 	int cnt, i;
1626 
1627 	kvo = kinfo_getvmobject(&cnt);
1628 	if (kvo == NULL) {
1629 		xo_warn("Failed to fetch VM object list");
1630 		return;
1631 	}
1632 	xo_emit("{T:RES/%5s} {T:ACT/%5s} {T:INACT/%5s} {T:REF/%3s} {T:SHD/%3s} "
1633 	    "{T:CM/%3s} {T:TP/%2s} {T:PATH/%s}\n");
1634 	xo_open_list("object");
1635 	for (i = 0; i < cnt; i++)
1636 		display_object(&kvo[i]);
1637 	free(kvo);
1638 	xo_close_list("object");
1639 }
1640 
1641 /*
1642  * kread reads something from the kernel, given its nlist index.
1643  */
1644 static void
1645 kreado(int nlx, void *addr, size_t size, size_t offset)
1646 {
1647 	const char *sym;
1648 
1649 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
1650 		sym = namelist[nlx].n_name;
1651 		if (*sym == '_')
1652 			++sym;
1653 		xo_errx(1, "symbol %s not defined", sym);
1654 	}
1655 	if ((size_t)kvm_read(kd, namelist[nlx].n_value + offset, addr,
1656 	    size) != size) {
1657 		sym = namelist[nlx].n_name;
1658 		if (*sym == '_')
1659 			++sym;
1660 		xo_errx(1, "%s: %s", sym, kvm_geterr(kd));
1661 	}
1662 }
1663 
1664 static void
1665 kread(int nlx, void *addr, size_t size)
1666 {
1667 
1668 	kreado(nlx, addr, size, 0);
1669 }
1670 
1671 static void
1672 kreadptr(uintptr_t addr, void *buf, size_t size)
1673 {
1674 
1675 	if ((size_t)kvm_read(kd, addr, buf, size) != size)
1676 		xo_errx(1, "%s", kvm_geterr(kd));
1677 }
1678 
1679 static void __dead2
1680 usage(void)
1681 {
1682 	xo_error("%s%s",
1683 	    "usage: vmstat [-afHhimoPsz] [-M core [-N system]] [-c count] [-n devs]\n",
1684 	    "              [-p type,if,pass] [-w wait] [disks] [wait [count]]\n");
1685 	xo_finish();
1686 	exit(1);
1687 }
1688