vmstat.c revision 1.172 1 /* $NetBSD: vmstat.c,v 1.172 2010/12/24 23:39:19 enami Exp $ */
2
3 /*-
4 * Copyright (c) 1998, 2000, 2001, 2007 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation by:
8 * - Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center.
10 * - Simon Burge and Luke Mewburn of Wasabi Systems, Inc.
11 *
12 * Redistribution and use in source and binary forms, with or without
13 * modification, are permitted provided that the following conditions
14 * are met:
15 * 1. Redistributions of source code must retain the above copyright
16 * notice, this list of conditions and the following disclaimer.
17 * 2. Redistributions in binary form must reproduce the above copyright
18 * notice, this list of conditions and the following disclaimer in the
19 * documentation and/or other materials provided with the distribution.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
22 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
23 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
24 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
25 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
26 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
27 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
28 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
29 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
30 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
31 * POSSIBILITY OF SUCH DAMAGE.
32 */
33
34 /*
35 * Copyright (c) 1980, 1986, 1991, 1993
36 * The Regents of the University of California. All rights reserved.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * SUCH DAMAGE.
61 */
62
63 #include <sys/cdefs.h>
64 #ifndef lint
65 __COPYRIGHT("@(#) Copyright (c) 1980, 1986, 1991, 1993\
66 The Regents of the University of California. All rights reserved.");
67 #endif /* not lint */
68
69 #ifndef lint
70 #if 0
71 static char sccsid[] = "@(#)vmstat.c 8.2 (Berkeley) 3/1/95";
72 #else
73 __RCSID("$NetBSD: vmstat.c,v 1.172 2010/12/24 23:39:19 enami Exp $");
74 #endif
75 #endif /* not lint */
76
77 #define __POOL_EXPOSE
78
79 #include <sys/param.h>
80 #include <sys/mount.h>
81 #include <sys/uio.h>
82
83 #include <sys/buf.h>
84 #include <sys/evcnt.h>
85 #include <sys/ioctl.h>
86 #include <sys/malloc.h>
87 #include <sys/mallocvar.h>
88 #include <sys/namei.h>
89 #include <sys/pool.h>
90 #include <sys/proc.h>
91 #include <sys/sched.h>
92 #include <sys/socket.h>
93 #include <sys/sysctl.h>
94 #include <sys/time.h>
95 #include <sys/user.h>
96 #include <sys/queue.h>
97 #include <sys/cpu.h>
98
99 #include <uvm/uvm_extern.h>
100 #include <uvm/uvm_stat.h>
101
102 #include <net/if.h>
103 #include <netinet/in.h>
104 #include <netinet/in_var.h>
105
106 #include <ufs/ufs/inode.h>
107
108 #include <nfs/rpcv2.h>
109 #include <nfs/nfsproto.h>
110 #include <nfs/nfsnode.h>
111
112 #include <ctype.h>
113 #include <err.h>
114 #include <errno.h>
115 #include <fcntl.h>
116 #include <kvm.h>
117 #include <limits.h>
118 #include <nlist.h>
119 #undef n_hash
120 #include <paths.h>
121 #include <signal.h>
122 #include <stdio.h>
123 #include <stddef.h>
124 #include <stdlib.h>
125 #include <string.h>
126 #include <time.h>
127 #include <unistd.h>
128 #include <util.h>
129
130 #include "drvstats.h"
131
132 /*
133 * General namelist
134 */
135 struct nlist namelist[] =
136 {
137 #define X_BOOTTIME 0
138 { .n_name = "_boottime" },
139 #define X_HZ 1
140 { .n_name = "_hz" },
141 #define X_STATHZ 2
142 { .n_name = "_stathz" },
143 #define X_NCHSTATS 3
144 { .n_name = "_nchstats" },
145 #define X_KMEMSTAT 4
146 { .n_name = "_kmemstatistics" },
147 #define X_KMEMBUCKETS 5
148 { .n_name = "_kmembuckets" },
149 #define X_ALLEVENTS 6
150 { .n_name = "_allevents" },
151 #define X_POOLHEAD 7
152 { .n_name = "_pool_head" },
153 #define X_UVMEXP 8
154 { .n_name = "_uvmexp" },
155 #define X_TIME_SECOND 9
156 { .n_name = "_time_second" },
157 #define X_TIME 10
158 { .n_name = "_time" },
159 #define X_CPU_QUEUE 11
160 { .n_name = "_cpu_queue" },
161 #define X_NL_SIZE 12
162 { .n_name = NULL },
163 };
164
165 /*
166 * Namelist for pre-evcnt interrupt counters.
167 */
168 struct nlist intrnl[] =
169 {
170 #define X_INTRNAMES 0
171 { .n_name = "_intrnames" },
172 #define X_EINTRNAMES 1
173 { .n_name = "_eintrnames" },
174 #define X_INTRCNT 2
175 { .n_name = "_intrcnt" },
176 #define X_EINTRCNT 3
177 { .n_name = "_eintrcnt" },
178 #define X_INTRNL_SIZE 4
179 { .n_name = NULL },
180 };
181
182
183 /*
184 * Namelist for hash statistics
185 */
186 struct nlist hashnl[] =
187 {
188 #define X_NFSNODE 0
189 { .n_name = "_nfsnodehash" },
190 #define X_NFSNODETBL 1
191 { .n_name = "_nfsnodehashtbl" },
192 #define X_IHASH 2
193 { .n_name = "_ihash" },
194 #define X_IHASHTBL 3
195 { .n_name = "_ihashtbl" },
196 #define X_BUFHASH 4
197 { .n_name = "_bufhash" },
198 #define X_BUFHASHTBL 5
199 { .n_name = "_bufhashtbl" },
200 #define X_UIHASH 6
201 { .n_name = "_uihash" },
202 #define X_UIHASHTBL 7
203 { .n_name = "_uihashtbl" },
204 #define X_IFADDRHASH 8
205 { .n_name = "_in_ifaddrhash" },
206 #define X_IFADDRHASHTBL 9
207 { .n_name = "_in_ifaddrhashtbl" },
208 #define X_NCHASH 10
209 { .n_name = "_nchash" },
210 #define X_NCHASHTBL 11
211 { .n_name = "_nchashtbl" },
212 #define X_NCVHASH 12
213 { .n_name = "_ncvhash" },
214 #define X_NCVHASHTBL 13
215 { .n_name = "_ncvhashtbl" },
216 #define X_HASHNL_SIZE 14 /* must be last */
217 { .n_name = NULL },
218 };
219
220 /*
221 * Namelist for UVM histories
222 */
223 struct nlist histnl[] =
224 {
225 { .n_name = "_uvm_histories" },
226 #define X_UVM_HISTORIES 0
227 { .n_name = NULL },
228 };
229
230
231 #define KILO 1024
232
233 struct cpu_counter {
234 uint64_t nintr;
235 uint64_t nsyscall;
236 uint64_t nswtch;
237 uint64_t nfault;
238 uint64_t ntrap;
239 uint64_t nsoft;
240 } cpucounter, ocpucounter;
241
242 struct uvmexp uvmexp, ouvmexp;
243 struct cpuqueue cpu_queue;
244 int ndrives;
245
246 int winlines = 20;
247
248 kvm_t *kd;
249
250 #define FORKSTAT 1<<0
251 #define INTRSTAT 1<<1
252 #define MEMSTAT 1<<2
253 #define SUMSTAT 1<<3
254 #define EVCNTSTAT 1<<4
255 #define VMSTAT 1<<5
256 #define HISTLIST 1<<6
257 #define HISTDUMP 1<<7
258 #define HASHSTAT 1<<8
259 #define HASHLIST 1<<9
260 #define VMTOTAL 1<<10
261 #define POOLCACHESTAT 1<<11
262
263 /*
264 * Print single word. `ovflow' is number of characters didn't fit
265 * on the last word. `fmt' is a format string to print this word.
266 * It must contain asterisk for field width. `width' is a width
267 * occupied by this word. `fixed' is a number of constant chars in
268 * `fmt'. `val' is a value to be printed using format string `fmt'.
269 */
270 #define PRWORD(ovflw, fmt, width, fixed, val) do { \
271 (ovflw) += printf((fmt), \
272 (width) - (fixed) - (ovflw) > 0 ? \
273 (width) - (fixed) - (ovflw) : 0, \
274 (val)) - (width); \
275 if ((ovflw) < 0) \
276 (ovflw) = 0; \
277 } while (/* CONSTCOND */0)
278
279 void cpustats(int *);
280 void cpucounters(struct cpu_counter *);
281 void deref_kptr(const void *, void *, size_t, const char *);
282 void drvstats(int *);
283 void doevcnt(int verbose);
284 void dohashstat(int, int, const char *);
285 void dointr(int verbose);
286 void domem(void);
287 void dopool(int, int);
288 void dopoolcache(void);
289 void dosum(void);
290 void dovmstat(struct timespec *, int);
291 void print_total_hdr(void);
292 void dovmtotal(struct timespec *, int);
293 void kread(struct nlist *, int, void *, size_t);
294 int kreadc(struct nlist *, int, void *, size_t);
295 void needhdr(int);
296 long getuptime(void);
297 void printhdr(void);
298 long pct(long, long);
299 void usage(void);
300 void doforkst(void);
301
302 void hist_traverse(int, const char *);
303 void hist_dodump(struct uvm_history *);
304
305 int main(int, char **);
306 char **choosedrives(char **);
307
308 /* Namelist and memory file names. */
309 char *nlistf, *memf;
310
311 /* allow old usage [vmstat 1] */
312 #define BACKWARD_COMPATIBILITY
313
314 static const int vmmeter_mib[] = { CTL_VM, VM_METER };
315 static const int uvmexp2_mib[] = { CTL_VM, VM_UVMEXP2 };
316
317 int
318 main(int argc, char *argv[])
319 {
320 int c, todo, verbose, wide;
321 struct timespec interval;
322 int reps;
323 char errbuf[_POSIX2_LINE_MAX];
324 gid_t egid = getegid();
325 const char *histname, *hashname;
326 size_t i;
327
328 histname = hashname = NULL;
329 (void)setegid(getgid());
330 memf = nlistf = NULL;
331 reps = todo = verbose = wide = 0;
332 interval.tv_sec = 0;
333 interval.tv_nsec = 0;
334 while ((c = getopt(argc, argv, "Cc:efh:HilLM:mN:stu:UvWw:")) != -1) {
335 switch (c) {
336 case 'c':
337 reps = atoi(optarg);
338 break;
339 case 'C':
340 todo |= POOLCACHESTAT;
341 break;
342 case 'e':
343 todo |= EVCNTSTAT;
344 break;
345 case 'f':
346 todo |= FORKSTAT;
347 break;
348 case 'h':
349 hashname = optarg;
350 /* FALLTHROUGH */
351 case 'H':
352 todo |= HASHSTAT;
353 break;
354 case 'i':
355 todo |= INTRSTAT;
356 break;
357 case 'l':
358 todo |= HISTLIST;
359 break;
360 case 'L':
361 todo |= HASHLIST;
362 break;
363 case 'M':
364 memf = optarg;
365 break;
366 case 'm':
367 todo |= MEMSTAT;
368 break;
369 case 'N':
370 nlistf = optarg;
371 break;
372 case 's':
373 todo |= SUMSTAT;
374 break;
375 case 't':
376 todo |= VMTOTAL;
377 break;
378 case 'u':
379 histname = optarg;
380 /* FALLTHROUGH */
381 case 'U':
382 todo |= HISTDUMP;
383 break;
384 case 'v':
385 verbose++;
386 break;
387 case 'W':
388 wide++;
389 break;
390 case 'w':
391 interval.tv_sec = atol(optarg);
392 break;
393 case '?':
394 default:
395 usage();
396 }
397 }
398 argc -= optind;
399 argv += optind;
400
401 if (todo == 0)
402 todo = VMSTAT;
403
404 /*
405 * Discard setgid privileges. If not the running kernel, we toss
406 * them away totally so that bad guys can't print interesting stuff
407 * from kernel memory, otherwise switch back to kmem for the
408 * duration of the kvm_openfiles() call.
409 */
410 if (nlistf != NULL || memf != NULL)
411 (void)setgid(getgid());
412 else
413 (void)setegid(egid);
414
415 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf);
416 if (kd == NULL)
417 errx(1, "kvm_openfiles: %s", errbuf);
418
419 if (nlistf == NULL && memf == NULL)
420 (void)setgid(getgid());
421
422 if ((c = kvm_nlist(kd, namelist)) != 0) {
423 int doexit = 0;
424 if (c == -1)
425 errx(1, "kvm_nlist: %s %s", "namelist", kvm_geterr(kd));
426 for (i = 0; i < sizeof(namelist) / sizeof(namelist[0])-1; i++)
427 if (namelist[i].n_type == 0 &&
428 i != X_TIME_SECOND &&
429 i != X_TIME) {
430 if (doexit++ == 0)
431 (void)fprintf(stderr,
432 "%s: undefined symbols:",
433 getprogname());
434 (void)fprintf(stderr, " %s",
435 namelist[i].n_name);
436 }
437 if (doexit) {
438 (void)fputc('\n', stderr);
439 exit(1);
440 }
441 }
442 if (todo & INTRSTAT)
443 (void) kvm_nlist(kd, intrnl);
444 if ((c = kvm_nlist(kd, hashnl)) == -1 || c == X_HASHNL_SIZE)
445 errx(1, "kvm_nlist: %s %s", "hashnl", kvm_geterr(kd));
446 if (kvm_nlist(kd, histnl) == -1)
447 errx(1, "kvm_nlist: %s %s", "histnl", kvm_geterr(kd));
448
449 if (todo & VMSTAT) {
450 struct winsize winsize;
451
452 (void)drvinit(0);/* Initialize disk stats, no disks selected. */
453
454 (void)setgid(getgid()); /* don't need privs anymore */
455
456 argv = choosedrives(argv); /* Select disks. */
457 winsize.ws_row = 0;
458 (void)ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
459 if (winsize.ws_row > 0)
460 winlines = winsize.ws_row;
461
462 }
463
464 #ifdef BACKWARD_COMPATIBILITY
465 if (*argv) {
466 interval.tv_sec = atol(*argv);
467 if (*++argv)
468 reps = atoi(*argv);
469 }
470 #endif
471
472 if (interval.tv_sec) {
473 if (!reps)
474 reps = -1;
475 } else if (reps)
476 interval.tv_sec = 1;
477
478
479 /*
480 * Statistics dumping is incompatible with the default
481 * VMSTAT/dovmstat() output. So perform the interval/reps handling
482 * for it here.
483 */
484 if ((todo & (VMSTAT|VMTOTAL)) == 0) {
485 for (;;) {
486 if (todo & (HISTLIST|HISTDUMP)) {
487 if ((todo & (HISTLIST|HISTDUMP)) ==
488 (HISTLIST|HISTDUMP))
489 errx(1, "you may list or dump,"
490 " but not both!");
491 hist_traverse(todo, histname);
492 (void)putchar('\n');
493 }
494 if (todo & FORKSTAT) {
495 doforkst();
496 (void)putchar('\n');
497 }
498 if (todo & MEMSTAT) {
499 domem();
500 dopool(verbose, wide);
501 (void)putchar('\n');
502 }
503 if (todo & POOLCACHESTAT) {
504 dopoolcache();
505 (void)putchar('\n');
506 }
507 if (todo & SUMSTAT) {
508 dosum();
509 (void)putchar('\n');
510 }
511 if (todo & INTRSTAT) {
512 dointr(verbose);
513 (void)putchar('\n');
514 }
515 if (todo & EVCNTSTAT) {
516 doevcnt(verbose);
517 (void)putchar('\n');
518 }
519 if (todo & (HASHLIST|HASHSTAT)) {
520 if ((todo & (HASHLIST|HASHSTAT)) ==
521 (HASHLIST|HASHSTAT))
522 errx(1, "you may list or display,"
523 " but not both!");
524 dohashstat(verbose, todo, hashname);
525 (void)putchar('\n');
526 }
527
528 fflush(stdout);
529 if (reps >= 0 && --reps <=0)
530 break;
531 (void)nanosleep(&interval, NULL);
532 }
533 } else {
534 if ((todo & (VMSTAT|VMTOTAL)) == (VMSTAT|VMTOTAL)) {
535 errx(1, "you may not both do vmstat and vmtotal");
536 }
537 if (todo & VMSTAT)
538 dovmstat(&interval, reps);
539 if (todo & VMTOTAL)
540 dovmtotal(&interval, reps);
541 }
542 return 0;
543 }
544
545 char **
546 choosedrives(char **argv)
547 {
548 size_t i;
549
550 /*
551 * Choose drives to be displayed. Priority goes to (in order) drives
552 * supplied as arguments, default drives. If everything isn't filled
553 * in and there are drives not taken care of, display the first few
554 * that fit.
555 */
556 #define BACKWARD_COMPATIBILITY
557 for (ndrives = 0; *argv; ++argv) {
558 #ifdef BACKWARD_COMPATIBILITY
559 if (isdigit((unsigned char)**argv))
560 break;
561 #endif
562 for (i = 0; i < ndrive; i++) {
563 if (strcmp(dr_name[i], *argv))
564 continue;
565 drv_select[i] = 1;
566 ++ndrives;
567 break;
568 }
569 }
570 for (i = 0; i < ndrive && ndrives < 2; i++) {
571 if (drv_select[i])
572 continue;
573 drv_select[i] = 1;
574 ++ndrives;
575 }
576
577 return (argv);
578 }
579
580 long
581 getuptime(void)
582 {
583 static struct timeval boottime;
584 struct timeval now;
585 time_t uptime, nowsec;
586
587 if (boottime.tv_sec == 0)
588 kread(namelist, X_BOOTTIME, &boottime, sizeof(boottime));
589 if (kreadc(namelist, X_TIME_SECOND, &nowsec, sizeof(nowsec))) {
590 /*
591 * XXX this assignment dance can be removed once timeval tv_sec
592 * is SUS mandated time_t
593 */
594 now.tv_sec = nowsec;
595 now.tv_usec = 0;
596 } else {
597 kread(namelist, X_TIME, &now, sizeof(now));
598 }
599 uptime = now.tv_sec - boottime.tv_sec;
600 if (uptime <= 0 || uptime > 60*60*24*365*10)
601 errx(1, "time makes no sense; namelist must be wrong.");
602 return (uptime);
603 }
604
605 int hz, hdrcnt;
606
607 void
608 print_total_hdr()
609 {
610
611 (void)printf("procs memory\n");
612 (void)printf("ru dw pw sl");
613 (void)printf(" total-v active-v active-r");
614 (void)printf(" vm-sh avm-sh rm-sh arm-sh free\n");
615 hdrcnt = winlines - 2;
616 }
617
618 void
619 dovmtotal(struct timespec *interval, int reps)
620 {
621 struct vmtotal total;
622 size_t size;
623
624 (void)signal(SIGCONT, needhdr);
625
626 for (hdrcnt = 1;;) {
627 if (!--hdrcnt)
628 print_total_hdr();
629 if (memf != NULL) {
630 warnx("Unable to get vmtotals from crash dump.");
631 (void)memset(&total, 0, sizeof(total));
632 } else {
633 size = sizeof(total);
634 if (sysctl(vmmeter_mib, __arraycount(vmmeter_mib),
635 &total, &size, NULL, 0) == -1) {
636 warn("Can't get vmtotals");
637 (void)memset(&total, 0, sizeof(total));
638 }
639 }
640 (void)printf("%2d ", total.t_rq);
641 (void)printf("%2d ", total.t_dw);
642 (void)printf("%2d ", total.t_pw);
643 (void)printf("%2d ", total.t_sl);
644
645 (void)printf("%9d ", total.t_vm);
646 (void)printf("%9d ", total.t_avm);
647 (void)printf("%9d ", total.t_arm);
648 (void)printf("%5d ", total.t_vmshr);
649 (void)printf("%6d ", total.t_avmshr);
650 (void)printf("%5d ", total.t_rmshr);
651 (void)printf("%6d ", total.t_armshr);
652 (void)printf("%5d", total.t_free);
653
654 (void)putchar('\n');
655
656 (void)fflush(stdout);
657 if (reps >= 0 && --reps <= 0)
658 break;
659
660 (void)nanosleep(interval, NULL);
661 }
662 }
663
664 void
665 dovmstat(struct timespec *interval, int reps)
666 {
667 struct vmtotal total;
668 time_t uptime, halfuptime;
669 size_t size;
670 int pagesize = getpagesize();
671 int ovflw;
672
673 uptime = getuptime();
674 halfuptime = uptime / 2;
675 (void)signal(SIGCONT, needhdr);
676
677 if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
678 kread(namelist, X_STATHZ, &hz, sizeof(hz));
679 if (!hz)
680 kread(namelist, X_HZ, &hz, sizeof(hz));
681
682 kread(namelist, X_CPU_QUEUE, &cpu_queue, sizeof(cpu_queue));
683
684 for (hdrcnt = 1;;) {
685 if (!--hdrcnt)
686 printhdr();
687 /* Read new disk statistics */
688 cpureadstats();
689 drvreadstats();
690 tkreadstats();
691 kread(namelist, X_UVMEXP, &uvmexp, sizeof(uvmexp));
692 if (memf != NULL) {
693 /*
694 * XXX Can't do this if we're reading a crash
695 * XXX dump because they're lazily-calculated.
696 */
697 warnx("Unable to get vmtotals from crash dump.");
698 (void)memset(&total, 0, sizeof(total));
699 } else {
700 size = sizeof(total);
701 if (sysctl(vmmeter_mib, __arraycount(vmmeter_mib),
702 &total, &size, NULL, 0) == -1) {
703 warn("Can't get vmtotals");
704 (void)memset(&total, 0, sizeof(total));
705 }
706 }
707 cpucounters(&cpucounter);
708 ovflw = 0;
709 PRWORD(ovflw, " %*d", 2, 1, total.t_rq - 1);
710 PRWORD(ovflw, " %*d", 2, 1, total.t_dw + total.t_pw);
711 #define pgtok(a) (long)((a) * ((uint32_t)pagesize >> 10))
712 #define rate(x) (u_long)(((x) + halfuptime) / uptime) /* round */
713 PRWORD(ovflw, " %*ld", 9, 1, pgtok(total.t_avm));
714 PRWORD(ovflw, " %*ld", 7, 1, pgtok(total.t_free));
715 PRWORD(ovflw, " %*ld", 5, 1,
716 rate(cpucounter.nfault - ocpucounter.nfault));
717 PRWORD(ovflw, " %*ld", 4, 1,
718 rate(uvmexp.pdreact - ouvmexp.pdreact));
719 PRWORD(ovflw, " %*ld", 4, 1,
720 rate(uvmexp.pageins - ouvmexp.pageins));
721 PRWORD(ovflw, " %*ld", 5, 1,
722 rate(uvmexp.pgswapout - ouvmexp.pgswapout));
723 PRWORD(ovflw, " %*ld", 5, 1,
724 rate(uvmexp.pdfreed - ouvmexp.pdfreed));
725 PRWORD(ovflw, " %*ld", 6, 2,
726 rate(uvmexp.pdscans - ouvmexp.pdscans));
727 drvstats(&ovflw);
728 PRWORD(ovflw, " %*ld", 5, 1,
729 rate(cpucounter.nintr - ocpucounter.nintr));
730 PRWORD(ovflw, " %*ld", 5, 1,
731 rate(cpucounter.nsyscall - ocpucounter.nsyscall));
732 PRWORD(ovflw, " %*ld", 4, 1,
733 rate(cpucounter.nswtch - ocpucounter.nswtch));
734 cpustats(&ovflw);
735 (void)putchar('\n');
736 (void)fflush(stdout);
737 if (reps >= 0 && --reps <= 0)
738 break;
739 ouvmexp = uvmexp;
740 ocpucounter = cpucounter;
741 uptime = interval->tv_sec;
742 /*
743 * We round upward to avoid losing low-frequency events
744 * (i.e., >= 1 per interval but < 1 per second).
745 */
746 halfuptime = uptime == 1 ? 0 : (uptime + 1) / 2;
747 (void)nanosleep(interval, NULL);
748 }
749 }
750
751 void
752 printhdr(void)
753 {
754 size_t i;
755
756 (void)printf(" procs memory page%*s", 23, "");
757 if (ndrives > 0)
758 (void)printf("%s %*sfaults cpu\n",
759 ((ndrives > 1) ? "disks" : "disk"),
760 ((ndrives > 1) ? ndrives * 3 - 4 : 0), "");
761 else
762 (void)printf("%*s faults cpu\n",
763 ndrives * 3, "");
764
765 (void)printf(" r b avm fre flt re pi po fr sr ");
766 for (i = 0; i < ndrive; i++)
767 if (drv_select[i])
768 (void)printf("%c%c ", dr_name[i][0],
769 dr_name[i][strlen(dr_name[i]) - 1]);
770 (void)printf(" in sy cs us sy id\n");
771 hdrcnt = winlines - 2;
772 }
773
774 /*
775 * Force a header to be prepended to the next output.
776 */
777 void
778 /*ARGSUSED*/
779 needhdr(int dummy)
780 {
781
782 hdrcnt = 1;
783 }
784
785 long
786 pct(long top, long bot)
787 {
788 long ans;
789
790 if (bot == 0)
791 return (0);
792 ans = (long)((quad_t)top * 100 / bot);
793 return (ans);
794 }
795
796 #define PCT(top, bot) (int)pct((long)(top), (long)(bot))
797
798 void
799 dosum(void)
800 {
801 struct nchstats nchstats;
802 u_long nchtotal;
803 struct uvmexp_sysctl uvmexp2;
804 size_t ssize;
805 int active_kernel;
806 struct cpu_counter cc;
807
808 /*
809 * The "active" and "inactive" variables
810 * are now estimated by the kernel and sadly
811 * can not easily be dug out of a crash dump.
812 */
813 ssize = sizeof(uvmexp2);
814 memset(&uvmexp2, 0, ssize);
815 active_kernel = (memf == NULL);
816 if (active_kernel) {
817 /* only on active kernel */
818 if (sysctl(uvmexp2_mib, __arraycount(uvmexp2_mib), &uvmexp2,
819 &ssize, NULL, 0) == -1)
820 warn("sysctl vm.uvmexp2 failed");
821 }
822
823 kread(namelist, X_UVMEXP, &uvmexp, sizeof(uvmexp));
824
825 (void)printf("%9u bytes per page\n", uvmexp.pagesize);
826
827 (void)printf("%9u page color%s\n",
828 uvmexp.ncolors, uvmexp.ncolors == 1 ? "" : "s");
829
830 (void)printf("%9u pages managed\n", uvmexp.npages);
831 (void)printf("%9u pages free\n", uvmexp.free);
832 if (active_kernel) {
833 (void)printf("%9" PRIu64 " pages active\n", uvmexp2.active);
834 (void)printf("%9" PRIu64 " pages inactive\n", uvmexp2.inactive);
835 }
836 (void)printf("%9u pages paging\n", uvmexp.paging);
837 (void)printf("%9u pages wired\n", uvmexp.wired);
838 (void)printf("%9u zero pages\n", uvmexp.zeropages);
839 (void)printf("%9u reserve pagedaemon pages\n",
840 uvmexp.reserve_pagedaemon);
841 (void)printf("%9u reserve kernel pages\n", uvmexp.reserve_kernel);
842 (void)printf("%9u anonymous pages\n", uvmexp.anonpages);
843 (void)printf("%9u cached file pages\n", uvmexp.filepages);
844 (void)printf("%9u cached executable pages\n", uvmexp.execpages);
845
846 (void)printf("%9u minimum free pages\n", uvmexp.freemin);
847 (void)printf("%9u target free pages\n", uvmexp.freetarg);
848 (void)printf("%9u maximum wired pages\n", uvmexp.wiredmax);
849
850 (void)printf("%9u swap devices\n", uvmexp.nswapdev);
851 (void)printf("%9u swap pages\n", uvmexp.swpages);
852 (void)printf("%9u swap pages in use\n", uvmexp.swpginuse);
853 (void)printf("%9u swap allocations\n", uvmexp.nswget);
854
855 kread(namelist, X_CPU_QUEUE, &cpu_queue, sizeof(cpu_queue));
856 cpucounters(&cc);
857 (void)printf("%9" PRIu64 " total faults taken\n", cc.nfault);
858 (void)printf("%9" PRIu64 " traps\n", cc.ntrap);
859 (void)printf("%9" PRIu64 " device interrupts\n", cc.nintr);
860 (void)printf("%9" PRIu64 " CPU context switches\n", cc.nswtch);
861 (void)printf("%9" PRIu64 " software interrupts\n", cc.nsoft);
862 (void)printf("%9" PRIu64 " system calls\n", cc.nsyscall);
863 (void)printf("%9u pagein requests\n", uvmexp.pageins);
864 (void)printf("%9u pageout requests\n", uvmexp.pdpageouts);
865 (void)printf("%9u pages swapped in\n", uvmexp.pgswapin);
866 (void)printf("%9u pages swapped out\n", uvmexp.pgswapout);
867 (void)printf("%9u forks total\n", uvmexp.forks);
868 (void)printf("%9u forks blocked parent\n", uvmexp.forks_ppwait);
869 (void)printf("%9u forks shared address space with parent\n",
870 uvmexp.forks_sharevm);
871 (void)printf("%9u pagealloc zero wanted and avail\n",
872 uvmexp.pga_zerohit);
873 (void)printf("%9u pagealloc zero wanted and not avail\n",
874 uvmexp.pga_zeromiss);
875 (void)printf("%9u aborts of idle page zeroing\n",
876 uvmexp.zeroaborts);
877 (void)printf("%9u pagealloc desired color avail\n",
878 uvmexp.colorhit);
879 (void)printf("%9u pagealloc desired color not avail\n",
880 uvmexp.colormiss);
881 (void)printf("%9u pagealloc local cpu avail\n",
882 uvmexp.cpuhit);
883 (void)printf("%9u pagealloc local cpu not avail\n",
884 uvmexp.cpumiss);
885
886 (void)printf("%9u faults with no memory\n", uvmexp.fltnoram);
887 (void)printf("%9u faults with no anons\n", uvmexp.fltnoanon);
888 (void)printf("%9u faults had to wait on pages\n", uvmexp.fltpgwait);
889 (void)printf("%9u faults found released page\n", uvmexp.fltpgrele);
890 (void)printf("%9u faults relock (%u ok)\n", uvmexp.fltrelck,
891 uvmexp.fltrelckok);
892 (void)printf("%9u anon page faults\n", uvmexp.fltanget);
893 (void)printf("%9u anon retry faults\n", uvmexp.fltanretry);
894 (void)printf("%9u amap copy faults\n", uvmexp.fltamcopy);
895 (void)printf("%9u neighbour anon page faults\n", uvmexp.fltnamap);
896 (void)printf("%9u neighbour object page faults\n", uvmexp.fltnomap);
897 (void)printf("%9u locked pager get faults\n", uvmexp.fltlget);
898 (void)printf("%9u unlocked pager get faults\n", uvmexp.fltget);
899 (void)printf("%9u anon faults\n", uvmexp.flt_anon);
900 (void)printf("%9u anon copy on write faults\n", uvmexp.flt_acow);
901 (void)printf("%9u object faults\n", uvmexp.flt_obj);
902 (void)printf("%9u promote copy faults\n", uvmexp.flt_prcopy);
903 (void)printf("%9u promote zero fill faults\n", uvmexp.flt_przero);
904
905 (void)printf("%9u times daemon wokeup\n",uvmexp.pdwoke);
906 (void)printf("%9u revolutions of the clock hand\n", uvmexp.pdrevs);
907 (void)printf("%9u pages freed by daemon\n", uvmexp.pdfreed);
908 (void)printf("%9u pages scanned by daemon\n", uvmexp.pdscans);
909 (void)printf("%9u anonymous pages scanned by daemon\n",
910 uvmexp.pdanscan);
911 (void)printf("%9u object pages scanned by daemon\n", uvmexp.pdobscan);
912 (void)printf("%9u pages reactivated\n", uvmexp.pdreact);
913 (void)printf("%9u pages found busy by daemon\n", uvmexp.pdbusy);
914 (void)printf("%9u total pending pageouts\n", uvmexp.pdpending);
915 (void)printf("%9u pages deactivated\n", uvmexp.pddeact);
916
917 kread(namelist, X_NCHSTATS, &nchstats, sizeof(nchstats));
918 nchtotal = nchstats.ncs_goodhits + nchstats.ncs_neghits +
919 nchstats.ncs_badhits + nchstats.ncs_falsehits +
920 nchstats.ncs_miss + nchstats.ncs_long;
921 (void)printf("%9lu total name lookups\n", nchtotal);
922 (void)printf("%9lu good hits\n", nchstats.ncs_goodhits);
923 (void)printf("%9lu negative hits\n", nchstats.ncs_neghits);
924 (void)printf("%9lu bad hits\n", nchstats.ncs_badhits);
925 (void)printf("%9lu false hits\n", nchstats.ncs_falsehits);
926 (void)printf("%9lu miss\n", nchstats.ncs_miss);
927 (void)printf("%9lu too long\n", nchstats.ncs_long);
928 (void)printf("%9lu pass2 hits\n", nchstats.ncs_pass2);
929 (void)printf("%9lu 2passes\n", nchstats.ncs_2passes);
930 (void)printf(
931 "%9s cache hits (%d%% pos + %d%% neg) system %d%% per-process\n",
932 "", PCT(nchstats.ncs_goodhits, nchtotal),
933 PCT(nchstats.ncs_neghits, nchtotal),
934 PCT(nchstats.ncs_pass2, nchtotal));
935 (void)printf("%9s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
936 PCT(nchstats.ncs_badhits, nchtotal),
937 PCT(nchstats.ncs_falsehits, nchtotal),
938 PCT(nchstats.ncs_long, nchtotal));
939 }
940
941 void
942 doforkst(void)
943 {
944
945 kread(namelist, X_UVMEXP, &uvmexp, sizeof(uvmexp));
946
947 (void)printf("%u forks total\n", uvmexp.forks);
948 (void)printf("%u forks blocked parent\n", uvmexp.forks_ppwait);
949 (void)printf("%u forks shared address space with parent\n",
950 uvmexp.forks_sharevm);
951 }
952
953 void
954 drvstats(int *ovflwp)
955 {
956 size_t dn;
957 double etime;
958 int ovflw = *ovflwp;
959
960 /* Calculate disk stat deltas. */
961 cpuswap();
962 drvswap();
963 tkswap();
964 etime = cur.cp_etime;
965
966 for (dn = 0; dn < ndrive; ++dn) {
967 if (!drv_select[dn])
968 continue;
969 PRWORD(ovflw, " %*.0f", 3, 1,
970 (cur.rxfer[dn] + cur.wxfer[dn]) / etime);
971 }
972 *ovflwp = ovflw;
973 }
974
975 void
976 cpucounters(struct cpu_counter *cc)
977 {
978 struct cpu_info *ci;
979 (void)memset(cc, 0, sizeof(*cc));
980 CIRCLEQ_FOREACH(ci, &cpu_queue, ci_data.cpu_qchain) {
981 struct cpu_info tci;
982 if ((size_t)kvm_read(kd, (u_long)ci, &tci, sizeof(tci))
983 != sizeof(tci)) {
984 warnx("Can't read cpu info from %p (%s)",
985 ci, kvm_geterr(kd));
986 continue;
987 }
988 /* Found the fake element, done */
989 if (tci.ci_data.cpu_qchain.cqe_prev == NULL)
990 break;
991 cc->nintr += tci.ci_data.cpu_nintr;
992 cc->nsyscall += tci.ci_data.cpu_nsyscall;
993 cc->nswtch = tci.ci_data.cpu_nswtch;
994 cc->nfault = tci.ci_data.cpu_nfault;
995 cc->ntrap = tci.ci_data.cpu_ntrap;
996 cc->nsoft = tci.ci_data.cpu_nsoft;
997 ci = &tci;
998 }
999 }
1000
1001 void
1002 cpustats(int *ovflwp)
1003 {
1004 int state;
1005 double pcnt, total;
1006 double stat_us, stat_sy, stat_id;
1007 int ovflw = *ovflwp;
1008
1009 total = 0;
1010 for (state = 0; state < CPUSTATES; ++state)
1011 total += cur.cp_time[state];
1012 if (total)
1013 pcnt = 100 / total;
1014 else
1015 pcnt = 0;
1016 stat_us = (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * pcnt;
1017 stat_sy = (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * pcnt;
1018 stat_id = cur.cp_time[CP_IDLE] * pcnt;
1019 PRWORD(ovflw, " %*.0f", ((stat_sy >= 100) ? 2 : 3), 1, stat_us);
1020 PRWORD(ovflw, " %*.0f", ((stat_us >= 100 || stat_id >= 100) ? 2 : 3), 1,
1021 stat_sy);
1022 PRWORD(ovflw, " %*.0f", 3, 1, stat_id);
1023 *ovflwp = ovflw;
1024 }
1025
1026 void
1027 dointr(int verbose)
1028 {
1029 unsigned long *intrcnt, *ointrcnt;
1030 unsigned long long inttotal, uptime;
1031 int nintr, inamlen;
1032 char *intrname, *ointrname;
1033 struct evcntlist allevents;
1034 struct evcnt evcnt, *evptr;
1035 char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
1036
1037 inttotal = 0;
1038 uptime = getuptime();
1039 (void)printf("%-34s %16s %8s\n", "interrupt", "total", "rate");
1040 nintr = intrnl[X_EINTRCNT].n_value - intrnl[X_INTRCNT].n_value;
1041 inamlen = intrnl[X_EINTRNAMES].n_value - intrnl[X_INTRNAMES].n_value;
1042 if (nintr != 0 && inamlen != 0) {
1043 ointrcnt = intrcnt = malloc((size_t)nintr);
1044 ointrname = intrname = malloc((size_t)inamlen);
1045 if (intrcnt == NULL || intrname == NULL)
1046 errx(1, "%s", "");
1047 kread(intrnl, X_INTRCNT, intrcnt, (size_t)nintr);
1048 kread(intrnl, X_INTRNAMES, intrname, (size_t)inamlen);
1049 nintr /= sizeof(long);
1050 while (--nintr >= 0) {
1051 if (*intrcnt || verbose)
1052 (void)printf("%-34s %16llu %8llu\n", intrname,
1053 (unsigned long long)*intrcnt,
1054 (unsigned long long)
1055 (*intrcnt / uptime));
1056 intrname += strlen(intrname) + 1;
1057 inttotal += *intrcnt++;
1058 }
1059 free(ointrcnt);
1060 free(ointrname);
1061 }
1062
1063 kread(namelist, X_ALLEVENTS, &allevents, sizeof allevents);
1064 evptr = TAILQ_FIRST(&allevents);
1065 while (evptr) {
1066 deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
1067 evptr = TAILQ_NEXT(&evcnt, ev_list);
1068 if (evcnt.ev_type != EVCNT_TYPE_INTR)
1069 continue;
1070
1071 if (evcnt.ev_count == 0 && !verbose)
1072 continue;
1073
1074 deref_kptr(evcnt.ev_group, evgroup,
1075 (size_t)evcnt.ev_grouplen + 1, "event chain trashed");
1076 deref_kptr(evcnt.ev_name, evname,
1077 (size_t)evcnt.ev_namelen + 1, "event chain trashed");
1078
1079 (void)printf("%s %s%*s %16llu %8llu\n", evgroup, evname,
1080 34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
1081 (unsigned long long)evcnt.ev_count,
1082 (unsigned long long)(evcnt.ev_count / uptime));
1083
1084 inttotal += evcnt.ev_count++;
1085 }
1086 (void)printf("%-34s %16llu %8llu\n", "Total", inttotal,
1087 (unsigned long long)(inttotal / uptime));
1088 }
1089
1090 void
1091 doevcnt(int verbose)
1092 {
1093 static const char * evtypes [] = { "misc", "intr", "trap" };
1094 unsigned long long uptime;
1095 struct evcntlist allevents;
1096 struct evcnt evcnt, *evptr;
1097 char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
1098
1099 /* XXX should print type! */
1100
1101 uptime = getuptime();
1102 (void)printf("%-34s %16s %8s %s\n", "event", "total", "rate", "type");
1103 kread(namelist, X_ALLEVENTS, &allevents, sizeof allevents);
1104 evptr = TAILQ_FIRST(&allevents);
1105 while (evptr) {
1106 deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
1107
1108 evptr = TAILQ_NEXT(&evcnt, ev_list);
1109 if (evcnt.ev_count == 0 && !verbose)
1110 continue;
1111
1112 deref_kptr(evcnt.ev_group, evgroup,
1113 (size_t)evcnt.ev_grouplen + 1, "event chain trashed");
1114 deref_kptr(evcnt.ev_name, evname,
1115 (size_t)evcnt.ev_namelen + 1, "event chain trashed");
1116
1117 (void)printf("%s %s%*s %16llu %8llu %s\n", evgroup, evname,
1118 34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
1119 (unsigned long long)evcnt.ev_count,
1120 (unsigned long long)(evcnt.ev_count / uptime),
1121 (evcnt.ev_type < sizeof(evtypes)/sizeof(evtypes[0]) ?
1122 evtypes[evcnt.ev_type] : "?"));
1123 }
1124 }
1125
1126 static char memname[64];
1127
1128 void
1129 domem(void)
1130 {
1131 struct kmembuckets *kp;
1132 struct malloc_type ks, *ksp;
1133 int i, j;
1134 int len, size, first;
1135 long totuse = 0, totfree = 0, totreq = 0;
1136 struct kmembuckets buckets[MINBUCKET + 16];
1137
1138 kread(namelist, X_KMEMBUCKETS, buckets, sizeof(buckets));
1139 for (first = 1, i = MINBUCKET, kp = &buckets[i]; i < MINBUCKET + 16;
1140 i++, kp++) {
1141 if (kp->kb_calls == 0)
1142 continue;
1143 if (first) {
1144 (void)printf("Memory statistics by bucket size\n");
1145 (void)printf(
1146 " Size In Use Free Requests HighWater Couldfree\n");
1147 first = 0;
1148 }
1149 size = 1 << i;
1150 (void)printf("%8d %8ld %6ld %10ld %7ld %10ld\n", size,
1151 kp->kb_total - kp->kb_totalfree,
1152 kp->kb_totalfree, kp->kb_calls,
1153 kp->kb_highwat, kp->kb_couldfree);
1154 totfree += size * kp->kb_totalfree;
1155 }
1156
1157 /*
1158 * If kmem statistics are not being gathered by the kernel,
1159 * first will still be 1.
1160 */
1161 if (first) {
1162 warnx("Kmem statistics are not being gathered by the kernel.");
1163 return;
1164 }
1165
1166 (void)printf("\nMemory usage type by bucket size\n");
1167 (void)printf(" Size Type(s)\n");
1168 kp = &buckets[MINBUCKET];
1169 for (j = 1 << MINBUCKET; j < 1 << (MINBUCKET + 16); j <<= 1, kp++) {
1170 if (kp->kb_calls == 0)
1171 continue;
1172 first = 1;
1173 len = 8;
1174 for (kread(namelist, X_KMEMSTAT, &ksp, sizeof(ksp));
1175 ksp != NULL; ksp = ks.ks_next) {
1176 deref_kptr(ksp, &ks, sizeof(ks), "malloc type");
1177 if (ks.ks_calls == 0)
1178 continue;
1179 if ((ks.ks_size & j) == 0)
1180 continue;
1181 deref_kptr(ks.ks_shortdesc, memname,
1182 sizeof(memname), "malloc type name");
1183 len += 2 + strlen(memname);
1184 if (first)
1185 (void)printf("%8d %s", j, memname);
1186 else
1187 (void)printf(",");
1188 if (len >= 80) {
1189 (void)printf("\n\t ");
1190 len = 10 + strlen(memname);
1191 }
1192 if (!first)
1193 (void)printf(" %s", memname);
1194 first = 0;
1195 }
1196 (void)putchar('\n');
1197 }
1198
1199 (void)printf(
1200 "\nMemory statistics by type Type Kern\n");
1201 (void)printf(
1202 " Type InUse MemUse HighUse Limit Requests Limit Limit Size(s)\n");
1203 for (kread(namelist, X_KMEMSTAT, &ksp, sizeof(ksp));
1204 ksp != NULL; ksp = ks.ks_next) {
1205 deref_kptr(ksp, &ks, sizeof(ks), "malloc type");
1206 if (ks.ks_calls == 0)
1207 continue;
1208 deref_kptr(ks.ks_shortdesc, memname,
1209 sizeof(memname), "malloc type name");
1210 (void)printf("%15s %5ld %6ldK %6ldK %6ldK %10ld %5u %5u",
1211 memname,
1212 ks.ks_inuse, howmany(ks.ks_memuse, KILO),
1213 howmany(ks.ks_maxused, KILO),
1214 howmany(ks.ks_limit, KILO), ks.ks_calls,
1215 ks.ks_limblocks, ks.ks_mapblocks);
1216 first = 1;
1217 for (j = 1 << MINBUCKET, i = MINBUCKET;
1218 j < 1 << (MINBUCKET + 16);
1219 j <<= 1, i++)
1220 {
1221 if ((ks.ks_size & j) == 0)
1222 continue;
1223 if (first)
1224 (void)printf(" %d", j);
1225 else
1226 (void)printf(",%d", j);
1227 first = 0;
1228 (void)printf(":%u", ks.ks_active[i - MINBUCKET]);
1229 }
1230 (void)printf("\n");
1231 totuse += ks.ks_memuse;
1232 totreq += ks.ks_calls;
1233 }
1234 (void)printf("\nMemory totals: In Use Free Requests\n");
1235 (void)printf(" %7ldK %6ldK %8ld\n\n",
1236 howmany(totuse, KILO), howmany(totfree, KILO), totreq);
1237 }
1238
1239 void
1240 dopool(int verbose, int wide)
1241 {
1242 int first, ovflw;
1243 void *addr;
1244 long total, inuse, this_total, this_inuse;
1245 TAILQ_HEAD(,pool) pool_head;
1246 struct pool pool, *pp = &pool;
1247 struct pool_allocator pa;
1248 char name[32], maxp[32];
1249
1250 kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
1251 addr = TAILQ_FIRST(&pool_head);
1252
1253 total = inuse = 0;
1254
1255 for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
1256 deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
1257 deref_kptr(pp->pr_alloc, &pa, sizeof(pa),
1258 "pool allocator trashed");
1259 deref_kptr(pp->pr_wchan, name, sizeof(name),
1260 "pool wait channel trashed");
1261 name[sizeof(name)-1] = '\0';
1262
1263 if (first) {
1264 (void)printf("Memory resource pool statistics\n");
1265 (void)printf(
1266 "%-*s%*s%*s%5s%*s%s%s%*s%*s%6s%s%6s%6s%6s%5s%s%s\n",
1267 wide ? 16 : 11, "Name",
1268 wide ? 6 : 5, "Size",
1269 wide ? 12 : 9, "Requests",
1270 "Fail",
1271 wide ? 12 : 9, "Releases",
1272 wide ? " InUse" : "",
1273 wide ? " Avail" : "",
1274 wide ? 7 : 6, "Pgreq",
1275 wide ? 7 : 6, "Pgrel",
1276 "Npage",
1277 wide ? " PageSz" : "",
1278 "Hiwat",
1279 "Minpg",
1280 "Maxpg",
1281 "Idle",
1282 wide ? " Flags" : "",
1283 wide ? " Util" : "");
1284 first = 0;
1285 }
1286 if (pp->pr_nget == 0 && !verbose)
1287 continue;
1288 if (pp->pr_maxpages == UINT_MAX)
1289 (void)snprintf(maxp, sizeof(maxp), "inf");
1290 else
1291 (void)snprintf(maxp, sizeof(maxp), "%u",
1292 pp->pr_maxpages);
1293 ovflw = 0;
1294 PRWORD(ovflw, "%-*s", wide ? 16 : 11, 0, name);
1295 PRWORD(ovflw, " %*u", wide ? 6 : 5, 1, pp->pr_size);
1296 PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nget);
1297 PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nfail);
1298 PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nput);
1299 if (wide)
1300 PRWORD(ovflw, " %*u", 7, 1, pp->pr_nout);
1301 if (wide)
1302 PRWORD(ovflw, " %*u", 6, 1, pp->pr_nitems);
1303 PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagealloc);
1304 PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagefree);
1305 PRWORD(ovflw, " %*u", 6, 1, pp->pr_npages);
1306 if (wide)
1307 PRWORD(ovflw, " %*u", 7, 1, pa.pa_pagesz);
1308 PRWORD(ovflw, " %*u", 6, 1, pp->pr_hiwat);
1309 PRWORD(ovflw, " %*u", 6, 1, pp->pr_minpages);
1310 PRWORD(ovflw, " %*s", 6, 1, maxp);
1311 PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nidle);
1312 if (wide)
1313 PRWORD(ovflw, " 0x%0*x", 4, 1,
1314 pp->pr_flags | pp->pr_roflags);
1315
1316 this_inuse = pp->pr_nout * pp->pr_size;
1317 this_total = pp->pr_npages * pa.pa_pagesz;
1318 if (pp->pr_roflags & PR_RECURSIVE) {
1319 /*
1320 * Don't count in-use memory, since it's part
1321 * of another pool and will be accounted for
1322 * there.
1323 */
1324 total += (this_total - this_inuse);
1325 } else {
1326 inuse += this_inuse;
1327 total += this_total;
1328 }
1329 if (wide) {
1330 if (this_total == 0)
1331 (void)printf(" ---");
1332 else
1333 (void)printf(" %5.1f%%",
1334 (100.0 * this_inuse) / this_total);
1335 }
1336 (void)printf("\n");
1337 }
1338
1339 inuse /= KILO;
1340 total /= KILO;
1341 (void)printf(
1342 "\nIn use %ldK, total allocated %ldK; utilization %.1f%%\n",
1343 inuse, total, (100.0 * inuse) / total);
1344 }
1345
1346 void
1347 dopoolcache(void)
1348 {
1349 struct pool_cache pool_cache, *pc = &pool_cache;
1350 pool_cache_cpu_t cache_cpu, *cc = &cache_cpu;
1351 TAILQ_HEAD(,pool) pool_head;
1352 struct pool pool, *pp = &pool;
1353 char name[32];
1354 uint64_t cpuhit, cpumiss, tot;
1355 void *addr;
1356 int first, ovflw;
1357 size_t i;
1358 double p;
1359
1360 kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
1361 addr = TAILQ_FIRST(&pool_head);
1362
1363 for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
1364 deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
1365 if (pp->pr_cache == NULL)
1366 continue;
1367 deref_kptr(pp->pr_wchan, name, sizeof(name),
1368 "pool wait channel trashed");
1369 deref_kptr(pp->pr_cache, pc, sizeof(*pc), "pool cache trashed");
1370 name[sizeof(name)-1] = '\0';
1371
1372 cpuhit = 0;
1373 cpumiss = 0;
1374 for (i = 0; i < sizeof(pc->pc_cpus) / sizeof(pc->pc_cpus[0]);
1375 i++) {
1376 if ((addr = pc->pc_cpus[i]) == NULL)
1377 continue;
1378 deref_kptr(addr, cc, sizeof(*cc),
1379 "pool cache cpu trashed");
1380 cpuhit += cc->cc_hits;
1381 cpumiss += cc->cc_misses;
1382 }
1383
1384 if (first) {
1385 (void)printf("Pool cache statistics.\n");
1386 (void)printf("%-*s%*s%*s%*s%*s%*s%*s%*s%*s%*s\n",
1387 12, "Name",
1388 6, "Spin",
1389 6, "GrpSz",
1390 5, "Full",
1391 5, "Emty",
1392 10, "PoolLayer",
1393 11, "CacheLayer",
1394 6, "Hit%",
1395 12, "CpuLayer",
1396 6, "Hit%"
1397 );
1398 first = 0;
1399 }
1400
1401 ovflw = 0;
1402 PRWORD(ovflw, "%-*s", 13, 1, name);
1403 PRWORD(ovflw, " %*llu", 6, 1, (long long)pc->pc_contended);
1404 PRWORD(ovflw, " %*u", 6, 1, pc->pc_pcgsize);
1405 PRWORD(ovflw, " %*u", 5, 1, pc->pc_nfull);
1406 PRWORD(ovflw, " %*u", 5, 1, pc->pc_nempty);
1407 PRWORD(ovflw, " %*llu", 10, 1, (long long)pc->pc_misses);
1408
1409 tot = pc->pc_hits + pc->pc_misses;
1410 p = pc->pc_hits * 100.0 / (tot);
1411 PRWORD(ovflw, " %*llu", 11, 1, (long long)tot);
1412 PRWORD(ovflw, " %*.1f", 6, 1, p);
1413
1414 tot = cpuhit + cpumiss;
1415 p = cpuhit * 100.0 / (tot);
1416 PRWORD(ovflw, " %*llu", 12, 1, (long long)tot);
1417 PRWORD(ovflw, " %*.1f", 6, 1, p);
1418 printf("\n");
1419 }
1420 }
1421
1422 enum hashtype { /* from <sys/systm.h> */
1423 HASH_LIST,
1424 HASH_TAILQ
1425 };
1426
1427 struct uidinfo { /* XXX: no kernel header file */
1428 LIST_ENTRY(uidinfo) ui_hash;
1429 uid_t ui_uid;
1430 long ui_proccnt;
1431 };
1432
1433 struct kernel_hash {
1434 const char * description; /* description */
1435 int hashsize; /* nlist index for hash size */
1436 int hashtbl; /* nlist index for hash table */
1437 enum hashtype type; /* type of hash table */
1438 size_t offset; /* offset of {LIST,TAILQ}_NEXT */
1439 } khashes[] =
1440 {
1441 {
1442 "buffer hash",
1443 X_BUFHASH, X_BUFHASHTBL,
1444 HASH_LIST, offsetof(struct buf, b_hash)
1445 }, {
1446 "inode cache (ihash)",
1447 X_IHASH, X_IHASHTBL,
1448 HASH_LIST, offsetof(struct inode, i_hash)
1449 }, {
1450 "ipv4 address -> interface hash",
1451 X_IFADDRHASH, X_IFADDRHASHTBL,
1452 HASH_LIST, offsetof(struct in_ifaddr, ia_hash),
1453 }, {
1454 "name cache hash",
1455 X_NCHASH, X_NCHASHTBL,
1456 HASH_LIST, offsetof(struct namecache, nc_hash),
1457 }, {
1458 "name cache directory hash",
1459 X_NCVHASH, X_NCVHASHTBL,
1460 HASH_LIST, offsetof(struct namecache, nc_vhash),
1461 }, {
1462 "user info (uid -> used processes) hash",
1463 X_UIHASH, X_UIHASHTBL,
1464 HASH_LIST, offsetof(struct uidinfo, ui_hash),
1465 }, {
1466 NULL, -1, -1, 0, 0,
1467 }
1468 };
1469
1470 void
1471 dohashstat(int verbose, int todo, const char *hashname)
1472 {
1473 LIST_HEAD(, generic) *hashtbl_list;
1474 TAILQ_HEAD(, generic) *hashtbl_tailq;
1475 struct kernel_hash *curhash;
1476 void *hashaddr, *hashbuf, *nhashbuf, *nextaddr;
1477 size_t elemsize, hashbufsize, thissize;
1478 u_long hashsize, i;
1479 int used, items, chain, maxchain;
1480
1481 hashbuf = NULL;
1482 hashbufsize = 0;
1483
1484 if (todo & HASHLIST) {
1485 (void)printf("Supported hashes:\n");
1486 for (curhash = khashes; curhash->description; curhash++) {
1487 if (hashnl[curhash->hashsize].n_value == 0 ||
1488 hashnl[curhash->hashtbl].n_value == 0)
1489 continue;
1490 (void)printf("\t%-16s%s\n",
1491 hashnl[curhash->hashsize].n_name + 1,
1492 curhash->description);
1493 }
1494 return;
1495 }
1496
1497 if (hashname != NULL) {
1498 for (curhash = khashes; curhash->description; curhash++) {
1499 if (strcmp(hashnl[curhash->hashsize].n_name + 1,
1500 hashname) == 0 &&
1501 hashnl[curhash->hashsize].n_value != 0 &&
1502 hashnl[curhash->hashtbl].n_value != 0)
1503 break;
1504 }
1505 if (curhash->description == NULL) {
1506 warnx("%s: no such hash", hashname);
1507 return;
1508 }
1509 }
1510
1511 (void)printf(
1512 "%-16s %8s %8s %8s %8s %8s %8s\n"
1513 "%-16s %8s %8s %8s %8s %8s %8s\n",
1514 "", "total", "used", "util", "num", "average", "maximum",
1515 "hash table", "buckets", "buckets", "%", "items", "chain",
1516 "chain");
1517
1518 for (curhash = khashes; curhash->description; curhash++) {
1519 if (hashnl[curhash->hashsize].n_value == 0 ||
1520 hashnl[curhash->hashtbl].n_value == 0)
1521 continue;
1522 if (hashname != NULL &&
1523 strcmp(hashnl[curhash->hashsize].n_name + 1, hashname))
1524 continue;
1525 elemsize = curhash->type == HASH_LIST ?
1526 sizeof(*hashtbl_list) : sizeof(*hashtbl_tailq);
1527 deref_kptr((void *)hashnl[curhash->hashsize].n_value,
1528 &hashsize, sizeof(hashsize),
1529 hashnl[curhash->hashsize].n_name);
1530 hashsize++;
1531 deref_kptr((void *)hashnl[curhash->hashtbl].n_value,
1532 &hashaddr, sizeof(hashaddr),
1533 hashnl[curhash->hashtbl].n_name);
1534 if (verbose)
1535 (void)printf(
1536 "%s %lu, %s %p, offset %ld, elemsize %llu\n",
1537 hashnl[curhash->hashsize].n_name + 1, hashsize,
1538 hashnl[curhash->hashtbl].n_name + 1, hashaddr,
1539 (long)curhash->offset,
1540 (unsigned long long)elemsize);
1541 thissize = hashsize * elemsize;
1542 if (hashbuf == NULL || thissize > hashbufsize) {
1543 if ((nhashbuf = realloc(hashbuf, thissize)) == NULL)
1544 errx(1, "malloc hashbuf %llu",
1545 (unsigned long long)hashbufsize);
1546 hashbuf = nhashbuf;
1547 hashbufsize = thissize;
1548 }
1549 deref_kptr(hashaddr, hashbuf, thissize,
1550 hashnl[curhash->hashtbl].n_name);
1551 used = 0;
1552 items = maxchain = 0;
1553 if (curhash->type == HASH_LIST) {
1554 hashtbl_list = hashbuf;
1555 hashtbl_tailq = NULL;
1556 } else {
1557 hashtbl_list = NULL;
1558 hashtbl_tailq = hashbuf;
1559 }
1560 for (i = 0; i < hashsize; i++) {
1561 if (curhash->type == HASH_LIST)
1562 nextaddr = LIST_FIRST(&hashtbl_list[i]);
1563 else
1564 nextaddr = TAILQ_FIRST(&hashtbl_tailq[i]);
1565 if (nextaddr == NULL)
1566 continue;
1567 if (verbose)
1568 (void)printf("%5lu: %p\n", i, nextaddr);
1569 used++;
1570 chain = 0;
1571 do {
1572 chain++;
1573 deref_kptr((char *)nextaddr + curhash->offset,
1574 &nextaddr, sizeof(void *),
1575 "hash chain corrupted");
1576 if (verbose > 1)
1577 (void)printf("got nextaddr as %p\n",
1578 nextaddr);
1579 } while (nextaddr != NULL);
1580 items += chain;
1581 if (verbose && chain > 1)
1582 (void)printf("\tchain = %d\n", chain);
1583 if (chain > maxchain)
1584 maxchain = chain;
1585 }
1586 (void)printf("%-16s %8ld %8d %8.2f %8d %8.2f %8d\n",
1587 hashnl[curhash->hashsize].n_name + 1,
1588 hashsize, used, used * 100.0 / hashsize,
1589 items, used ? (double)items / used : 0.0, maxchain);
1590 }
1591 }
1592
1593 /*
1594 * kreadc like kread but returns 1 if sucessful, 0 otherwise
1595 */
1596 int
1597 kreadc(struct nlist *nl, int nlx, void *addr, size_t size)
1598 {
1599 const char *sym;
1600
1601 sym = nl[nlx].n_name;
1602 if (*sym == '_')
1603 ++sym;
1604 if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
1605 return 0;
1606 deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
1607 return 1;
1608 }
1609
1610 /*
1611 * kread reads something from the kernel, given its nlist index in namelist[].
1612 */
1613 void
1614 kread(struct nlist *nl, int nlx, void *addr, size_t size)
1615 {
1616 const char *sym;
1617
1618 sym = nl[nlx].n_name;
1619 if (*sym == '_')
1620 ++sym;
1621 if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
1622 errx(1, "symbol %s not defined", sym);
1623 deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
1624 }
1625
1626 /*
1627 * Dereference the kernel pointer `kptr' and fill in the local copy
1628 * pointed to by `ptr'. The storage space must be pre-allocated,
1629 * and the size of the copy passed in `len'.
1630 */
1631 void
1632 deref_kptr(const void *kptr, void *ptr, size_t len, const char *msg)
1633 {
1634
1635 if (*msg == '_')
1636 msg++;
1637 if ((size_t)kvm_read(kd, (u_long)kptr, (char *)ptr, len) != len)
1638 errx(1, "kptr %lx: %s: %s", (u_long)kptr, msg, kvm_geterr(kd));
1639 }
1640
1641 /*
1642 * Traverse the UVM history buffers, performing the requested action.
1643 *
1644 * Note, we assume that if we're not listing, we're dumping.
1645 */
1646 void
1647 hist_traverse(int todo, const char *histname)
1648 {
1649 struct uvm_history_head histhead;
1650 struct uvm_history hist, *histkva;
1651 char *name = NULL;
1652 size_t namelen = 0;
1653
1654 if (histnl[0].n_value == 0) {
1655 warnx("UVM history is not compiled into the kernel.");
1656 return;
1657 }
1658
1659 deref_kptr((void *)histnl[X_UVM_HISTORIES].n_value, &histhead,
1660 sizeof(histhead), histnl[X_UVM_HISTORIES].n_name);
1661
1662 if (histhead.lh_first == NULL) {
1663 warnx("No active UVM history logs.");
1664 return;
1665 }
1666
1667 if (todo & HISTLIST)
1668 (void)printf("Active UVM histories:");
1669
1670 for (histkva = LIST_FIRST(&histhead); histkva != NULL;
1671 histkva = LIST_NEXT(&hist, list)) {
1672 deref_kptr(histkva, &hist, sizeof(hist), "histkva");
1673 if (name == NULL || hist.namelen > namelen) {
1674 if (name != NULL)
1675 free(name);
1676 namelen = hist.namelen;
1677 if ((name = malloc(namelen + 1)) == NULL)
1678 err(1, "malloc history name");
1679 }
1680
1681 deref_kptr(hist.name, name, namelen, "history name");
1682 name[namelen] = '\0';
1683 if (todo & HISTLIST)
1684 (void)printf(" %s", name);
1685 else {
1686 /*
1687 * If we're dumping all histories, do it, else
1688 * check to see if this is the one we want.
1689 */
1690 if (histname == NULL || strcmp(histname, name) == 0) {
1691 if (histname == NULL)
1692 (void)printf(
1693 "\nUVM history `%s':\n", name);
1694 hist_dodump(&hist);
1695 }
1696 }
1697 }
1698
1699 if (todo & HISTLIST)
1700 (void)putchar('\n');
1701
1702 if (name != NULL)
1703 free(name);
1704 }
1705
1706 /*
1707 * Actually dump the history buffer at the specified KVA.
1708 */
1709 void
1710 hist_dodump(struct uvm_history *histp)
1711 {
1712 struct uvm_history_ent *histents, *e;
1713 size_t histsize;
1714 char *fmt = NULL, *fn = NULL;
1715 size_t fmtlen = 0, fnlen = 0;
1716 unsigned i;
1717
1718 histsize = sizeof(struct uvm_history_ent) * histp->n;
1719
1720 if ((histents = malloc(histsize)) == NULL)
1721 err(1, "malloc history entries");
1722
1723 (void)memset(histents, 0, histsize);
1724
1725 deref_kptr(histp->e, histents, histsize, "history entries");
1726 i = histp->f;
1727 do {
1728 e = &histents[i];
1729 if (e->fmt != NULL) {
1730 if (fmt == NULL || e->fmtlen > fmtlen) {
1731 if (fmt != NULL)
1732 free(fmt);
1733 fmtlen = e->fmtlen;
1734 if ((fmt = malloc(fmtlen + 1)) == NULL)
1735 err(1, "malloc printf format");
1736 }
1737 if (fn == NULL || e->fnlen > fnlen) {
1738 if (fn != NULL)
1739 free(fn);
1740 fnlen = e->fnlen;
1741 if ((fn = malloc(fnlen + 1)) == NULL)
1742 err(1, "malloc function name");
1743 }
1744
1745 deref_kptr(e->fmt, fmt, fmtlen, "printf format");
1746 fmt[fmtlen] = '\0';
1747
1748 deref_kptr(e->fn, fn, fnlen, "function name");
1749 fn[fnlen] = '\0';
1750
1751 (void)printf("%06ld.%06ld ", (long int)e->tv.tv_sec,
1752 (long int)e->tv.tv_usec);
1753 (void)printf("%s#%ld: ", fn, e->call);
1754 (void)printf(fmt, e->v[0], e->v[1], e->v[2], e->v[3]);
1755 (void)putchar('\n');
1756 }
1757 i = (i + 1) % histp->n;
1758 } while (i != histp->f);
1759
1760 free(histents);
1761 if (fmt != NULL)
1762 free(fmt);
1763 if (fn != NULL)
1764 free(fn);
1765 }
1766
1767 void
1768 usage(void)
1769 {
1770
1771 (void)fprintf(stderr,
1772 "usage: %s [-CefHiLlmstUvW] [-c count] [-h hashname] [-M core] [-N system]\n"
1773 "\t\t[-u histname] [-w wait] [disks]\n", getprogname());
1774 exit(1);
1775 }
1776