xref: /freebsd/usr.bin/vmstat/vmstat.c (revision 33b77e2decd50e53798014b70bf7ca3bdc4c0c7e)
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: vmstat.c,v 1.21 1997/10/10 18:19:48 phk 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 
78 struct 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 
151 struct _disk {
152 	long time[CPUSTATES];
153 	long *xfer;
154 } cur, last;
155 
156 struct	vmmeter sum, osum;
157 char	**dr_name;
158 int	*dr_select, dk_ndrive, ndrives;
159 
160 int	winlines = 20;
161 
162 kvm_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 
173 void	cpustats(), dkstats(), dointr(), domem(), dosum();
174 void	dovmstat(), kread(), usage();
175 #ifdef notyet
176 void	dotimes(), doforkst();
177 #endif
178 void printhdr __P((void));
179 
180 int
181 main(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 
312 char **
313 getdrivedata(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 
376 long
377 getuptime()
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 
391 int	hz, hdrcnt;
392 
393 void
394 dovmstat(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 
464 void
465 printhdr()
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  */
487 void
488 needhdr()
489 {
490 
491 	hdrcnt = 1;
492 }
493 
494 #ifdef notyet
495 void
496 dotimes()
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 
514 long
515 pct(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 
532 void
533 dosum()
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 zero fill pages zeroed\n", sum.v_zfod);
563 	(void)printf("%9u intransit blocking page faults\n", sum.v_intrans);
564 	(void)printf("%9u total VM faults taken\n", sum.v_vm_faults);
565 	(void)printf("%9u pages freed\n", sum.v_tfree);
566 	(void)printf("%9u pages freed by daemon\n", sum.v_dfree);
567 	(void)printf("%9u pages freed by exiting processes\n", sum.v_pfree);
568 	(void)printf("%9u pages active\n", sum.v_active_count);
569 	(void)printf("%9u pages inactive\n", sum.v_inactive_count);
570 	(void)printf("%9u pages in VM cache\n", sum.v_cache_count);
571 	(void)printf("%9u pages wired down\n", sum.v_wire_count);
572 	(void)printf("%9u pages free\n", sum.v_free_count);
573 	(void)printf("%9u bytes per page\n", sum.v_page_size);
574 	kread(X_NCHSTATS, &nchstats, sizeof(nchstats));
575 	nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
576 	    nchstats.ncs_badhits + nchstats.ncs_falsehits +
577 	    nchstats.ncs_miss + nchstats.ncs_long;
578 	(void)printf("%9ld total name lookups\n", nchtotal);
579 	(void)printf(
580 	    "%9s cache hits (%ld%% pos + %ld%% neg) system %ld%% per-directory\n",
581 	    "", PCT(nchstats.ncs_goodhits, nchtotal),
582 	    PCT(nchstats.ncs_neghits, nchtotal),
583 	    PCT(nchstats.ncs_pass2, nchtotal));
584 	(void)printf("%9s deletions %ld%%, falsehits %ld%%, toolong %ld%%\n", "",
585 	    PCT(nchstats.ncs_badhits, nchtotal),
586 	    PCT(nchstats.ncs_falsehits, nchtotal),
587 	    PCT(nchstats.ncs_long, nchtotal));
588 #if defined(tahoe)
589 	kread(X_CKEYSTATS, &keystats, sizeof(keystats));
590 	(void)printf("%9d %s (free %d%% norefs %d%% taken %d%% shared %d%%)\n",
591 	    keystats.ks_allocs, "code cache keys allocated",
592 	    PCT(keystats.ks_allocfree, keystats.ks_allocs),
593 	    PCT(keystats.ks_norefs, keystats.ks_allocs),
594 	    PCT(keystats.ks_taken, keystats.ks_allocs),
595 	    PCT(keystats.ks_shared, keystats.ks_allocs));
596 	kread(X_DKEYSTATS, &keystats, sizeof(keystats));
597 	(void)printf("%9d %s (free %d%% norefs %d%% taken %d%% shared %d%%)\n",
598 	    keystats.ks_allocs, "data cache keys allocated",
599 	    PCT(keystats.ks_allocfree, keystats.ks_allocs),
600 	    PCT(keystats.ks_norefs, keystats.ks_allocs),
601 	    PCT(keystats.ks_taken, keystats.ks_allocs),
602 	    PCT(keystats.ks_shared, keystats.ks_allocs));
603 #endif
604 }
605 
606 #ifdef notyet
607 void
608 doforkst()
609 {
610 	struct forkstat fks;
611 
612 	kread(X_FORKSTAT, &fks, sizeof(struct forkstat));
613 	(void)printf("%d forks, %d pages, average %.2f\n",
614 	    fks.cntfork, fks.sizfork, (double)fks.sizfork / fks.cntfork);
615 	(void)printf("%d vforks, %d pages, average %.2f\n",
616 	    fks.cntvfork, fks.sizvfork, (double)fks.sizvfork / fks.cntvfork);
617 }
618 #endif
619 
620 void
621 dkstats()
622 {
623 	register int dn, state;
624 	double etime;
625 	long tmp;
626 
627 	for (dn = 0; dn < dk_ndrive; ++dn) {
628 		tmp = cur.xfer[dn];
629 		cur.xfer[dn] -= last.xfer[dn];
630 		last.xfer[dn] = tmp;
631 	}
632 	etime = 0;
633 	for (state = 0; state < CPUSTATES; ++state) {
634 		tmp = cur.time[state];
635 		cur.time[state] -= last.time[state];
636 		last.time[state] = tmp;
637 		etime += cur.time[state];
638 	}
639 	if (etime == 0)
640 		etime = 1;
641 	etime /= hz;
642 	for (dn = 0; dn < dk_ndrive; ++dn) {
643 		if (!dr_select[dn])
644 			continue;
645 		(void)printf("%2.0f ", cur.xfer[dn] / etime);
646 	}
647 }
648 
649 void
650 cpustats()
651 {
652 	register int state;
653 	double pct, total;
654 
655 	total = 0;
656 	for (state = 0; state < CPUSTATES; ++state)
657 		total += cur.time[state];
658 	if (total)
659 		pct = 100 / total;
660 	else
661 		pct = 0;
662 	(void)printf("%2.0f ", (cur.time[CP_USER] + cur.time[CP_NICE]) * pct);
663 	(void)printf("%2.0f ", (cur.time[CP_SYS] + cur.time[CP_INTR]) * pct);
664 	(void)printf("%2.0f", cur.time[CP_IDLE] * pct);
665 }
666 
667 void
668 dointr()
669 {
670 	register long *intrcnt, inttotal, uptime;
671 	register int nintr, inamlen;
672 	register char *intrname;
673 
674 	uptime = getuptime();
675 	nintr = namelist[X_EINTRCNT].n_value - namelist[X_INTRCNT].n_value;
676 	inamlen =
677 	    namelist[X_EINTRNAMES].n_value - namelist[X_INTRNAMES].n_value;
678 	intrcnt = malloc((size_t)nintr);
679 	intrname = malloc((size_t)inamlen);
680 	if (intrcnt == NULL || intrname == NULL)
681 		errx(1, "malloc");
682 	kread(X_INTRCNT, intrcnt, (size_t)nintr);
683 	kread(X_INTRNAMES, intrname, (size_t)inamlen);
684 	(void)printf("interrupt      total      rate\n");
685 	inttotal = 0;
686 	nintr /= sizeof(long);
687 	while (--nintr >= 0) {
688 		if (*intrcnt)
689 			(void)printf("%-12s %8ld %8ld\n", intrname,
690 			    *intrcnt, *intrcnt / uptime);
691 		intrname += strlen(intrname) + 1;
692 		inttotal += *intrcnt++;
693 	}
694 	(void)printf("Total        %8ld %8ld\n", inttotal, inttotal / uptime);
695 }
696 
697 void
698 domem()
699 {
700 	register struct kmembuckets *kp;
701 	register struct malloc_type *ks;
702 	register int i, j;
703 	int len, size, first, nkms;
704 	long totuse = 0, totfree = 0, totreq = 0;
705 	const char *name;
706 	struct malloc_type kmemstats[200],*kmsp;
707 	char *kmemnames[200];
708 	char buf[1024];
709 	struct kmembuckets buckets[MINBUCKET + 16];
710 
711 	kread(X_KMEMBUCKETS, buckets, sizeof(buckets));
712 	kread(X_KMEMSTATISTICS, &kmsp, sizeof(kmsp));
713 	for (nkms=0; nkms < 200 && kmsp; nkms++) {
714 		if (sizeof(kmemstats[0]) != kvm_read(kd, (u_long)kmsp,
715 		    &kmemstats[nkms], sizeof(kmemstats[0])))
716 			err(1,"kvm_read(%08x)", (u_long)kmsp);
717 		if (sizeof(buf) !=  kvm_read(kd,
718 	            (u_long)kmemstats[nkms].ks_shortdesc, buf, sizeof(buf)))
719 			err(1,"kvm_read(%08x)",
720 			    (u_long)kmemstats[nkms].ks_shortdesc);
721 		kmemstats[nkms].ks_shortdesc = strdup(buf);
722 		kmsp = kmemstats[nkms].ks_next;
723 	}
724 	(void)printf("Memory statistics by bucket size\n");
725 	(void)printf(
726 	    "Size   In Use   Free   Requests  HighWater  Couldfree\n");
727 	for (i = MINBUCKET, kp = &buckets[i]; i < MINBUCKET + 16; i++, kp++) {
728 		if (kp->kb_calls == 0)
729 			continue;
730 		size = 1 << i;
731 		if(size < 1024)
732 			(void)printf("%4d",size);
733 		else
734 			(void)printf("%3dK",size>>10);
735 		(void)printf(" %8ld %6ld %10ld %7ld %10ld\n",
736 			kp->kb_total - kp->kb_totalfree,
737 			kp->kb_totalfree, kp->kb_calls,
738 			kp->kb_highwat, kp->kb_couldfree);
739 		totfree += size * kp->kb_totalfree;
740 	}
741 
742 	(void)printf("\nMemory usage type by bucket size\n");
743 	(void)printf("Size  Type(s)\n");
744 	kp = &buckets[MINBUCKET];
745 	for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1, kp++) {
746 		if (kp->kb_calls == 0)
747 			continue;
748 		first = 1;
749 		len = 8;
750 		for (i = 0, ks = &kmemstats[0]; i < nkms; i++, ks++) {
751 			if (ks->ks_calls == 0)
752 				continue;
753 			if ((ks->ks_size & j) == 0)
754 				continue;
755 			name = ks->ks_shortdesc;
756 			len += 2 + strlen(name);
757 			if (first && j < 1024)
758 				printf("%4d  %s", j, name);
759 			else if (first)
760 				printf("%3dK  %s", j>>10, name);
761 			else
762 				printf(",");
763 			if (len >= 79) {
764 				printf("\n\t ");
765 				len = 10 + strlen(name);
766 			}
767 			if (!first)
768 				printf(" %s", name);
769 			first = 0;
770 		}
771 		printf("\n");
772 	}
773 
774 	(void)printf(
775 	    "\nMemory statistics by type                          Type  Kern\n");
776 	(void)printf(
777 "        Type  InUse MemUse HighUse  Limit Requests Limit Limit Size(s)\n");
778 	for (i = 0, ks = &kmemstats[0]; i < nkms; i++, ks++) {
779 		if (ks->ks_calls == 0)
780 			continue;
781 		(void)printf("%13s%6ld%6ldK%7ldK%6ldK%9ld%5u%6u",
782 		    ks->ks_shortdesc,
783 		    ks->ks_inuse, (ks->ks_memuse + 1023) / 1024,
784 		    (ks->ks_maxused + 1023) / 1024,
785 		    (ks->ks_limit + 1023) / 1024, ks->ks_calls,
786 		    ks->ks_limblocks, ks->ks_mapblocks);
787 		first = 1;
788 		for (j =  1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1) {
789 			if ((ks->ks_size & j) == 0)
790 				continue;
791 			if (first)
792 				printf("  ");
793 			else
794 				printf(",");
795 			if(j<1024)
796 				printf("%d",j);
797 			else
798 				printf("%dK",j>>10);
799 			first = 0;
800 		}
801 		printf("\n");
802 		totuse += ks->ks_memuse;
803 		totreq += ks->ks_calls;
804 	}
805 	(void)printf("\nMemory Totals:  In Use    Free    Requests\n");
806 	(void)printf("              %7ldK %6ldK    %8ld\n",
807 	     (totuse + 1023) / 1024, (totfree + 1023) / 1024, totreq);
808 }
809 
810 /*
811  * kread reads something from the kernel, given its nlist index.
812  */
813 void
814 kread(nlx, addr, size)
815 	int nlx;
816 	void *addr;
817 	size_t size;
818 {
819 	char *sym;
820 
821 	if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) {
822 		sym = namelist[nlx].n_name;
823 		if (*sym == '_')
824 			++sym;
825 		errx(1, "symbol %s not defined", sym);
826 	}
827 	if (kvm_read(kd, namelist[nlx].n_value, addr, size) != size) {
828 		sym = namelist[nlx].n_name;
829 		if (*sym == '_')
830 			++sym;
831 		errx(1, "%s: %s", sym, kvm_geterr(kd));
832 	}
833 }
834 
835 void
836 usage()
837 {
838 	(void)fprintf(stderr,
839 "usage: vmstat [-ims] [-c count] [-M core] [-N system] [-w wait] [disks]\n");
840 	exit(1);
841 }
842