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