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