vmstat.c revision 34214
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
35static 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#ifndef lint
41#if 0
42static char sccsid[] = "@(#)vmstat.c	8.1 (Berkeley) 6/6/93";
43#endif
44static const char rcsid[] =
45	"$Id: vmstat.c,v 1.22 1997/12/05 19:28:28 bde Exp $";
46#endif /* not lint */
47
48#include <sys/param.h>
49#include <sys/time.h>
50#include <sys/proc.h>
51#include <sys/dkstat.h>
52#include <sys/buf.h>
53#include <sys/uio.h>
54#include <sys/namei.h>
55#include <sys/malloc.h>
56#include <sys/signal.h>
57#include <sys/fcntl.h>
58#include <sys/ioctl.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 <err.h>
66#include <errno.h>
67#include <kvm.h>
68#include <limits.h>
69#include <nlist.h>
70#include <paths.h>
71#include <stdio.h>
72#include <stdlib.h>
73#include <string.h>
74#include <sysexits.h>
75#include <time.h>
76#include <unistd.h>
77
78struct nlist namelist[] = {
79#define	X_CPTIME	0
80	{ "_cp_time" },
81#define	X_DK_NDRIVE	1
82	{ "_dk_ndrive" },
83#define X_SUM		2
84	{ "_cnt" },
85#define	X_BOOTTIME	3
86	{ "_boottime" },
87#define	X_DKXFER	4
88	{ "_dk_xfer" },
89#define X_HZ		5
90	{ "_hz" },
91#define X_STATHZ	6
92	{ "_stathz" },
93#define X_NCHSTATS	7
94	{ "_nchstats" },
95#define	X_INTRNAMES	8
96	{ "_intrnames" },
97#define	X_EINTRNAMES	9
98	{ "_eintrnames" },
99#define	X_INTRCNT	10
100	{ "_intrcnt" },
101#define	X_EINTRCNT	11
102	{ "_eintrcnt" },
103#define	X_KMEMSTATISTICS	12
104	{ "_kmemstatistics" },
105#define	X_KMEMBUCKETS	13
106	{ "_bucket" },
107#ifdef notyet
108#define	X_DEFICIT	14
109	{ "_deficit" },
110#define	X_FORKSTAT	15
111	{ "_forkstat" },
112#define X_REC		16
113	{ "_rectime" },
114#define X_PGIN		17
115	{ "_pgintime" },
116#define	X_XSTATS	18
117	{ "_xstats" },
118#define X_END		19
119#else
120#define X_END		14
121#endif
122#if defined(hp300) || defined(luna68k)
123#define	X_HPDINIT	(X_END)
124	{ "_hp_dinit" },
125#endif
126#if defined(i386)
127#define X_DK_NAMES	(X_END)
128	{ "_dk_names" },
129#endif
130#ifdef mips
131#define	X_SCSI_DINIT	(X_END)
132	{ "_scsi_dinit" },
133#endif
134#ifdef tahoe
135#define	X_VBDINIT	(X_END)
136	{ "_vbdinit" },
137#define	X_CKEYSTATS	(X_END+1)
138	{ "_ckeystats" },
139#define	X_DKEYSTATS	(X_END+2)
140	{ "_dkeystats" },
141#endif
142#ifdef vax
143#define X_MBDINIT	(X_END)
144	{ "_mbdinit" },
145#define X_UBDINIT	(X_END+1)
146	{ "_ubdinit" },
147#endif
148	{ "" },
149};
150
151struct _disk {
152	long time[CPUSTATES];
153	long *xfer;
154} cur, last;
155
156struct	vmmeter sum, osum;
157char	**dr_name;
158int	*dr_select, dk_ndrive, ndrives;
159
160int	winlines = 20;
161
162kvm_t *kd;
163
164#define	FORKSTAT	0x01
165#define	INTRSTAT	0x02
166#define	MEMSTAT		0x04
167#define	SUMSTAT		0x08
168#define	TIMESTAT	0x10
169#define	VMSTAT		0x20
170
171#include "names.c"			/* disk names -- machine dependent */
172
173void	cpustats(), dkstats(), dointr(), domem(), dosum();
174void	dovmstat(), kread(), usage();
175#ifdef notyet
176void	dotimes(), doforkst();
177#endif
178void printhdr __P((void));
179
180int
181main(argc, argv)
182	register int argc;
183	register char **argv;
184{
185	register int c, todo;
186	u_int interval;
187	int reps;
188	char *memf, *nlistf;
189        char errbuf[_POSIX2_LINE_MAX];
190
191	memf = nlistf = NULL;
192	interval = reps = todo = 0;
193	while ((c = getopt(argc, argv, "c:fiM:mN:stw:")) != -1) {
194		switch (c) {
195		case 'c':
196			reps = atoi(optarg);
197			break;
198		case 'f':
199#ifdef notyet
200			todo |= FORKSTAT;
201#else
202			errx(EX_USAGE, "sorry, -f is not (re)implemented yet");
203#endif
204			break;
205		case 'i':
206			todo |= INTRSTAT;
207			break;
208		case 'M':
209			memf = optarg;
210			break;
211		case 'm':
212			todo |= MEMSTAT;
213			break;
214		case 'N':
215			nlistf = optarg;
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 '?':
231		default:
232			usage();
233		}
234	}
235	argc -= optind;
236	argv += optind;
237
238	if (todo == 0)
239		todo = VMSTAT;
240
241	/*
242	 * Discard setgid privileges if not the running kernel so that bad
243	 * guys can't print interesting stuff from kernel memory.
244	 */
245	if (nlistf != NULL || memf != NULL)
246		setgid(getgid());
247
248	kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
249	if (kd == 0)
250		errx(1, "kvm_openfiles: %s", errbuf);
251
252	if ((c = kvm_nlist(kd, namelist)) != 0) {
253		if (c > 0) {
254			warnx("undefined symbols:");
255			for (c = 0;
256			    c < sizeof(namelist)/sizeof(namelist[0]); c++)
257				if (namelist[c].n_type == 0)
258					fprintf(stderr, " %s",
259					    namelist[c].n_name);
260			(void)fputc('\n', stderr);
261		} else
262			warnx("kvm_nlist: %s", kvm_geterr(kd));
263		exit(1);
264	}
265
266	if (todo & VMSTAT) {
267		char **getdrivedata();
268		struct winsize winsize;
269
270		argv = getdrivedata(argv);
271		winsize.ws_row = 0;
272		(void) ioctl(STDOUT_FILENO, TIOCGWINSZ, (char *)&winsize);
273		if (winsize.ws_row > 0)
274			winlines = winsize.ws_row;
275
276	}
277
278#define	BACKWARD_COMPATIBILITY
279#ifdef	BACKWARD_COMPATIBILITY
280	if (*argv) {
281		interval = atoi(*argv);
282		if (*++argv)
283			reps = atoi(*argv);
284	}
285#endif
286
287	if (interval) {
288		if (!reps)
289			reps = -1;
290	} else if (reps)
291		interval = 1;
292
293#ifdef notyet
294	if (todo & FORKSTAT)
295		doforkst();
296#endif
297	if (todo & MEMSTAT)
298		domem();
299	if (todo & SUMSTAT)
300		dosum();
301#ifdef notyet
302	if (todo & TIMESTAT)
303		dotimes();
304#endif
305	if (todo & INTRSTAT)
306		dointr();
307	if (todo & VMSTAT)
308		dovmstat(interval, reps);
309	exit(0);
310}
311
312char **
313getdrivedata(argv)
314	char **argv;
315{
316	register int i;
317	register char **cp;
318	char buf[30];
319
320	kread(X_DK_NDRIVE, &dk_ndrive, sizeof(dk_ndrive));
321	if (dk_ndrive < 0)
322		errx(1, "dk_ndrive %d", dk_ndrive);
323	dr_select = calloc((size_t)dk_ndrive, sizeof(int));
324	dr_name = calloc((size_t)dk_ndrive, sizeof(char *));
325	for (i = 0; i < dk_ndrive; i++)
326		dr_name[i] = NULL;
327	cur.xfer = calloc((size_t)dk_ndrive, sizeof(long));
328	last.xfer = calloc((size_t)dk_ndrive, sizeof(long));
329	if (!read_names())
330		exit (1);
331	for (i = 0; i < dk_ndrive; i++)
332		if (dr_name[i] == NULL) {
333			(void)sprintf(buf, "??%d", i);
334			dr_name[i] = strdup(buf);
335		}
336
337	/*
338	 * Choose drives to be displayed.  Priority goes to (in order) drives
339	 * supplied as arguments, default drives.  If everything isn't filled
340	 * in and there are drives not taken care of, display the first few
341	 * that fit.
342	 */
343#define BACKWARD_COMPATIBILITY
344	for (ndrives = 0; *argv; ++argv) {
345#ifdef	BACKWARD_COMPATIBILITY
346		if (isdigit(**argv))
347			break;
348#endif
349		for (i = 0; i < dk_ndrive; i++) {
350			if (strcmp(dr_name[i], *argv))
351				continue;
352			dr_select[i] = 1;
353			++ndrives;
354			break;
355		}
356	}
357	for (i = 0; i < dk_ndrive && ndrives < 4; i++) {
358		if (dr_select[i])
359			continue;
360		for (cp = defdrives; *cp; cp++)
361			if (strcmp(dr_name[i], *cp) == 0) {
362				dr_select[i] = 1;
363				++ndrives;
364				break;
365			}
366	}
367	for (i = 0; i < dk_ndrive && ndrives < 4; i++) {
368		if (dr_select[i])
369			continue;
370		dr_select[i] = 1;
371		++ndrives;
372	}
373	return(argv);
374}
375
376long
377getuptime()
378{
379	static time_t now, boottime;
380	time_t uptime;
381
382	if (boottime == 0)
383		kread(X_BOOTTIME, &boottime, sizeof(boottime));
384	(void)time(&now);
385	uptime = now - boottime;
386	if (uptime <= 0 || uptime > 60*60*24*365*10)
387		errx(1, "time makes no sense; namelist must be wrong");
388	return(uptime);
389}
390
391int	hz, hdrcnt;
392
393void
394dovmstat(interval, reps)
395	u_int interval;
396	int reps;
397{
398	struct vmtotal total;
399	time_t uptime, halfuptime;
400	void needhdr();
401	int mib[2], size;
402
403	uptime = getuptime();
404	halfuptime = uptime / 2;
405	(void)signal(SIGCONT, needhdr);
406
407	if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
408		kread(X_STATHZ, &hz, sizeof(hz));
409	if (!hz)
410		kread(X_HZ, &hz, sizeof(hz));
411
412	for (hdrcnt = 1;;) {
413		if (!--hdrcnt)
414			printhdr();
415		kread(X_CPTIME, cur.time, sizeof(cur.time));
416		kread(X_DKXFER, cur.xfer, sizeof(*cur.xfer) * dk_ndrive);
417		kread(X_SUM, &sum, sizeof(sum));
418		size = sizeof(total);
419		mib[0] = CTL_VM;
420		mib[1] = VM_METER;
421		if (sysctl(mib, 2, &total, &size, NULL, 0) < 0) {
422			printf("Can't get kerninfo: %s\n", strerror(errno));
423			bzero(&total, sizeof(total));
424		}
425		(void)printf("%2d%2d%2d",
426		    total.t_rq - 1, total.t_dw + total.t_pw, total.t_sw);
427#define pgtok(a) ((a) * sum.v_page_size >> 10)
428#define	rate(x)	(((x) + halfuptime) / uptime)	/* round */
429		(void)printf("%8ld%6ld ",
430		    (long)pgtok(total.t_avm), (long)pgtok(total.t_free));
431		(void)printf("%4lu ", rate(sum.v_vm_faults - osum.v_vm_faults));
432		(void)printf("%3lu ",
433		    rate(sum.v_reactivated - osum.v_reactivated));
434		(void)printf("%3lu ", rate(sum.v_swapin + sum.v_vnodein -
435		    (osum.v_swapin + osum.v_vnodein)));
436		(void)printf("%3lu ", rate(sum.v_swapout + sum.v_vnodeout -
437		    (osum.v_swapout + osum.v_vnodeout)));
438		(void)printf("%3lu ", rate(sum.v_tfree - osum.v_tfree));
439		(void)printf("%3lu ", rate(sum.v_pdpages - osum.v_pdpages));
440		dkstats();
441		(void)printf("%4lu %4lu %3lu ",
442		    rate(sum.v_intr - osum.v_intr),
443		    rate(sum.v_syscall - osum.v_syscall),
444		    rate(sum.v_swtch - osum.v_swtch));
445		cpustats();
446		(void)printf("\n");
447		(void)fflush(stdout);
448		if (reps >= 0 && --reps <= 0)
449			break;
450		osum = sum;
451		uptime = interval;
452		/*
453		 * We round upward to avoid losing low-frequency events
454		 * (i.e., >= 1 per interval but < 1 per second).
455		 */
456		if (interval != 1)
457			halfuptime = (uptime + 1) / 2;
458		else
459			halfuptime = 0;
460		(void)sleep(interval);
461	}
462}
463
464void
465printhdr()
466{
467	register int i;
468
469	(void)printf(" procs      memory     page%*s", 20, "");
470	if (ndrives > 1)
471		(void)printf("disks %*s  faults      cpu\n",
472		   ndrives * 3 - 6, "");
473	else
474		(void)printf("%*s  faults      cpu\n", ndrives * 3, "");
475	(void)printf(" r b w     avm   fre  flt  re  pi  po  fr  sr ");
476	for (i = 0; i < dk_ndrive; i++)
477		if (dr_select[i])
478			(void)printf("%c%c ", dr_name[i][0],
479			    dr_name[i][strlen(dr_name[i]) - 1]);
480	(void)printf("  in   sy  cs us sy id\n");
481	hdrcnt = winlines - 2;
482}
483
484/*
485 * Force a header to be prepended to the next output.
486 */
487void
488needhdr()
489{
490
491	hdrcnt = 1;
492}
493
494#ifdef notyet
495void
496dotimes()
497{
498	u_int pgintime, rectime;
499
500	kread(X_REC, &rectime, sizeof(rectime));
501	kread(X_PGIN, &pgintime, sizeof(pgintime));
502	kread(X_SUM, &sum, sizeof(sum));
503	(void)printf("%u reclaims, %u total time (usec)\n",
504	    sum.v_pgrec, rectime);
505	(void)printf("average: %u usec / reclaim\n", rectime / sum.v_pgrec);
506	(void)printf("\n");
507	(void)printf("%u page ins, %u total time (msec)\n",
508	    sum.v_pgin, pgintime / 10);
509	(void)printf("average: %8.1f msec / page in\n",
510	    pgintime / (sum.v_pgin * 10.0));
511}
512#endif
513
514long
515pct(top, bot)
516	long top, bot;
517{
518	long ans;
519
520	if (bot == 0)
521		return(0);
522	ans = (quad_t)top * 100 / bot;
523	return (ans);
524}
525
526#define	PCT(top, bot) pct((long)(top), (long)(bot))
527
528#if defined(tahoe)
529#include <machine/cpu.h>
530#endif
531
532void
533dosum()
534{
535	struct nchstats nchstats;
536	long nchtotal;
537#if defined(tahoe)
538	struct keystats keystats;
539#endif
540
541	kread(X_SUM, &sum, sizeof(sum));
542	(void)printf("%9u cpu context switches\n", sum.v_swtch);
543	(void)printf("%9u device interrupts\n", sum.v_intr);
544	(void)printf("%9u software interrupts\n", sum.v_soft);
545#ifdef vax
546	(void)printf("%9u pseudo-dma dz interrupts\n", sum.v_pdma);
547#endif
548	(void)printf("%9u traps\n", sum.v_trap);
549	(void)printf("%9u system calls\n", sum.v_syscall);
550	(void)printf("%9u swap pager pageins\n", sum.v_swapin);
551	(void)printf("%9u swap pager pages paged in\n", sum.v_swappgsin);
552	(void)printf("%9u swap pager pageouts\n", sum.v_swapout);
553	(void)printf("%9u swap pager pages paged out\n", sum.v_swappgsout);
554	(void)printf("%9u vnode pager pageins\n", sum.v_vnodein);
555	(void)printf("%9u vnode pager pages paged in\n", sum.v_vnodepgsin);
556	(void)printf("%9u vnode pager pageouts\n", sum.v_vnodeout);
557	(void)printf("%9u vnode pager pages paged out\n", sum.v_vnodepgsout);
558	(void)printf("%9u page daemon wakeups\n", sum.v_pdwakeups);
559	(void)printf("%9u pages examined by the page daemon\n", sum.v_pdpages);
560	(void)printf("%9u pages reactivated\n", sum.v_reactivated);
561	(void)printf("%9u copy-on-write faults\n", sum.v_cow_faults);
562	(void)printf("%9u copy-on-write optimized faults\n", sum.v_cow_optim);
563	(void)printf("%9u zero fill pages zeroed\n", sum.v_zfod);
564	(void)printf("%9u zero fill pages prezeroed\n", sum.v_ozfod);
565	(void)printf("%9u intransit blocking page faults\n", sum.v_intrans);
566	(void)printf("%9u total VM faults taken\n", sum.v_vm_faults);
567	(void)printf("%9u pages freed\n", sum.v_tfree);
568	(void)printf("%9u pages freed by daemon\n", sum.v_dfree);
569	(void)printf("%9u pages freed by exiting processes\n", sum.v_pfree);
570	(void)printf("%9u pages active\n", sum.v_active_count);
571	(void)printf("%9u pages inactive\n", sum.v_inactive_count);
572	(void)printf("%9u pages in VM cache\n", sum.v_cache_count);
573	(void)printf("%9u pages wired down\n", sum.v_wire_count);
574	(void)printf("%9u pages free\n", sum.v_free_count);
575	(void)printf("%9u bytes per page\n", sum.v_page_size);
576	kread(X_NCHSTATS, &nchstats, sizeof(nchstats));
577	nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
578	    nchstats.ncs_badhits + nchstats.ncs_falsehits +
579	    nchstats.ncs_miss + nchstats.ncs_long;
580	(void)printf("%9ld total name lookups\n", nchtotal);
581	(void)printf(
582	    "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
583	    "", PCT(nchstats.ncs_goodhits, nchtotal),
584	    PCT(nchstats.ncs_neghits, nchtotal),
585	    PCT(nchstats.ncs_pass2, nchtotal));
586	(void)printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
587	    PCT(nchstats.ncs_badhits, nchtotal),
588	    PCT(nchstats.ncs_falsehits, nchtotal),
589	    PCT(nchstats.ncs_long, nchtotal));
590#if defined(tahoe)
591	kread(X_CKEYSTATS, &keystats, sizeof(keystats));
592	(void)printf("%9d %s (free %d%% norefs %d%% taken %d%% shared %d%%)\n",
593	    keystats.ks_allocs, "code cache keys allocated",
594	    PCT(keystats.ks_allocfree, keystats.ks_allocs),
595	    PCT(keystats.ks_norefs, keystats.ks_allocs),
596	    PCT(keystats.ks_taken, keystats.ks_allocs),
597	    PCT(keystats.ks_shared, keystats.ks_allocs));
598	kread(X_DKEYSTATS, &keystats, sizeof(keystats));
599	(void)printf("%9d %s (free %d%% norefs %d%% taken %d%% shared %d%%)\n",
600	    keystats.ks_allocs, "data cache keys allocated",
601	    PCT(keystats.ks_allocfree, keystats.ks_allocs),
602	    PCT(keystats.ks_norefs, keystats.ks_allocs),
603	    PCT(keystats.ks_taken, keystats.ks_allocs),
604	    PCT(keystats.ks_shared, keystats.ks_allocs));
605#endif
606}
607
608#ifdef notyet
609void
610doforkst()
611{
612	struct forkstat fks;
613
614	kread(X_FORKSTAT, &fks, sizeof(struct forkstat));
615	(void)printf("%d forks, %d pages, average %.2f\n",
616	    fks.cntfork, fks.sizfork, (double)fks.sizfork / fks.cntfork);
617	(void)printf("%d vforks, %d pages, average %.2f\n",
618	    fks.cntvfork, fks.sizvfork, (double)fks.sizvfork / fks.cntvfork);
619}
620#endif
621
622void
623dkstats()
624{
625	register int dn, state;
626	double etime;
627	long tmp;
628
629	for (dn = 0; dn < dk_ndrive; ++dn) {
630		tmp = cur.xfer[dn];
631		cur.xfer[dn] -= last.xfer[dn];
632		last.xfer[dn] = tmp;
633	}
634	etime = 0;
635	for (state = 0; state < CPUSTATES; ++state) {
636		tmp = cur.time[state];
637		cur.time[state] -= last.time[state];
638		last.time[state] = tmp;
639		etime += cur.time[state];
640	}
641	if (etime == 0)
642		etime = 1;
643	etime /= hz;
644	for (dn = 0; dn < dk_ndrive; ++dn) {
645		if (!dr_select[dn])
646			continue;
647		(void)printf("%2.0f ", cur.xfer[dn] / etime);
648	}
649}
650
651void
652cpustats()
653{
654	register int state;
655	double pct, total;
656
657	total = 0;
658	for (state = 0; state < CPUSTATES; ++state)
659		total += cur.time[state];
660	if (total)
661		pct = 100 / total;
662	else
663		pct = 0;
664	(void)printf("%2.0f ", (cur.time[CP_USER] + cur.time[CP_NICE]) * pct);
665	(void)printf("%2.0f ", (cur.time[CP_SYS] + cur.time[CP_INTR]) * pct);
666	(void)printf("%2.0f", cur.time[CP_IDLE] * pct);
667}
668
669void
670dointr()
671{
672	register long *intrcnt, inttotal, uptime;
673	register int nintr, inamlen;
674	register char *intrname;
675
676	uptime = getuptime();
677	nintr = namelist[X_EINTRCNT].n_value - namelist[X_INTRCNT].n_value;
678	inamlen =
679	    namelist[X_EINTRNAMES].n_value - namelist[X_INTRNAMES].n_value;
680	intrcnt = malloc((size_t)nintr);
681	intrname = malloc((size_t)inamlen);
682	if (intrcnt == NULL || intrname == NULL)
683		errx(1, "malloc");
684	kread(X_INTRCNT, intrcnt, (size_t)nintr);
685	kread(X_INTRNAMES, intrname, (size_t)inamlen);
686	(void)printf("interrupt      total      rate\n");
687	inttotal = 0;
688	nintr /= sizeof(long);
689	while (--nintr >= 0) {
690		if (*intrcnt)
691			(void)printf("%-12s %8ld %8ld\n", intrname,
692			    *intrcnt, *intrcnt / uptime);
693		intrname += strlen(intrname) + 1;
694		inttotal += *intrcnt++;
695	}
696	(void)printf("Total        %8ld %8ld\n", inttotal, inttotal / uptime);
697}
698
699void
700domem()
701{
702	register struct kmembuckets *kp;
703	register struct malloc_type *ks;
704	register int i, j;
705	int len, size, first, nkms;
706	long totuse = 0, totfree = 0, totreq = 0;
707	const char *name;
708	struct malloc_type kmemstats[200],*kmsp;
709	char *kmemnames[200];
710	char buf[1024];
711	struct kmembuckets buckets[MINBUCKET + 16];
712
713	kread(X_KMEMBUCKETS, buckets, sizeof(buckets));
714	kread(X_KMEMSTATISTICS, &kmsp, sizeof(kmsp));
715	for (nkms=0; nkms < 200 && kmsp; nkms++) {
716		if (sizeof(kmemstats[0]) != kvm_read(kd, (u_long)kmsp,
717		    &kmemstats[nkms], sizeof(kmemstats[0])))
718			err(1,"kvm_read(%08x)", (u_long)kmsp);
719		if (sizeof(buf) !=  kvm_read(kd,
720	            (u_long)kmemstats[nkms].ks_shortdesc, buf, sizeof(buf)))
721			err(1,"kvm_read(%08x)",
722			    (u_long)kmemstats[nkms].ks_shortdesc);
723		kmemstats[nkms].ks_shortdesc = strdup(buf);
724		kmsp = kmemstats[nkms].ks_next;
725	}
726	(void)printf("Memory statistics by bucket size\n");
727	(void)printf(
728	    "Size   In Use   Free   Requests  HighWater  Couldfree\n");
729	for (i = MINBUCKET, kp = &buckets[i]; i < MINBUCKET + 16; i++, kp++) {
730		if (kp->kb_calls == 0)
731			continue;
732		size = 1 << i;
733		if(size < 1024)
734			(void)printf("%4d",size);
735		else
736			(void)printf("%3dK",size>>10);
737		(void)printf(" %8ld %6ld %10ld %7ld %10ld\n",
738			kp->kb_total - kp->kb_totalfree,
739			kp->kb_totalfree, kp->kb_calls,
740			kp->kb_highwat, kp->kb_couldfree);
741		totfree += size * kp->kb_totalfree;
742	}
743
744	(void)printf("\nMemory usage type by bucket size\n");
745	(void)printf("Size  Type(s)\n");
746	kp = &buckets[MINBUCKET];
747	for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1, kp++) {
748		if (kp->kb_calls == 0)
749			continue;
750		first = 1;
751		len = 8;
752		for (i = 0, ks = &kmemstats[0]; i < nkms; i++, ks++) {
753			if (ks->ks_calls == 0)
754				continue;
755			if ((ks->ks_size & j) == 0)
756				continue;
757			name = ks->ks_shortdesc;
758			len += 2 + strlen(name);
759			if (first && j < 1024)
760				printf("%4d  %s", j, name);
761			else if (first)
762				printf("%3dK  %s", j>>10, name);
763			else
764				printf(",");
765			if (len >= 79) {
766				printf("\n\t ");
767				len = 10 + strlen(name);
768			}
769			if (!first)
770				printf(" %s", name);
771			first = 0;
772		}
773		printf("\n");
774	}
775
776	(void)printf(
777	    "\nMemory statistics by type                          Type  Kern\n");
778	(void)printf(
779"        Type  InUse MemUse HighUse  Limit Requests Limit Limit Size(s)\n");
780	for (i = 0, ks = &kmemstats[0]; i < nkms; i++, ks++) {
781		if (ks->ks_calls == 0)
782			continue;
783		(void)printf("%13s%6ld%6ldK%7ldK%6ldK%9ld%5u%6u",
784		    ks->ks_shortdesc,
785		    ks->ks_inuse, (ks->ks_memuse + 1023) / 1024,
786		    (ks->ks_maxused + 1023) / 1024,
787		    (ks->ks_limit + 1023) / 1024, ks->ks_calls,
788		    ks->ks_limblocks, ks->ks_mapblocks);
789		first = 1;
790		for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
791			if ((ks->ks_size & j) == 0)
792				continue;
793			if (first)
794				printf("  ");
795			else
796				printf(",");
797			if(j<1024)
798				printf("%d",j);
799			else
800				printf("%dK",j>>10);
801			first = 0;
802		}
803		printf("\n");
804		totuse += ks->ks_memuse;
805		totreq += ks->ks_calls;
806	}
807	(void)printf("\nMemory Totals:  In Use    Free    Requests\n");
808	(void)printf("              %7ldK %6ldK    %8ld\n",
809	     (totuse + 1023) / 1024, (totfree + 1023) / 1024, totreq);
810}
811
812/*
813 * kread reads something from the kernel, given its nlist index.
814 */
815void
816kread(nlx, addr, size)
817	int nlx;
818	void *addr;
819	size_t size;
820{
821	char *sym;
822
823	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
824		sym = namelist[nlx].n_name;
825		if (*sym == '_')
826			++sym;
827		errx(1, "symbol %s not defined", sym);
828	}
829	if (kvm_read(kd, namelist[nlx].n_value, addr, size) != size) {
830		sym = namelist[nlx].n_name;
831		if (*sym == '_')
832			++sym;
833		errx(1, "%s: %s", sym, kvm_geterr(kd));
834	}
835}
836
837void
838usage()
839{
840	(void)fprintf(stderr,
841"usage: vmstat [-ims] [-c count] [-M core] [-N system] [-w wait] [disks]\n");
842	exit(1);
843}
844