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