vmstat.c revision 1.215 1 /* $NetBSD: vmstat.c,v 1.215 2017/01/05 03:42:27 pgoyette 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.215 2017/01/05 03:42:27 pgoyette Exp $");
74 #endif
75 #endif /* not lint */
76
77 #define __POOL_EXPOSE
78
79 #include <sys/param.h>
80 #include <sys/types.h>
81 #include <sys/mount.h>
82 #include <sys/uio.h>
83
84 #include <sys/buf.h>
85 #include <sys/evcnt.h>
86 #include <sys/ioctl.h>
87 #include <sys/malloc.h>
88 #include <sys/mallocvar.h>
89 #include <sys/namei.h>
90 #include <sys/pool.h>
91 #include <sys/proc.h>
92 #include <sys/sched.h>
93 #include <sys/socket.h>
94 #include <sys/sysctl.h>
95 #include <sys/time.h>
96 #include <sys/queue.h>
97 #include <sys/kernhist.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 * All this mess will go away once everything is converted.
134 */
135 #ifdef __HAVE_CPU_DATA_FIRST
136
137 # include <sys/cpu_data.h>
138 struct cpu_info {
139 struct cpu_data ci_data;
140 };
141 #else
142 # include <sys/cpu.h>
143 #endif
144
145 /*
146 * General namelist
147 */
148 struct nlist namelist[] =
149 {
150 #define X_BOOTTIME 0
151 { .n_name = "_boottime" },
152 #define X_HZ 1
153 { .n_name = "_hz" },
154 #define X_STATHZ 2
155 { .n_name = "_stathz" },
156 #define X_NCHSTATS 3
157 { .n_name = "_nchstats" },
158 #define X_ALLEVENTS 4
159 { .n_name = "_allevents" },
160 #define X_POOLHEAD 5
161 { .n_name = "_pool_head" },
162 #define X_UVMEXP 6
163 { .n_name = "_uvmexp" },
164 #define X_TIME_SECOND 7
165 { .n_name = "_time_second" },
166 #define X_TIME 8
167 { .n_name = "_time" },
168 #define X_CPU_INFOS 9
169 { .n_name = "_cpu_infos" },
170 #define X_NL_SIZE 10
171 { .n_name = NULL },
172 };
173
174 /*
175 * Namelist for pre-evcnt interrupt counters.
176 */
177 struct nlist intrnl[] =
178 {
179 #define X_INTRNAMES 0
180 { .n_name = "_intrnames" },
181 #define X_EINTRNAMES 1
182 { .n_name = "_eintrnames" },
183 #define X_INTRCNT 2
184 { .n_name = "_intrcnt" },
185 #define X_EINTRCNT 3
186 { .n_name = "_eintrcnt" },
187 #define X_INTRNL_SIZE 4
188 { .n_name = NULL },
189 };
190
191
192 /*
193 * Namelist for hash statistics
194 */
195 struct nlist hashnl[] =
196 {
197 #define X_NFSNODE 0
198 { .n_name = "_nfsnodehash" },
199 #define X_NFSNODETBL 1
200 { .n_name = "_nfsnodehashtbl" },
201 #define X_IHASH 2
202 { .n_name = "_ihash" },
203 #define X_IHASHTBL 3
204 { .n_name = "_ihashtbl" },
205 #define X_BUFHASH 4
206 { .n_name = "_bufhash" },
207 #define X_BUFHASHTBL 5
208 { .n_name = "_bufhashtbl" },
209 #define X_UIHASH 6
210 { .n_name = "_uihash" },
211 #define X_UIHASHTBL 7
212 { .n_name = "_uihashtbl" },
213 #define X_IFADDRHASH 8
214 { .n_name = "_in_ifaddrhash" },
215 #define X_IFADDRHASHTBL 9
216 { .n_name = "_in_ifaddrhashtbl" },
217 #define X_NCHASH 10
218 { .n_name = "_nchash" },
219 #define X_NCHASHTBL 11
220 { .n_name = "_nchashtbl" },
221 #define X_NCVHASH 12
222 { .n_name = "_ncvhash" },
223 #define X_NCVHASHTBL 13
224 { .n_name = "_ncvhashtbl" },
225 #define X_HASHNL_SIZE 14 /* must be last */
226 { .n_name = NULL },
227 };
228
229 /*
230 * Namelist for kernel histories
231 */
232 struct nlist histnl[] =
233 {
234 { .n_name = "_kern_histories" },
235 #define X_KERN_HISTORIES 0
236 { .n_name = NULL },
237 };
238
239
240 #define KILO 1024
241
242 struct cpu_counter {
243 uint64_t nintr;
244 uint64_t nsyscall;
245 uint64_t nswtch;
246 uint64_t nfault;
247 uint64_t ntrap;
248 uint64_t nsoft;
249 } cpucounter, ocpucounter;
250
251 struct uvmexp_sysctl uvmexp, ouvmexp;
252 int ndrives;
253
254 int winlines = 20;
255
256 kvm_t *kd;
257
258
259 #define FORKSTAT 0x001
260 #define INTRSTAT 0x002
261 #define MEMSTAT 0x004
262 #define SUMSTAT 0x008
263 #define EVCNTSTAT 0x010
264 #define VMSTAT 0x020
265 #define HISTLIST 0x040
266 #define HISTDUMP 0x080
267 #define HASHSTAT 0x100
268 #define HASHLIST 0x200
269 #define VMTOTAL 0x400
270 #define POOLCACHESTAT 0x800
271
272 /*
273 * Print single word. `ovflow' is number of characters didn't fit
274 * on the last word. `fmt' is a format string to print this word.
275 * It must contain asterisk for field width. `width' is a width
276 * occupied by this word. `fixed' is a number of constant chars in
277 * `fmt'. `val' is a value to be printed using format string `fmt'.
278 */
279 #define PRWORD(ovflw, fmt, width, fixed, val) do { \
280 (ovflw) += printf((fmt), \
281 (width) - (fixed) - (ovflw) > 0 ? \
282 (width) - (fixed) - (ovflw) : 0, \
283 (val)) - (width); \
284 if ((ovflw) < 0) \
285 (ovflw) = 0; \
286 } while (/* CONSTCOND */0)
287
288 void cpustats(int *);
289 void cpucounters(struct cpu_counter *);
290 void deref_kptr(const void *, void *, size_t, const char *);
291 void drvstats(int *);
292 void doevcnt(int verbose, int type);
293 void dohashstat(int, int, const char *);
294 void dointr(int verbose);
295 void dopool(int, int);
296 void dopoolcache(int);
297 void dosum(void);
298 void dovmstat(struct timespec *, int);
299 void print_total_hdr(void);
300 void dovmtotal(struct timespec *, int);
301 void kread(struct nlist *, int, void *, size_t);
302 int kreadc(struct nlist *, int, void *, size_t);
303 void needhdr(int);
304 void getnlist(int);
305 long getuptime(void);
306 void printhdr(void);
307 long pct(u_long, u_long);
308 __dead static void usage(void);
309 void doforkst(void);
310
311 void hist_traverse(int, const char *);
312 void hist_dodump(struct kern_history *);
313 void hist_traverse_sysctl(int, const char *);
314 void hist_dodump_sysctl(int[], unsigned int);
315
316 char **choosedrives(char **);
317
318 /* Namelist and memory file names. */
319 char *nlistf, *memf;
320
321 /* allow old usage [vmstat 1] */
322 #define BACKWARD_COMPATIBILITY
323
324 static const int clockrate_mib[] = { CTL_KERN, KERN_CLOCKRATE };
325 static const int vmmeter_mib[] = { CTL_VM, VM_METER };
326 static const int uvmexp2_mib[] = { CTL_VM, VM_UVMEXP2 };
327 static const int boottime_mib[] = { CTL_KERN, KERN_BOOTTIME };
328 static char kvm_errbuf[_POSIX2_LINE_MAX];
329
330 int
331 main(int argc, char *argv[])
332 {
333 int c, todo, verbose, wide;
334 struct timespec interval;
335 int reps;
336 gid_t egid = getegid();
337 const char *histname, *hashname;
338
339 histname = hashname = NULL;
340 (void)setegid(getgid());
341 memf = nlistf = NULL;
342 reps = todo = verbose = wide = 0;
343 interval.tv_sec = 0;
344 interval.tv_nsec = 0;
345 while ((c = getopt(argc, argv, "Cc:efh:HilLM:mN:stu:UvWw:")) != -1) {
346 switch (c) {
347 case 'c':
348 reps = atoi(optarg);
349 break;
350 case 'C':
351 todo |= POOLCACHESTAT;
352 break;
353 case 'e':
354 todo |= EVCNTSTAT;
355 break;
356 case 'f':
357 todo |= FORKSTAT;
358 break;
359 case 'h':
360 hashname = optarg;
361 /* FALLTHROUGH */
362 case 'H':
363 todo |= HASHSTAT;
364 break;
365 case 'i':
366 todo |= INTRSTAT;
367 break;
368 case 'l':
369 todo |= HISTLIST;
370 break;
371 case 'L':
372 todo |= HASHLIST;
373 break;
374 case 'M':
375 memf = optarg;
376 break;
377 case 'm':
378 todo |= MEMSTAT;
379 break;
380 case 'N':
381 nlistf = optarg;
382 break;
383 case 's':
384 todo |= SUMSTAT;
385 break;
386 case 't':
387 todo |= VMTOTAL;
388 break;
389 case 'u':
390 histname = optarg;
391 /* FALLTHROUGH */
392 case 'U':
393 todo |= HISTDUMP;
394 break;
395 case 'v':
396 verbose++;
397 break;
398 case 'W':
399 wide++;
400 break;
401 case 'w':
402 interval.tv_sec = atol(optarg);
403 break;
404 case '?':
405 default:
406 usage();
407 }
408 }
409 argc -= optind;
410 argv += optind;
411
412 if (todo == 0)
413 todo = VMSTAT;
414
415 /*
416 * Discard setgid privileges. If not the running kernel, we toss
417 * them away totally so that bad guys can't print interesting stuff
418 * from kernel memory, otherwise switch back to kmem for the
419 * duration of the kvm_openfiles() call.
420 */
421 if (nlistf != NULL || memf != NULL)
422 (void)setgid(getgid());
423 else
424 (void)setegid(egid);
425
426 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, kvm_errbuf);
427 if (kd == NULL) {
428 if (nlistf != NULL || memf != NULL) {
429 errx(1, "kvm_openfiles: %s", kvm_errbuf);
430 }
431 }
432
433 if (nlistf == NULL && memf == NULL)
434 (void)setgid(getgid());
435
436
437 if (todo & VMSTAT) {
438 struct winsize winsize;
439
440 (void)drvinit(0);/* Initialize disk stats, no disks selected. */
441
442 (void)setgid(getgid()); /* don't need privs anymore */
443
444 argv = choosedrives(argv); /* Select disks. */
445 winsize.ws_row = 0;
446 (void)ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
447 if (winsize.ws_row > 0)
448 winlines = winsize.ws_row;
449
450 }
451
452 #ifdef BACKWARD_COMPATIBILITY
453 if (*argv) {
454 interval.tv_sec = atol(*argv);
455 if (*++argv)
456 reps = atoi(*argv);
457 }
458 #endif
459
460 if (interval.tv_sec) {
461 if (!reps)
462 reps = -1;
463 } else if (reps)
464 interval.tv_sec = 1;
465
466
467 getnlist(todo);
468 /*
469 * Statistics dumping is incompatible with the default
470 * VMSTAT/dovmstat() output. So perform the interval/reps handling
471 * for it here.
472 */
473 if ((todo & (VMSTAT|VMTOTAL)) == 0) {
474 for (;;) {
475 if (todo & (HISTLIST|HISTDUMP)) {
476 if ((todo & (HISTLIST|HISTDUMP)) ==
477 (HISTLIST|HISTDUMP))
478 errx(1, "you may list or dump,"
479 " but not both!");
480 if (memf != NULL)
481 hist_traverse(todo, histname);
482 else
483 hist_traverse_sysctl(todo, histname);
484 (void)putchar('\n');
485 }
486 if (todo & FORKSTAT) {
487 doforkst();
488 (void)putchar('\n');
489 }
490 if (todo & MEMSTAT) {
491 dopool(verbose, wide);
492 (void)putchar('\n');
493 }
494 if (todo & POOLCACHESTAT) {
495 dopoolcache(verbose);
496 (void)putchar('\n');
497 }
498 if (todo & SUMSTAT) {
499 dosum();
500 (void)putchar('\n');
501 }
502 if (todo & INTRSTAT) {
503 dointr(verbose);
504 (void)putchar('\n');
505 }
506 if (todo & EVCNTSTAT) {
507 doevcnt(verbose, EVCNT_TYPE_ANY);
508 (void)putchar('\n');
509 }
510 if (todo & (HASHLIST|HASHSTAT)) {
511 if ((todo & (HASHLIST|HASHSTAT)) ==
512 (HASHLIST|HASHSTAT))
513 errx(1, "you may list or display,"
514 " but not both!");
515 dohashstat(verbose, todo, hashname);
516 (void)putchar('\n');
517 }
518
519 fflush(stdout);
520 if (reps >= 0 && --reps <=0)
521 break;
522 (void)nanosleep(&interval, NULL);
523 }
524 } else {
525 if ((todo & (VMSTAT|VMTOTAL)) == (VMSTAT|VMTOTAL)) {
526 errx(1, "you may not both do vmstat and vmtotal");
527 }
528 if (todo & VMSTAT)
529 dovmstat(&interval, reps);
530 if (todo & VMTOTAL)
531 dovmtotal(&interval, reps);
532 }
533 return 0;
534 }
535
536 void
537 getnlist(int todo)
538 {
539 static int namelist_done = 0;
540 static int done = 0;
541 int c;
542 size_t i;
543
544 if (kd == NULL)
545 errx(1, "kvm_openfiles: %s", kvm_errbuf);
546
547 if (!namelist_done) {
548 namelist_done = 1;
549 if ((c = kvm_nlist(kd, namelist)) != 0) {
550 int doexit = 0;
551 if (c == -1)
552 errx(1, "kvm_nlist: %s %s",
553 "namelist", kvm_geterr(kd));
554 for (i = 0; i < __arraycount(namelist)-1; i++)
555 if (namelist[i].n_type == 0 &&
556 i != X_TIME_SECOND &&
557 i != X_TIME) {
558 if (doexit++ == 0)
559 (void)fprintf(stderr,
560 "%s: undefined symbols:",
561 getprogname());
562 (void)fprintf(stderr, " %s",
563 namelist[i].n_name);
564 }
565 if (doexit) {
566 (void)fputc('\n', stderr);
567 exit(1);
568 }
569 }
570 }
571 if ((todo & (SUMSTAT|INTRSTAT)) && !(done & (SUMSTAT|INTRSTAT))) {
572 done |= SUMSTAT|INTRSTAT;
573 (void) kvm_nlist(kd, intrnl);
574 }
575 if ((todo & (HASHLIST|HASHSTAT)) && !(done & (HASHLIST|HASHSTAT))) {
576 done |= HASHLIST|HASHSTAT;
577 if ((c = kvm_nlist(kd, hashnl)) == -1 || c == X_HASHNL_SIZE)
578 errx(1, "kvm_nlist: %s %s", "hashnl", kvm_geterr(kd));
579 }
580 if ((todo & (HISTLIST|HISTDUMP)) && !(done & (HISTLIST|HISTDUMP))) {
581 done |= HISTLIST|HISTDUMP;
582 if (kvm_nlist(kd, histnl) == -1)
583 errx(1, "kvm_nlist: %s %s", "histnl", kvm_geterr(kd));
584 }
585 }
586
587 char **
588 choosedrives(char **argv)
589 {
590 size_t i;
591
592 /*
593 * Choose drives to be displayed. Priority goes to (in order) drives
594 * supplied as arguments, default drives. If everything isn't filled
595 * in and there are drives not taken care of, display the first few
596 * that fit.
597 */
598 #define BACKWARD_COMPATIBILITY
599 for (ndrives = 0; *argv; ++argv) {
600 #ifdef BACKWARD_COMPATIBILITY
601 if (isdigit((unsigned char)**argv))
602 break;
603 #endif
604 for (i = 0; i < ndrive; i++) {
605 if (strcmp(dr_name[i], *argv))
606 continue;
607 drv_select[i] = 1;
608 ++ndrives;
609 break;
610 }
611 }
612 for (i = 0; i < ndrive && ndrives < 2; i++) {
613 if (drv_select[i])
614 continue;
615 drv_select[i] = 1;
616 ++ndrives;
617 }
618
619 return (argv);
620 }
621
622 long
623 getuptime(void)
624 {
625 static struct timespec boottime;
626 struct timespec now;
627 time_t uptime, nowsec;
628
629 if (memf == NULL) {
630 if (boottime.tv_sec == 0) {
631 size_t buflen = sizeof(boottime);
632 if (sysctl(boottime_mib, __arraycount(boottime_mib),
633 &boottime, &buflen, NULL, 0) == -1)
634 warn("Can't get boottime");
635 }
636 clock_gettime(CLOCK_REALTIME, &now);
637 } else {
638 if (boottime.tv_sec == 0)
639 kread(namelist, X_BOOTTIME, &boottime,
640 sizeof(boottime));
641 if (kreadc(namelist, X_TIME_SECOND, &nowsec, sizeof(nowsec))) {
642 /*
643 * XXX this assignment dance can be removed once
644 * timeval tv_sec is SUS mandated time_t
645 */
646 now.tv_sec = nowsec;
647 now.tv_nsec = 0;
648 } else {
649 kread(namelist, X_TIME, &now, sizeof(now));
650 }
651 }
652 uptime = now.tv_sec - boottime.tv_sec;
653 if (uptime <= 0 || uptime > 60*60*24*365*10)
654 errx(1, "time makes no sense; namelist must be wrong.");
655 return (uptime);
656 }
657
658 int hz, hdrcnt;
659
660 void
661 print_total_hdr(void)
662 {
663
664 (void)printf("procs memory\n");
665 (void)printf("ru dw pw sl");
666 (void)printf(" total-v active-v active-r");
667 (void)printf(" vm-sh avm-sh rm-sh arm-sh free\n");
668 hdrcnt = winlines - 2;
669 }
670
671 void
672 dovmtotal(struct timespec *interval, int reps)
673 {
674 struct vmtotal total;
675 size_t size;
676
677 (void)signal(SIGCONT, needhdr);
678
679 for (hdrcnt = 1;;) {
680 if (!--hdrcnt)
681 print_total_hdr();
682 if (memf != NULL) {
683 warnx("Unable to get vmtotals from crash dump.");
684 (void)memset(&total, 0, sizeof(total));
685 } else {
686 size = sizeof(total);
687 if (sysctl(vmmeter_mib, __arraycount(vmmeter_mib),
688 &total, &size, NULL, 0) == -1) {
689 warn("Can't get vmtotals");
690 (void)memset(&total, 0, sizeof(total));
691 }
692 }
693 (void)printf("%2d ", total.t_rq);
694 (void)printf("%2d ", total.t_dw);
695 (void)printf("%2d ", total.t_pw);
696 (void)printf("%2d ", total.t_sl);
697
698 (void)printf("%9d ", total.t_vm);
699 (void)printf("%9d ", total.t_avm);
700 (void)printf("%9d ", total.t_arm);
701 (void)printf("%5d ", total.t_vmshr);
702 (void)printf("%6d ", total.t_avmshr);
703 (void)printf("%5d ", total.t_rmshr);
704 (void)printf("%6d ", total.t_armshr);
705 (void)printf("%5d", total.t_free);
706
707 (void)putchar('\n');
708
709 (void)fflush(stdout);
710 if (reps >= 0 && --reps <= 0)
711 break;
712
713 (void)nanosleep(interval, NULL);
714 }
715 }
716
717 void
718 dovmstat(struct timespec *interval, int reps)
719 {
720 struct vmtotal total;
721 time_t uptime, halfuptime;
722 size_t size;
723 int pagesize = getpagesize();
724 int ovflw;
725
726 uptime = getuptime();
727 halfuptime = uptime / 2;
728 (void)signal(SIGCONT, needhdr);
729
730 if (memf != NULL) {
731 if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
732 kread(namelist, X_STATHZ, &hz, sizeof(hz));
733 if (!hz)
734 kread(namelist, X_HZ, &hz, sizeof(hz));
735 } else {
736 struct clockinfo clockinfo;
737 size = sizeof(clockinfo);
738 if (sysctl(clockrate_mib, 2, &clockinfo, &size, NULL, 0) == -1)
739 err(1, "sysctl kern.clockrate failed");
740 hz = clockinfo.stathz;
741 if (!hz)
742 hz = clockinfo.hz;
743 }
744
745 for (hdrcnt = 1;;) {
746 if (!--hdrcnt)
747 printhdr();
748 /* Read new disk statistics */
749 cpureadstats();
750 drvreadstats();
751 tkreadstats();
752 if (memf != NULL) {
753 struct uvmexp uvmexp_kernel;
754 /*
755 * XXX Can't do this if we're reading a crash
756 * XXX dump because they're lazily-calculated.
757 */
758 warnx("Unable to get vmtotals from crash dump.");
759 (void)memset(&total, 0, sizeof(total));
760 kread(namelist, X_UVMEXP, &uvmexp_kernel, sizeof(uvmexp_kernel));
761 #define COPY(field) uvmexp.field = uvmexp_kernel.field
762 COPY(pdreact);
763 COPY(pageins);
764 COPY(pgswapout);
765 COPY(pdfreed);
766 COPY(pdscans);
767 #undef COPY
768 } else {
769 size = sizeof(total);
770 if (sysctl(vmmeter_mib, __arraycount(vmmeter_mib),
771 &total, &size, NULL, 0) == -1) {
772 warn("Can't get vmtotals");
773 (void)memset(&total, 0, sizeof(total));
774 }
775 size = sizeof(uvmexp);
776 if (sysctl(uvmexp2_mib, __arraycount(uvmexp2_mib), &uvmexp,
777 &size, NULL, 0) == -1)
778 warn("sysctl vm.uvmexp2 failed");
779 }
780 cpucounters(&cpucounter);
781 ovflw = 0;
782 PRWORD(ovflw, " %*d", 2, 1, total.t_rq - 1);
783 PRWORD(ovflw, " %*d", 2, 1, total.t_dw + total.t_pw);
784 #define pgtok(a) (long)((a) * ((uint32_t)pagesize >> 10))
785 #define rate(x) (u_long)(((x) + halfuptime) / uptime) /* round */
786 PRWORD(ovflw, " %*ld", 9, 1, pgtok(total.t_avm));
787 PRWORD(ovflw, " %*ld", 7, 1, pgtok(total.t_free));
788 PRWORD(ovflw, " %*ld", 5, 1,
789 rate(cpucounter.nfault - ocpucounter.nfault));
790 PRWORD(ovflw, " %*ld", 4, 1,
791 rate(uvmexp.pdreact - ouvmexp.pdreact));
792 PRWORD(ovflw, " %*ld", 4, 1,
793 rate(uvmexp.pageins - ouvmexp.pageins));
794 PRWORD(ovflw, " %*ld", 5, 1,
795 rate(uvmexp.pgswapout - ouvmexp.pgswapout));
796 PRWORD(ovflw, " %*ld", 5, 1,
797 rate(uvmexp.pdfreed - ouvmexp.pdfreed));
798 PRWORD(ovflw, " %*ld", 6, 2,
799 rate(uvmexp.pdscans - ouvmexp.pdscans));
800 drvstats(&ovflw);
801 PRWORD(ovflw, " %*ld", 5, 1,
802 rate(cpucounter.nintr - ocpucounter.nintr));
803 PRWORD(ovflw, " %*ld", 5, 1,
804 rate(cpucounter.nsyscall - ocpucounter.nsyscall));
805 PRWORD(ovflw, " %*ld", 4, 1,
806 rate(cpucounter.nswtch - ocpucounter.nswtch));
807 cpustats(&ovflw);
808 (void)putchar('\n');
809 (void)fflush(stdout);
810 if (reps >= 0 && --reps <= 0)
811 break;
812 ouvmexp = uvmexp;
813 ocpucounter = cpucounter;
814 uptime = interval->tv_sec;
815 /*
816 * We round upward to avoid losing low-frequency events
817 * (i.e., >= 1 per interval but < 1 per second).
818 */
819 halfuptime = uptime == 1 ? 0 : (uptime + 1) / 2;
820 (void)nanosleep(interval, NULL);
821 }
822 }
823
824 void
825 printhdr(void)
826 {
827 size_t i;
828
829 (void)printf(" procs memory page%*s", 23, "");
830 if (ndrives > 0)
831 (void)printf("%s %*sfaults cpu\n",
832 ((ndrives > 1) ? "disks" : "disk"),
833 ((ndrives > 1) ? ndrives * 3 - 4 : 0), "");
834 else
835 (void)printf("%*s faults cpu\n",
836 ndrives * 3, "");
837
838 (void)printf(" r b avm fre flt re pi po fr sr ");
839 for (i = 0; i < ndrive; i++)
840 if (drv_select[i])
841 (void)printf("%c%c ", dr_name[i][0],
842 dr_name[i][strlen(dr_name[i]) - 1]);
843 (void)printf(" in sy cs us sy id\n");
844 hdrcnt = winlines - 2;
845 }
846
847 /*
848 * Force a header to be prepended to the next output.
849 */
850 void
851 /*ARGSUSED*/
852 needhdr(int dummy)
853 {
854
855 hdrcnt = 1;
856 }
857
858 long
859 pct(u_long top, u_long bot)
860 {
861 long ans;
862
863 if (bot == 0)
864 return (0);
865 ans = (long)((quad_t)top * 100 / bot);
866 return (ans);
867 }
868
869 #define PCT(top, bot) (int)pct((u_long)(top), (u_long)(bot))
870
871 void
872 dosum(void)
873 {
874 struct nchstats nch_stats;
875 uint64_t nchtotal;
876 size_t ssize;
877 int active_kernel;
878 struct cpu_counter cc;
879
880 /*
881 * The "active" and "inactive" variables
882 * are now estimated by the kernel and sadly
883 * can not easily be dug out of a crash dump.
884 */
885 ssize = sizeof(uvmexp);
886 memset(&uvmexp, 0, ssize);
887 active_kernel = (memf == NULL);
888 if (active_kernel) {
889 /* only on active kernel */
890 if (sysctl(uvmexp2_mib, __arraycount(uvmexp2_mib), &uvmexp,
891 &ssize, NULL, 0) == -1)
892 warn("sysctl vm.uvmexp2 failed");
893 } else {
894 struct uvmexp uvmexp_kernel;
895 kread(namelist, X_UVMEXP, &uvmexp_kernel, sizeof(uvmexp_kernel));
896 #define COPY(field) uvmexp.field = uvmexp_kernel.field
897 COPY(pagesize);
898 COPY(ncolors);
899 COPY(npages);
900 COPY(free);
901 COPY(paging);
902 COPY(wired);
903 COPY(zeropages);
904 COPY(reserve_pagedaemon);
905 COPY(reserve_kernel);
906 COPY(anonpages);
907 COPY(filepages);
908 COPY(execpages);
909 COPY(freemin);
910 COPY(freetarg);
911 COPY(wiredmax);
912 COPY(nswapdev);
913 COPY(swpages);
914 COPY(swpginuse);
915 COPY(nswget);
916 COPY(pageins);
917 COPY(pdpageouts);
918 COPY(pgswapin);
919 COPY(pgswapout);
920 COPY(forks);
921 COPY(forks_ppwait);
922 COPY(forks_sharevm);
923 COPY(pga_zerohit);
924 COPY(pga_zeromiss);
925 COPY(zeroaborts);
926 COPY(colorhit);
927 COPY(colormiss);
928 COPY(cpuhit);
929 COPY(cpumiss);
930 COPY(fltnoram);
931 COPY(fltnoanon);
932 COPY(fltpgwait);
933 COPY(fltpgrele);
934 COPY(fltrelck);
935 COPY(fltrelckok);
936 COPY(fltanget);
937 COPY(fltanretry);
938 COPY(fltamcopy);
939 COPY(fltamcopy);
940 COPY(fltnomap);
941 COPY(fltlget);
942 COPY(fltget);
943 COPY(flt_anon);
944 COPY(flt_acow);
945 COPY(flt_obj);
946 COPY(flt_prcopy);
947 COPY(flt_przero);
948 COPY(pdwoke);
949 COPY(pdrevs);
950 COPY(pdfreed);
951 COPY(pdscans);
952 COPY(pdanscan);
953 COPY(pdobscan);
954 COPY(pdreact);
955 COPY(pdbusy);
956 COPY(pdpending);
957 COPY(pddeact);
958 #undef COPY
959 }
960
961
962 (void)printf("%9" PRIu64 " bytes per page\n", uvmexp.pagesize);
963
964 (void)printf("%9" PRIu64 " page color%s\n",
965 uvmexp.ncolors, uvmexp.ncolors == 1 ? "" : "s");
966
967 (void)printf("%9" PRIu64 " pages managed\n", uvmexp.npages);
968 (void)printf("%9" PRIu64 " pages free\n", uvmexp.free);
969 if (active_kernel) {
970 (void)printf("%9" PRIu64 " pages active\n", uvmexp.active);
971 (void)printf("%9" PRIu64 " pages inactive\n", uvmexp.inactive);
972 }
973 (void)printf("%9" PRIu64 " pages paging\n", uvmexp.paging);
974 (void)printf("%9" PRIu64 " pages wired\n", uvmexp.wired);
975 (void)printf("%9" PRIu64 " zero pages\n", uvmexp.zeropages);
976 (void)printf("%9" PRIu64 " reserve pagedaemon pages\n",
977 uvmexp.reserve_pagedaemon);
978 (void)printf("%9" PRIu64 " reserve kernel pages\n", uvmexp.reserve_kernel);
979 (void)printf("%9" PRIu64 " anonymous pages\n", uvmexp.anonpages);
980 (void)printf("%9" PRIu64 " cached file pages\n", uvmexp.filepages);
981 (void)printf("%9" PRIu64 " cached executable pages\n", uvmexp.execpages);
982
983 (void)printf("%9" PRIu64 " minimum free pages\n", uvmexp.freemin);
984 (void)printf("%9" PRIu64 " target free pages\n", uvmexp.freetarg);
985 (void)printf("%9" PRIu64 " maximum wired pages\n", uvmexp.wiredmax);
986
987 (void)printf("%9" PRIu64 " swap devices\n", uvmexp.nswapdev);
988 (void)printf("%9" PRIu64 " swap pages\n", uvmexp.swpages);
989 (void)printf("%9" PRIu64 " swap pages in use\n", uvmexp.swpginuse);
990 (void)printf("%9" PRIu64 " swap allocations\n", uvmexp.nswget);
991
992 cpucounters(&cc);
993
994 (void)printf("%9" PRIu64 " total faults taken\n", cc.nfault);
995 (void)printf("%9" PRIu64 " traps\n", cc.ntrap);
996 (void)printf("%9" PRIu64 " device interrupts\n", cc.nintr);
997 (void)printf("%9" PRIu64 " CPU context switches\n", cc.nswtch);
998 (void)printf("%9" PRIu64 " software interrupts\n", cc.nsoft);
999 (void)printf("%9" PRIu64 " system calls\n", cc.nsyscall);
1000 (void)printf("%9" PRIu64 " pagein requests\n", uvmexp.pageins);
1001 (void)printf("%9" PRIu64 " pageout requests\n", uvmexp.pdpageouts);
1002 (void)printf("%9" PRIu64 " pages swapped in\n", uvmexp.pgswapin);
1003 (void)printf("%9" PRIu64 " pages swapped out\n", uvmexp.pgswapout);
1004 (void)printf("%9" PRIu64 " forks total\n", uvmexp.forks);
1005 (void)printf("%9" PRIu64 " forks blocked parent\n", uvmexp.forks_ppwait);
1006 (void)printf("%9" PRIu64 " forks shared address space with parent\n",
1007 uvmexp.forks_sharevm);
1008 (void)printf("%9" PRIu64 " pagealloc zero wanted and avail\n",
1009 uvmexp.pga_zerohit);
1010 (void)printf("%9" PRIu64 " pagealloc zero wanted and not avail\n",
1011 uvmexp.pga_zeromiss);
1012 (void)printf("%9" PRIu64 " aborts of idle page zeroing\n",
1013 uvmexp.zeroaborts);
1014 (void)printf("%9" PRIu64 " pagealloc desired color avail\n",
1015 uvmexp.colorhit);
1016 (void)printf("%9" PRIu64 " pagealloc desired color not avail\n",
1017 uvmexp.colormiss);
1018 (void)printf("%9" PRIu64 " pagealloc local cpu avail\n",
1019 uvmexp.cpuhit);
1020 (void)printf("%9" PRIu64 " pagealloc local cpu not avail\n",
1021 uvmexp.cpumiss);
1022
1023 (void)printf("%9" PRIu64 " faults with no memory\n", uvmexp.fltnoram);
1024 (void)printf("%9" PRIu64 " faults with no anons\n", uvmexp.fltnoanon);
1025 (void)printf("%9" PRIu64 " faults had to wait on pages\n", uvmexp.fltpgwait);
1026 (void)printf("%9" PRIu64 " faults found released page\n", uvmexp.fltpgrele);
1027 (void)printf("%9" PRIu64 " faults relock (%" PRIu64 " ok)\n", uvmexp.fltrelck,
1028 uvmexp.fltrelckok);
1029 (void)printf("%9" PRIu64 " anon page faults\n", uvmexp.fltanget);
1030 (void)printf("%9" PRIu64 " anon retry faults\n", uvmexp.fltanretry);
1031 (void)printf("%9" PRIu64 " amap copy faults\n", uvmexp.fltamcopy);
1032 (void)printf("%9" PRIu64 " neighbour anon page faults\n", uvmexp.fltnamap);
1033 (void)printf("%9" PRIu64 " neighbour object page faults\n", uvmexp.fltnomap);
1034 (void)printf("%9" PRIu64 " locked pager get faults\n", uvmexp.fltlget);
1035 (void)printf("%9" PRIu64 " unlocked pager get faults\n", uvmexp.fltget);
1036 (void)printf("%9" PRIu64 " anon faults\n", uvmexp.flt_anon);
1037 (void)printf("%9" PRIu64 " anon copy on write faults\n", uvmexp.flt_acow);
1038 (void)printf("%9" PRIu64 " object faults\n", uvmexp.flt_obj);
1039 (void)printf("%9" PRIu64 " promote copy faults\n", uvmexp.flt_prcopy);
1040 (void)printf("%9" PRIu64 " promote zero fill faults\n", uvmexp.flt_przero);
1041
1042 (void)printf("%9" PRIu64 " times daemon wokeup\n",uvmexp.pdwoke);
1043 (void)printf("%9" PRIu64 " revolutions of the clock hand\n", uvmexp.pdrevs);
1044 (void)printf("%9" PRIu64 " pages freed by daemon\n", uvmexp.pdfreed);
1045 (void)printf("%9" PRIu64 " pages scanned by daemon\n", uvmexp.pdscans);
1046 (void)printf("%9" PRIu64 " anonymous pages scanned by daemon\n",
1047 uvmexp.pdanscan);
1048 (void)printf("%9" PRIu64 " object pages scanned by daemon\n", uvmexp.pdobscan);
1049 (void)printf("%9" PRIu64 " pages reactivated\n", uvmexp.pdreact);
1050 (void)printf("%9" PRIu64 " pages found busy by daemon\n", uvmexp.pdbusy);
1051 (void)printf("%9" PRIu64 " total pending pageouts\n", uvmexp.pdpending);
1052 (void)printf("%9" PRIu64 " pages deactivated\n", uvmexp.pddeact);
1053
1054 if (active_kernel) {
1055 ssize = sizeof(nch_stats);
1056 if (sysctlbyname("vfs.namecache_stats", &nch_stats, &ssize,
1057 NULL, 0)) {
1058 warn("vfs.namecache_stats failed");
1059 memset(&nch_stats, 0, sizeof(nch_stats));
1060 }
1061 } else {
1062 kread(namelist, X_NCHSTATS, &nch_stats, sizeof(nch_stats));
1063 }
1064
1065 nchtotal = nch_stats.ncs_goodhits + nch_stats.ncs_neghits +
1066 nch_stats.ncs_badhits + nch_stats.ncs_falsehits +
1067 nch_stats.ncs_miss + nch_stats.ncs_long;
1068 (void)printf("%9" PRIu64 " total name lookups\n", nchtotal);
1069 (void)printf("%9" PRIu64 " good hits\n", nch_stats.ncs_goodhits);
1070 (void)printf("%9" PRIu64 " negative hits\n", nch_stats.ncs_neghits);
1071 (void)printf("%9" PRIu64 " bad hits\n", nch_stats.ncs_badhits);
1072 (void)printf("%9" PRIu64 " false hits\n", nch_stats.ncs_falsehits);
1073 (void)printf("%9" PRIu64 " miss\n", nch_stats.ncs_miss);
1074 (void)printf("%9" PRIu64 " too long\n", nch_stats.ncs_long);
1075 (void)printf("%9" PRIu64 " pass2 hits\n", nch_stats.ncs_pass2);
1076 (void)printf("%9" PRIu64 " 2passes\n", nch_stats.ncs_2passes);
1077 (void)printf(
1078 "%9s cache hits (%d%% pos + %d%% neg) system %d%% per-process\n",
1079 "", PCT(nch_stats.ncs_goodhits, nchtotal),
1080 PCT(nch_stats.ncs_neghits, nchtotal),
1081 PCT(nch_stats.ncs_pass2, nchtotal));
1082 (void)printf("%9s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
1083 PCT(nch_stats.ncs_badhits, nchtotal),
1084 PCT(nch_stats.ncs_falsehits, nchtotal),
1085 PCT(nch_stats.ncs_long, nchtotal));
1086 }
1087
1088 void
1089 doforkst(void)
1090 {
1091 if (memf != NULL) {
1092 struct uvmexp uvmexp_kernel;
1093 kread(namelist, X_UVMEXP, &uvmexp_kernel, sizeof(uvmexp_kernel));
1094 #define COPY(field) uvmexp.field = uvmexp_kernel.field
1095 COPY(forks);
1096 COPY(forks_ppwait);
1097 COPY(forks_sharevm);
1098 #undef COPY
1099 } else {
1100 size_t size = sizeof(uvmexp);
1101 if (sysctl(uvmexp2_mib, __arraycount(uvmexp2_mib), &uvmexp,
1102 &size, NULL, 0) == -1)
1103 warn("sysctl vm.uvmexp2 failed");
1104 }
1105
1106 (void)printf("%" PRIu64 " forks total\n", uvmexp.forks);
1107 (void)printf("%" PRIu64 " forks blocked parent\n", uvmexp.forks_ppwait);
1108 (void)printf("%" PRIu64 " forks shared address space with parent\n",
1109 uvmexp.forks_sharevm);
1110 }
1111
1112 void
1113 drvstats(int *ovflwp)
1114 {
1115 size_t dn;
1116 double etime;
1117 int ovflw = *ovflwp;
1118
1119 /* Calculate disk stat deltas. */
1120 cpuswap();
1121 drvswap();
1122 tkswap();
1123 etime = cur.cp_etime;
1124
1125 for (dn = 0; dn < ndrive; ++dn) {
1126 if (!drv_select[dn])
1127 continue;
1128 PRWORD(ovflw, " %*.0f", 3, 1,
1129 (cur.rxfer[dn] + cur.wxfer[dn]) / etime);
1130 }
1131 *ovflwp = ovflw;
1132 }
1133
1134 void
1135 cpucounters(struct cpu_counter *cc)
1136 {
1137 static struct cpu_info **cpu_infos;
1138 static int initialised;
1139 struct cpu_info **slot;
1140
1141 if (memf == NULL) {
1142 cc->nintr = uvmexp.intrs;
1143 cc->nsyscall = uvmexp.syscalls;
1144 cc->nswtch = uvmexp.swtch;
1145 cc->nfault = uvmexp.faults;
1146 cc->ntrap = uvmexp.traps;
1147 cc->nsoft = uvmexp.softs;
1148 return;
1149 }
1150
1151 if (!initialised) {
1152 kread(namelist, X_CPU_INFOS, &cpu_infos, sizeof(cpu_infos));
1153 initialised = 1;
1154 }
1155
1156 slot = cpu_infos;
1157
1158 memset(cc, 0, sizeof(*cc));
1159
1160 for (;;) {
1161 struct cpu_info tci, *ci = NULL;
1162
1163 deref_kptr(slot++, &ci, sizeof(ci), "CPU array trashed");
1164 if (!ci) {
1165 break;
1166 }
1167
1168 if ((size_t)kvm_read(kd, (u_long)ci, &tci, sizeof(tci))
1169 != sizeof(tci)) {
1170 warnx("Can't read cpu info from %p (%s)",
1171 ci, kvm_geterr(kd));
1172 memset(cc, 0, sizeof(*cc));
1173 return;
1174 }
1175 cc->nintr += tci.ci_data.cpu_nintr;
1176 cc->nsyscall += tci.ci_data.cpu_nsyscall;
1177 cc->nswtch = tci.ci_data.cpu_nswtch;
1178 cc->nfault = tci.ci_data.cpu_nfault;
1179 cc->ntrap = tci.ci_data.cpu_ntrap;
1180 cc->nsoft = tci.ci_data.cpu_nsoft;
1181 }
1182 }
1183
1184 void
1185 cpustats(int *ovflwp)
1186 {
1187 int state;
1188 double pcnt, total;
1189 double stat_us, stat_sy, stat_id;
1190 int ovflw = *ovflwp;
1191
1192 total = 0;
1193 for (state = 0; state < CPUSTATES; ++state)
1194 total += cur.cp_time[state];
1195 if (total)
1196 pcnt = 100 / total;
1197 else
1198 pcnt = 0;
1199 stat_us = (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) * pcnt;
1200 stat_sy = (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) * pcnt;
1201 stat_id = cur.cp_time[CP_IDLE] * pcnt;
1202 PRWORD(ovflw, " %*.0f", ((stat_sy >= 100) ? 2 : 3), 1, stat_us);
1203 PRWORD(ovflw, " %*.0f", ((stat_us >= 100 || stat_id >= 100) ? 2 : 3), 1,
1204 stat_sy);
1205 PRWORD(ovflw, " %*.0f", 3, 1, stat_id);
1206 *ovflwp = ovflw;
1207 }
1208
1209 void
1210 dointr(int verbose)
1211 {
1212 unsigned long *intrcnt, *ointrcnt;
1213 unsigned long long inttotal, uptime;
1214 int nintr, inamlen;
1215 char *intrname, *ointrname;
1216
1217 inttotal = 0;
1218 uptime = getuptime();
1219 (void)printf("%-34s %16s %8s\n", "interrupt", "total", "rate");
1220 nintr = intrnl[X_EINTRCNT].n_value - intrnl[X_INTRCNT].n_value;
1221 inamlen = intrnl[X_EINTRNAMES].n_value - intrnl[X_INTRNAMES].n_value;
1222 if (nintr != 0 && inamlen != 0) {
1223 ointrcnt = intrcnt = malloc((size_t)nintr);
1224 ointrname = intrname = malloc((size_t)inamlen);
1225 if (intrcnt == NULL || intrname == NULL)
1226 errx(1, "%s", "");
1227 kread(intrnl, X_INTRCNT, intrcnt, (size_t)nintr);
1228 kread(intrnl, X_INTRNAMES, intrname, (size_t)inamlen);
1229 nintr /= sizeof(long);
1230 while (--nintr >= 0) {
1231 if (*intrcnt || verbose)
1232 (void)printf("%-34s %16llu %8llu\n", intrname,
1233 (unsigned long long)*intrcnt,
1234 (unsigned long long)
1235 (*intrcnt / uptime));
1236 intrname += strlen(intrname) + 1;
1237 inttotal += *intrcnt++;
1238 }
1239 free(ointrcnt);
1240 free(ointrname);
1241 }
1242
1243 doevcnt(verbose, EVCNT_TYPE_INTR);
1244 }
1245
1246 void
1247 doevcnt(int verbose, int type)
1248 {
1249 static const char * const evtypes [] = { "misc", "intr", "trap" };
1250 uint64_t counttotal, uptime;
1251 struct evcntlist allevents;
1252 struct evcnt evcnt, *evptr;
1253 char evgroup[EVCNT_STRING_MAX], evname[EVCNT_STRING_MAX];
1254
1255 counttotal = 0;
1256 uptime = getuptime();
1257 if (type == EVCNT_TYPE_ANY)
1258 (void)printf("%-34s %16s %8s %s\n", "event", "total", "rate",
1259 "type");
1260
1261 if (memf == NULL) do {
1262 const int mib[4] = { CTL_KERN, KERN_EVCNT, type,
1263 verbose ? KERN_EVCNT_COUNT_ANY : KERN_EVCNT_COUNT_NONZERO };
1264 size_t buflen = 0;
1265 void *buf = NULL;
1266 const struct evcnt_sysctl *evs, *last_evs;
1267 for (;;) {
1268 size_t newlen;
1269 int error;
1270 if (buflen)
1271 buf = malloc(buflen);
1272 error = sysctl(mib, __arraycount(mib),
1273 buf, &newlen, NULL, 0);
1274 if (error) {
1275 err(1, "kern.evcnt");
1276 if (buf)
1277 free(buf);
1278 return;
1279 }
1280 if (newlen <= buflen) {
1281 buflen = newlen;
1282 break;
1283 }
1284 if (buf)
1285 free(buf);
1286 buflen = newlen;
1287 }
1288 evs = buf;
1289 last_evs = (void *)((char *)buf + buflen);
1290 buflen /= sizeof(uint64_t);
1291 while (evs < last_evs
1292 && buflen >= sizeof(*evs)/sizeof(uint64_t)
1293 && buflen >= evs->ev_len) {
1294 (void)printf(type == EVCNT_TYPE_ANY ?
1295 "%s %s%*s %16"PRIu64" %8"PRIu64" %s\n" :
1296 "%s %s%*s %16"PRIu64" %8"PRIu64"\n",
1297 evs->ev_strings,
1298 evs->ev_strings + evs->ev_grouplen + 1,
1299 34 - (evs->ev_grouplen + 1 + evs->ev_namelen), "",
1300 evs->ev_count,
1301 evs->ev_count / uptime,
1302 (evs->ev_type < __arraycount(evtypes) ?
1303 evtypes[evs->ev_type] : "?"));
1304 buflen -= evs->ev_len;
1305 counttotal += evs->ev_count;
1306 evs = (const void *)((const uint64_t *)evs + evs->ev_len);
1307 }
1308 free(buf);
1309 if (type != EVCNT_TYPE_ANY)
1310 (void)printf("%-34s %16"PRIu64" %8"PRIu64"\n",
1311 "Total", counttotal, counttotal / uptime);
1312 return;
1313 } while (/*CONSTCOND*/ 0);
1314
1315 kread(namelist, X_ALLEVENTS, &allevents, sizeof allevents);
1316 evptr = TAILQ_FIRST(&allevents);
1317 while (evptr) {
1318 deref_kptr(evptr, &evcnt, sizeof(evcnt), "event chain trashed");
1319
1320 evptr = TAILQ_NEXT(&evcnt, ev_list);
1321 if (evcnt.ev_count == 0 && !verbose)
1322 continue;
1323 if (type != EVCNT_TYPE_ANY && evcnt.ev_type != type)
1324 continue;
1325
1326 deref_kptr(evcnt.ev_group, evgroup,
1327 (size_t)evcnt.ev_grouplen + 1, "event chain trashed");
1328 deref_kptr(evcnt.ev_name, evname,
1329 (size_t)evcnt.ev_namelen + 1, "event chain trashed");
1330
1331 (void)printf(type == EVCNT_TYPE_ANY ?
1332 "%s %s%*s %16"PRIu64" %8"PRIu64" %s\n" :
1333 "%s %s%*s %16"PRIu64" %8"PRIu64"\n",
1334 evgroup, evname,
1335 34 - (evcnt.ev_grouplen + 1 + evcnt.ev_namelen), "",
1336 evcnt.ev_count,
1337 (evcnt.ev_count / uptime),
1338 (evcnt.ev_type < __arraycount(evtypes) ?
1339 evtypes[evcnt.ev_type] : "?"));
1340
1341 counttotal += evcnt.ev_count;
1342 }
1343 if (type != EVCNT_TYPE_ANY)
1344 (void)printf("%-34s %16"PRIu64" %8"PRIu64"\n",
1345 "Total", counttotal, counttotal / uptime);
1346 }
1347
1348 static void
1349 dopool_sysctl(int verbose, int wide)
1350 {
1351 uint64_t total, inuse, this_total, this_inuse;
1352 struct {
1353 uint64_t pt_nget;
1354 uint64_t pt_nfail;
1355 uint64_t pt_nput;
1356 uint64_t pt_nout;
1357 uint64_t pt_nitems;
1358 uint64_t pt_npagealloc;
1359 uint64_t pt_npagefree;
1360 uint64_t pt_npages;
1361 } pool_totals;
1362 size_t i, len;
1363 int name_len, ovflw;
1364 struct pool_sysctl *pp, *data;
1365 char in_use[8], avail[8], maxp[32];
1366
1367 data = asysctlbyname("kern.pool", &len);
1368 if (data == NULL)
1369 err(1, "failed to reead kern.pool");
1370
1371 memset(&pool_totals, 0, sizeof pool_totals);
1372 total = inuse = 0;
1373 len /= sizeof(*data);
1374
1375 (void)printf("Memory resource pool statistics\n");
1376 (void)printf(
1377 "%-*s%*s%*s%5s%*s%s%s%*s%*s%6s%s%6s%6s%6s%5s%s%s\n",
1378 wide ? 16 : 11, "Name",
1379 wide ? 6 : 5, "Size",
1380 wide ? 12 : 9, "Requests",
1381 "Fail",
1382 wide ? 12 : 9, "Releases",
1383 wide ? " InUse" : "",
1384 wide ? " Avail" : "",
1385 wide ? 7 : 6, "Pgreq",
1386 wide ? 7 : 6, "Pgrel",
1387 "Npage",
1388 wide ? " PageSz" : "",
1389 "Hiwat",
1390 "Minpg",
1391 "Maxpg",
1392 "Idle",
1393 wide ? " Flags" : "",
1394 wide ? " Util" : "");
1395
1396 name_len = MIN((int)sizeof(pp->pr_wchan), wide ? 16 : 11);
1397 for (i = 0; i < len; ++i) {
1398 pp = &data[i];
1399 if (pp->pr_nget == 0 && !verbose)
1400 continue;
1401 if (pp->pr_maxpages == UINT_MAX)
1402 (void)snprintf(maxp, sizeof(maxp), "inf");
1403 else
1404 (void)snprintf(maxp, sizeof(maxp), "%" PRIu64,
1405 pp->pr_maxpages);
1406 ovflw = 0;
1407 PRWORD(ovflw, "%-*s", name_len, 0, pp->pr_wchan);
1408 PRWORD(ovflw, " %*" PRIu64, wide ? 6 : 5, 1, pp->pr_size);
1409 PRWORD(ovflw, " %*" PRIu64, wide ? 12 : 9, 1, pp->pr_nget);
1410 pool_totals.pt_nget += pp->pr_nget;
1411 PRWORD(ovflw, " %*" PRIu64, 5, 1, pp->pr_nfail);
1412 pool_totals.pt_nfail += pp->pr_nfail;
1413 PRWORD(ovflw, " %*" PRIu64, wide ? 12 : 9, 1, pp->pr_nput);
1414 pool_totals.pt_nput += pp->pr_nput;
1415 if (wide) {
1416 PRWORD(ovflw, " %*" PRIu64, 7, 1, pp->pr_nout);
1417 pool_totals.pt_nout += pp->pr_nout;
1418 }
1419 if (wide) {
1420 PRWORD(ovflw, " %*" PRIu64, 6, 1, pp->pr_nitems);
1421 pool_totals.pt_nitems += pp->pr_nitems;
1422 }
1423 PRWORD(ovflw, " %*" PRIu64, wide ? 7 : 6, 1, pp->pr_npagealloc);
1424 pool_totals.pt_npagealloc += pp->pr_npagealloc;
1425 PRWORD(ovflw, " %*" PRIu64, wide ? 7 : 6, 1, pp->pr_npagefree);
1426 pool_totals.pt_npagefree += pp->pr_npagefree;
1427 PRWORD(ovflw, " %*" PRIu64, 6, 1, pp->pr_npages);
1428 pool_totals.pt_npages += pp->pr_npages;
1429 if (wide)
1430 PRWORD(ovflw, " %*" PRIu64, 7, 1, pp->pr_pagesize);
1431 PRWORD(ovflw, " %*" PRIu64, 6, 1, pp->pr_hiwat);
1432 PRWORD(ovflw, " %*" PRIu64, 6, 1, pp->pr_minpages);
1433 PRWORD(ovflw, " %*s", 6, 1, maxp);
1434 PRWORD(ovflw, " %*" PRIu64, 5, 1, pp->pr_nidle);
1435 if (wide)
1436 PRWORD(ovflw, " 0x%0*" PRIx64, 4, 1,
1437 pp->pr_flags);
1438
1439 this_inuse = pp->pr_nout * pp->pr_size;
1440 this_total = pp->pr_npages * pp->pr_pagesize;
1441 if (pp->pr_flags & PR_RECURSIVE) {
1442 /*
1443 * Don't count in-use memory, since it's part
1444 * of another pool and will be accounted for
1445 * there.
1446 */
1447 total += (this_total - this_inuse);
1448 } else {
1449 inuse += this_inuse;
1450 total += this_total;
1451 }
1452 if (wide) {
1453 if (this_total == 0)
1454 (void)printf(" ---");
1455 else
1456 (void)printf(" %5.1f%%",
1457 (100.0 * this_inuse) / this_total);
1458 }
1459 (void)printf("\n");
1460 }
1461 if (wide) {
1462 snprintf(in_use, sizeof in_use, "%7"PRId64, pool_totals.pt_nout);
1463 snprintf(avail, sizeof avail, "%6"PRId64, pool_totals.pt_nitems);
1464 } else {
1465 in_use[0] = '\0';
1466 avail[0] = '\0';
1467 }
1468 (void)printf(
1469 "%-*s%*s%*"PRId64"%5"PRId64"%*"PRId64"%s%s%*"PRId64"%*"PRId64"%6"PRId64"\n",
1470 wide ? 16 : 11, "Totals",
1471 wide ? 6 : 5, "",
1472 wide ? 12 : 9, pool_totals.pt_nget,
1473 pool_totals.pt_nfail,
1474 wide ? 12 : 9, pool_totals.pt_nput,
1475 in_use,
1476 avail,
1477 wide ? 7 : 6, pool_totals.pt_npagealloc,
1478 wide ? 7 : 6, pool_totals.pt_npagefree,
1479 pool_totals.pt_npages);
1480
1481 inuse /= KILO;
1482 total /= KILO;
1483 (void)printf(
1484 "\nIn use %" PRIu64 "K, "
1485 "total allocated %" PRIu64 "K; utilization %.1f%%\n",
1486 inuse, total, (100.0 * inuse) / total);
1487
1488 free(data);
1489 }
1490
1491 void
1492 dopool(int verbose, int wide)
1493 {
1494 int first, ovflw;
1495 void *addr;
1496 long total, inuse, this_total, this_inuse;
1497 struct {
1498 uint64_t pt_nget;
1499 uint64_t pt_nfail;
1500 uint64_t pt_nput;
1501 uint64_t pt_nout;
1502 uint64_t pt_nitems;
1503 uint64_t pt_npagealloc;
1504 uint64_t pt_npagefree;
1505 uint64_t pt_npages;
1506 } pool_totals;
1507 char in_use[8];
1508 char avail[8];
1509 TAILQ_HEAD(,pool) pool_head;
1510 struct pool pool, *pp = &pool;
1511 struct pool_allocator pa;
1512 char name[32], maxp[32];
1513
1514 if (memf == NULL)
1515 return dopool_sysctl(verbose, wide);
1516
1517 memset(&pool_totals, 0, sizeof pool_totals);
1518 kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
1519 addr = TAILQ_FIRST(&pool_head);
1520
1521 total = inuse = 0;
1522
1523 for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
1524 deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
1525 deref_kptr(pp->pr_alloc, &pa, sizeof(pa),
1526 "pool allocator trashed");
1527 deref_kptr(pp->pr_wchan, name, sizeof(name),
1528 "pool wait channel trashed");
1529 name[sizeof(name)-1] = '\0';
1530
1531 if (first) {
1532 (void)printf("Memory resource pool statistics\n");
1533 (void)printf(
1534 "%-*s%*s%*s%5s%*s%s%s%*s%*s%6s%s%6s%6s%6s%5s%s%s\n",
1535 wide ? 16 : 11, "Name",
1536 wide ? 6 : 5, "Size",
1537 wide ? 12 : 9, "Requests",
1538 "Fail",
1539 wide ? 12 : 9, "Releases",
1540 wide ? " InUse" : "",
1541 wide ? " Avail" : "",
1542 wide ? 7 : 6, "Pgreq",
1543 wide ? 7 : 6, "Pgrel",
1544 "Npage",
1545 wide ? " PageSz" : "",
1546 "Hiwat",
1547 "Minpg",
1548 "Maxpg",
1549 "Idle",
1550 wide ? " Flags" : "",
1551 wide ? " Util" : "");
1552 first = 0;
1553 }
1554 if (pp->pr_nget == 0 && !verbose)
1555 continue;
1556 if (pp->pr_maxpages == UINT_MAX)
1557 (void)snprintf(maxp, sizeof(maxp), "inf");
1558 else
1559 (void)snprintf(maxp, sizeof(maxp), "%u",
1560 pp->pr_maxpages);
1561 ovflw = 0;
1562 PRWORD(ovflw, "%-*s", wide ? 16 : 11, 0, name);
1563 PRWORD(ovflw, " %*u", wide ? 6 : 5, 1, pp->pr_size);
1564 PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nget);
1565 pool_totals.pt_nget += pp->pr_nget;
1566 PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nfail);
1567 pool_totals.pt_nfail += pp->pr_nfail;
1568 PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nput);
1569 pool_totals.pt_nput += pp->pr_nput;
1570 if (wide) {
1571 PRWORD(ovflw, " %*u", 7, 1, pp->pr_nout);
1572 pool_totals.pt_nout += pp->pr_nout;
1573 }
1574 if (wide) {
1575 PRWORD(ovflw, " %*u", 6, 1, pp->pr_nitems);
1576 pool_totals.pt_nitems += pp->pr_nitems;
1577 }
1578 PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagealloc);
1579 pool_totals.pt_npagealloc += pp->pr_npagealloc;
1580 PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagefree);
1581 pool_totals.pt_npagefree += pp->pr_npagefree;
1582 PRWORD(ovflw, " %*u", 6, 1, pp->pr_npages);
1583 pool_totals.pt_npages += pp->pr_npages;
1584 if (wide)
1585 PRWORD(ovflw, " %*u", 7, 1, pa.pa_pagesz);
1586 PRWORD(ovflw, " %*u", 6, 1, pp->pr_hiwat);
1587 PRWORD(ovflw, " %*u", 6, 1, pp->pr_minpages);
1588 PRWORD(ovflw, " %*s", 6, 1, maxp);
1589 PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nidle);
1590 if (wide)
1591 PRWORD(ovflw, " 0x%0*x", 4, 1,
1592 pp->pr_flags | pp->pr_roflags);
1593
1594 this_inuse = pp->pr_nout * pp->pr_size;
1595 this_total = pp->pr_npages * pa.pa_pagesz;
1596 if (pp->pr_roflags & PR_RECURSIVE) {
1597 /*
1598 * Don't count in-use memory, since it's part
1599 * of another pool and will be accounted for
1600 * there.
1601 */
1602 total += (this_total - this_inuse);
1603 } else {
1604 inuse += this_inuse;
1605 total += this_total;
1606 }
1607 if (wide) {
1608 if (this_total == 0)
1609 (void)printf(" ---");
1610 else
1611 (void)printf(" %5.1f%%",
1612 (100.0 * this_inuse) / this_total);
1613 }
1614 (void)printf("\n");
1615 }
1616 if (wide) {
1617 snprintf(in_use, sizeof in_use, "%7"PRId64, pool_totals.pt_nout);
1618 snprintf(avail, sizeof avail, "%6"PRId64, pool_totals.pt_nitems);
1619 } else {
1620 in_use[0] = '\0';
1621 avail[0] = '\0';
1622 }
1623 (void)printf(
1624 "%-*s%*s%*"PRId64"%5"PRId64"%*"PRId64"%s%s%*"PRId64"%*"PRId64"%6"PRId64"\n",
1625 wide ? 16 : 11, "Totals",
1626 wide ? 6 : 5, "",
1627 wide ? 12 : 9, pool_totals.pt_nget,
1628 pool_totals.pt_nfail,
1629 wide ? 12 : 9, pool_totals.pt_nput,
1630 in_use,
1631 avail,
1632 wide ? 7 : 6, pool_totals.pt_npagealloc,
1633 wide ? 7 : 6, pool_totals.pt_npagefree,
1634 pool_totals.pt_npages);
1635
1636 inuse /= KILO;
1637 total /= KILO;
1638 (void)printf(
1639 "\nIn use %ldK, total allocated %ldK; utilization %.1f%%\n",
1640 inuse, total, (100.0 * inuse) / total);
1641 }
1642
1643 static void
1644 dopoolcache_sysctl(int verbose)
1645 {
1646 struct pool_sysctl *data, *pp;
1647 size_t i, len;
1648 bool first = true;
1649 int ovflw;
1650 uint64_t tot;
1651 double p;
1652
1653 data = asysctlbyname("kern.pool", &len);
1654 if (data == NULL)
1655 err(1, "failed to reead kern.pool");
1656 len /= sizeof(*data);
1657
1658 for (i = 0; i < len; ++i) {
1659 pp = &data[i];
1660 if (pp->pr_cache_meta_size == 0)
1661 continue;
1662
1663 if (pp->pr_cache_nmiss_global == 0 && !verbose)
1664 continue;
1665
1666 if (first) {
1667 (void)printf("Pool cache statistics.\n");
1668 (void)printf("%-*s%*s%*s%*s%*s%*s%*s%*s%*s%*s\n",
1669 12, "Name",
1670 6, "Spin",
1671 6, "GrpSz",
1672 5, "Full",
1673 5, "Emty",
1674 10, "PoolLayer",
1675 11, "CacheLayer",
1676 6, "Hit%",
1677 12, "CpuLayer",
1678 6, "Hit%"
1679 );
1680 first = false;
1681 }
1682
1683 ovflw = 0;
1684 PRWORD(ovflw, "%-*s", MIN((int)sizeof(pp->pr_wchan), 13), 1,
1685 pp->pr_wchan);
1686 PRWORD(ovflw, " %*" PRIu64, 6, 1, pp->pr_cache_ncontended);
1687 PRWORD(ovflw, " %*" PRIu64, 6, 1, pp->pr_cache_meta_size);
1688 PRWORD(ovflw, " %*" PRIu64, 5, 1, pp->pr_cache_nfull);
1689 PRWORD(ovflw, " %*" PRIu64, 5, 1, pp->pr_cache_nempty);
1690 PRWORD(ovflw, " %*" PRIu64, 10, 1, pp->pr_cache_nmiss_global);
1691
1692 tot = pp->pr_cache_nhit_global + pp->pr_cache_nmiss_global;
1693 p = pp->pr_cache_nhit_global * 100.0 / tot;
1694 PRWORD(ovflw, " %*" PRIu64, 11, 1, tot);
1695 PRWORD(ovflw, " %*.1f", 6, 1, p);
1696
1697 tot = pp->pr_cache_nhit_pcpu + pp->pr_cache_nmiss_pcpu;
1698 p = pp->pr_cache_nhit_pcpu * 100.0 / tot;
1699 PRWORD(ovflw, " %*" PRIu64, 12, 1, tot);
1700 PRWORD(ovflw, " %*.1f", 6, 1, p);
1701 printf("\n");
1702 }
1703 }
1704
1705 void
1706 dopoolcache(int verbose)
1707 {
1708 struct pool_cache pool_cache, *pc = &pool_cache;
1709 pool_cache_cpu_t cache_cpu, *cc = &cache_cpu;
1710 TAILQ_HEAD(,pool) pool_head;
1711 struct pool pool, *pp = &pool;
1712 char name[32];
1713 uint64_t cpuhit, cpumiss, tot;
1714 void *addr;
1715 int first, ovflw;
1716 size_t i;
1717 double p;
1718
1719 if (memf == NULL)
1720 return dopoolcache_sysctl(verbose);
1721
1722 kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
1723 addr = TAILQ_FIRST(&pool_head);
1724
1725 for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
1726 deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
1727 if (pp->pr_cache == NULL)
1728 continue;
1729 deref_kptr(pp->pr_wchan, name, sizeof(name),
1730 "pool wait channel trashed");
1731 deref_kptr(pp->pr_cache, pc, sizeof(*pc), "pool cache trashed");
1732 if (pc->pc_misses == 0 && !verbose)
1733 continue;
1734 name[sizeof(name)-1] = '\0';
1735
1736 cpuhit = 0;
1737 cpumiss = 0;
1738 for (i = 0; i < __arraycount(pc->pc_cpus); i++) {
1739 if ((addr = pc->pc_cpus[i]) == NULL)
1740 continue;
1741 deref_kptr(addr, cc, sizeof(*cc),
1742 "pool cache cpu trashed");
1743 cpuhit += cc->cc_hits;
1744 cpumiss += cc->cc_misses;
1745 }
1746
1747 if (first) {
1748 (void)printf("Pool cache statistics.\n");
1749 (void)printf("%-*s%*s%*s%*s%*s%*s%*s%*s%*s%*s\n",
1750 12, "Name",
1751 6, "Spin",
1752 6, "GrpSz",
1753 5, "Full",
1754 5, "Emty",
1755 10, "PoolLayer",
1756 11, "CacheLayer",
1757 6, "Hit%",
1758 12, "CpuLayer",
1759 6, "Hit%"
1760 );
1761 first = 0;
1762 }
1763
1764 ovflw = 0;
1765 PRWORD(ovflw, "%-*s", 13, 1, name);
1766 PRWORD(ovflw, " %*llu", 6, 1, (long long)pc->pc_contended);
1767 PRWORD(ovflw, " %*u", 6, 1, pc->pc_pcgsize);
1768 PRWORD(ovflw, " %*u", 5, 1, pc->pc_nfull);
1769 PRWORD(ovflw, " %*u", 5, 1, pc->pc_nempty);
1770 PRWORD(ovflw, " %*llu", 10, 1, (long long)pc->pc_misses);
1771
1772 tot = pc->pc_hits + pc->pc_misses;
1773 p = pc->pc_hits * 100.0 / (tot);
1774 PRWORD(ovflw, " %*llu", 11, 1, (long long)tot);
1775 PRWORD(ovflw, " %*.1f", 6, 1, p);
1776
1777 tot = cpuhit + cpumiss;
1778 p = cpuhit * 100.0 / (tot);
1779 PRWORD(ovflw, " %*llu", 12, 1, (long long)tot);
1780 PRWORD(ovflw, " %*.1f", 6, 1, p);
1781 printf("\n");
1782 }
1783 }
1784
1785 enum hashtype { /* from <sys/systm.h> */
1786 HASH_LIST,
1787 HASH_TAILQ
1788 };
1789
1790 struct uidinfo { /* XXX: no kernel header file */
1791 LIST_ENTRY(uidinfo) ui_hash;
1792 uid_t ui_uid;
1793 long ui_proccnt;
1794 };
1795
1796 struct kernel_hash {
1797 const char * description; /* description */
1798 int hashsize; /* nlist index for hash size */
1799 int hashtbl; /* nlist index for hash table */
1800 enum hashtype type; /* type of hash table */
1801 size_t offset; /* offset of {LIST,TAILQ}_NEXT */
1802 } khashes[] =
1803 {
1804 {
1805 "buffer hash",
1806 X_BUFHASH, X_BUFHASHTBL,
1807 HASH_LIST, offsetof(struct buf, b_hash)
1808 }, {
1809 "ipv4 address -> interface hash",
1810 X_IFADDRHASH, X_IFADDRHASHTBL,
1811 HASH_LIST, offsetof(struct in_ifaddr, ia_hash),
1812 }, {
1813 "name cache hash",
1814 X_NCHASH, X_NCHASHTBL,
1815 HASH_LIST, offsetof(struct namecache, nc_hash),
1816 }, {
1817 "name cache directory hash",
1818 X_NCVHASH, X_NCVHASHTBL,
1819 HASH_LIST, offsetof(struct namecache, nc_vhash),
1820 }, {
1821 "user info (uid -> used processes) hash",
1822 X_UIHASH, X_UIHASHTBL,
1823 HASH_LIST, offsetof(struct uidinfo, ui_hash),
1824 }, {
1825 NULL, -1, -1, 0, 0,
1826 }
1827 };
1828
1829 void
1830 dohashstat(int verbose, int todo, const char *hashname)
1831 {
1832 LIST_HEAD(, generic) *hashtbl_list;
1833 TAILQ_HEAD(, generic) *hashtbl_tailq;
1834 struct kernel_hash *curhash;
1835 void *hashaddr, *hashbuf, *nhashbuf, *nextaddr;
1836 size_t elemsize, hashbufsize, thissize;
1837 u_long hashsize, i;
1838 int used, items, chain, maxchain;
1839
1840 hashbuf = NULL;
1841 hashbufsize = 0;
1842
1843 if (todo & HASHLIST) {
1844 (void)printf("Supported hashes:\n");
1845 for (curhash = khashes; curhash->description; curhash++) {
1846 if (hashnl[curhash->hashsize].n_value == 0 ||
1847 hashnl[curhash->hashtbl].n_value == 0)
1848 continue;
1849 (void)printf("\t%-16s%s\n",
1850 hashnl[curhash->hashsize].n_name + 1,
1851 curhash->description);
1852 }
1853 return;
1854 }
1855
1856 if (hashname != NULL) {
1857 for (curhash = khashes; curhash->description; curhash++) {
1858 if (strcmp(hashnl[curhash->hashsize].n_name + 1,
1859 hashname) == 0 &&
1860 hashnl[curhash->hashsize].n_value != 0 &&
1861 hashnl[curhash->hashtbl].n_value != 0)
1862 break;
1863 }
1864 if (curhash->description == NULL) {
1865 warnx("%s: no such hash", hashname);
1866 return;
1867 }
1868 }
1869
1870 (void)printf(
1871 "%-16s %8s %8s %8s %8s %8s %8s\n"
1872 "%-16s %8s %8s %8s %8s %8s %8s\n",
1873 "", "total", "used", "util", "num", "average", "maximum",
1874 "hash table", "buckets", "buckets", "%", "items", "chain",
1875 "chain");
1876
1877 for (curhash = khashes; curhash->description; curhash++) {
1878 if (hashnl[curhash->hashsize].n_value == 0 ||
1879 hashnl[curhash->hashtbl].n_value == 0)
1880 continue;
1881 if (hashname != NULL &&
1882 strcmp(hashnl[curhash->hashsize].n_name + 1, hashname))
1883 continue;
1884 elemsize = curhash->type == HASH_LIST ?
1885 sizeof(*hashtbl_list) : sizeof(*hashtbl_tailq);
1886 deref_kptr((void *)hashnl[curhash->hashsize].n_value,
1887 &hashsize, sizeof(hashsize),
1888 hashnl[curhash->hashsize].n_name);
1889 hashsize++;
1890 deref_kptr((void *)hashnl[curhash->hashtbl].n_value,
1891 &hashaddr, sizeof(hashaddr),
1892 hashnl[curhash->hashtbl].n_name);
1893 if (verbose)
1894 (void)printf(
1895 "%s %lu, %s %p, offset %ld, elemsize %llu\n",
1896 hashnl[curhash->hashsize].n_name + 1, hashsize,
1897 hashnl[curhash->hashtbl].n_name + 1, hashaddr,
1898 (long)curhash->offset,
1899 (unsigned long long)elemsize);
1900 thissize = hashsize * elemsize;
1901 if (hashbuf == NULL || thissize > hashbufsize) {
1902 if ((nhashbuf = realloc(hashbuf, thissize)) == NULL)
1903 errx(1, "malloc hashbuf %llu",
1904 (unsigned long long)hashbufsize);
1905 hashbuf = nhashbuf;
1906 hashbufsize = thissize;
1907 }
1908 deref_kptr(hashaddr, hashbuf, thissize,
1909 hashnl[curhash->hashtbl].n_name);
1910 used = 0;
1911 items = maxchain = 0;
1912 if (curhash->type == HASH_LIST) {
1913 hashtbl_list = hashbuf;
1914 hashtbl_tailq = NULL;
1915 } else {
1916 hashtbl_list = NULL;
1917 hashtbl_tailq = hashbuf;
1918 }
1919 for (i = 0; i < hashsize; i++) {
1920 if (curhash->type == HASH_LIST)
1921 nextaddr = LIST_FIRST(&hashtbl_list[i]);
1922 else
1923 nextaddr = TAILQ_FIRST(&hashtbl_tailq[i]);
1924 if (nextaddr == NULL)
1925 continue;
1926 if (verbose)
1927 (void)printf("%5lu: %p\n", i, nextaddr);
1928 used++;
1929 chain = 0;
1930 do {
1931 chain++;
1932 deref_kptr((char *)nextaddr + curhash->offset,
1933 &nextaddr, sizeof(void *),
1934 "hash chain corrupted");
1935 if (verbose > 1)
1936 (void)printf("got nextaddr as %p\n",
1937 nextaddr);
1938 } while (nextaddr != NULL);
1939 items += chain;
1940 if (verbose && chain > 1)
1941 (void)printf("\tchain = %d\n", chain);
1942 if (chain > maxchain)
1943 maxchain = chain;
1944 }
1945 (void)printf("%-16s %8ld %8d %8.2f %8d %8.2f %8d\n",
1946 hashnl[curhash->hashsize].n_name + 1,
1947 hashsize, used, used * 100.0 / hashsize,
1948 items, used ? (double)items / used : 0.0, maxchain);
1949 }
1950 }
1951
1952 /*
1953 * kreadc like kread but returns 1 if sucessful, 0 otherwise
1954 */
1955 int
1956 kreadc(struct nlist *nl, int nlx, void *addr, size_t size)
1957 {
1958 const char *sym;
1959
1960 sym = nl[nlx].n_name;
1961 if (*sym == '_')
1962 ++sym;
1963 if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
1964 return 0;
1965 deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
1966 return 1;
1967 }
1968
1969 /*
1970 * kread reads something from the kernel, given its nlist index in namelist[].
1971 */
1972 void
1973 kread(struct nlist *nl, int nlx, void *addr, size_t size)
1974 {
1975 const char *sym;
1976
1977 sym = nl[nlx].n_name;
1978 if (*sym == '_')
1979 ++sym;
1980 if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
1981 errx(1, "symbol %s not defined", sym);
1982 deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
1983 }
1984
1985 /*
1986 * Dereference the kernel pointer `kptr' and fill in the local copy
1987 * pointed to by `ptr'. The storage space must be pre-allocated,
1988 * and the size of the copy passed in `len'.
1989 */
1990 void
1991 deref_kptr(const void *kptr, void *ptr, size_t len, const char *msg)
1992 {
1993
1994 if (*msg == '_')
1995 msg++;
1996 if ((size_t)kvm_read(kd, (u_long)kptr, (char *)ptr, len) != len)
1997 errx(1, "kptr %lx: %s: %s", (u_long)kptr, msg, kvm_geterr(kd));
1998 }
1999
2000 /*
2001 * Traverse the kernel history buffers, performing the requested action.
2002 *
2003 * Note, we assume that if we're not listing, we're dumping.
2004 */
2005 void
2006 hist_traverse(int todo, const char *histname)
2007 {
2008 struct kern_history_head histhead;
2009 struct kern_history hist, *histkva;
2010 char *name = NULL;
2011 size_t namelen = 0;
2012
2013 if (histnl[0].n_value == 0) {
2014 warnx("kernel history is not compiled into the kernel.");
2015 return;
2016 }
2017
2018 deref_kptr((void *)histnl[X_KERN_HISTORIES].n_value, &histhead,
2019 sizeof(histhead), histnl[X_KERN_HISTORIES].n_name);
2020
2021 if (histhead.lh_first == NULL) {
2022 warnx("No active kernel history logs.");
2023 return;
2024 }
2025
2026 if (todo & HISTLIST)
2027 (void)printf("Active kernel histories:");
2028
2029 for (histkva = LIST_FIRST(&histhead); histkva != NULL;
2030 histkva = LIST_NEXT(&hist, list)) {
2031 deref_kptr(histkva, &hist, sizeof(hist), "histkva");
2032 if (name == NULL || hist.namelen > namelen) {
2033 if (name != NULL)
2034 free(name);
2035 namelen = hist.namelen;
2036 if ((name = malloc(namelen + 1)) == NULL)
2037 err(1, "malloc history name");
2038 }
2039
2040 deref_kptr(hist.name, name, namelen, "history name");
2041 name[namelen] = '\0';
2042 if (todo & HISTLIST)
2043 (void)printf(" %s", name);
2044 else {
2045 /*
2046 * If we're dumping all histories, do it, else
2047 * check to see if this is the one we want.
2048 */
2049 if (histname == NULL || strcmp(histname, name) == 0) {
2050 if (histname == NULL)
2051 (void)printf(
2052 "\nkernel history `%s':\n", name);
2053 hist_dodump(&hist);
2054 }
2055 }
2056 }
2057
2058 if (todo & HISTLIST)
2059 (void)putchar('\n');
2060
2061 if (name != NULL)
2062 free(name);
2063 }
2064
2065 /*
2066 * Actually dump the history buffer at the specified KVA.
2067 */
2068 void
2069 hist_dodump(struct kern_history *histp)
2070 {
2071 struct kern_history_ent *histents, *e;
2072 struct timeval tv;
2073 size_t histsize;
2074 char *fmt = NULL, *fn = NULL;
2075 size_t fmtlen = 0, fnlen = 0;
2076 unsigned i;
2077
2078 histsize = sizeof(struct kern_history_ent) * histp->n;
2079
2080 if ((histents = malloc(histsize)) == NULL)
2081 err(1, "malloc history entries");
2082
2083 (void)memset(histents, 0, histsize);
2084
2085 (void)printf("%"PRIu32" entries, next is %"PRIu32"\n",
2086 histp->n, histp->f);
2087
2088 deref_kptr(histp->e, histents, histsize, "history entries");
2089 i = histp->f;
2090 do {
2091 e = &histents[i];
2092 if (e->fmt != NULL) {
2093 if (fmt == NULL || e->fmtlen > fmtlen) {
2094 if (fmt != NULL)
2095 free(fmt);
2096 fmtlen = e->fmtlen;
2097 if ((fmt = malloc(fmtlen + 1)) == NULL)
2098 err(1, "malloc printf format");
2099 }
2100 if (fn == NULL || e->fnlen > fnlen) {
2101 if (fn != NULL)
2102 free(fn);
2103 fnlen = e->fnlen;
2104 if ((fn = malloc(fnlen + 1)) == NULL)
2105 err(1, "malloc function name");
2106 }
2107
2108 deref_kptr(e->fmt, fmt, fmtlen, "printf format");
2109 fmt[fmtlen] = '\0';
2110
2111 deref_kptr(e->fn, fn, fnlen, "function name");
2112 fn[fnlen] = '\0';
2113
2114 bintime2timeval(&e->bt, &tv);
2115 (void)printf("%06ld.%06ld ", (long int)tv.tv_sec,
2116 (long int)tv.tv_usec);
2117 (void)printf("%s#%ld@%d: ", fn, e->call, e->cpunum);
2118 (void)printf(fmt, e->v[0], e->v[1], e->v[2], e->v[3]);
2119 (void)putchar('\n');
2120 }
2121 i = (i + 1) % histp->n;
2122 } while (i != histp->f);
2123
2124 free(histents);
2125 if (fmt != NULL)
2126 free(fmt);
2127 if (fn != NULL)
2128 free(fn);
2129 }
2130
2131 void
2132 hist_traverse_sysctl(int todo, const char *histname)
2133 {
2134 int error;
2135 int mib[4];
2136 unsigned int i;
2137 size_t len, miblen;
2138 struct sysctlnode query, histnode[32];
2139
2140 /* retrieve names of available histories */
2141 miblen = __arraycount(mib);
2142 error = sysctlnametomib("kern.hist", mib, &miblen);
2143 if (error != 0) {
2144 if (errno == ENOENT) {
2145 warnx("kernel history is not compiled into the kernel.");
2146 return;
2147 } else
2148 err(EXIT_FAILURE, "nametomib failed");
2149 }
2150
2151 /* get the list of nodenames below kern.hist */
2152 mib[2] = CTL_QUERY;
2153 memset(&query, 0, sizeof(query));
2154 query.sysctl_flags = SYSCTL_VERSION;
2155 len = sizeof(histnode);
2156 error = sysctl(mib, 3, &histnode[0], &len, &query, sizeof(query));
2157 if (error != 0) {
2158 err(1, "query failed");
2159 return;
2160 }
2161 if (len == 0) {
2162 warnx("No active kernel history logs.");
2163 return;
2164 }
2165
2166 len = len / sizeof(histnode[0]); /* get # of entries returned */
2167
2168 if (todo & HISTLIST)
2169 (void)printf("Active kernel histories:");
2170
2171 for (i = 0; i < len; i++) {
2172 if (todo & HISTLIST)
2173 (void)printf(" %s", histnode[i].sysctl_name);
2174 else {
2175 /*
2176 * If we're dumping all histories, do it, else
2177 * check to see if this is the one we want.
2178 */
2179 if (histname == NULL ||
2180 strcmp(histname, histnode[i].sysctl_name) == 0) {
2181 if (histname == NULL)
2182 (void)printf(
2183 "\nkernel history `%s':\n",
2184 histnode[i].sysctl_name);
2185 mib[2] = histnode[i].sysctl_num;
2186 mib[3] = CTL_EOL;
2187 hist_dodump_sysctl(mib, 4);
2188 }
2189 }
2190 }
2191
2192 if (todo & HISTLIST)
2193 (void)putchar('\n');
2194 }
2195
2196 /*
2197 * Actually dump the history buffer at the specified KVA.
2198 */
2199 void
2200 hist_dodump_sysctl(int mib[], unsigned int miblen)
2201 {
2202 struct sysctl_history *hist;
2203 struct timeval tv;
2204 struct sysctl_history_event *e;
2205 size_t histsize;
2206 char *strp;
2207 unsigned i;
2208 char *fmt = NULL, *fn = NULL;
2209
2210 hist = NULL;
2211 histsize = 0;
2212 do {
2213 errno = 0;
2214 if (sysctl(mib, miblen, hist, &histsize, NULL, 0) == 0)
2215 break;
2216 if (errno != ENOMEM)
2217 break;
2218 if ((hist = realloc(hist, histsize)) == NULL)
2219 errx(1, "realloc history buffer");
2220 } while (errno == ENOMEM);
2221 if (errno != 0)
2222 err(1, "sysctl failed");
2223
2224 strp = (char *)(&hist->sh_events[hist->sh_listentry.shle_numentries]);
2225
2226 (void)printf("%"PRIu32" entries, next is %"PRIu32"\n",
2227 hist->sh_listentry.shle_numentries,
2228 hist->sh_listentry.shle_nextfree);
2229
2230 i = hist->sh_listentry.shle_nextfree;
2231
2232 do {
2233 e = &hist->sh_events[i];
2234 if (e->she_fmtoffset != 0) {
2235 fmt = &strp[e->she_fmtoffset];
2236 fn = &strp[e->she_funcoffset];
2237 bintime2timeval(&e->she_bintime, &tv);
2238 (void)printf("%06ld.%06ld %s#%"PRIu64"@%"PRIu32": ",
2239 (long int)tv.tv_sec, (long int)tv.tv_usec,
2240 fn, e->she_callnumber, e->she_cpunum);
2241 (void)printf(fmt, e->she_values[0], e->she_values[1],
2242 e->she_values[2], e->she_values[3]);
2243 (void)putchar('\n');
2244 }
2245 i = (i + 1) % hist->sh_listentry.shle_numentries;
2246 } while (i != hist->sh_listentry.shle_nextfree);
2247
2248 free(hist);
2249 }
2250
2251 static void
2252 usage(void)
2253 {
2254
2255 (void)fprintf(stderr,
2256 "usage: %s [-CefHiLlmstUvW] [-c count] [-h hashname] [-M core] [-N system]\n"
2257 "\t\t[-u histname] [-w wait] [disks]\n", getprogname());
2258 exit(1);
2259 }
2260