vmstat.c revision 1.197 1 /* $NetBSD: vmstat.c,v 1.197 2014/06/03 21:45:41 joerg 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.197 2014/06/03 21:45:41 joerg 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 struct cpu_info **cpu_infos;
146
147 /*
148 * General namelist
149 */
150 struct nlist namelist[] =
151 {
152 #define X_BOOTTIME 0
153 { .n_name = "_boottime" },
154 #define X_HZ 1
155 { .n_name = "_hz" },
156 #define X_STATHZ 2
157 { .n_name = "_stathz" },
158 #define X_NCHSTATS 3
159 { .n_name = "_nchstats" },
160 #define X_ALLEVENTS 4
161 { .n_name = "_allevents" },
162 #define X_POOLHEAD 5
163 { .n_name = "_pool_head" },
164 #define X_UVMEXP 6
165 { .n_name = "_uvmexp" },
166 #define X_TIME_SECOND 7
167 { .n_name = "_time_second" },
168 #define X_TIME 8
169 { .n_name = "_time" },
170 #define X_CPU_INFOS 9
171 { .n_name = "_cpu_infos" },
172 #define X_NL_SIZE 10
173 { .n_name = NULL },
174 };
175
176 /*
177 * Namelist for pre-evcnt interrupt counters.
178 */
179 struct nlist intrnl[] =
180 {
181 #define X_INTRNAMES 0
182 { .n_name = "_intrnames" },
183 #define X_EINTRNAMES 1
184 { .n_name = "_eintrnames" },
185 #define X_INTRCNT 2
186 { .n_name = "_intrcnt" },
187 #define X_EINTRCNT 3
188 { .n_name = "_eintrcnt" },
189 #define X_INTRNL_SIZE 4
190 { .n_name = NULL },
191 };
192
193
194 /*
195 * Namelist for hash statistics
196 */
197 struct nlist hashnl[] =
198 {
199 #define X_NFSNODE 0
200 { .n_name = "_nfsnodehash" },
201 #define X_NFSNODETBL 1
202 { .n_name = "_nfsnodehashtbl" },
203 #define X_IHASH 2
204 { .n_name = "_ihash" },
205 #define X_IHASHTBL 3
206 { .n_name = "_ihashtbl" },
207 #define X_BUFHASH 4
208 { .n_name = "_bufhash" },
209 #define X_BUFHASHTBL 5
210 { .n_name = "_bufhashtbl" },
211 #define X_UIHASH 6
212 { .n_name = "_uihash" },
213 #define X_UIHASHTBL 7
214 { .n_name = "_uihashtbl" },
215 #define X_IFADDRHASH 8
216 { .n_name = "_in_ifaddrhash" },
217 #define X_IFADDRHASHTBL 9
218 { .n_name = "_in_ifaddrhashtbl" },
219 #define X_NCHASH 10
220 { .n_name = "_nchash" },
221 #define X_NCHASHTBL 11
222 { .n_name = "_nchashtbl" },
223 #define X_NCVHASH 12
224 { .n_name = "_ncvhash" },
225 #define X_NCVHASHTBL 13
226 { .n_name = "_ncvhashtbl" },
227 #define X_HASHNL_SIZE 14 /* must be last */
228 { .n_name = NULL },
229 };
230
231 /*
232 * Namelist for kernel histories
233 */
234 struct nlist histnl[] =
235 {
236 { .n_name = "_kern_histories" },
237 #define X_KERN_HISTORIES 0
238 { .n_name = NULL },
239 };
240
241
242 #define KILO 1024
243
244 struct cpu_counter {
245 uint64_t nintr;
246 uint64_t nsyscall;
247 uint64_t nswtch;
248 uint64_t nfault;
249 uint64_t ntrap;
250 uint64_t nsoft;
251 } cpucounter, ocpucounter;
252
253 struct uvmexp_sysctl uvmexp, ouvmexp;
254 int ndrives;
255
256 int winlines = 20;
257
258 kvm_t *kd;
259
260
261 #define FORKSTAT 0x001
262 #define INTRSTAT 0x002
263 #define MEMSTAT 0x004
264 #define SUMSTAT 0x008
265 #define EVCNTSTAT 0x010
266 #define VMSTAT 0x020
267 #define HISTLIST 0x040
268 #define HISTDUMP 0x080
269 #define HASHSTAT 0x100
270 #define HASHLIST 0x200
271 #define VMTOTAL 0x400
272 #define POOLCACHESTAT 0x800
273
274 /*
275 * Print single word. `ovflow' is number of characters didn't fit
276 * on the last word. `fmt' is a format string to print this word.
277 * It must contain asterisk for field width. `width' is a width
278 * occupied by this word. `fixed' is a number of constant chars in
279 * `fmt'. `val' is a value to be printed using format string `fmt'.
280 */
281 #define PRWORD(ovflw, fmt, width, fixed, val) do { \
282 (ovflw) += printf((fmt), \
283 (width) - (fixed) - (ovflw) > 0 ? \
284 (width) - (fixed) - (ovflw) : 0, \
285 (val)) - (width); \
286 if ((ovflw) < 0) \
287 (ovflw) = 0; \
288 } while (/* CONSTCOND */0)
289
290 void cpustats(int *);
291 void cpucounters(struct cpu_counter *);
292 void deref_kptr(const void *, void *, size_t, const char *);
293 void drvstats(int *);
294 void doevcnt(int verbose, int type);
295 void dohashstat(int, int, const char *);
296 void dointr(int verbose);
297 void dopool(int, int);
298 void dopoolcache(int);
299 void dosum(void);
300 void dovmstat(struct timespec *, int);
301 void print_total_hdr(void);
302 void dovmtotal(struct timespec *, int);
303 void kread(struct nlist *, int, void *, size_t);
304 int kreadc(struct nlist *, int, void *, size_t);
305 void needhdr(int);
306 void getnlist(int);
307 long getuptime(void);
308 void printhdr(void);
309 long pct(long, long);
310 __dead static void usage(void);
311 void doforkst(void);
312
313 void hist_traverse(int, const char *);
314 void hist_dodump(struct kern_history *);
315
316 int main(int, char **);
317 char **choosedrives(char **);
318
319 /* Namelist and memory file names. */
320 char *nlistf, *memf;
321
322 /* allow old usage [vmstat 1] */
323 #define BACKWARD_COMPATIBILITY
324
325 static const int clockrate_mib[] = { CTL_KERN, KERN_CLOCKRATE };
326 static const int vmmeter_mib[] = { CTL_VM, VM_METER };
327 static const int uvmexp2_mib[] = { CTL_VM, VM_UVMEXP2 };
328 static const int boottime_mib[] = { CTL_KERN, KERN_BOOTTIME };
329 static char kvm_errbuf[_POSIX2_LINE_MAX];
330
331 int
332 main(int argc, char *argv[])
333 {
334 int c, todo, verbose, wide;
335 struct timespec interval;
336 int reps;
337 gid_t egid = getegid();
338 const char *histname, *hashname;
339
340 histname = hashname = NULL;
341 (void)setegid(getgid());
342 memf = nlistf = NULL;
343 reps = todo = verbose = wide = 0;
344 interval.tv_sec = 0;
345 interval.tv_nsec = 0;
346 while ((c = getopt(argc, argv, "Cc:efh:HilLM:mN:stu:UvWw:")) != -1) {
347 switch (c) {
348 case 'c':
349 reps = atoi(optarg);
350 break;
351 case 'C':
352 todo |= POOLCACHESTAT;
353 break;
354 case 'e':
355 todo |= EVCNTSTAT;
356 break;
357 case 'f':
358 todo |= FORKSTAT;
359 break;
360 case 'h':
361 hashname = optarg;
362 /* FALLTHROUGH */
363 case 'H':
364 todo |= HASHSTAT;
365 break;
366 case 'i':
367 todo |= INTRSTAT;
368 break;
369 case 'l':
370 todo |= HISTLIST;
371 break;
372 case 'L':
373 todo |= HASHLIST;
374 break;
375 case 'M':
376 memf = optarg;
377 break;
378 case 'm':
379 todo |= MEMSTAT;
380 break;
381 case 'N':
382 nlistf = optarg;
383 break;
384 case 's':
385 todo |= SUMSTAT;
386 break;
387 case 't':
388 todo |= VMTOTAL;
389 break;
390 case 'u':
391 histname = optarg;
392 /* FALLTHROUGH */
393 case 'U':
394 todo |= HISTDUMP;
395 break;
396 case 'v':
397 verbose++;
398 break;
399 case 'W':
400 wide++;
401 break;
402 case 'w':
403 interval.tv_sec = atol(optarg);
404 break;
405 case '?':
406 default:
407 usage();
408 }
409 }
410 argc -= optind;
411 argv += optind;
412
413 if (todo == 0)
414 todo = VMSTAT;
415
416 /*
417 * Discard setgid privileges. If not the running kernel, we toss
418 * them away totally so that bad guys can't print interesting stuff
419 * from kernel memory, otherwise switch back to kmem for the
420 * duration of the kvm_openfiles() call.
421 */
422 if (nlistf != NULL || memf != NULL)
423 (void)setgid(getgid());
424 else
425 (void)setegid(egid);
426
427 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, kvm_errbuf);
428 if (kd == NULL) {
429 if (nlistf != NULL || memf != NULL) {
430 errx(1, "kvm_openfiles: %s", kvm_errbuf);
431 }
432 }
433
434 if (nlistf == NULL && memf == NULL)
435 (void)setgid(getgid());
436
437
438 if (todo & VMSTAT) {
439 struct winsize winsize;
440
441 (void)drvinit(0);/* Initialize disk stats, no disks selected. */
442
443 (void)setgid(getgid()); /* don't need privs anymore */
444
445 argv = choosedrives(argv); /* Select disks. */
446 winsize.ws_row = 0;
447 (void)ioctl(STDOUT_FILENO, TIOCGWINSZ, &winsize);
448 if (winsize.ws_row > 0)
449 winlines = winsize.ws_row;
450
451 }
452
453 #ifdef BACKWARD_COMPATIBILITY
454 if (*argv) {
455 interval.tv_sec = atol(*argv);
456 if (*++argv)
457 reps = atoi(*argv);
458 }
459 #endif
460
461 if (interval.tv_sec) {
462 if (!reps)
463 reps = -1;
464 } else if (reps)
465 interval.tv_sec = 1;
466
467
468 getnlist(todo);
469 /*
470 * Statistics dumping is incompatible with the default
471 * VMSTAT/dovmstat() output. So perform the interval/reps handling
472 * for it here.
473 */
474 if ((todo & (VMSTAT|VMTOTAL)) == 0) {
475 for (;;) {
476 if (todo & (HISTLIST|HISTDUMP)) {
477 if ((todo & (HISTLIST|HISTDUMP)) ==
478 (HISTLIST|HISTDUMP))
479 errx(1, "you may list or dump,"
480 " but not both!");
481 hist_traverse(todo, histname);
482 (void)putchar('\n');
483 }
484 if (todo & FORKSTAT) {
485 doforkst();
486 (void)putchar('\n');
487 }
488 if (todo & MEMSTAT) {
489 dopool(verbose, wide);
490 (void)putchar('\n');
491 }
492 if (todo & POOLCACHESTAT) {
493 dopoolcache(verbose);
494 (void)putchar('\n');
495 }
496 if (todo & SUMSTAT) {
497 dosum();
498 (void)putchar('\n');
499 }
500 if (todo & INTRSTAT) {
501 dointr(verbose);
502 (void)putchar('\n');
503 }
504 if (todo & EVCNTSTAT) {
505 doevcnt(verbose, EVCNT_TYPE_ANY);
506 (void)putchar('\n');
507 }
508 if (todo & (HASHLIST|HASHSTAT)) {
509 if ((todo & (HASHLIST|HASHSTAT)) ==
510 (HASHLIST|HASHSTAT))
511 errx(1, "you may list or display,"
512 " but not both!");
513 dohashstat(verbose, todo, hashname);
514 (void)putchar('\n');
515 }
516
517 fflush(stdout);
518 if (reps >= 0 && --reps <=0)
519 break;
520 (void)nanosleep(&interval, NULL);
521 }
522 } else {
523 if ((todo & (VMSTAT|VMTOTAL)) == (VMSTAT|VMTOTAL)) {
524 errx(1, "you may not both do vmstat and vmtotal");
525 }
526 if (todo & VMSTAT)
527 dovmstat(&interval, reps);
528 if (todo & VMTOTAL)
529 dovmtotal(&interval, reps);
530 }
531 return 0;
532 }
533
534 void
535 getnlist(int todo)
536 {
537 static int namelist_done = 0;
538 static int done = 0;
539 int c;
540 size_t i;
541
542 if (kd == NULL)
543 errx(1, "kvm_openfiles: %s", kvm_errbuf);
544
545 if (!namelist_done) {
546 namelist_done = 1;
547 if ((c = kvm_nlist(kd, namelist)) != 0) {
548 int doexit = 0;
549 if (c == -1)
550 errx(1, "kvm_nlist: %s %s",
551 "namelist", kvm_geterr(kd));
552 for (i = 0; i < __arraycount(namelist)-1; i++)
553 if (namelist[i].n_type == 0 &&
554 i != X_TIME_SECOND &&
555 i != X_TIME) {
556 if (doexit++ == 0)
557 (void)fprintf(stderr,
558 "%s: undefined symbols:",
559 getprogname());
560 (void)fprintf(stderr, " %s",
561 namelist[i].n_name);
562 }
563 if (doexit) {
564 (void)fputc('\n', stderr);
565 exit(1);
566 }
567 }
568 }
569 if ((todo & (SUMSTAT|INTRSTAT)) && !(done & (SUMSTAT|INTRSTAT))) {
570 done |= SUMSTAT|INTRSTAT;
571 (void) kvm_nlist(kd, intrnl);
572 }
573 if ((todo & (HASHLIST|HASHSTAT)) && !(done & (HASHLIST|HASHSTAT))) {
574 done |= HASHLIST|HASHSTAT;
575 if ((c = kvm_nlist(kd, hashnl)) == -1 || c == X_HASHNL_SIZE)
576 errx(1, "kvm_nlist: %s %s", "hashnl", kvm_geterr(kd));
577 }
578 if ((todo & (HISTLIST|HISTDUMP)) && !(done & (HISTLIST|HISTDUMP))) {
579 done |= HISTLIST|HISTDUMP;
580 if (kvm_nlist(kd, histnl) == -1)
581 errx(1, "kvm_nlist: %s %s", "histnl", kvm_geterr(kd));
582 }
583 }
584
585 char **
586 choosedrives(char **argv)
587 {
588 size_t i;
589
590 /*
591 * Choose drives to be displayed. Priority goes to (in order) drives
592 * supplied as arguments, default drives. If everything isn't filled
593 * in and there are drives not taken care of, display the first few
594 * that fit.
595 */
596 #define BACKWARD_COMPATIBILITY
597 for (ndrives = 0; *argv; ++argv) {
598 #ifdef BACKWARD_COMPATIBILITY
599 if (isdigit((unsigned char)**argv))
600 break;
601 #endif
602 for (i = 0; i < ndrive; i++) {
603 if (strcmp(dr_name[i], *argv))
604 continue;
605 drv_select[i] = 1;
606 ++ndrives;
607 break;
608 }
609 }
610 for (i = 0; i < ndrive && ndrives < 2; i++) {
611 if (drv_select[i])
612 continue;
613 drv_select[i] = 1;
614 ++ndrives;
615 }
616
617 return (argv);
618 }
619
620 long
621 getuptime(void)
622 {
623 static struct timespec boottime;
624 struct timespec now;
625 time_t uptime, nowsec;
626
627 if (memf == NULL) {
628 if (boottime.tv_sec == 0) {
629 size_t buflen = sizeof(boottime);
630 if (sysctl(boottime_mib, __arraycount(boottime_mib),
631 &boottime, &buflen, NULL, 0) == -1)
632 warn("Can't get boottime");
633 }
634 clock_gettime(CLOCK_REALTIME, &now);
635 } else {
636 if (boottime.tv_sec == 0)
637 kread(namelist, X_BOOTTIME, &boottime,
638 sizeof(boottime));
639 if (kreadc(namelist, X_TIME_SECOND, &nowsec, sizeof(nowsec))) {
640 /*
641 * XXX this assignment dance can be removed once
642 * timeval tv_sec is SUS mandated time_t
643 */
644 now.tv_sec = nowsec;
645 now.tv_nsec = 0;
646 } else {
647 kread(namelist, X_TIME, &now, sizeof(now));
648 }
649 }
650 uptime = now.tv_sec - boottime.tv_sec;
651 if (uptime <= 0 || uptime > 60*60*24*365*10)
652 errx(1, "time makes no sense; namelist must be wrong.");
653 return (uptime);
654 }
655
656 int hz, hdrcnt;
657
658 void
659 print_total_hdr(void)
660 {
661
662 (void)printf("procs memory\n");
663 (void)printf("ru dw pw sl");
664 (void)printf(" total-v active-v active-r");
665 (void)printf(" vm-sh avm-sh rm-sh arm-sh free\n");
666 hdrcnt = winlines - 2;
667 }
668
669 void
670 dovmtotal(struct timespec *interval, int reps)
671 {
672 struct vmtotal total;
673 size_t size;
674
675 (void)signal(SIGCONT, needhdr);
676
677 for (hdrcnt = 1;;) {
678 if (!--hdrcnt)
679 print_total_hdr();
680 if (memf != NULL) {
681 warnx("Unable to get vmtotals from crash dump.");
682 (void)memset(&total, 0, sizeof(total));
683 } else {
684 size = sizeof(total);
685 if (sysctl(vmmeter_mib, __arraycount(vmmeter_mib),
686 &total, &size, NULL, 0) == -1) {
687 warn("Can't get vmtotals");
688 (void)memset(&total, 0, sizeof(total));
689 }
690 }
691 (void)printf("%2d ", total.t_rq);
692 (void)printf("%2d ", total.t_dw);
693 (void)printf("%2d ", total.t_pw);
694 (void)printf("%2d ", total.t_sl);
695
696 (void)printf("%9d ", total.t_vm);
697 (void)printf("%9d ", total.t_avm);
698 (void)printf("%9d ", total.t_arm);
699 (void)printf("%5d ", total.t_vmshr);
700 (void)printf("%6d ", total.t_avmshr);
701 (void)printf("%5d ", total.t_rmshr);
702 (void)printf("%6d ", total.t_armshr);
703 (void)printf("%5d", total.t_free);
704
705 (void)putchar('\n');
706
707 (void)fflush(stdout);
708 if (reps >= 0 && --reps <= 0)
709 break;
710
711 (void)nanosleep(interval, NULL);
712 }
713 }
714
715 void
716 dovmstat(struct timespec *interval, int reps)
717 {
718 struct vmtotal total;
719 time_t uptime, halfuptime;
720 size_t size;
721 int pagesize = getpagesize();
722 int ovflw;
723
724 uptime = getuptime();
725 halfuptime = uptime / 2;
726 (void)signal(SIGCONT, needhdr);
727
728 if (memf != NULL) {
729 if (namelist[X_STATHZ].n_type != 0 && namelist[X_STATHZ].n_value != 0)
730 kread(namelist, X_STATHZ, &hz, sizeof(hz));
731 if (!hz)
732 kread(namelist, X_HZ, &hz, sizeof(hz));
733 } else {
734 struct clockinfo clockinfo;
735 size = sizeof(clockinfo);
736 if (sysctl(clockrate_mib, 2, &clockinfo, &size, NULL, 0) == -1)
737 err(1, "sysctl kern.clockrate failed");
738 hz = clockinfo.stathz;
739 if (!hz)
740 hz = clockinfo.hz;
741 }
742
743 kread(namelist, X_CPU_INFOS, &cpu_infos, sizeof(cpu_infos));
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(long top, 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((long)(top), (long)(bot))
870
871 void
872 dosum(void)
873 {
874 struct nchstats_sysctl 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 kread(namelist, X_CPU_INFOS, &cpu_infos, sizeof(cpu_infos));
993 cpucounters(&cc);
994
995 (void)printf("%9" PRIu64 " total faults taken\n", cc.nfault);
996 (void)printf("%9" PRIu64 " traps\n", cc.ntrap);
997 (void)printf("%9" PRIu64 " device interrupts\n", cc.nintr);
998 (void)printf("%9" PRIu64 " CPU context switches\n", cc.nswtch);
999 (void)printf("%9" PRIu64 " software interrupts\n", cc.nsoft);
1000 (void)printf("%9" PRIu64 " system calls\n", cc.nsyscall);
1001 (void)printf("%9" PRIu64 " pagein requests\n", uvmexp.pageins);
1002 (void)printf("%9" PRIu64 " pageout requests\n", uvmexp.pdpageouts);
1003 (void)printf("%9" PRIu64 " pages swapped in\n", uvmexp.pgswapin);
1004 (void)printf("%9" PRIu64 " pages swapped out\n", uvmexp.pgswapout);
1005 (void)printf("%9" PRIu64 " forks total\n", uvmexp.forks);
1006 (void)printf("%9" PRIu64 " forks blocked parent\n", uvmexp.forks_ppwait);
1007 (void)printf("%9" PRIu64 " forks shared address space with parent\n",
1008 uvmexp.forks_sharevm);
1009 (void)printf("%9" PRIu64 " pagealloc zero wanted and avail\n",
1010 uvmexp.pga_zerohit);
1011 (void)printf("%9" PRIu64 " pagealloc zero wanted and not avail\n",
1012 uvmexp.pga_zeromiss);
1013 (void)printf("%9" PRIu64 " aborts of idle page zeroing\n",
1014 uvmexp.zeroaborts);
1015 (void)printf("%9" PRIu64 " pagealloc desired color avail\n",
1016 uvmexp.colorhit);
1017 (void)printf("%9" PRIu64 " pagealloc desired color not avail\n",
1018 uvmexp.colormiss);
1019 (void)printf("%9" PRIu64 " pagealloc local cpu avail\n",
1020 uvmexp.cpuhit);
1021 (void)printf("%9" PRIu64 " pagealloc local cpu not avail\n",
1022 uvmexp.cpumiss);
1023
1024 (void)printf("%9" PRIu64 " faults with no memory\n", uvmexp.fltnoram);
1025 (void)printf("%9" PRIu64 " faults with no anons\n", uvmexp.fltnoanon);
1026 (void)printf("%9" PRIu64 " faults had to wait on pages\n", uvmexp.fltpgwait);
1027 (void)printf("%9" PRIu64 " faults found released page\n", uvmexp.fltpgrele);
1028 (void)printf("%9" PRIu64 " faults relock (%" PRIu64 " ok)\n", uvmexp.fltrelck,
1029 uvmexp.fltrelckok);
1030 (void)printf("%9" PRIu64 " anon page faults\n", uvmexp.fltanget);
1031 (void)printf("%9" PRIu64 " anon retry faults\n", uvmexp.fltanretry);
1032 (void)printf("%9" PRIu64 " amap copy faults\n", uvmexp.fltamcopy);
1033 (void)printf("%9" PRIu64 " neighbour anon page faults\n", uvmexp.fltnamap);
1034 (void)printf("%9" PRIu64 " neighbour object page faults\n", uvmexp.fltnomap);
1035 (void)printf("%9" PRIu64 " locked pager get faults\n", uvmexp.fltlget);
1036 (void)printf("%9" PRIu64 " unlocked pager get faults\n", uvmexp.fltget);
1037 (void)printf("%9" PRIu64 " anon faults\n", uvmexp.flt_anon);
1038 (void)printf("%9" PRIu64 " anon copy on write faults\n", uvmexp.flt_acow);
1039 (void)printf("%9" PRIu64 " object faults\n", uvmexp.flt_obj);
1040 (void)printf("%9" PRIu64 " promote copy faults\n", uvmexp.flt_prcopy);
1041 (void)printf("%9" PRIu64 " promote zero fill faults\n", uvmexp.flt_przero);
1042
1043 (void)printf("%9" PRIu64 " times daemon wokeup\n",uvmexp.pdwoke);
1044 (void)printf("%9" PRIu64 " revolutions of the clock hand\n", uvmexp.pdrevs);
1045 (void)printf("%9" PRIu64 " pages freed by daemon\n", uvmexp.pdfreed);
1046 (void)printf("%9" PRIu64 " pages scanned by daemon\n", uvmexp.pdscans);
1047 (void)printf("%9" PRIu64 " anonymous pages scanned by daemon\n",
1048 uvmexp.pdanscan);
1049 (void)printf("%9" PRIu64 " object pages scanned by daemon\n", uvmexp.pdobscan);
1050 (void)printf("%9" PRIu64 " pages reactivated\n", uvmexp.pdreact);
1051 (void)printf("%9" PRIu64 " pages found busy by daemon\n", uvmexp.pdbusy);
1052 (void)printf("%9" PRIu64 " total pending pageouts\n", uvmexp.pdpending);
1053 (void)printf("%9" PRIu64 " pages deactivated\n", uvmexp.pddeact);
1054
1055 if (active_kernel) {
1056 ssize = sizeof(nch_stats);
1057 if (sysctlbyname("vfs.namecache_stats", &nch_stats, &ssize,
1058 NULL, 0)) {
1059 warn("vfs.namecache_stats failed");
1060 memset(&nch_stats, 0, sizeof(nch_stats));
1061 }
1062 } else {
1063 struct nchstats nch_stats_kvm;
1064
1065 kread(namelist, X_NCHSTATS, &nch_stats_kvm,
1066 sizeof(nch_stats_kvm));
1067 nch_stats.ncs_goodhits = nch_stats_kvm.ncs_goodhits;
1068 nch_stats.ncs_neghits = nch_stats_kvm.ncs_neghits;
1069 nch_stats.ncs_badhits = nch_stats_kvm.ncs_badhits;
1070 nch_stats.ncs_falsehits = nch_stats_kvm.ncs_falsehits;
1071 nch_stats.ncs_miss = nch_stats_kvm.ncs_miss;
1072 nch_stats.ncs_long = nch_stats_kvm.ncs_long;
1073 nch_stats.ncs_pass2 = nch_stats_kvm.ncs_pass2;
1074 nch_stats.ncs_2passes = nch_stats_kvm.ncs_2passes;
1075 nch_stats.ncs_revhits = nch_stats_kvm.ncs_revhits;
1076 nch_stats.ncs_revmiss = nch_stats_kvm.ncs_revmiss;
1077 }
1078
1079 nchtotal = nch_stats.ncs_goodhits + nch_stats.ncs_neghits +
1080 nch_stats.ncs_badhits + nch_stats.ncs_falsehits +
1081 nch_stats.ncs_miss + nch_stats.ncs_long;
1082 (void)printf("%9" PRIu64 " total name lookups\n", nchtotal);
1083 (void)printf("%9" PRIu64 " good hits\n", nch_stats.ncs_goodhits);
1084 (void)printf("%9" PRIu64 " negative hits\n", nch_stats.ncs_neghits);
1085 (void)printf("%9" PRIu64 " bad hits\n", nch_stats.ncs_badhits);
1086 (void)printf("%9" PRIu64 " false hits\n", nch_stats.ncs_falsehits);
1087 (void)printf("%9" PRIu64 " miss\n", nch_stats.ncs_miss);
1088 (void)printf("%9" PRIu64 " too long\n", nch_stats.ncs_long);
1089 (void)printf("%9" PRIu64 " pass2 hits\n", nch_stats.ncs_pass2);
1090 (void)printf("%9" PRIu64 " 2passes\n", nch_stats.ncs_2passes);
1091 (void)printf(
1092 "%9s cache hits (%d%% pos + %d%% neg) system %d%% per-process\n",
1093 "", PCT(nch_stats.ncs_goodhits, nchtotal),
1094 PCT(nch_stats.ncs_neghits, nchtotal),
1095 PCT(nch_stats.ncs_pass2, nchtotal));
1096 (void)printf("%9s deletions %d%%, falsehits %d%%, toolong %d%%\n", "",
1097 PCT(nch_stats.ncs_badhits, nchtotal),
1098 PCT(nch_stats.ncs_falsehits, nchtotal),
1099 PCT(nch_stats.ncs_long, nchtotal));
1100 }
1101
1102 void
1103 doforkst(void)
1104 {
1105 kread(namelist, X_UVMEXP, &uvmexp, sizeof(uvmexp));
1106 if (memf != NULL) {
1107 struct uvmexp uvmexp_kernel;
1108 kread(namelist, X_UVMEXP, &uvmexp_kernel, sizeof(uvmexp_kernel));
1109 #define COPY(field) uvmexp.field = uvmexp_kernel.field
1110 COPY(forks);
1111 COPY(forks_ppwait);
1112 COPY(forks_sharevm);
1113 #undef COPY
1114 } else {
1115 size_t size = sizeof(uvmexp);
1116 if (sysctl(uvmexp2_mib, __arraycount(uvmexp2_mib), &uvmexp,
1117 &size, NULL, 0) == -1)
1118 warn("sysctl vm.uvmexp2 failed");
1119 }
1120
1121 (void)printf("%" PRIu64 " forks total\n", uvmexp.forks);
1122 (void)printf("%" PRIu64 " forks blocked parent\n", uvmexp.forks_ppwait);
1123 (void)printf("%" PRIu64 " forks shared address space with parent\n",
1124 uvmexp.forks_sharevm);
1125 }
1126
1127 void
1128 drvstats(int *ovflwp)
1129 {
1130 size_t dn;
1131 double etime;
1132 int ovflw = *ovflwp;
1133
1134 /* Calculate disk stat deltas. */
1135 cpuswap();
1136 drvswap();
1137 tkswap();
1138 etime = cur.cp_etime;
1139
1140 for (dn = 0; dn < ndrive; ++dn) {
1141 if (!drv_select[dn])
1142 continue;
1143 PRWORD(ovflw, " %*.0f", 3, 1,
1144 (cur.rxfer[dn] + cur.wxfer[dn]) / etime);
1145 }
1146 *ovflwp = ovflw;
1147 }
1148
1149 void
1150 cpucounters(struct cpu_counter *cc)
1151 {
1152 struct cpu_info **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 void
1345 dopool(int verbose, int wide)
1346 {
1347 int first, ovflw;
1348 void *addr;
1349 long total, inuse, this_total, this_inuse;
1350 struct {
1351 uint64_t pt_nget;
1352 uint64_t pt_nfail;
1353 uint64_t pt_nput;
1354 uint64_t pt_nout;
1355 uint64_t pt_nitems;
1356 uint64_t pt_npagealloc;
1357 uint64_t pt_npagefree;
1358 uint64_t pt_npages;
1359 } pool_totals;
1360 char in_use[8];
1361 char avail[8];
1362 TAILQ_HEAD(,pool) pool_head;
1363 struct pool pool, *pp = &pool;
1364 struct pool_allocator pa;
1365 char name[32], maxp[32];
1366
1367 memset(&pool_totals, 0, sizeof pool_totals);
1368 kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
1369 addr = TAILQ_FIRST(&pool_head);
1370
1371 total = inuse = 0;
1372
1373 for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
1374 deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
1375 deref_kptr(pp->pr_alloc, &pa, sizeof(pa),
1376 "pool allocator trashed");
1377 deref_kptr(pp->pr_wchan, name, sizeof(name),
1378 "pool wait channel trashed");
1379 name[sizeof(name)-1] = '\0';
1380
1381 if (first) {
1382 (void)printf("Memory resource pool statistics\n");
1383 (void)printf(
1384 "%-*s%*s%*s%5s%*s%s%s%*s%*s%6s%s%6s%6s%6s%5s%s%s\n",
1385 wide ? 16 : 11, "Name",
1386 wide ? 6 : 5, "Size",
1387 wide ? 12 : 9, "Requests",
1388 "Fail",
1389 wide ? 12 : 9, "Releases",
1390 wide ? " InUse" : "",
1391 wide ? " Avail" : "",
1392 wide ? 7 : 6, "Pgreq",
1393 wide ? 7 : 6, "Pgrel",
1394 "Npage",
1395 wide ? " PageSz" : "",
1396 "Hiwat",
1397 "Minpg",
1398 "Maxpg",
1399 "Idle",
1400 wide ? " Flags" : "",
1401 wide ? " Util" : "");
1402 first = 0;
1403 }
1404 if (pp->pr_nget == 0 && !verbose)
1405 continue;
1406 if (pp->pr_maxpages == UINT_MAX)
1407 (void)snprintf(maxp, sizeof(maxp), "inf");
1408 else
1409 (void)snprintf(maxp, sizeof(maxp), "%u",
1410 pp->pr_maxpages);
1411 ovflw = 0;
1412 PRWORD(ovflw, "%-*s", wide ? 16 : 11, 0, name);
1413 PRWORD(ovflw, " %*u", wide ? 6 : 5, 1, pp->pr_size);
1414 PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nget);
1415 pool_totals.pt_nget += pp->pr_nget;
1416 PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nfail);
1417 pool_totals.pt_nfail += pp->pr_nfail;
1418 PRWORD(ovflw, " %*lu", wide ? 12 : 9, 1, pp->pr_nput);
1419 pool_totals.pt_nput += pp->pr_nput;
1420 if (wide) {
1421 PRWORD(ovflw, " %*u", 7, 1, pp->pr_nout);
1422 pool_totals.pt_nout += pp->pr_nout;
1423 }
1424 if (wide) {
1425 PRWORD(ovflw, " %*u", 6, 1, pp->pr_nitems);
1426 pool_totals.pt_nitems += pp->pr_nitems;
1427 }
1428 PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagealloc);
1429 pool_totals.pt_npagealloc += pp->pr_npagealloc;
1430 PRWORD(ovflw, " %*lu", wide ? 7 : 6, 1, pp->pr_npagefree);
1431 pool_totals.pt_npagefree += pp->pr_npagefree;
1432 PRWORD(ovflw, " %*u", 6, 1, pp->pr_npages);
1433 pool_totals.pt_npages += pp->pr_npages;
1434 if (wide)
1435 PRWORD(ovflw, " %*u", 7, 1, pa.pa_pagesz);
1436 PRWORD(ovflw, " %*u", 6, 1, pp->pr_hiwat);
1437 PRWORD(ovflw, " %*u", 6, 1, pp->pr_minpages);
1438 PRWORD(ovflw, " %*s", 6, 1, maxp);
1439 PRWORD(ovflw, " %*lu", 5, 1, pp->pr_nidle);
1440 if (wide)
1441 PRWORD(ovflw, " 0x%0*x", 4, 1,
1442 pp->pr_flags | pp->pr_roflags);
1443
1444 this_inuse = pp->pr_nout * pp->pr_size;
1445 this_total = pp->pr_npages * pa.pa_pagesz;
1446 if (pp->pr_roflags & PR_RECURSIVE) {
1447 /*
1448 * Don't count in-use memory, since it's part
1449 * of another pool and will be accounted for
1450 * there.
1451 */
1452 total += (this_total - this_inuse);
1453 } else {
1454 inuse += this_inuse;
1455 total += this_total;
1456 }
1457 if (wide) {
1458 if (this_total == 0)
1459 (void)printf(" ---");
1460 else
1461 (void)printf(" %5.1f%%",
1462 (100.0 * this_inuse) / this_total);
1463 }
1464 (void)printf("\n");
1465 }
1466 if (wide) {
1467 snprintf(in_use, sizeof in_use, "%7"PRId64, pool_totals.pt_nout);
1468 snprintf(avail, sizeof avail, "%6"PRId64, pool_totals.pt_nitems);
1469 } else {
1470 in_use[0] = '\0';
1471 avail[0] = '\0';
1472 }
1473 (void)printf(
1474 "%-*s%*s%*"PRId64"%5"PRId64"%*"PRId64"%s%s%*"PRId64"%*"PRId64"%6"PRId64"\n",
1475 wide ? 16 : 11, "Totals",
1476 wide ? 6 : 5, "",
1477 wide ? 12 : 9, pool_totals.pt_nget,
1478 pool_totals.pt_nfail,
1479 wide ? 12 : 9, pool_totals.pt_nput,
1480 in_use,
1481 avail,
1482 wide ? 7 : 6, pool_totals.pt_npagealloc,
1483 wide ? 7 : 6, pool_totals.pt_npagefree,
1484 pool_totals.pt_npages);
1485
1486 inuse /= KILO;
1487 total /= KILO;
1488 (void)printf(
1489 "\nIn use %ldK, total allocated %ldK; utilization %.1f%%\n",
1490 inuse, total, (100.0 * inuse) / total);
1491 }
1492
1493 void
1494 dopoolcache(int verbose)
1495 {
1496 struct pool_cache pool_cache, *pc = &pool_cache;
1497 pool_cache_cpu_t cache_cpu, *cc = &cache_cpu;
1498 TAILQ_HEAD(,pool) pool_head;
1499 struct pool pool, *pp = &pool;
1500 char name[32];
1501 uint64_t cpuhit, cpumiss, tot;
1502 void *addr;
1503 int first, ovflw;
1504 size_t i;
1505 double p;
1506
1507 kread(namelist, X_POOLHEAD, &pool_head, sizeof(pool_head));
1508 addr = TAILQ_FIRST(&pool_head);
1509
1510 for (first = 1; addr != NULL; addr = TAILQ_NEXT(pp, pr_poollist) ) {
1511 deref_kptr(addr, pp, sizeof(*pp), "pool chain trashed");
1512 if (pp->pr_cache == NULL)
1513 continue;
1514 deref_kptr(pp->pr_wchan, name, sizeof(name),
1515 "pool wait channel trashed");
1516 deref_kptr(pp->pr_cache, pc, sizeof(*pc), "pool cache trashed");
1517 if (pc->pc_misses == 0 && !verbose)
1518 continue;
1519 name[sizeof(name)-1] = '\0';
1520
1521 cpuhit = 0;
1522 cpumiss = 0;
1523 for (i = 0; i < __arraycount(pc->pc_cpus); i++) {
1524 if ((addr = pc->pc_cpus[i]) == NULL)
1525 continue;
1526 deref_kptr(addr, cc, sizeof(*cc),
1527 "pool cache cpu trashed");
1528 cpuhit += cc->cc_hits;
1529 cpumiss += cc->cc_misses;
1530 }
1531
1532 if (first) {
1533 (void)printf("Pool cache statistics.\n");
1534 (void)printf("%-*s%*s%*s%*s%*s%*s%*s%*s%*s%*s\n",
1535 12, "Name",
1536 6, "Spin",
1537 6, "GrpSz",
1538 5, "Full",
1539 5, "Emty",
1540 10, "PoolLayer",
1541 11, "CacheLayer",
1542 6, "Hit%",
1543 12, "CpuLayer",
1544 6, "Hit%"
1545 );
1546 first = 0;
1547 }
1548
1549 ovflw = 0;
1550 PRWORD(ovflw, "%-*s", 13, 1, name);
1551 PRWORD(ovflw, " %*llu", 6, 1, (long long)pc->pc_contended);
1552 PRWORD(ovflw, " %*u", 6, 1, pc->pc_pcgsize);
1553 PRWORD(ovflw, " %*u", 5, 1, pc->pc_nfull);
1554 PRWORD(ovflw, " %*u", 5, 1, pc->pc_nempty);
1555 PRWORD(ovflw, " %*llu", 10, 1, (long long)pc->pc_misses);
1556
1557 tot = pc->pc_hits + pc->pc_misses;
1558 p = pc->pc_hits * 100.0 / (tot);
1559 PRWORD(ovflw, " %*llu", 11, 1, (long long)tot);
1560 PRWORD(ovflw, " %*.1f", 6, 1, p);
1561
1562 tot = cpuhit + cpumiss;
1563 p = cpuhit * 100.0 / (tot);
1564 PRWORD(ovflw, " %*llu", 12, 1, (long long)tot);
1565 PRWORD(ovflw, " %*.1f", 6, 1, p);
1566 printf("\n");
1567 }
1568 }
1569
1570 enum hashtype { /* from <sys/systm.h> */
1571 HASH_LIST,
1572 HASH_TAILQ
1573 };
1574
1575 struct uidinfo { /* XXX: no kernel header file */
1576 LIST_ENTRY(uidinfo) ui_hash;
1577 uid_t ui_uid;
1578 long ui_proccnt;
1579 };
1580
1581 struct kernel_hash {
1582 const char * description; /* description */
1583 int hashsize; /* nlist index for hash size */
1584 int hashtbl; /* nlist index for hash table */
1585 enum hashtype type; /* type of hash table */
1586 size_t offset; /* offset of {LIST,TAILQ}_NEXT */
1587 } khashes[] =
1588 {
1589 {
1590 "buffer hash",
1591 X_BUFHASH, X_BUFHASHTBL,
1592 HASH_LIST, offsetof(struct buf, b_hash)
1593 }, {
1594 "ipv4 address -> interface hash",
1595 X_IFADDRHASH, X_IFADDRHASHTBL,
1596 HASH_LIST, offsetof(struct in_ifaddr, ia_hash),
1597 }, {
1598 "name cache hash",
1599 X_NCHASH, X_NCHASHTBL,
1600 HASH_LIST, offsetof(struct namecache, nc_hash),
1601 }, {
1602 "name cache directory hash",
1603 X_NCVHASH, X_NCVHASHTBL,
1604 HASH_LIST, offsetof(struct namecache, nc_vhash),
1605 }, {
1606 "user info (uid -> used processes) hash",
1607 X_UIHASH, X_UIHASHTBL,
1608 HASH_LIST, offsetof(struct uidinfo, ui_hash),
1609 }, {
1610 NULL, -1, -1, 0, 0,
1611 }
1612 };
1613
1614 void
1615 dohashstat(int verbose, int todo, const char *hashname)
1616 {
1617 LIST_HEAD(, generic) *hashtbl_list;
1618 TAILQ_HEAD(, generic) *hashtbl_tailq;
1619 struct kernel_hash *curhash;
1620 void *hashaddr, *hashbuf, *nhashbuf, *nextaddr;
1621 size_t elemsize, hashbufsize, thissize;
1622 u_long hashsize, i;
1623 int used, items, chain, maxchain;
1624
1625 hashbuf = NULL;
1626 hashbufsize = 0;
1627
1628 if (todo & HASHLIST) {
1629 (void)printf("Supported hashes:\n");
1630 for (curhash = khashes; curhash->description; curhash++) {
1631 if (hashnl[curhash->hashsize].n_value == 0 ||
1632 hashnl[curhash->hashtbl].n_value == 0)
1633 continue;
1634 (void)printf("\t%-16s%s\n",
1635 hashnl[curhash->hashsize].n_name + 1,
1636 curhash->description);
1637 }
1638 return;
1639 }
1640
1641 if (hashname != NULL) {
1642 for (curhash = khashes; curhash->description; curhash++) {
1643 if (strcmp(hashnl[curhash->hashsize].n_name + 1,
1644 hashname) == 0 &&
1645 hashnl[curhash->hashsize].n_value != 0 &&
1646 hashnl[curhash->hashtbl].n_value != 0)
1647 break;
1648 }
1649 if (curhash->description == NULL) {
1650 warnx("%s: no such hash", hashname);
1651 return;
1652 }
1653 }
1654
1655 (void)printf(
1656 "%-16s %8s %8s %8s %8s %8s %8s\n"
1657 "%-16s %8s %8s %8s %8s %8s %8s\n",
1658 "", "total", "used", "util", "num", "average", "maximum",
1659 "hash table", "buckets", "buckets", "%", "items", "chain",
1660 "chain");
1661
1662 for (curhash = khashes; curhash->description; curhash++) {
1663 if (hashnl[curhash->hashsize].n_value == 0 ||
1664 hashnl[curhash->hashtbl].n_value == 0)
1665 continue;
1666 if (hashname != NULL &&
1667 strcmp(hashnl[curhash->hashsize].n_name + 1, hashname))
1668 continue;
1669 elemsize = curhash->type == HASH_LIST ?
1670 sizeof(*hashtbl_list) : sizeof(*hashtbl_tailq);
1671 deref_kptr((void *)hashnl[curhash->hashsize].n_value,
1672 &hashsize, sizeof(hashsize),
1673 hashnl[curhash->hashsize].n_name);
1674 hashsize++;
1675 deref_kptr((void *)hashnl[curhash->hashtbl].n_value,
1676 &hashaddr, sizeof(hashaddr),
1677 hashnl[curhash->hashtbl].n_name);
1678 if (verbose)
1679 (void)printf(
1680 "%s %lu, %s %p, offset %ld, elemsize %llu\n",
1681 hashnl[curhash->hashsize].n_name + 1, hashsize,
1682 hashnl[curhash->hashtbl].n_name + 1, hashaddr,
1683 (long)curhash->offset,
1684 (unsigned long long)elemsize);
1685 thissize = hashsize * elemsize;
1686 if (hashbuf == NULL || thissize > hashbufsize) {
1687 if ((nhashbuf = realloc(hashbuf, thissize)) == NULL)
1688 errx(1, "malloc hashbuf %llu",
1689 (unsigned long long)hashbufsize);
1690 hashbuf = nhashbuf;
1691 hashbufsize = thissize;
1692 }
1693 deref_kptr(hashaddr, hashbuf, thissize,
1694 hashnl[curhash->hashtbl].n_name);
1695 used = 0;
1696 items = maxchain = 0;
1697 if (curhash->type == HASH_LIST) {
1698 hashtbl_list = hashbuf;
1699 hashtbl_tailq = NULL;
1700 } else {
1701 hashtbl_list = NULL;
1702 hashtbl_tailq = hashbuf;
1703 }
1704 for (i = 0; i < hashsize; i++) {
1705 if (curhash->type == HASH_LIST)
1706 nextaddr = LIST_FIRST(&hashtbl_list[i]);
1707 else
1708 nextaddr = TAILQ_FIRST(&hashtbl_tailq[i]);
1709 if (nextaddr == NULL)
1710 continue;
1711 if (verbose)
1712 (void)printf("%5lu: %p\n", i, nextaddr);
1713 used++;
1714 chain = 0;
1715 do {
1716 chain++;
1717 deref_kptr((char *)nextaddr + curhash->offset,
1718 &nextaddr, sizeof(void *),
1719 "hash chain corrupted");
1720 if (verbose > 1)
1721 (void)printf("got nextaddr as %p\n",
1722 nextaddr);
1723 } while (nextaddr != NULL);
1724 items += chain;
1725 if (verbose && chain > 1)
1726 (void)printf("\tchain = %d\n", chain);
1727 if (chain > maxchain)
1728 maxchain = chain;
1729 }
1730 (void)printf("%-16s %8ld %8d %8.2f %8d %8.2f %8d\n",
1731 hashnl[curhash->hashsize].n_name + 1,
1732 hashsize, used, used * 100.0 / hashsize,
1733 items, used ? (double)items / used : 0.0, maxchain);
1734 }
1735 }
1736
1737 /*
1738 * kreadc like kread but returns 1 if sucessful, 0 otherwise
1739 */
1740 int
1741 kreadc(struct nlist *nl, int nlx, void *addr, size_t size)
1742 {
1743 const char *sym;
1744
1745 sym = nl[nlx].n_name;
1746 if (*sym == '_')
1747 ++sym;
1748 if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
1749 return 0;
1750 deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
1751 return 1;
1752 }
1753
1754 /*
1755 * kread reads something from the kernel, given its nlist index in namelist[].
1756 */
1757 void
1758 kread(struct nlist *nl, int nlx, void *addr, size_t size)
1759 {
1760 const char *sym;
1761
1762 sym = nl[nlx].n_name;
1763 if (*sym == '_')
1764 ++sym;
1765 if (nl[nlx].n_type == 0 || nl[nlx].n_value == 0)
1766 errx(1, "symbol %s not defined", sym);
1767 deref_kptr((void *)nl[nlx].n_value, addr, size, sym);
1768 }
1769
1770 /*
1771 * Dereference the kernel pointer `kptr' and fill in the local copy
1772 * pointed to by `ptr'. The storage space must be pre-allocated,
1773 * and the size of the copy passed in `len'.
1774 */
1775 void
1776 deref_kptr(const void *kptr, void *ptr, size_t len, const char *msg)
1777 {
1778
1779 if (*msg == '_')
1780 msg++;
1781 if ((size_t)kvm_read(kd, (u_long)kptr, (char *)ptr, len) != len)
1782 errx(1, "kptr %lx: %s: %s", (u_long)kptr, msg, kvm_geterr(kd));
1783 }
1784
1785 /*
1786 * Traverse the kernel history buffers, performing the requested action.
1787 *
1788 * Note, we assume that if we're not listing, we're dumping.
1789 */
1790 void
1791 hist_traverse(int todo, const char *histname)
1792 {
1793 struct kern_history_head histhead;
1794 struct kern_history hist, *histkva;
1795 char *name = NULL;
1796 size_t namelen = 0;
1797
1798 if (histnl[0].n_value == 0) {
1799 warnx("kernel history is not compiled into the kernel.");
1800 return;
1801 }
1802
1803 deref_kptr((void *)histnl[X_KERN_HISTORIES].n_value, &histhead,
1804 sizeof(histhead), histnl[X_KERN_HISTORIES].n_name);
1805
1806 if (histhead.lh_first == NULL) {
1807 warnx("No active kernel history logs.");
1808 return;
1809 }
1810
1811 if (todo & HISTLIST)
1812 (void)printf("Active kernel histories:");
1813
1814 for (histkva = LIST_FIRST(&histhead); histkva != NULL;
1815 histkva = LIST_NEXT(&hist, list)) {
1816 deref_kptr(histkva, &hist, sizeof(hist), "histkva");
1817 if (name == NULL || hist.namelen > namelen) {
1818 if (name != NULL)
1819 free(name);
1820 namelen = hist.namelen;
1821 if ((name = malloc(namelen + 1)) == NULL)
1822 err(1, "malloc history name");
1823 }
1824
1825 deref_kptr(hist.name, name, namelen, "history name");
1826 name[namelen] = '\0';
1827 if (todo & HISTLIST)
1828 (void)printf(" %s", name);
1829 else {
1830 /*
1831 * If we're dumping all histories, do it, else
1832 * check to see if this is the one we want.
1833 */
1834 if (histname == NULL || strcmp(histname, name) == 0) {
1835 if (histname == NULL)
1836 (void)printf(
1837 "\nkernel history `%s':\n", name);
1838 hist_dodump(&hist);
1839 }
1840 }
1841 }
1842
1843 if (todo & HISTLIST)
1844 (void)putchar('\n');
1845
1846 if (name != NULL)
1847 free(name);
1848 }
1849
1850 /*
1851 * Actually dump the history buffer at the specified KVA.
1852 */
1853 void
1854 hist_dodump(struct kern_history *histp)
1855 {
1856 struct kern_history_ent *histents, *e;
1857 size_t histsize;
1858 char *fmt = NULL, *fn = NULL;
1859 size_t fmtlen = 0, fnlen = 0;
1860 unsigned i;
1861
1862 histsize = sizeof(struct kern_history_ent) * histp->n;
1863
1864 if ((histents = malloc(histsize)) == NULL)
1865 err(1, "malloc history entries");
1866
1867 (void)memset(histents, 0, histsize);
1868
1869 deref_kptr(histp->e, histents, histsize, "history entries");
1870 i = histp->f;
1871 do {
1872 e = &histents[i];
1873 if (e->fmt != NULL) {
1874 if (fmt == NULL || e->fmtlen > fmtlen) {
1875 if (fmt != NULL)
1876 free(fmt);
1877 fmtlen = e->fmtlen;
1878 if ((fmt = malloc(fmtlen + 1)) == NULL)
1879 err(1, "malloc printf format");
1880 }
1881 if (fn == NULL || e->fnlen > fnlen) {
1882 if (fn != NULL)
1883 free(fn);
1884 fnlen = e->fnlen;
1885 if ((fn = malloc(fnlen + 1)) == NULL)
1886 err(1, "malloc function name");
1887 }
1888
1889 deref_kptr(e->fmt, fmt, fmtlen, "printf format");
1890 fmt[fmtlen] = '\0';
1891
1892 deref_kptr(e->fn, fn, fnlen, "function name");
1893 fn[fnlen] = '\0';
1894
1895 (void)printf("%06ld.%06ld ", (long int)e->tv.tv_sec,
1896 (long int)e->tv.tv_usec);
1897 (void)printf("%s#%ld: ", fn, e->call);
1898 (void)printf(fmt, e->v[0], e->v[1], e->v[2], e->v[3]);
1899 (void)putchar('\n');
1900 }
1901 i = (i + 1) % histp->n;
1902 } while (i != histp->f);
1903
1904 free(histents);
1905 if (fmt != NULL)
1906 free(fmt);
1907 if (fn != NULL)
1908 free(fn);
1909 }
1910
1911 static void
1912 usage(void)
1913 {
1914
1915 (void)fprintf(stderr,
1916 "usage: %s [-CefHiLlmstUvW] [-c count] [-h hashname] [-M core] [-N system]\n"
1917 "\t\t[-u histname] [-w wait] [disks]\n", getprogname());
1918 exit(1);
1919 }
1920