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