xref: /freebsd/usr.bin/vmstat/vmstat.c (revision 2b743a9e9ddc6736208dc8ca1ce06ce64ad20a19)
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. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 #ifndef lint
35 static const char copyright[] =
36 "@(#) Copyright (c) 1980, 1986, 1991, 1993\n\
37 	The Regents of the University of California.  All rights reserved.\n";
38 #endif /* not lint */
39 
40 #if 0
41 #ifndef lint
42 static char sccsid[] = "@(#)vmstat.c	8.1 (Berkeley) 6/6/93";
43 #endif /* not lint */
44 #endif
45 
46 #include <sys/cdefs.h>
47 __FBSDID("$FreeBSD$");
48 
49 #include <sys/param.h>
50 #include <sys/time.h>
51 #include <sys/proc.h>
52 #include <sys/uio.h>
53 #include <sys/namei.h>
54 #include <sys/malloc.h>
55 #include <sys/signal.h>
56 #include <sys/fcntl.h>
57 #include <sys/ioctl.h>
58 #include <sys/resource.h>
59 #include <sys/sysctl.h>
60 #include <sys/vmmeter.h>
61 
62 #include <vm/vm_param.h>
63 
64 #include <ctype.h>
65 #include <devstat.h>
66 #include <err.h>
67 #include <errno.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 
80 static char da[] = "da";
81 
82 static struct nlist namelist[] = {
83 #define	X_CPTIME	0
84 	{ "_cp_time" },
85 #define X_SUM		1
86 	{ "_cnt" },
87 #define	X_BOOTTIME	2
88 	{ "_boottime" },
89 #define X_HZ		3
90 	{ "_hz" },
91 #define X_STATHZ	4
92 	{ "_stathz" },
93 #define X_NCHSTATS	5
94 	{ "_nchstats" },
95 #define	X_INTRNAMES	6
96 	{ "_intrnames" },
97 #define	X_EINTRNAMES	7
98 	{ "_eintrnames" },
99 #define	X_INTRCNT	8
100 	{ "_intrcnt" },
101 #define	X_EINTRCNT	9
102 	{ "_eintrcnt" },
103 #define	X_KMEMSTATS	10
104 	{ "_kmemstatistics" },
105 #define	X_KMEMZONES	11
106 	{ "_kmemzones" },
107 #ifdef notyet
108 #define	X_DEFICIT	XXX
109 	{ "_deficit" },
110 #define X_REC		XXX
111 	{ "_rectime" },
112 #define X_PGIN		XXX
113 	{ "_pgintime" },
114 #define	X_XSTATS	XXX
115 	{ "_xstats" },
116 #define X_END		XXX
117 #else
118 #define X_END		12
119 #endif
120 	{ "" },
121 };
122 
123 static struct statinfo cur, last;
124 static int num_devices, maxshowdevs;
125 static long generation;
126 static struct device_selection *dev_select;
127 static int num_selected;
128 static struct devstat_match *matches;
129 static int num_matches = 0;
130 static int num_devices_specified, num_selections;
131 static long select_generation;
132 static char **specified_devices;
133 static devstat_select_mode select_mode;
134 
135 static struct	vmmeter sum, osum;
136 
137 static int	winlines = 20;
138 static int	aflag;
139 static int	nflag;
140 
141 static kvm_t   *kd;
142 
143 #define	FORKSTAT	0x01
144 #define	INTRSTAT	0x02
145 #define	MEMSTAT		0x04
146 #define	SUMSTAT		0x08
147 #define	TIMESTAT	0x10
148 #define	VMSTAT		0x20
149 #define ZMEMSTAT	0x40
150 
151 static void	cpustats(void);
152 static void	devstats(void);
153 static void	doforkst(void);
154 static void	dointr(void);
155 static void	dosum(void);
156 static void	dovmstat(unsigned int, int);
157 static void	domemstat_malloc(void);
158 static void	domemstat_zone(void);
159 static void	kread(int, void *, size_t);
160 static void	kreado(int, void *, size_t, size_t);
161 static char    *kgetstr(const char *);
162 static void	needhdr(int);
163 static void	printhdr(void);
164 static void	usage(void);
165 
166 static long	pct(long, long);
167 static long	getuptime(void);
168 
169 static char   **getdrivedata(char **);
170 
171 int
172 main(int argc, char *argv[])
173 {
174 	int c, todo;
175 	unsigned int interval;
176 	int reps;
177 	char *memf, *nlistf;
178 	char errbuf[_POSIX2_LINE_MAX];
179 
180 	memf = nlistf = NULL;
181 	interval = reps = todo = 0;
182 	maxshowdevs = 2;
183 	while ((c = getopt(argc, argv, "ac:fiM:mN:n:p:stw:z")) != -1) {
184 		switch (c) {
185 		case 'a':
186 			aflag++;
187 			break;
188 		case 'c':
189 			reps = atoi(optarg);
190 			break;
191 		case 'f':
192 			todo |= FORKSTAT;
193 			break;
194 		case 'i':
195 			todo |= INTRSTAT;
196 			break;
197 		case 'M':
198 			memf = optarg;
199 			break;
200 		case 'm':
201 			todo |= MEMSTAT;
202 			break;
203 		case 'N':
204 			nlistf = optarg;
205 			break;
206 		case 'n':
207 			nflag = 1;
208 			maxshowdevs = atoi(optarg);
209 			if (maxshowdevs < 0)
210 				errx(1, "number of devices %d is < 0",
211 				     maxshowdevs);
212 			break;
213 		case 'p':
214 			if (devstat_buildmatch(optarg, &matches, &num_matches) != 0)
215 				errx(1, "%s", devstat_errbuf);
216 			break;
217 		case 's':
218 			todo |= SUMSTAT;
219 			break;
220 		case 't':
221 #ifdef notyet
222 			todo |= TIMESTAT;
223 #else
224 			errx(EX_USAGE, "sorry, -t is not (re)implemented yet");
225 #endif
226 			break;
227 		case 'w':
228 			interval = atoi(optarg);
229 			break;
230 		case 'z':
231 			todo |= ZMEMSTAT;
232 			break;
233 		case '?':
234 		default:
235 			usage();
236 		}
237 	}
238 	argc -= optind;
239 	argv += optind;
240 
241 	if (todo == 0)
242 		todo = VMSTAT;
243 
244 	if (memf != NULL) {
245 		kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
246 		if (kd == NULL)
247 			errx(1, "kvm_openfiles: %s", errbuf);
248 	}
249 
250 	if (kd != NULL && (c = kvm_nlist(kd, namelist)) != 0) {
251 		if (c > 0) {
252 			warnx("undefined symbols:");
253 			for (c = 0;
254 			     c < (int)(sizeof(namelist)/sizeof(namelist[0]));
255 			     c++)
256 				if (namelist[c].n_type == 0)
257 					(void)fprintf(stderr, " %s",
258 					    namelist[c].n_name);
259 			(void)fputc('\n', stderr);
260 		} else
261 			warnx("kvm_nlist: %s", kvm_geterr(kd));
262 		exit(1);
263 	}
264 
265 	if (todo & VMSTAT) {
266 		struct winsize winsize;
267 
268 		/*
269 		 * Make sure that the userland devstat version matches the
270 		 * kernel devstat version.  If not, exit and print a
271 		 * message informing the user of his mistake.
272 		 */
273 		if (devstat_checkversion(NULL) < 0)
274 			errx(1, "%s", devstat_errbuf);
275 
276 
277 		argv = getdrivedata(argv);
278 		winsize.ws_row = 0;
279 		(void) ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
280 		if (winsize.ws_row > 0)
281 			winlines = winsize.ws_row;
282 
283 	}
284 
285 #define	BACKWARD_COMPATIBILITY
286 #ifdef	BACKWARD_COMPATIBILITY
287 	if (*argv) {
288 		interval = atoi(*argv);
289 		if (*++argv)
290 			reps = atoi(*argv);
291 	}
292 #endif
293 
294 	if (interval) {
295 		if (!reps)
296 			reps = -1;
297 	} else if (reps)
298 		interval = 1;
299 
300 	if (todo & FORKSTAT)
301 		doforkst();
302 	if (todo & MEMSTAT)
303 		domemstat_malloc();
304 	if (todo & ZMEMSTAT)
305 		domemstat_zone();
306 	if (todo & SUMSTAT)
307 		dosum();
308 #ifdef notyet
309 	if (todo & TIMESTAT)
310 		dotimes();
311 #endif
312 	if (todo & INTRSTAT)
313 		dointr();
314 	if (todo & VMSTAT)
315 		dovmstat(interval, reps);
316 	exit(0);
317 }
318 
319 static int
320 mysysctl(const char *name, void *oldp, size_t *oldlenp,
321     void *newp, size_t newlen)
322 {
323 	int error;
324 
325 	error = sysctlbyname(name, oldp, oldlenp, newp, newlen);
326 	if (error != 0 && errno != ENOMEM)
327 		err(1, "sysctl(%s)", name);
328 	return (error);
329 }
330 
331 static char **
332 getdrivedata(char **argv)
333 {
334 	if ((num_devices = devstat_getnumdevs(NULL)) < 0)
335 		errx(1, "%s", devstat_errbuf);
336 
337 	cur.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
338 	last.dinfo = (struct devinfo *)malloc(sizeof(struct devinfo));
339 	bzero(cur.dinfo, sizeof(struct devinfo));
340 	bzero(last.dinfo, sizeof(struct devinfo));
341 
342 	if (devstat_getdevs(NULL, &cur) == -1)
343 		errx(1, "%s", devstat_errbuf);
344 
345 	num_devices = cur.dinfo->numdevs;
346 	generation = cur.dinfo->generation;
347 
348 	specified_devices = (char **)malloc(sizeof(char *));
349 	for (num_devices_specified = 0; *argv; ++argv) {
350 		if (isdigit(**argv))
351 			break;
352 		num_devices_specified++;
353 		specified_devices = (char **)realloc(specified_devices,
354 						     sizeof(char *) *
355 						     num_devices_specified);
356 		specified_devices[num_devices_specified - 1] = *argv;
357 	}
358 	dev_select = NULL;
359 
360 	if (nflag == 0 && maxshowdevs < num_devices_specified)
361 			maxshowdevs = num_devices_specified;
362 
363 	/*
364 	 * People are generally only interested in disk statistics when
365 	 * they're running vmstat.  So, that's what we're going to give
366 	 * them if they don't specify anything by default.  We'll also give
367 	 * them any other random devices in the system so that we get to
368 	 * maxshowdevs devices, if that many devices exist.  If the user
369 	 * specifies devices on the command line, either through a pattern
370 	 * match or by naming them explicitly, we will give the user only
371 	 * those devices.
372 	 */
373 	if ((num_devices_specified == 0) && (num_matches == 0)) {
374 		if (devstat_buildmatch(da, &matches, &num_matches) != 0)
375 			errx(1, "%s", devstat_errbuf);
376 
377 		select_mode = DS_SELECT_ADD;
378 	} else
379 		select_mode = DS_SELECT_ONLY;
380 
381 	/*
382 	 * At this point, selectdevs will almost surely indicate that the
383 	 * device list has changed, so we don't look for return values of 0
384 	 * or 1.  If we get back -1, though, there is an error.
385 	 */
386 	if (devstat_selectdevs(&dev_select, &num_selected, &num_selections,
387 		       &select_generation, generation, cur.dinfo->devices,
388 		       num_devices, matches, num_matches, specified_devices,
389 		       num_devices_specified, select_mode,
390 		       maxshowdevs, 0) == -1)
391 		errx(1, "%s", devstat_errbuf);
392 
393 	return(argv);
394 }
395 
396 static long
397 getuptime(void)
398 {
399 	struct timespec sp;
400 	time_t uptime;
401 
402 	(void)clock_gettime(CLOCK_MONOTONIC, &sp);
403 	uptime = sp.tv_sec;
404 	if (uptime <= 0 || uptime > 60*60*24*365*10)
405 		errx(1, "time makes no sense; namelist must be wrong");
406 
407 	return(uptime);
408 }
409 
410 static void
411 fill_vmmeter(struct vmmeter *vmmp)
412 {
413 	if (kd != NULL) {
414 		kread(X_SUM, vmmp, sizeof(*vmmp));
415 	} else {
416 		size_t size = sizeof(unsigned int);
417 #define GET_VM_STATS(cat, name) \
418 	mysysctl("vm.stats." #cat "." #name, &vmmp->name, &size, NULL, 0)
419 		/* sys */
420 		GET_VM_STATS(sys, v_swtch);
421 		GET_VM_STATS(sys, v_trap);
422 		GET_VM_STATS(sys, v_syscall);
423 		GET_VM_STATS(sys, v_intr);
424 		GET_VM_STATS(sys, v_soft);
425 
426 		/* vm */
427 		GET_VM_STATS(vm, v_vm_faults);
428 		GET_VM_STATS(vm, v_cow_faults);
429 		GET_VM_STATS(vm, v_cow_optim);
430 		GET_VM_STATS(vm, v_zfod);
431 		GET_VM_STATS(vm, v_ozfod);
432 		GET_VM_STATS(vm, v_swapin);
433 		GET_VM_STATS(vm, v_swapout);
434 		GET_VM_STATS(vm, v_swappgsin);
435 		GET_VM_STATS(vm, v_swappgsout);
436 		GET_VM_STATS(vm, v_vnodein);
437 		GET_VM_STATS(vm, v_vnodeout);
438 		GET_VM_STATS(vm, v_vnodepgsin);
439 		GET_VM_STATS(vm, v_vnodepgsout);
440 		GET_VM_STATS(vm, v_intrans);
441 		GET_VM_STATS(vm, v_reactivated);
442 		GET_VM_STATS(vm, v_pdwakeups);
443 		GET_VM_STATS(vm, v_pdpages);
444 		GET_VM_STATS(vm, v_dfree);
445 		GET_VM_STATS(vm, v_pfree);
446 		GET_VM_STATS(vm, v_tfree);
447 		GET_VM_STATS(vm, v_page_size);
448 		GET_VM_STATS(vm, v_page_count);
449 		GET_VM_STATS(vm, v_free_reserved);
450 		GET_VM_STATS(vm, v_free_target);
451 		GET_VM_STATS(vm, v_free_min);
452 		GET_VM_STATS(vm, v_free_count);
453 		GET_VM_STATS(vm, v_wire_count);
454 		GET_VM_STATS(vm, v_active_count);
455 		GET_VM_STATS(vm, v_inactive_target);
456 		GET_VM_STATS(vm, v_inactive_count);
457 		GET_VM_STATS(vm, v_cache_count);
458 		GET_VM_STATS(vm, v_cache_min);
459 		GET_VM_STATS(vm, v_cache_max);
460 		GET_VM_STATS(vm, v_pageout_free_min);
461 		GET_VM_STATS(vm, v_interrupt_free_min);
462 		/*GET_VM_STATS(vm, v_free_severe);*/
463 		GET_VM_STATS(vm, v_forks);
464 		GET_VM_STATS(vm, v_vforks);
465 		GET_VM_STATS(vm, v_rforks);
466 		GET_VM_STATS(vm, v_kthreads);
467 		GET_VM_STATS(vm, v_forkpages);
468 		GET_VM_STATS(vm, v_vforkpages);
469 		GET_VM_STATS(vm, v_rforkpages);
470 		GET_VM_STATS(vm, v_kthreadpages);
471 #undef GET_VM_STATS
472 	}
473 }
474 
475 static void
476 fill_vmtotal(struct vmtotal *vmtp)
477 {
478 	if (kd != NULL) {
479 		/* XXX fill vmtp */
480 		errx(1, "not implemented");
481 	} else {
482 		size_t size = sizeof(*vmtp);
483 		mysysctl("vm.vmtotal", vmtp, &size, NULL, 0);
484 		if (size != sizeof(*vmtp))
485 			errx(1, "vm.total size mismatch");
486 	}
487 }
488 
489 static int hz, hdrcnt;
490 
491 static void
492 dovmstat(unsigned int interval, int reps)
493 {
494 	struct vmtotal total;
495 	time_t uptime, halfuptime;
496 	struct devinfo *tmp_dinfo;
497 	size_t size;
498 
499 	uptime = getuptime();
500 	halfuptime = uptime / 2;
501 	(void)signal(SIGCONT, needhdr);
502 
503 	if (kd != NULL) {
504 		if (namelist[X_STATHZ].n_type != 0 &&
505 		    namelist[X_STATHZ].n_value != 0)
506 			kread(X_STATHZ, &hz, sizeof(hz));
507 		if (!hz)
508 			kread(X_HZ, &hz, sizeof(hz));
509 	} else {
510 		struct clockinfo clockrate;
511 
512 		size = sizeof(clockrate);
513 		mysysctl("kern.clockrate", &clockrate, &size, NULL, 0);
514 		if (size != sizeof(clockrate))
515 			errx(1, "clockrate size mismatch");
516 		hz = clockrate.hz;
517 	}
518 
519 	for (hdrcnt = 1;;) {
520 		if (!--hdrcnt)
521 			printhdr();
522 		if (kd != NULL) {
523 			kread(X_CPTIME, cur.cp_time, sizeof(cur.cp_time));
524 		} else {
525 			size = sizeof(cur.cp_time);
526 			mysysctl("kern.cp_time", &cur.cp_time, &size, NULL, 0);
527 			if (size != sizeof(cur.cp_time))
528 				errx(1, "cp_time size mismatch");
529 		}
530 
531 		tmp_dinfo = last.dinfo;
532 		last.dinfo = cur.dinfo;
533 		cur.dinfo = tmp_dinfo;
534 		last.snap_time = cur.snap_time;
535 
536 		/*
537 		 * Here what we want to do is refresh our device stats.
538 		 * getdevs() returns 1 when the device list has changed.
539 		 * If the device list has changed, we want to go through
540 		 * the selection process again, in case a device that we
541 		 * were previously displaying has gone away.
542 		 */
543 		switch (devstat_getdevs(NULL, &cur)) {
544 		case -1:
545 			errx(1, "%s", devstat_errbuf);
546 			break;
547 		case 1: {
548 			int retval;
549 
550 			num_devices = cur.dinfo->numdevs;
551 			generation = cur.dinfo->generation;
552 
553 			retval = devstat_selectdevs(&dev_select, &num_selected,
554 					    &num_selections, &select_generation,
555 					    generation, cur.dinfo->devices,
556 					    num_devices, matches, num_matches,
557 					    specified_devices,
558 					    num_devices_specified, select_mode,
559 					    maxshowdevs, 0);
560 			switch (retval) {
561 			case -1:
562 				errx(1, "%s", devstat_errbuf);
563 				break;
564 			case 1:
565 				printhdr();
566 				break;
567 			default:
568 				break;
569 			}
570 		}
571 		default:
572 			break;
573 		}
574 
575 		fill_vmmeter(&sum);
576 		fill_vmtotal(&total);
577 		(void)printf("%2d %1d %1d",
578 		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
579 #define vmstat_pgtok(a) ((a) * (sum.v_page_size >> 10))
580 #define	rate(x)	(((x) + halfuptime) / uptime)	/* round */
581 		(void)printf(" %7d %6d ", vmstat_pgtok(total.t_avm),
582 		    vmstat_pgtok(total.t_free));
583 		(void)printf("%5lu ",
584 		    (unsigned long)rate(sum.v_vm_faults - osum.v_vm_faults));
585 		(void)printf("%3lu ",
586 		    (unsigned long)rate(sum.v_reactivated - osum.v_reactivated));
587 		(void)printf("%3lu ",
588 		    (unsigned long)rate(sum.v_swapin + sum.v_vnodein -
589 		    (osum.v_swapin + osum.v_vnodein)));
590 		(void)printf("%3lu ",
591 		    (unsigned long)rate(sum.v_swapout + sum.v_vnodeout -
592 		    (osum.v_swapout + osum.v_vnodeout)));
593 		(void)printf("%5lu ",
594 		    (unsigned long)rate(sum.v_tfree - osum.v_tfree));
595 		(void)printf("%3lu ",
596 		    (unsigned long)rate(sum.v_pdpages - osum.v_pdpages));
597 		devstats();
598 		(void)printf("%4lu %4lu %4lu ",
599 		    (unsigned long)rate(sum.v_intr - osum.v_intr),
600 		    (unsigned long)rate(sum.v_syscall - osum.v_syscall),
601 		    (unsigned long)rate(sum.v_swtch - osum.v_swtch));
602 		cpustats();
603 		(void)printf("\n");
604 		(void)fflush(stdout);
605 		if (reps >= 0 && --reps <= 0)
606 			break;
607 		osum = sum;
608 		uptime = interval;
609 		/*
610 		 * We round upward to avoid losing low-frequency events
611 		 * (i.e., >= 1 per interval but < 1 per second).
612 		 */
613 		if (interval != 1)
614 			halfuptime = (uptime + 1) / 2;
615 		else
616 			halfuptime = 0;
617 		(void)sleep(interval);
618 	}
619 }
620 
621 static void
622 printhdr(void)
623 {
624 	int i, num_shown;
625 
626 	num_shown = (num_selected < maxshowdevs) ? num_selected : maxshowdevs;
627 	(void)printf(" procs      memory      page%*s", 19, "");
628 	if (num_shown > 1)
629 		(void)printf(" disks %*s", num_shown * 4 - 7, "");
630 	else if (num_shown == 1)
631 		(void)printf("disk");
632 	(void)printf("   faults      cpu\n");
633 	(void)printf(" r b w     avm    fre   flt  re  pi  po    fr  sr ");
634 	for (i = 0; i < num_devices; i++)
635 		if ((dev_select[i].selected)
636 		 && (dev_select[i].selected <= maxshowdevs))
637 			(void)printf("%c%c%d ", dev_select[i].device_name[0],
638 				     dev_select[i].device_name[1],
639 				     dev_select[i].unit_number);
640 	(void)printf("  in   sy   cs us sy id\n");
641 	hdrcnt = winlines - 2;
642 }
643 
644 /*
645  * Force a header to be prepended to the next output.
646  */
647 static void
648 needhdr(int dummy __unused)
649 {
650 
651 	hdrcnt = 1;
652 }
653 
654 #ifdef notyet
655 static void
656 dotimes(void)
657 {
658 	unsigned int pgintime, rectime;
659 
660 	kread(X_REC, &rectime, sizeof(rectime));
661 	kread(X_PGIN, &pgintime, sizeof(pgintime));
662 	kread(X_SUM, &sum, sizeof(sum));
663 	(void)printf("%u reclaims, %u total time (usec)\n",
664 	    sum.v_pgrec, rectime);
665 	(void)printf("average: %u usec / reclaim\n", rectime / sum.v_pgrec);
666 	(void)printf("\n");
667 	(void)printf("%u page ins, %u total time (msec)\n",
668 	    sum.v_pgin, pgintime / 10);
669 	(void)printf("average: %8.1f msec / page in\n",
670 	    pgintime / (sum.v_pgin * 10.0));
671 }
672 #endif
673 
674 static long
675 pct(long top, long bot)
676 {
677 	long ans;
678 
679 	if (bot == 0)
680 		return(0);
681 	ans = (quad_t)top * 100 / bot;
682 	return (ans);
683 }
684 
685 #define	PCT(top, bot) pct((long)(top), (long)(bot))
686 
687 static void
688 dosum(void)
689 {
690 	struct nchstats lnchstats;
691 	long nchtotal;
692 
693 	fill_vmmeter(&sum);
694 	(void)printf("%9u cpu context switches\n", sum.v_swtch);
695 	(void)printf("%9u device interrupts\n", sum.v_intr);
696 	(void)printf("%9u software interrupts\n", sum.v_soft);
697 	(void)printf("%9u traps\n", sum.v_trap);
698 	(void)printf("%9u system calls\n", sum.v_syscall);
699 	(void)printf("%9u kernel threads created\n", sum.v_kthreads);
700 	(void)printf("%9u  fork() calls\n", sum.v_forks);
701 	(void)printf("%9u vfork() calls\n", sum.v_vforks);
702 	(void)printf("%9u rfork() calls\n", sum.v_rforks);
703 	(void)printf("%9u swap pager pageins\n", sum.v_swapin);
704 	(void)printf("%9u swap pager pages paged in\n", sum.v_swappgsin);
705 	(void)printf("%9u swap pager pageouts\n", sum.v_swapout);
706 	(void)printf("%9u swap pager pages paged out\n", sum.v_swappgsout);
707 	(void)printf("%9u vnode pager pageins\n", sum.v_vnodein);
708 	(void)printf("%9u vnode pager pages paged in\n", sum.v_vnodepgsin);
709 	(void)printf("%9u vnode pager pageouts\n", sum.v_vnodeout);
710 	(void)printf("%9u vnode pager pages paged out\n", sum.v_vnodepgsout);
711 	(void)printf("%9u page daemon wakeups\n", sum.v_pdwakeups);
712 	(void)printf("%9u pages examined by the page daemon\n", sum.v_pdpages);
713 	(void)printf("%9u pages reactivated\n", sum.v_reactivated);
714 	(void)printf("%9u copy-on-write faults\n", sum.v_cow_faults);
715 	(void)printf("%9u copy-on-write optimized faults\n", sum.v_cow_optim);
716 	(void)printf("%9u zero fill pages zeroed\n", sum.v_zfod);
717 	(void)printf("%9u zero fill pages prezeroed\n", sum.v_ozfod);
718 	(void)printf("%9u intransit blocking page faults\n", sum.v_intrans);
719 	(void)printf("%9u total VM faults taken\n", sum.v_vm_faults);
720 	(void)printf("%9u pages affected by kernel thread creation\n", sum.v_kthreadpages);
721 	(void)printf("%9u pages affected by  fork()\n", sum.v_forkpages);
722 	(void)printf("%9u pages affected by vfork()\n", sum.v_vforkpages);
723 	(void)printf("%9u pages affected by rfork()\n", sum.v_rforkpages);
724 	(void)printf("%9u pages freed\n", sum.v_tfree);
725 	(void)printf("%9u pages freed by daemon\n", sum.v_dfree);
726 	(void)printf("%9u pages freed by exiting processes\n", sum.v_pfree);
727 	(void)printf("%9u pages active\n", sum.v_active_count);
728 	(void)printf("%9u pages inactive\n", sum.v_inactive_count);
729 	(void)printf("%9u pages in VM cache\n", sum.v_cache_count);
730 	(void)printf("%9u pages wired down\n", sum.v_wire_count);
731 	(void)printf("%9u pages free\n", sum.v_free_count);
732 	(void)printf("%9u bytes per page\n", sum.v_page_size);
733 	if (kd != NULL) {
734 		kread(X_NCHSTATS, &lnchstats, sizeof(lnchstats));
735 	} else {
736 		size_t size = sizeof(lnchstats);
737 		mysysctl("vfs.cache.nchstats", &lnchstats, &size, NULL, 0);
738 		if (size != sizeof(lnchstats))
739 			errx(1, "vfs.cache.nchstats size mismatch");
740 	}
741 	nchtotal = lnchstats.ncs_goodhits + lnchstats.ncs_neghits +
742 	    lnchstats.ncs_badhits + lnchstats.ncs_falsehits +
743 	    lnchstats.ncs_miss + lnchstats.ncs_long;
744 	(void)printf("%9ld total name lookups\n", nchtotal);
745 	(void)printf(
746 	    "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
747 	    "", PCT(lnchstats.ncs_goodhits, nchtotal),
748 	    PCT(lnchstats.ncs_neghits, nchtotal),
749 	    PCT(lnchstats.ncs_pass2, nchtotal));
750 	(void)printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
751 	    PCT(lnchstats.ncs_badhits, nchtotal),
752 	    PCT(lnchstats.ncs_falsehits, nchtotal),
753 	    PCT(lnchstats.ncs_long, nchtotal));
754 }
755 
756 static void
757 doforkst(void)
758 {
759 	fill_vmmeter(&sum);
760 	(void)printf("%u forks, %u pages, average %.2f\n",
761 	    sum.v_forks, sum.v_forkpages,
762 	    sum.v_forks == 0 ? 0.0 :
763 	    (double)sum.v_forkpages / sum.v_forks);
764 	(void)printf("%u vforks, %u pages, average %.2f\n",
765 	    sum.v_vforks, sum.v_vforkpages,
766 	    sum.v_vforks == 0 ? 0.0 :
767 	    (double)sum.v_vforkpages / sum.v_vforks);
768 	(void)printf("%u rforks, %u pages, average %.2f\n",
769 	    sum.v_rforks, sum.v_rforkpages,
770 	    sum.v_rforks == 0 ? 0.0 :
771 	    (double)sum.v_rforkpages / sum.v_rforks);
772 }
773 
774 static void
775 devstats(void)
776 {
777 	int dn, state;
778 	long double transfers_per_second;
779 	long double busy_seconds;
780 	long tmp;
781 
782 	for (state = 0; state < CPUSTATES; ++state) {
783 		tmp = cur.cp_time[state];
784 		cur.cp_time[state] -= last.cp_time[state];
785 		last.cp_time[state] = tmp;
786 	}
787 
788 	busy_seconds = cur.snap_time - last.snap_time;
789 
790 	for (dn = 0; dn < num_devices; dn++) {
791 		int di;
792 
793 		if ((dev_select[dn].selected == 0)
794 		 || (dev_select[dn].selected > maxshowdevs))
795 			continue;
796 
797 		di = dev_select[dn].position;
798 
799 		if (devstat_compute_statistics(&cur.dinfo->devices[di],
800 		    &last.dinfo->devices[di], busy_seconds,
801 		    DSM_TRANSFERS_PER_SECOND, &transfers_per_second,
802 		    DSM_NONE) != 0)
803 			errx(1, "%s", devstat_errbuf);
804 
805 		(void)printf("%3.0Lf ", transfers_per_second);
806 	}
807 }
808 
809 static void
810 cpustats(void)
811 {
812 	int state;
813 	double lpct, total;
814 
815 	total = 0;
816 	for (state = 0; state < CPUSTATES; ++state)
817 		total += cur.cp_time[state];
818 	if (total)
819 		lpct = 100.0 / total;
820 	else
821 		lpct = 0.0;
822 	(void)printf("%2.0f ", (cur.cp_time[CP_USER] +
823 				cur.cp_time[CP_NICE]) * lpct);
824 	(void)printf("%2.0f ", (cur.cp_time[CP_SYS] +
825 				cur.cp_time[CP_INTR]) * lpct);
826 	(void)printf("%2.0f", cur.cp_time[CP_IDLE] * lpct);
827 }
828 
829 static void
830 dointr(void)
831 {
832 	unsigned long *intrcnt, uptime;
833 	uint64_t inttotal;
834 	size_t clen, inamlen, intrcntlen, istrnamlen;
835 	unsigned int i, nintr;
836 	char *intrname, *tintrname;
837 
838 	uptime = getuptime();
839 	if (kd != NULL) {
840 		intrcntlen = namelist[X_EINTRCNT].n_value -
841 		    namelist[X_INTRCNT].n_value;
842 		inamlen = namelist[X_EINTRNAMES].n_value -
843 		    namelist[X_INTRNAMES].n_value;
844 		if ((intrcnt = malloc(intrcntlen)) == NULL ||
845 		    (intrname = malloc(inamlen)) == NULL)
846 			err(1, "malloc()");
847 		kread(X_INTRCNT, intrcnt, intrcntlen);
848 		kread(X_INTRNAMES, intrname, inamlen);
849 	} else {
850 		for (intrcnt = NULL, intrcntlen = 1024; ; intrcntlen *= 2) {
851 			if ((intrcnt = reallocf(intrcnt, intrcntlen)) == NULL)
852 				err(1, "reallocf()");
853 			if (mysysctl("hw.intrcnt",
854 			    intrcnt, &intrcntlen, NULL, 0) == 0)
855 				break;
856 		}
857 		for (intrname = NULL, inamlen = 1024; ; inamlen *= 2) {
858 			if ((intrname = reallocf(intrname, inamlen)) == NULL)
859 				err(1, "reallocf()");
860 			if (mysysctl("hw.intrnames",
861 			    intrname, &inamlen, NULL, 0) == 0)
862 				break;
863 		}
864 	}
865 	nintr = intrcntlen / sizeof(unsigned long);
866 	tintrname = intrname;
867 	istrnamlen = strlen("interrupt");
868 	for (i = 0; i < nintr; i++) {
869 		clen = strlen(tintrname);
870 		if (clen > istrnamlen)
871 			istrnamlen = clen;
872 		tintrname += clen + 1;
873 	}
874 	(void)printf("%-*s %20s %10s\n", istrnamlen, "interrupt", "total",
875 	    "rate");
876 	inttotal = 0;
877 	for (i = 0; i < nintr; i++) {
878 		if (intrname[0] != '\0' && (*intrcnt != 0 || aflag))
879 			(void)printf("%-*s %20lu %10lu\n", istrnamlen, intrname,
880 			    *intrcnt, *intrcnt / uptime);
881 		intrname += strlen(intrname) + 1;
882 		inttotal += *intrcnt++;
883 	}
884 	(void)printf("%-*s %20llu %10llu\n", istrnamlen, "Total",
885 	    (long long)inttotal, (long long)(inttotal / uptime));
886 }
887 
888 static void
889 domemstat_malloc(void)
890 {
891 	struct memory_type_list *mtlp;
892 	struct memory_type *mtp;
893 	int error, first, i;
894 
895 	mtlp = memstat_mtl_alloc();
896 	if (mtlp == NULL) {
897 		warn("memstat_mtl_alloc");
898 		return;
899 	}
900 	if (kd == NULL) {
901 		if (memstat_sysctl_malloc(mtlp, 0) < 0) {
902 			warnx("memstat_sysctl_malloc: %s",
903 			    memstat_strerror(memstat_mtl_geterror(mtlp)));
904 			return;
905 		}
906 	} else {
907 		if (memstat_kvm_malloc(mtlp, kd) < 0) {
908 			error = memstat_mtl_geterror(mtlp);
909 			if (error == MEMSTAT_ERROR_KVM)
910 				warnx("memstat_kvm_malloc: %s",
911 				    kvm_geterr(kd));
912 			else
913 				warnx("memstat_kvm_malloc: %s",
914 				    memstat_strerror(error));
915 		}
916 	}
917 	printf("%13s %5s %6s %7s %8s  Size(s)\n", "Type", "InUse", "MemUse",
918 	    "HighUse", "Requests");
919 	for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
920 	    mtp = memstat_mtl_next(mtp)) {
921 		if (memstat_get_numallocs(mtp) == 0 &&
922 		    memstat_get_count(mtp) == 0)
923 			continue;
924 		printf("%13s %5lld %5lldK %7s %8lld  ",
925 		    memstat_get_name(mtp), memstat_get_count(mtp),
926 		    ((int64_t)memstat_get_bytes(mtp) + 1023) / 1024, "-",
927 		    memstat_get_numallocs(mtp));
928 		first = 1;
929 		for (i = 0; i < 32; i++) {
930 			if (memstat_get_sizemask(mtp) & (1 << i)) {
931 				if (!first)
932 					printf(",");
933 				printf("%d", 1 << (i + 4));
934 				first = 0;
935 			}
936 		}
937 		printf("\n");
938 	}
939 	memstat_mtl_free(mtlp);
940 }
941 
942 static void
943 domemstat_zone(void)
944 {
945 	struct memory_type_list *mtlp;
946 	struct memory_type *mtp;
947 	char name[MEMTYPE_MAXNAME + 1];
948 	int error;
949 
950 	mtlp = memstat_mtl_alloc();
951 	if (mtlp == NULL) {
952 		warn("memstat_mtl_alloc");
953 		return;
954 	}
955 	if (kd == NULL) {
956 		if (memstat_sysctl_uma(mtlp, 0) < 0) {
957 			warnx("memstat_sysctl_uma: %s",
958 			    memstat_strerror(memstat_mtl_geterror(mtlp)));
959 			return;
960 		}
961 	} else {
962 		if (memstat_kvm_uma(mtlp, kd) < 0) {
963 			error = memstat_mtl_geterror(mtlp);
964 			if (error == MEMSTAT_ERROR_KVM)
965 				warnx("memstat_kvm_uma: %s",
966 				    kvm_geterr(kd));
967 			else
968 				warnx("memstat_kvm_uma: %s",
969 				    memstat_strerror(error));
970 		}
971 	}
972 	printf("%-20s %8s  %8s  %8s  %8s  %8s  %8s\n\n", "ITEM", "SIZE",
973 	    "LIMIT", "USED", "FREE", "REQUESTS", "FAILURES");
974 	for (mtp = memstat_mtl_first(mtlp); mtp != NULL;
975 	    mtp = memstat_mtl_next(mtp)) {
976 		strlcpy(name, memstat_get_name(mtp), MEMTYPE_MAXNAME);
977 		strcat(name, ":");
978 		printf("%-20s %8llu, %8llu, %8llu, %8llu, %8llu, %8llu\n", name,
979 		    memstat_get_size(mtp), memstat_get_countlimit(mtp),
980 		    memstat_get_count(mtp), memstat_get_free(mtp),
981 		    memstat_get_numallocs(mtp), memstat_get_failures(mtp));
982 	}
983 	memstat_mtl_free(mtlp);
984 	printf("\n");
985 }
986 
987 /*
988  * kread reads something from the kernel, given its nlist index.
989  */
990 static void
991 kreado(int nlx, void *addr, size_t size, size_t offset)
992 {
993 	const char *sym;
994 
995 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
996 		sym = namelist[nlx].n_name;
997 		if (*sym == '_')
998 			++sym;
999 		errx(1, "symbol %s not defined", sym);
1000 	}
1001 	if ((size_t)kvm_read(kd, namelist[nlx].n_value + offset, addr,
1002 	    size) != size) {
1003 		sym = namelist[nlx].n_name;
1004 		if (*sym == '_')
1005 			++sym;
1006 		errx(1, "%s: %s", sym, kvm_geterr(kd));
1007 	}
1008 }
1009 
1010 static void
1011 kread(int nlx, void *addr, size_t size)
1012 {
1013 	kreado(nlx, addr, size, 0);
1014 }
1015 
1016 static char *
1017 kgetstr(const char *strp)
1018 {
1019 	int n = 0, size = 1;
1020 	char *ret = NULL;
1021 
1022 	do {
1023 		if (size == n + 1) {
1024 			ret = realloc(ret, size);
1025 			if (ret == NULL)
1026 				err(1, "%s: realloc", __func__);
1027 			size *= 2;
1028 		}
1029 		if (kvm_read(kd, (u_long)strp + n, &ret[n], 1) != 1)
1030 			errx(1, "%s: %s", __func__, kvm_geterr(kd));
1031 	} while (ret[n++] != '\0');
1032 	return (ret);
1033 }
1034 
1035 static void
1036 usage(void)
1037 {
1038 	(void)fprintf(stderr, "%s%s",
1039 		"usage: vmstat [-afimsz] [-c count] [-M core [-N system]] [-w wait]\n",
1040 		"              [-n devs] [-p type,if,pass] [disks]\n");
1041 	exit(1);
1042 }
1043