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