1 /*- 2 * SPDX-License-Identifier: BSD-3-Clause 3 * 4 * Copyright (c) 1980, 1986, 1991, 1993 5 * The Regents of the University of California. All rights reserved. 6 * 7 * Redistribution and use in source and binary forms, with or without 8 * modification, are permitted provided that the following conditions 9 * are met: 10 * 1. Redistributions of source code must retain the above copyright 11 * notice, this list of conditions and the following disclaimer. 12 * 2. Redistributions in binary form must reproduce the above copyright 13 * notice, this list of conditions and the following disclaimer in the 14 * documentation and/or other materials provided with the distribution. 15 * 3. Neither the name of the University nor the names of its contributors 16 * may be used to endorse or promote products derived from this software 17 * without specific prior written permission. 18 * 19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 29 * SUCH DAMAGE. 30 */ 31 32 #ifndef lint 33 static const char copyright[] = 34 "@(#) Copyright (c) 1980, 1986, 1991, 1993\n\ 35 The Regents of the University of California. All rights reserved.\n"; 36 #endif /* not lint */ 37 38 #if 0 39 #ifndef lint 40 static char sccsid[] = "@(#)vmstat.c 8.1 (Berkeley) 6/6/93"; 41 #endif /* not lint */ 42 #endif 43 44 #include <sys/cdefs.h> 45 #include <sys/param.h> 46 #include <sys/proc.h> 47 #include <sys/uio.h> 48 #include <sys/namei.h> 49 #include <sys/malloc.h> 50 #include <sys/signal.h> 51 #include <sys/fcntl.h> 52 #include <sys/ioctl.h> 53 #include <sys/resource.h> 54 #include <sys/sysctl.h> 55 #include <sys/time.h> 56 #include <sys/user.h> 57 #define _WANT_VMMETER 58 #include <sys/vmmeter.h> 59 #include <sys/pcpu.h> 60 61 #include <vm/vm_param.h> 62 63 #include <ctype.h> 64 #include <devstat.h> 65 #include <err.h> 66 #include <errno.h> 67 #include <inttypes.h> 68 #include <kvm.h> 69 #include <limits.h> 70 #include <memstat.h> 71 #include <nlist.h> 72 #include <paths.h> 73 #include <stdio.h> 74 #include <stdlib.h> 75 #include <string.h> 76 #include <sysexits.h> 77 #include <time.h> 78 #include <unistd.h> 79 #include <libutil.h> 80 #include <libxo/xo.h> 81 82 #define VMSTAT_XO_VERSION "1" 83 84 static char da[] = "da"; 85 86 enum x_stats { X_SUM, X_HZ, X_STATHZ, X_NCHSTATS, X_INTRNAMES, X_SINTRNAMES, 87 X_INTRCNT, X_SINTRCNT, X_NINTRCNT }; 88 89 static struct nlist namelist[] = { 90 [X_SUM] = { .n_name = "_vm_cnt", }, 91 [X_HZ] = { .n_name = "_hz", }, 92 [X_STATHZ] = { .n_name = "_stathz", }, 93 [X_NCHSTATS] = { .n_name = "_nchstats", }, 94 [X_INTRNAMES] = { .n_name = "_intrnames", }, 95 [X_SINTRNAMES] = { .n_name = "_sintrnames", }, 96 [X_INTRCNT] = { .n_name = "_intrcnt", }, 97 [X_SINTRCNT] = { .n_name = "_sintrcnt", }, 98 [X_NINTRCNT] = { .n_name = "_nintrcnt", }, 99 { .n_name = NULL, }, 100 }; 101 102 static struct devstat_match *matches; 103 static struct device_selection *dev_select; 104 static struct statinfo cur, last; 105 static devstat_select_mode select_mode; 106 static size_t size_cp_times; 107 static long *cur_cp_times, *last_cp_times; 108 static long generation, select_generation; 109 static int hz, hdrcnt, maxshowdevs; 110 static int num_devices, num_devices_specified; 111 static int num_matches, num_selected, num_selections; 112 static char **specified_devices; 113 114 static struct __vmmeter { 115 uint64_t v_swtch; 116 uint64_t v_trap; 117 uint64_t v_syscall; 118 uint64_t v_intr; 119 uint64_t v_soft; 120 uint64_t v_vm_faults; 121 uint64_t v_io_faults; 122 uint64_t v_cow_faults; 123 uint64_t v_cow_optim; 124 uint64_t v_zfod; 125 uint64_t v_ozfod; 126 uint64_t v_swapin; 127 uint64_t v_swapout; 128 uint64_t v_swappgsin; 129 uint64_t v_swappgsout; 130 uint64_t v_vnodein; 131 uint64_t v_vnodeout; 132 uint64_t v_vnodepgsin; 133 uint64_t v_vnodepgsout; 134 uint64_t v_intrans; 135 uint64_t v_reactivated; 136 uint64_t v_pdwakeups; 137 uint64_t v_pdpages; 138 uint64_t v_pdshortfalls; 139 uint64_t v_dfree; 140 uint64_t v_pfree; 141 uint64_t v_tfree; 142 uint64_t v_forks; 143 uint64_t v_vforks; 144 uint64_t v_rforks; 145 uint64_t v_kthreads; 146 uint64_t v_forkpages; 147 uint64_t v_vforkpages; 148 uint64_t v_rforkpages; 149 uint64_t v_kthreadpages; 150 u_int v_page_size; 151 u_int v_page_count; 152 u_int v_free_reserved; 153 u_int v_free_target; 154 u_int v_free_min; 155 u_int v_free_count; 156 u_int v_wire_count; 157 u_long v_user_wire_count; 158 u_int v_active_count; 159 u_int v_inactive_target; 160 u_int v_inactive_count; 161 u_int v_laundry_count; 162 u_int v_pageout_free_min; 163 u_int v_interrupt_free_min; 164 u_int v_free_severe; 165 } sum, osum; 166 167 #define VMSTAT_DEFAULT_LINES 20 /* Default number of `winlines'. */ 168 static volatile sig_atomic_t wresized; /* Tty resized when non-zero. */ 169 static int winlines = VMSTAT_DEFAULT_LINES; /* Current number of tty rows. */ 170 171 static int aflag; 172 static int nflag; 173 static int Pflag; 174 static int hflag; 175 176 static kvm_t *kd; 177 178 #define FORKSTAT 0x01 179 #define INTRSTAT 0x02 180 #define MEMSTAT 0x04 181 #define SUMSTAT 0x08 182 #define TIMESTAT 0x10 183 #define VMSTAT 0x20 184 #define ZMEMSTAT 0x40 185 #define OBJSTAT 0x80 186 187 static void cpustats(void); 188 static void pcpustats(u_long, int); 189 static void devstats(void); 190 static void doforkst(void); 191 static void dointr(unsigned int, int); 192 static void doobjstat(void); 193 static void dosum(void); 194 static void dovmstat(unsigned int, int); 195 static void domemstat_malloc(void); 196 static void domemstat_zone(void); 197 static void kread(int, void *, size_t); 198 static void kreado(int, void *, size_t, size_t); 199 static void kreadptr(uintptr_t, void *, size_t); 200 static void needhdr(int); 201 static void needresize(int); 202 static void doresize(void); 203 static void printhdr(int, u_long); 204 static void usage(void); 205 206 static long pct(long, long); 207 static long long getuptime(void); 208 209 static char **getdrivedata(char **); 210 211 int 212 main(int argc, char *argv[]) 213 { 214 char *bp, *buf, *memf, *nlistf; 215 float f; 216 int bufsize, c, reps, todo; 217 size_t len; 218 unsigned int interval; 219 char errbuf[_POSIX2_LINE_MAX]; 220 221 memf = nlistf = NULL; 222 interval = reps = todo = 0; 223 maxshowdevs = 2; 224 225 argc = xo_parse_args(argc, argv); 226 if (argc < 0) 227 return (argc); 228 229 hflag = isatty(1); 230 231 while ((c = getopt(argc, argv, "ac:fhHiM:mN:n:oPp:sw:z")) != -1) { 232 switch (c) { 233 case 'a': 234 aflag++; 235 break; 236 case 'c': 237 reps = atoi(optarg); 238 break; 239 case 'P': 240 Pflag++; 241 break; 242 case 'f': 243 todo |= FORKSTAT; 244 break; 245 case 'h': 246 hflag = 1; 247 break; 248 case 'H': 249 hflag = 0; 250 break; 251 case 'i': 252 todo |= INTRSTAT; 253 break; 254 case 'M': 255 memf = optarg; 256 break; 257 case 'm': 258 todo |= MEMSTAT; 259 break; 260 case 'N': 261 nlistf = optarg; 262 break; 263 case 'n': 264 nflag = 1; 265 maxshowdevs = atoi(optarg); 266 if (maxshowdevs < 0) 267 xo_errx(1, "number of devices %d is < 0", 268 maxshowdevs); 269 break; 270 case 'o': 271 todo |= OBJSTAT; 272 break; 273 case 'p': 274 if (devstat_buildmatch(optarg, &matches, &num_matches) 275 != 0) 276 xo_errx(1, "%s", devstat_errbuf); 277 break; 278 case 's': 279 todo |= SUMSTAT; 280 break; 281 case 'w': 282 /* Convert to milliseconds. */ 283 f = atof(optarg); 284 interval = f * 1000; 285 break; 286 case 'z': 287 todo |= ZMEMSTAT; 288 break; 289 case '?': 290 default: 291 usage(); 292 } 293 } 294 argc -= optind; 295 argv += optind; 296 297 xo_set_version(VMSTAT_XO_VERSION); 298 if (!hflag) 299 xo_set_options(NULL, "no-humanize"); 300 if (todo == 0) 301 todo = VMSTAT; 302 303 if (memf != NULL) { 304 kd = kvm_openfiles(nlistf, memf, NULL, O_RDONLY, errbuf); 305 if (kd == NULL) 306 xo_errx(1, "kvm_openfiles: %s", errbuf); 307 } 308 309 retry_nlist: 310 if (kd != NULL && (c = kvm_nlist(kd, namelist)) != 0) { 311 if (c > 0) { 312 bufsize = 0; 313 len = 0; 314 315 /* 316 * 'cnt' was renamed to 'vm_cnt'. If 'vm_cnt' is not 317 * found try looking up older 'cnt' symbol. 318 * */ 319 if (namelist[X_SUM].n_type == 0 && 320 strcmp(namelist[X_SUM].n_name, "_vm_cnt") == 0) { 321 namelist[X_SUM].n_name = "_cnt"; 322 goto retry_nlist; 323 } 324 325 /* 326 * 'nintrcnt' doesn't exist in older kernels, but 327 * that isn't fatal. 328 */ 329 if (namelist[X_NINTRCNT].n_type == 0 && c == 1) 330 goto nlist_ok; 331 332 for (c = 0; c < (int)(nitems(namelist)); c++) 333 if (namelist[c].n_type == 0) 334 bufsize += strlen(namelist[c].n_name) 335 + 1; 336 bufsize += len + 1; 337 buf = bp = alloca(bufsize); 338 339 for (c = 0; c < (int)(nitems(namelist)); c++) 340 if (namelist[c].n_type == 0) { 341 xo_error(" %s", 342 namelist[c].n_name); 343 len = strlen(namelist[c].n_name); 344 *bp++ = ' '; 345 memcpy(bp, namelist[c].n_name, len); 346 bp += len; 347 } 348 *bp = '\0'; 349 xo_error("undefined symbols:\n", buf); 350 } else 351 xo_warnx("kvm_nlist: %s", kvm_geterr(kd)); 352 xo_finish(); 353 exit(1); 354 } 355 nlist_ok: 356 if (kd && Pflag) 357 xo_errx(1, "Cannot use -P with crash dumps"); 358 359 if (todo & VMSTAT) { 360 /* 361 * Make sure that the userland devstat version matches the 362 * kernel devstat version. If not, exit and print a 363 * message informing the user of his mistake. 364 */ 365 if (devstat_checkversion(NULL) < 0) 366 xo_errx(1, "%s", devstat_errbuf); 367 368 369 argv = getdrivedata(argv); 370 } 371 372 if (*argv) { 373 f = atof(*argv); 374 interval = f * 1000; 375 if (*++argv) 376 reps = atoi(*argv); 377 } 378 379 if (interval) { 380 if (!reps) 381 reps = -1; 382 } else if (reps) 383 interval = 1 * 1000; 384 385 if (todo & FORKSTAT) 386 doforkst(); 387 if (todo & MEMSTAT) 388 domemstat_malloc(); 389 if (todo & ZMEMSTAT) 390 domemstat_zone(); 391 if (todo & SUMSTAT) 392 dosum(); 393 if (todo & OBJSTAT) 394 doobjstat(); 395 if (todo & INTRSTAT) 396 dointr(interval, reps); 397 if (todo & VMSTAT) 398 dovmstat(interval, reps); 399 xo_finish(); 400 exit(0); 401 } 402 403 static int 404 mysysctl(const char *name, void *oldp, size_t *oldlenp) 405 { 406 int error; 407 408 error = sysctlbyname(name, oldp, oldlenp, NULL, 0); 409 if (error != 0 && errno != ENOMEM) 410 xo_err(1, "sysctl(%s)", name); 411 return (error); 412 } 413 414 static char ** 415 getdrivedata(char **argv) 416 { 417 418 if ((num_devices = devstat_getnumdevs(NULL)) < 0) 419 xo_errx(1, "%s", devstat_errbuf); 420 421 cur.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo)); 422 last.dinfo = (struct devinfo *)calloc(1, sizeof(struct devinfo)); 423 424 if (devstat_getdevs(NULL, &cur) == -1) 425 xo_errx(1, "%s", devstat_errbuf); 426 427 num_devices = cur.dinfo->numdevs; 428 generation = cur.dinfo->generation; 429 430 specified_devices = malloc(sizeof(char *)); 431 for (num_devices_specified = 0; *argv; ++argv) { 432 if (isdigit(**argv)) 433 break; 434 num_devices_specified++; 435 specified_devices = reallocf(specified_devices, 436 sizeof(char *) * num_devices_specified); 437 if (specified_devices == NULL) { 438 xo_errx(1, "%s", "reallocf (specified_devices)"); 439 } 440 specified_devices[num_devices_specified - 1] = *argv; 441 } 442 dev_select = NULL; 443 444 if (nflag == 0 && maxshowdevs < num_devices_specified) 445 maxshowdevs = num_devices_specified; 446 447 /* 448 * People are generally only interested in disk statistics when 449 * they're running vmstat. So, that's what we're going to give 450 * them if they don't specify anything by default. We'll also give 451 * them any other random devices in the system so that we get to 452 * maxshowdevs devices, if that many devices exist. If the user 453 * specifies devices on the command line, either through a pattern 454 * match or by naming them explicitly, we will give the user only 455 * those devices. 456 */ 457 if ((num_devices_specified == 0) && (num_matches == 0)) { 458 if (devstat_buildmatch(da, &matches, &num_matches) != 0) 459 xo_errx(1, "%s", devstat_errbuf); 460 select_mode = DS_SELECT_ADD; 461 } else 462 select_mode = DS_SELECT_ONLY; 463 464 /* 465 * At this point, selectdevs will almost surely indicate that the 466 * device list has changed, so we don't look for return values of 0 467 * or 1. If we get back -1, though, there is an error. 468 */ 469 if (devstat_selectdevs(&dev_select, &num_selected, &num_selections, 470 &select_generation, generation, cur.dinfo->devices, 471 num_devices, matches, num_matches, specified_devices, 472 num_devices_specified, select_mode, 473 maxshowdevs, 0) == -1) 474 xo_errx(1, "%s", devstat_errbuf); 475 476 return(argv); 477 } 478 479 /* Return system uptime in nanoseconds */ 480 static long long 481 getuptime(void) 482 { 483 struct timespec sp; 484 485 (void)clock_gettime(CLOCK_UPTIME, &sp); 486 return((long long)sp.tv_sec * 1000000000LL + sp.tv_nsec); 487 } 488 489 static void 490 fill_vmmeter(struct __vmmeter *vmmp) 491 { 492 struct vmmeter vm_cnt; 493 size_t size; 494 495 if (kd != NULL) { 496 kread(X_SUM, &vm_cnt, sizeof(vm_cnt)); 497 #define GET_COUNTER(name) \ 498 vmmp->name = kvm_counter_u64_fetch(kd, (u_long)vm_cnt.name) 499 GET_COUNTER(v_swtch); 500 GET_COUNTER(v_trap); 501 GET_COUNTER(v_syscall); 502 GET_COUNTER(v_intr); 503 GET_COUNTER(v_soft); 504 GET_COUNTER(v_vm_faults); 505 GET_COUNTER(v_io_faults); 506 GET_COUNTER(v_cow_faults); 507 GET_COUNTER(v_cow_optim); 508 GET_COUNTER(v_zfod); 509 GET_COUNTER(v_ozfod); 510 GET_COUNTER(v_swapin); 511 GET_COUNTER(v_swapout); 512 GET_COUNTER(v_swappgsin); 513 GET_COUNTER(v_swappgsout); 514 GET_COUNTER(v_vnodein); 515 GET_COUNTER(v_vnodeout); 516 GET_COUNTER(v_vnodepgsin); 517 GET_COUNTER(v_vnodepgsout); 518 GET_COUNTER(v_intrans); 519 GET_COUNTER(v_tfree); 520 GET_COUNTER(v_forks); 521 GET_COUNTER(v_vforks); 522 GET_COUNTER(v_rforks); 523 GET_COUNTER(v_kthreads); 524 GET_COUNTER(v_forkpages); 525 GET_COUNTER(v_vforkpages); 526 GET_COUNTER(v_rforkpages); 527 GET_COUNTER(v_kthreadpages); 528 #undef GET_COUNTER 529 } else { 530 #define GET_VM_STATS(cat, name) do { \ 531 size = sizeof(vmmp->name); \ 532 mysysctl("vm.stats." #cat "." #name, &vmmp->name, &size); \ 533 } while (0) 534 /* sys */ 535 GET_VM_STATS(sys, v_swtch); 536 GET_VM_STATS(sys, v_trap); 537 GET_VM_STATS(sys, v_syscall); 538 GET_VM_STATS(sys, v_intr); 539 GET_VM_STATS(sys, v_soft); 540 541 /* vm */ 542 GET_VM_STATS(vm, v_vm_faults); 543 GET_VM_STATS(vm, v_io_faults); 544 GET_VM_STATS(vm, v_cow_faults); 545 GET_VM_STATS(vm, v_cow_optim); 546 GET_VM_STATS(vm, v_zfod); 547 GET_VM_STATS(vm, v_ozfod); 548 GET_VM_STATS(vm, v_swapin); 549 GET_VM_STATS(vm, v_swapout); 550 GET_VM_STATS(vm, v_swappgsin); 551 GET_VM_STATS(vm, v_swappgsout); 552 GET_VM_STATS(vm, v_vnodein); 553 GET_VM_STATS(vm, v_vnodeout); 554 GET_VM_STATS(vm, v_vnodepgsin); 555 GET_VM_STATS(vm, v_vnodepgsout); 556 GET_VM_STATS(vm, v_intrans); 557 GET_VM_STATS(vm, v_reactivated); 558 GET_VM_STATS(vm, v_pdwakeups); 559 GET_VM_STATS(vm, v_pdpages); 560 GET_VM_STATS(vm, v_pdshortfalls); 561 GET_VM_STATS(vm, v_dfree); 562 GET_VM_STATS(vm, v_pfree); 563 GET_VM_STATS(vm, v_tfree); 564 GET_VM_STATS(vm, v_page_size); 565 GET_VM_STATS(vm, v_page_count); 566 GET_VM_STATS(vm, v_free_reserved); 567 GET_VM_STATS(vm, v_free_target); 568 GET_VM_STATS(vm, v_free_min); 569 GET_VM_STATS(vm, v_free_count); 570 GET_VM_STATS(vm, v_wire_count); 571 GET_VM_STATS(vm, v_user_wire_count); 572 GET_VM_STATS(vm, v_active_count); 573 GET_VM_STATS(vm, v_inactive_target); 574 GET_VM_STATS(vm, v_inactive_count); 575 GET_VM_STATS(vm, v_laundry_count); 576 GET_VM_STATS(vm, v_pageout_free_min); 577 GET_VM_STATS(vm, v_interrupt_free_min); 578 /*GET_VM_STATS(vm, v_free_severe);*/ 579 GET_VM_STATS(vm, v_forks); 580 GET_VM_STATS(vm, v_vforks); 581 GET_VM_STATS(vm, v_rforks); 582 GET_VM_STATS(vm, v_kthreads); 583 GET_VM_STATS(vm, v_forkpages); 584 GET_VM_STATS(vm, v_vforkpages); 585 GET_VM_STATS(vm, v_rforkpages); 586 GET_VM_STATS(vm, v_kthreadpages); 587 #undef GET_VM_STATS 588 } 589 } 590 591 static void 592 fill_vmtotal(struct vmtotal *vmtp) 593 { 594 size_t size; 595 596 if (kd != NULL) { 597 /* XXX fill vmtp */ 598 xo_errx(1, "not implemented"); 599 } else { 600 size = sizeof(*vmtp); 601 mysysctl("vm.vmtotal", vmtp, &size); 602 if (size != sizeof(*vmtp)) 603 xo_errx(1, "vm.total size mismatch"); 604 } 605 } 606 607 /* Determine how many cpu columns, and what index they are in kern.cp_times */ 608 static void 609 getcpuinfo(u_long *maskp, int *maxidp) 610 { 611 long *times; 612 u_long mask; 613 size_t size; 614 int empty, i, j, maxcpu, maxid; 615 616 if (kd != NULL) 617 xo_errx(1, "not implemented"); 618 mask = 0; 619 size = sizeof(maxcpu); 620 mysysctl("kern.smp.maxcpus", &maxcpu, &size); 621 if (size != sizeof(maxcpu)) 622 xo_errx(1, "sysctl kern.smp.maxcpus"); 623 size = sizeof(long) * maxcpu * CPUSTATES; 624 times = malloc(size); 625 if (times == NULL) 626 xo_err(1, "malloc %zd bytes", size); 627 mysysctl("kern.cp_times", times, &size); 628 maxid = (size / CPUSTATES / sizeof(long)) - 1; 629 for (i = 0; i <= maxid; i++) { 630 empty = 1; 631 for (j = 0; empty && j < CPUSTATES; j++) { 632 if (times[i * CPUSTATES + j] != 0) 633 empty = 0; 634 } 635 if (!empty) 636 mask |= (1ul << i); 637 } 638 if (maskp) 639 *maskp = mask; 640 if (maxidp) 641 *maxidp = maxid; 642 } 643 644 static void 645 dovmstat(unsigned int interval, int reps) 646 { 647 struct clockinfo clockrate; 648 struct vmtotal total; 649 struct devinfo *tmp_dinfo; 650 u_long cpumask; 651 size_t size; 652 time_t uptime, halfuptime; 653 int maxid, rate_adj, retval; 654 655 uptime = getuptime() / 1000000000LL; 656 halfuptime = uptime / 2; 657 rate_adj = 1; 658 maxid = 0; 659 cpumask = 0; 660 661 /* 662 * If the user stops the program (control-Z) and then resumes it, 663 * print out the header again. 664 */ 665 (void)signal(SIGCONT, needhdr); 666 667 /* 668 * If our standard output is a tty, then install a SIGWINCH handler 669 * and set wresized so that our first iteration through the main 670 * vmstat loop will peek at the terminal's current rows to find out 671 * how many lines can fit in a screenful of output. 672 */ 673 if (isatty(fileno(stdout)) != 0) { 674 wresized = 1; 675 (void)signal(SIGWINCH, needresize); 676 } else { 677 wresized = 0; 678 winlines = VMSTAT_DEFAULT_LINES; 679 } 680 681 if (kd != NULL) { 682 if (namelist[X_STATHZ].n_type != 0 && 683 namelist[X_STATHZ].n_value != 0) 684 kread(X_STATHZ, &hz, sizeof(hz)); 685 if (!hz) 686 kread(X_HZ, &hz, sizeof(hz)); 687 } else { 688 size = sizeof(clockrate); 689 mysysctl("kern.clockrate", &clockrate, &size); 690 if (size != sizeof(clockrate)) 691 xo_errx(1, "clockrate size mismatch"); 692 hz = clockrate.hz; 693 } 694 695 if (Pflag) { 696 getcpuinfo(&cpumask, &maxid); 697 size_cp_times = sizeof(long) * (maxid + 1) * CPUSTATES; 698 cur_cp_times = calloc(1, size_cp_times); 699 last_cp_times = calloc(1, size_cp_times); 700 } 701 for (hdrcnt = 1;;) { 702 if (!--hdrcnt) 703 printhdr(maxid, cpumask); 704 if (kd != NULL) { 705 if (kvm_getcptime(kd, cur.cp_time) < 0) 706 xo_errx(1, "kvm_getcptime: %s", kvm_geterr(kd)); 707 } else { 708 size = sizeof(cur.cp_time); 709 mysysctl("kern.cp_time", &cur.cp_time, &size); 710 if (size != sizeof(cur.cp_time)) 711 xo_errx(1, "cp_time size mismatch"); 712 } 713 if (Pflag) { 714 size = size_cp_times; 715 mysysctl("kern.cp_times", cur_cp_times, &size); 716 if (size != size_cp_times) 717 xo_errx(1, "cp_times mismatch"); 718 } 719 720 tmp_dinfo = last.dinfo; 721 last.dinfo = cur.dinfo; 722 cur.dinfo = tmp_dinfo; 723 last.snap_time = cur.snap_time; 724 725 /* 726 * Here what we want to do is refresh our device stats. 727 * getdevs() returns 1 when the device list has changed. 728 * If the device list has changed, we want to go through 729 * the selection process again, in case a device that we 730 * were previously displaying has gone away. 731 */ 732 switch (devstat_getdevs(NULL, &cur)) { 733 case -1: 734 xo_errx(1, "%s", devstat_errbuf); 735 break; 736 case 1: 737 num_devices = cur.dinfo->numdevs; 738 generation = cur.dinfo->generation; 739 740 retval = devstat_selectdevs(&dev_select, &num_selected, 741 &num_selections, &select_generation, 742 generation, cur.dinfo->devices, 743 num_devices, matches, num_matches, 744 specified_devices, 745 num_devices_specified, select_mode, 746 maxshowdevs, 0); 747 switch (retval) { 748 case -1: 749 xo_errx(1, "%s", devstat_errbuf); 750 break; 751 case 1: 752 printhdr(maxid, cpumask); 753 break; 754 default: 755 break; 756 } 757 break; 758 default: 759 break; 760 } 761 762 fill_vmmeter(&sum); 763 fill_vmtotal(&total); 764 xo_open_container("processes"); 765 xo_emit("{:runnable/%2d} {:waiting/%2ld} " 766 "{:swapped-out/%2ld}", total.t_rq - 1, total.t_dw + 767 total.t_pw, total.t_sw); 768 xo_close_container("processes"); 769 xo_open_container("memory"); 770 #define rate(x) (unsigned long)(((x) * rate_adj + halfuptime) / uptime) 771 xo_emit(" {[:4}{h,hn-decimal:available-memory/%ju}{]:}", 772 (uintmax_t)total.t_avm * sum.v_page_size); 773 xo_emit(" {[:4}{h,hn-decimal:free-memory/%ju}{]:}", 774 (uintmax_t)total.t_free * sum.v_page_size); 775 xo_emit(" {[:4}{h,hn-decimal,hn-1000:total-page-faults/%lu}{]:} ", 776 rate(sum.v_vm_faults - osum.v_vm_faults)); 777 xo_close_container("memory"); 778 779 xo_open_container("paging-rates"); 780 xo_emit("{:page-reactivated/%3lu} ", 781 rate(sum.v_reactivated - osum.v_reactivated)); 782 xo_emit("{:paged-in/%3lu} ", 783 rate(sum.v_swapin + sum.v_vnodein - 784 (osum.v_swapin + osum.v_vnodein))); 785 xo_emit("{:paged-out/%3lu}", 786 rate(sum.v_swapout + sum.v_vnodeout - 787 (osum.v_swapout + osum.v_vnodeout))); 788 xo_emit(" {[:4}{h,hn-decimal,hn-1000:freed/%lu}{]:}", 789 rate(sum.v_tfree - osum.v_tfree)); 790 xo_emit(" {[:4}{h,hn-decimal,hn-1000:scanned/%lu}{]:}", 791 rate(sum.v_pdpages - osum.v_pdpages)); 792 xo_close_container("paging-rates"); 793 794 devstats(); 795 xo_open_container("fault-rates"); 796 xo_emit(" {[:4}{h,hn-decimal,hn-1000:interrupts/%lu}{]:}" 797 " {[:4}{h,hn-decimal,hn-1000:system-calls/%lu}{]:}" 798 " {[:4}{h,hn-decimal,hn-1000:context-switches/%lu}{]:}", 799 rate(sum.v_intr - osum.v_intr), 800 rate(sum.v_syscall - osum.v_syscall), 801 rate(sum.v_swtch - osum.v_swtch)); 802 xo_close_container("fault-rates"); 803 if (Pflag) 804 pcpustats(cpumask, maxid); 805 else 806 cpustats(); 807 xo_emit("\n"); 808 xo_flush(); 809 if (reps >= 0 && --reps <= 0) 810 break; 811 osum = sum; 812 uptime = interval; 813 rate_adj = 1000; 814 /* 815 * We round upward to avoid losing low-frequency events 816 * (i.e., >= 1 per interval but < 1 per millisecond). 817 */ 818 if (interval != 1) 819 halfuptime = (uptime + 1) / 2; 820 else 821 halfuptime = 0; 822 (void)usleep(interval * 1000); 823 } 824 } 825 826 static void 827 printhdr(int maxid, u_long cpumask) 828 { 829 int i, num_shown; 830 831 num_shown = MIN(num_selected, maxshowdevs); 832 xo_emit(" {T:procs} {T:memory} {T:/page%*s}", 19, ""); 833 if (num_shown > 1) 834 xo_emit(" {T:/disks %*s} ", num_shown * 5 - 7, ""); 835 else if (num_shown == 1) 836 xo_emit(" {T:disks} "); 837 xo_emit(" {T:faults} "); 838 if (Pflag) { 839 for (i = 0; i <= maxid; i++) { 840 if (cpumask & (1ul << i)) 841 xo_emit(" {T:/cpu%d} ", i); 842 } 843 xo_emit("\n"); 844 } else 845 xo_emit(" {T:cpu}\n"); 846 xo_emit(" {T:r} {T:b} {T:w} {T:avm} {T:fre} {T:flt} {T:re}" 847 " {T:pi} {T:po} {T:fr} {T:sr} "); 848 for (i = 0; i < num_devices; i++) 849 if ((dev_select[i].selected) && 850 (dev_select[i].selected <= maxshowdevs)) 851 xo_emit("{T:/%3.3s%d} ", dev_select[i].device_name, 852 dev_select[i].unit_number); 853 xo_emit(" {T:in} {T:sy} {T:cs}"); 854 if (Pflag) { 855 for (i = 0; i <= maxid; i++) { 856 if (cpumask & (1ul << i)) 857 xo_emit(" {T:us} {T:sy} {T:id}"); 858 } 859 xo_emit("\n"); 860 } else 861 xo_emit(" {T:us} {T:sy} {T:id}\n"); 862 if (wresized != 0) 863 doresize(); 864 hdrcnt = winlines; 865 } 866 867 /* 868 * Force a header to be prepended to the next output. 869 */ 870 static void 871 needhdr(int dummy __unused) 872 { 873 874 hdrcnt = 1; 875 } 876 877 /* 878 * When the terminal is resized, force an update of the maximum number of rows 879 * printed between each header repetition. Then force a new header to be 880 * prepended to the next output. 881 */ 882 void 883 needresize(int signo __unused) 884 { 885 886 wresized = 1; 887 hdrcnt = 1; 888 } 889 890 /* 891 * Update the global `winlines' count of terminal rows. 892 */ 893 void 894 doresize(void) 895 { 896 struct winsize w; 897 int status; 898 899 for (;;) { 900 status = ioctl(fileno(stdout), TIOCGWINSZ, &w); 901 if (status == -1 && errno == EINTR) 902 continue; 903 else if (status == -1) 904 xo_err(1, "ioctl"); 905 if (w.ws_row > 3) 906 winlines = w.ws_row - 3; 907 else 908 winlines = VMSTAT_DEFAULT_LINES; 909 break; 910 } 911 912 /* 913 * Inhibit doresize() calls until we are rescheduled by SIGWINCH. 914 */ 915 wresized = 0; 916 } 917 918 static long 919 pct(long top, long bot) 920 { 921 long ans; 922 923 if (bot == 0) 924 return(0); 925 ans = (quad_t)top * 100 / bot; 926 return (ans); 927 } 928 929 #define PCT(top, bot) pct((long)(top), (long)(bot)) 930 931 static void 932 dosum(void) 933 { 934 struct nchstats lnchstats; 935 size_t size; 936 long nchtotal; 937 938 fill_vmmeter(&sum); 939 xo_open_container("summary-statistics"); 940 xo_emit("{:context-switches/%9u} {N:cpu context switches}\n", 941 sum.v_swtch); 942 xo_emit("{:interrupts/%9u} {N:device interrupts}\n", 943 sum.v_intr); 944 xo_emit("{:software-interrupts/%9u} {N:software interrupts}\n", 945 sum.v_soft); 946 xo_emit("{:traps/%9u} {N:traps}\n", sum.v_trap); 947 xo_emit("{:system-calls/%9u} {N:system calls}\n", 948 sum.v_syscall); 949 xo_emit("{:kernel-threads/%9u} {N:kernel threads created}\n", 950 sum.v_kthreads); 951 xo_emit("{:forks/%9u} {N: fork() calls}\n", sum.v_forks); 952 xo_emit("{:vforks/%9u} {N:vfork() calls}\n", 953 sum.v_vforks); 954 xo_emit("{:rforks/%9u} {N:rfork() calls}\n", 955 sum.v_rforks); 956 xo_emit("{:swap-ins/%9u} {N:swap pager pageins}\n", 957 sum.v_swapin); 958 xo_emit("{:swap-in-pages/%9u} {N:swap pager pages paged in}\n", 959 sum.v_swappgsin); 960 xo_emit("{:swap-outs/%9u} {N:swap pager pageouts}\n", 961 sum.v_swapout); 962 xo_emit("{:swap-out-pages/%9u} {N:swap pager pages paged out}\n", 963 sum.v_swappgsout); 964 xo_emit("{:vnode-page-ins/%9u} {N:vnode pager pageins}\n", 965 sum.v_vnodein); 966 xo_emit("{:vnode-page-in-pages/%9u} {N:vnode pager pages paged in}\n", 967 sum.v_vnodepgsin); 968 xo_emit("{:vnode-page-outs/%9u} {N:vnode pager pageouts}\n", 969 sum.v_vnodeout); 970 xo_emit("{:vnode-page-out-pages/%9u} {N:vnode pager pages paged out}\n", 971 sum.v_vnodepgsout); 972 xo_emit("{:page-daemon-wakeups/%9u} {N:page daemon wakeups}\n", 973 sum.v_pdwakeups); 974 xo_emit("{:page-daemon-pages/%9u} {N:pages examined by the page " 975 "daemon}\n", sum.v_pdpages); 976 xo_emit("{:page-reclamation-shortfalls/%9u} {N:clean page reclamation " 977 "shortfalls}\n", sum.v_pdshortfalls); 978 xo_emit("{:reactivated/%9u} {N:pages reactivated by the page daemon}\n", 979 sum.v_reactivated); 980 xo_emit("{:copy-on-write-faults/%9u} {N:copy-on-write faults}\n", 981 sum.v_cow_faults); 982 xo_emit("{:copy-on-write-optimized-faults/%9u} {N:copy-on-write " 983 "optimized faults}\n", sum.v_cow_optim); 984 xo_emit("{:zero-fill-pages/%9u} {N:zero fill pages zeroed}\n", 985 sum.v_zfod); 986 xo_emit("{:zero-fill-prezeroed/%9u} {N:zero fill pages prezeroed}\n", 987 sum.v_ozfod); 988 xo_emit("{:intransit-blocking/%9u} {N:intransit blocking page faults}\n", 989 sum.v_intrans); 990 xo_emit("{:total-faults/%9u} {N:total VM faults taken}\n", 991 sum.v_vm_faults); 992 xo_emit("{:faults-requiring-io/%9u} {N:page faults requiring I\\/O}\n", 993 sum.v_io_faults); 994 xo_emit("{:faults-from-thread-creation/%9u} {N:pages affected by " 995 "kernel thread creation}\n", sum.v_kthreadpages); 996 xo_emit("{:faults-from-fork/%9u} {N:pages affected by fork}()\n", 997 sum.v_forkpages); 998 xo_emit("{:faults-from-vfork/%9u} {N:pages affected by vfork}()\n", 999 sum.v_vforkpages); 1000 xo_emit("{:pages-rfork/%9u} {N:pages affected by rfork}()\n", 1001 sum.v_rforkpages); 1002 xo_emit("{:pages-freed/%9u} {N:pages freed}\n", 1003 sum.v_tfree); 1004 xo_emit("{:pages-freed-by-daemon/%9u} {N:pages freed by daemon}\n", 1005 sum.v_dfree); 1006 xo_emit("{:pages-freed-on-exit/%9u} {N:pages freed by exiting processes}\n", 1007 sum.v_pfree); 1008 xo_emit("{:active-pages/%9u} {N:pages active}\n", 1009 sum.v_active_count); 1010 xo_emit("{:inactive-pages/%9u} {N:pages inactive}\n", 1011 sum.v_inactive_count); 1012 xo_emit("{:laundry-pages/%9u} {N:pages in the laundry queue}\n", 1013 sum.v_laundry_count); 1014 xo_emit("{:wired-pages/%9u} {N:pages wired down}\n", 1015 sum.v_wire_count); 1016 xo_emit("{:virtual-user-wired-pages/%9lu} {N:virtual user pages wired " 1017 "down}\n", sum.v_user_wire_count); 1018 xo_emit("{:free-pages/%9u} {N:pages free}\n", 1019 sum.v_free_count); 1020 xo_emit("{:bytes-per-page/%9u} {N:bytes per page}\n", sum.v_page_size); 1021 if (kd != NULL) { 1022 kread(X_NCHSTATS, &lnchstats, sizeof(lnchstats)); 1023 } else { 1024 size = sizeof(lnchstats); 1025 mysysctl("vfs.cache.nchstats", &lnchstats, &size); 1026 if (size != sizeof(lnchstats)) 1027 xo_errx(1, "vfs.cache.nchstats size mismatch"); 1028 } 1029 nchtotal = lnchstats.ncs_goodhits + lnchstats.ncs_neghits + 1030 lnchstats.ncs_badhits + lnchstats.ncs_falsehits + 1031 lnchstats.ncs_miss + lnchstats.ncs_long; 1032 xo_emit("{:total-name-lookups/%9ld} {N:total name lookups}\n", 1033 nchtotal); 1034 xo_emit("{P:/%9s} {N:cache hits} " 1035 "({:positive-cache-hits/%ld}% pos + " 1036 "{:negative-cache-hits/%ld}% {N:neg}) " 1037 "system {:cache-hit-percent/%ld}% per-directory\n", 1038 "", PCT(lnchstats.ncs_goodhits, nchtotal), 1039 PCT(lnchstats.ncs_neghits, nchtotal), 1040 PCT(lnchstats.ncs_pass2, nchtotal)); 1041 xo_emit("{P:/%9s} {L:deletions} {:deletions/%ld}%, " 1042 "{L:falsehits} {:false-hits/%ld}%, " 1043 "{L:toolong} {:too-long/%ld}%\n", "", 1044 PCT(lnchstats.ncs_badhits, nchtotal), 1045 PCT(lnchstats.ncs_falsehits, nchtotal), 1046 PCT(lnchstats.ncs_long, nchtotal)); 1047 xo_close_container("summary-statistics"); 1048 } 1049 1050 static void 1051 doforkst(void) 1052 { 1053 1054 fill_vmmeter(&sum); 1055 xo_open_container("fork-statistics"); 1056 xo_emit("{:fork/%u} {N:forks}, {:fork-pages/%u} {N:pages}, " 1057 "{L:average} {:fork-average/%.2f}\n", 1058 sum.v_forks, sum.v_forkpages, 1059 sum.v_forks == 0 ? 0.0 : 1060 (double)sum.v_forkpages / sum.v_forks); 1061 xo_emit("{:vfork/%u} {N:vforks}, {:vfork-pages/%u} {N:pages}, " 1062 "{L:average} {:vfork-average/%.2f}\n", 1063 sum.v_vforks, sum.v_vforkpages, 1064 sum.v_vforks == 0 ? 0.0 : 1065 (double)sum.v_vforkpages / sum.v_vforks); 1066 xo_emit("{:rfork/%u} {N:rforks}, {:rfork-pages/%u} {N:pages}, " 1067 "{L:average} {:rfork-average/%.2f}\n", 1068 sum.v_rforks, sum.v_rforkpages, 1069 sum.v_rforks == 0 ? 0.0 : 1070 (double)sum.v_rforkpages / sum.v_rforks); 1071 xo_close_container("fork-statistics"); 1072 } 1073 1074 static void 1075 devstats(void) 1076 { 1077 long double busy_seconds, transfers_per_second; 1078 long tmp; 1079 int di, dn, state; 1080 1081 for (state = 0; state < CPUSTATES; ++state) { 1082 tmp = cur.cp_time[state]; 1083 cur.cp_time[state] -= last.cp_time[state]; 1084 last.cp_time[state] = tmp; 1085 } 1086 1087 busy_seconds = cur.snap_time - last.snap_time; 1088 1089 xo_open_list("device"); 1090 for (dn = 0; dn < num_devices; dn++) { 1091 if (dev_select[dn].selected == 0 || 1092 dev_select[dn].selected > maxshowdevs) 1093 continue; 1094 1095 di = dev_select[dn].position; 1096 1097 if (devstat_compute_statistics(&cur.dinfo->devices[di], 1098 &last.dinfo->devices[di], busy_seconds, 1099 DSM_TRANSFERS_PER_SECOND, &transfers_per_second, 1100 DSM_NONE) != 0) 1101 xo_errx(1, "%s", devstat_errbuf); 1102 1103 xo_open_instance("device"); 1104 xo_emit("{ekq:name/%s%d}", 1105 dev_select[dn].device_name, 1106 dev_select[dn].unit_number); 1107 xo_emit("{[:5}{h,hn-decimal,hn-1000:transfers/%ju}{]:}", 1108 (uintmax_t)transfers_per_second); 1109 xo_close_instance("device"); 1110 } 1111 xo_close_list("device"); 1112 } 1113 1114 static void 1115 percent(const char *name, long pctv, int *over) 1116 { 1117 char fmt[64]; 1118 1119 snprintf(fmt, sizeof(fmt), " {:%s/%%%ulld/%%lld}", name, 1120 (*over && pctv <= 9) ? 1 : 2); 1121 xo_emit(fmt, pctv); 1122 if (*over && pctv <= 9) 1123 (*over)--; 1124 else if (pctv >= 100) 1125 (*over)++; 1126 } 1127 1128 static void 1129 cpustats(void) 1130 { 1131 long total; 1132 int state, over; 1133 1134 total = 0; 1135 for (state = 0; state < CPUSTATES; ++state) 1136 total += cur.cp_time[state]; 1137 if (total == 0) 1138 total = 1; 1139 over = 0; 1140 xo_open_container("cpu-statistics"); 1141 percent("user", 100LL * (cur.cp_time[CP_USER] + cur.cp_time[CP_NICE]) / 1142 total, &over); 1143 percent("system", 100LL * (cur.cp_time[CP_SYS] + cur.cp_time[CP_INTR]) / 1144 total, &over); 1145 percent("idle", 100LL * cur.cp_time[CP_IDLE] / total, &over); 1146 xo_close_container("cpu-statistics"); 1147 } 1148 1149 static void 1150 pcpustats(u_long cpumask, int maxid) 1151 { 1152 long tmp, total; 1153 int i, state, over; 1154 1155 /* devstats does this for cp_time */ 1156 for (i = 0; i <= maxid; i++) { 1157 if ((cpumask & (1ul << i)) == 0) 1158 continue; 1159 for (state = 0; state < CPUSTATES; ++state) { 1160 tmp = cur_cp_times[i * CPUSTATES + state]; 1161 cur_cp_times[i * CPUSTATES + state] -= last_cp_times[i * 1162 CPUSTATES + state]; 1163 last_cp_times[i * CPUSTATES + state] = tmp; 1164 } 1165 } 1166 1167 over = 0; 1168 xo_open_list("cpu"); 1169 for (i = 0; i <= maxid; i++) { 1170 if ((cpumask & (1ul << i)) == 0) 1171 continue; 1172 xo_open_instance("cpu"); 1173 xo_emit("{ke:name/%d}", i); 1174 total = 0; 1175 for (state = 0; state < CPUSTATES; ++state) 1176 total += cur_cp_times[i * CPUSTATES + state]; 1177 if (total == 0) 1178 total = 1; 1179 percent("user", 1180 100LL * (cur_cp_times[i * CPUSTATES + CP_USER] + 1181 cur_cp_times[i * CPUSTATES + CP_NICE]) / total, &over); 1182 percent("system", 1183 100LL * (cur_cp_times[i * CPUSTATES + CP_SYS] + 1184 cur_cp_times[i * CPUSTATES + CP_INTR]) / total, &over); 1185 percent("idle", 1186 100LL * cur_cp_times[i * CPUSTATES + CP_IDLE] / total, 1187 &over); 1188 xo_close_instance("cpu"); 1189 } 1190 xo_close_list("cpu"); 1191 } 1192 1193 static unsigned int 1194 read_intrcnts(unsigned long **intrcnts) 1195 { 1196 size_t intrcntlen; 1197 uintptr_t kaddr; 1198 1199 if (kd != NULL) { 1200 kread(X_SINTRCNT, &intrcntlen, sizeof(intrcntlen)); 1201 if ((*intrcnts = malloc(intrcntlen)) == NULL) 1202 err(1, "malloc()"); 1203 if (namelist[X_NINTRCNT].n_type == 0) 1204 kread(X_INTRCNT, *intrcnts, intrcntlen); 1205 else { 1206 kread(X_INTRCNT, &kaddr, sizeof(kaddr)); 1207 kreadptr(kaddr, *intrcnts, intrcntlen); 1208 } 1209 } else { 1210 for (*intrcnts = NULL, intrcntlen = 1024; ; intrcntlen *= 2) { 1211 *intrcnts = reallocf(*intrcnts, intrcntlen); 1212 if (*intrcnts == NULL) 1213 err(1, "reallocf()"); 1214 if (mysysctl("hw.intrcnt", *intrcnts, &intrcntlen) == 0) 1215 break; 1216 } 1217 } 1218 1219 return (intrcntlen / sizeof(unsigned long)); 1220 } 1221 1222 static void 1223 print_intrcnts(unsigned long *intrcnts, unsigned long *old_intrcnts, 1224 char *intrnames, unsigned int nintr, size_t istrnamlen, long long period_ms) 1225 { 1226 uint64_t inttotal, old_inttotal, total_count, total_rate; 1227 unsigned long count, rate; 1228 unsigned int i; 1229 1230 inttotal = 0; 1231 old_inttotal = 0; 1232 xo_open_list("interrupt"); 1233 for (i = 0; i < nintr; i++) { 1234 if (intrnames[0] != '\0' && (*intrcnts != 0 || aflag)) { 1235 count = *intrcnts - *old_intrcnts; 1236 rate = ((uint64_t)count * 1000 + period_ms / 2) / period_ms; 1237 xo_open_instance("interrupt"); 1238 xo_emit("{d:name/%-*s}{ket:name/%s} " 1239 "{:total/%20lu} {:rate/%10lu}\n", 1240 (int)istrnamlen, intrnames, intrnames, count, rate); 1241 xo_close_instance("interrupt"); 1242 } 1243 intrnames += strlen(intrnames) + 1; 1244 inttotal += *intrcnts++; 1245 old_inttotal += *old_intrcnts++; 1246 } 1247 total_count = inttotal - old_inttotal; 1248 total_rate = (total_count * 1000 + period_ms / 2) / period_ms; 1249 xo_close_list("interrupt"); 1250 xo_emit("{L:/%-*s} {:total-interrupts/%20ju} " 1251 "{:total-rate/%10ju}\n", (int)istrnamlen, 1252 "Total", (uintmax_t)total_count, (uintmax_t)total_rate); 1253 } 1254 1255 static void 1256 dointr(unsigned int interval, int reps) 1257 { 1258 unsigned long *intrcnts, *old_intrcnts; 1259 char *intrname, *intrnames; 1260 long long period_ms, old_uptime, uptime; 1261 size_t clen, inamlen, istrnamlen; 1262 uintptr_t kaddr; 1263 unsigned int nintr; 1264 1265 old_intrcnts = NULL; 1266 uptime = getuptime(); 1267 1268 /* Get the names of each interrupt source */ 1269 if (kd != NULL) { 1270 kread(X_SINTRNAMES, &inamlen, sizeof(inamlen)); 1271 if ((intrnames = malloc(inamlen)) == NULL) 1272 xo_err(1, "malloc()"); 1273 if (namelist[X_NINTRCNT].n_type == 0) 1274 kread(X_INTRNAMES, intrnames, inamlen); 1275 else { 1276 kread(X_INTRNAMES, &kaddr, sizeof(kaddr)); 1277 kreadptr(kaddr, intrnames, inamlen); 1278 } 1279 } else { 1280 for (intrnames = NULL, inamlen = 1024; ; inamlen *= 2) { 1281 if ((intrnames = reallocf(intrnames, inamlen)) == NULL) 1282 xo_err(1, "reallocf()"); 1283 if (mysysctl("hw.intrnames", intrnames, &inamlen) == 0) 1284 break; 1285 } 1286 } 1287 1288 /* Determine the length of the longest interrupt name */ 1289 intrname = intrnames; 1290 istrnamlen = strlen("interrupt"); 1291 while (intrname < intrnames + inamlen) { 1292 clen = strlen(intrname); 1293 if (clen > istrnamlen) 1294 istrnamlen = clen; 1295 intrname += strlen(intrname) + 1; 1296 } 1297 xo_emit("{T:/%-*s} {T:/%20s} {T:/%10s}\n", 1298 (int)istrnamlen, "interrupt", "total", "rate"); 1299 1300 /* 1301 * Loop reps times printing differential interrupt counts. If reps is 1302 * zero, then run just once, printing total counts 1303 */ 1304 xo_open_container("interrupt-statistics"); 1305 1306 period_ms = uptime / 1000000; 1307 while(1) { 1308 nintr = read_intrcnts(&intrcnts); 1309 /* 1310 * Initialize old_intrcnts to 0 for the first pass, so 1311 * print_intrcnts will print total interrupts since boot 1312 */ 1313 if (old_intrcnts == NULL) { 1314 old_intrcnts = calloc(nintr, sizeof(unsigned long)); 1315 if (old_intrcnts == NULL) 1316 xo_err(1, "calloc()"); 1317 } 1318 1319 print_intrcnts(intrcnts, old_intrcnts, intrnames, nintr, 1320 istrnamlen, period_ms); 1321 xo_flush(); 1322 1323 free(old_intrcnts); 1324 old_intrcnts = intrcnts; 1325 if (reps >= 0 && --reps <= 0) 1326 break; 1327 usleep(interval * 1000); 1328 old_uptime = uptime; 1329 uptime = getuptime(); 1330 period_ms = (uptime - old_uptime) / 1000000; 1331 } 1332 1333 xo_close_container("interrupt-statistics"); 1334 } 1335 1336 static void 1337 domemstat_malloc(void) 1338 { 1339 struct memory_type_list *mtlp; 1340 struct memory_type *mtp; 1341 size_t i, zones; 1342 int error, first; 1343 1344 mtlp = memstat_mtl_alloc(); 1345 if (mtlp == NULL) { 1346 xo_warn("memstat_mtl_alloc"); 1347 return; 1348 } 1349 if (kd == NULL) { 1350 if (memstat_sysctl_malloc(mtlp, 0) < 0) { 1351 xo_warnx("memstat_sysctl_malloc: %s", 1352 memstat_strerror(memstat_mtl_geterror(mtlp))); 1353 return; 1354 } 1355 } else { 1356 if (memstat_kvm_malloc(mtlp, kd) < 0) { 1357 error = memstat_mtl_geterror(mtlp); 1358 if (error == MEMSTAT_ERROR_KVM) 1359 xo_warnx("memstat_kvm_malloc: %s", 1360 kvm_geterr(kd)); 1361 else 1362 xo_warnx("memstat_kvm_malloc: %s", 1363 memstat_strerror(error)); 1364 } 1365 } 1366 xo_open_container("malloc-statistics"); 1367 xo_emit("{T:/%16s} {T:/%4s} {T:/%5s} {T:/%3s} {T:Size(s)}\n", 1368 "Type", "Use", "Memory", "Req"); 1369 xo_open_list("memory"); 1370 zones = memstat_malloc_zone_get_count(); 1371 for (mtp = memstat_mtl_first(mtlp); mtp != NULL; 1372 mtp = memstat_mtl_next(mtp)) { 1373 if (memstat_get_numallocs(mtp) == 0 && 1374 memstat_get_count(mtp) == 0) 1375 continue; 1376 xo_open_instance("memory"); 1377 xo_emit("{k:type/%16s/%s} " 1378 "{[:4}{h,hn-decimal,hn-1000:in-use/%ju}{]:} " 1379 "{[:5}{h,hn-decimal:memory-use/%ju}{]:} " 1380 "{[:4}{h,hn-decimal,hn-1000:requests/%ju}{]:} ", 1381 memstat_get_name(mtp), (uintmax_t)memstat_get_count(mtp), 1382 (uintmax_t)memstat_get_bytes(mtp), 1383 (uintmax_t)memstat_get_numallocs(mtp)); 1384 first = 1; 1385 xo_open_list("size"); 1386 for (i = 0; i < zones; i++) { 1387 if (memstat_malloc_zone_used(mtp, i)) { 1388 if (!first) 1389 xo_emit(","); 1390 xo_emit("{lh:size/%d}", memstat_malloc_zone_get_size(i)); 1391 first = 0; 1392 } 1393 } 1394 xo_close_list("size"); 1395 xo_close_instance("memory"); 1396 xo_emit("\n"); 1397 } 1398 xo_close_list("memory"); 1399 xo_close_container("malloc-statistics"); 1400 memstat_mtl_free(mtlp); 1401 } 1402 1403 static void 1404 domemstat_zone(void) 1405 { 1406 struct memory_type_list *mtlp; 1407 struct memory_type *mtp; 1408 int error, len; 1409 1410 mtlp = memstat_mtl_alloc(); 1411 if (mtlp == NULL) { 1412 xo_warn("memstat_mtl_alloc"); 1413 return; 1414 } 1415 if (kd == NULL) { 1416 if (memstat_sysctl_uma(mtlp, 0) < 0) { 1417 xo_warnx("memstat_sysctl_uma: %s", 1418 memstat_strerror(memstat_mtl_geterror(mtlp))); 1419 return; 1420 } 1421 } else { 1422 if (memstat_kvm_uma(mtlp, kd) < 0) { 1423 error = memstat_mtl_geterror(mtlp); 1424 if (error == MEMSTAT_ERROR_KVM) 1425 xo_warnx("memstat_kvm_uma: %s", 1426 kvm_geterr(kd)); 1427 else 1428 xo_warnx("memstat_kvm_uma: %s", 1429 memstat_strerror(error)); 1430 } 1431 } 1432 xo_open_container("memory-zone-statistics"); 1433 xo_emit("{T:/%-19s} {T:/%7s} {T:/%7s} {T:/%8s} {T:/%8s} {T:/%8s} " 1434 "{T:/%4s} {T:/%4s} {T:/%4s}\n", "ITEM", "SIZE", 1435 "LIMIT", "USED", "FREE", "REQ", "FAIL", "SLEEP", "XDOM"); 1436 xo_open_list("zone"); 1437 for (mtp = memstat_mtl_first(mtlp); mtp != NULL; 1438 mtp = memstat_mtl_next(mtp)) { 1439 len = strlen(memstat_get_name(mtp)); 1440 xo_open_instance("zone"); 1441 xo_emit("{k:name/%s}:{d:size/%*ju}{e:size/%ju}," 1442 "{:limit/%7ju},{:used/%8ju}," 1443 "{:free/%8ju},{:requests/%8ju}," 1444 "{:fail/%4ju},{:sleep/%4ju},{:xdomain/%4ju}\n", 1445 memstat_get_name(mtp), MAX(1, 26 - len), 1446 (uintmax_t)memstat_get_size(mtp), 1447 (uintmax_t)memstat_get_size(mtp), 1448 (uintmax_t)memstat_get_countlimit(mtp), 1449 (uintmax_t)memstat_get_count(mtp), 1450 (uintmax_t)memstat_get_free(mtp), 1451 (uintmax_t)memstat_get_numallocs(mtp), 1452 (uintmax_t)memstat_get_failures(mtp), 1453 (uintmax_t)memstat_get_sleeps(mtp), 1454 (uintmax_t)memstat_get_xdomain(mtp)); 1455 xo_close_instance("zone"); 1456 } 1457 memstat_mtl_free(mtlp); 1458 xo_close_list("zone"); 1459 xo_close_container("memory-zone-statistics"); 1460 } 1461 1462 static void 1463 display_object(struct kinfo_vmobject *kvo) 1464 { 1465 const char *str; 1466 1467 xo_open_instance("object"); 1468 xo_emit("{:resident/%5ju} ", (uintmax_t)kvo->kvo_resident); 1469 xo_emit("{:active/%5ju} ", (uintmax_t)kvo->kvo_active); 1470 xo_emit("{:inactive/%5ju} ", (uintmax_t)kvo->kvo_inactive); 1471 xo_emit("{:refcount/%3d} ", kvo->kvo_ref_count); 1472 xo_emit("{:shadowcount/%3d} ", kvo->kvo_shadow_count); 1473 1474 #define MEMATTR_STR(type, val) \ 1475 if (kvo->kvo_memattr == (type)) { \ 1476 str = (val); \ 1477 } else 1478 #ifdef VM_MEMATTR_UNCACHEABLE 1479 MEMATTR_STR(VM_MEMATTR_UNCACHEABLE, "UC") 1480 #endif 1481 #ifdef VM_MEMATTR_WRITE_COMBINING 1482 MEMATTR_STR(VM_MEMATTR_WRITE_COMBINING, "WC") 1483 #endif 1484 #ifdef VM_MEMATTR_WRITE_THROUGH 1485 MEMATTR_STR(VM_MEMATTR_WRITE_THROUGH, "WT") 1486 #endif 1487 #ifdef VM_MEMATTR_WRITE_PROTECTED 1488 MEMATTR_STR(VM_MEMATTR_WRITE_PROTECTED, "WP") 1489 #endif 1490 #ifdef VM_MEMATTR_WRITE_BACK 1491 MEMATTR_STR(VM_MEMATTR_WRITE_BACK, "WB") 1492 #endif 1493 #ifdef VM_MEMATTR_WEAK_UNCACHEABLE 1494 MEMATTR_STR(VM_MEMATTR_WEAK_UNCACHEABLE, "UC-") 1495 #endif 1496 #ifdef VM_MEMATTR_WB_WA 1497 MEMATTR_STR(VM_MEMATTR_WB_WA, "WB") 1498 #endif 1499 #ifdef VM_MEMATTR_NOCACHE 1500 MEMATTR_STR(VM_MEMATTR_NOCACHE, "NC") 1501 #endif 1502 #ifdef VM_MEMATTR_DEVICE 1503 MEMATTR_STR(VM_MEMATTR_DEVICE, "DEV") 1504 #endif 1505 #ifdef VM_MEMATTR_DEVICE_NP 1506 MEMATTR_STR(VM_MEMATTR_DEVICE, "NP") 1507 #endif 1508 #ifdef VM_MEMATTR_CACHEABLE 1509 MEMATTR_STR(VM_MEMATTR_CACHEABLE, "C") 1510 #endif 1511 #ifdef VM_MEMATTR_PREFETCHABLE 1512 MEMATTR_STR(VM_MEMATTR_PREFETCHABLE, "PRE") 1513 #endif 1514 { 1515 str = "??"; 1516 } 1517 #undef MEMATTR_STR 1518 xo_emit("{:attribute/%-3s} ", str); 1519 switch (kvo->kvo_type) { 1520 case KVME_TYPE_NONE: 1521 str = "--"; 1522 break; 1523 case KVME_TYPE_DEFAULT: 1524 str = "df"; 1525 break; 1526 case KVME_TYPE_VNODE: 1527 str = "vn"; 1528 break; 1529 case KVME_TYPE_SWAP: 1530 str = "sw"; 1531 break; 1532 case KVME_TYPE_DEVICE: 1533 str = "dv"; 1534 break; 1535 case KVME_TYPE_PHYS: 1536 str = "ph"; 1537 break; 1538 case KVME_TYPE_DEAD: 1539 str = "dd"; 1540 break; 1541 case KVME_TYPE_SG: 1542 str = "sg"; 1543 break; 1544 case KVME_TYPE_MGTDEVICE: 1545 str = "md"; 1546 break; 1547 case KVME_TYPE_UNKNOWN: 1548 default: 1549 str = "??"; 1550 break; 1551 } 1552 xo_emit("{:type/%-2s} ", str); 1553 xo_emit("{:path/%-s}\n", kvo->kvo_path); 1554 xo_close_instance("object"); 1555 } 1556 1557 static void 1558 doobjstat(void) 1559 { 1560 struct kinfo_vmobject *kvo; 1561 int cnt, i; 1562 1563 kvo = kinfo_getvmobject(&cnt); 1564 if (kvo == NULL) { 1565 xo_warn("Failed to fetch VM object list"); 1566 return; 1567 } 1568 xo_emit("{T:RES/%5s} {T:ACT/%5s} {T:INACT/%5s} {T:REF/%3s} {T:SHD/%3s} " 1569 "{T:CM/%3s} {T:TP/%2s} {T:PATH/%s}\n"); 1570 xo_open_list("object"); 1571 for (i = 0; i < cnt; i++) 1572 display_object(&kvo[i]); 1573 free(kvo); 1574 xo_close_list("object"); 1575 } 1576 1577 /* 1578 * kread reads something from the kernel, given its nlist index. 1579 */ 1580 static void 1581 kreado(int nlx, void *addr, size_t size, size_t offset) 1582 { 1583 const char *sym; 1584 1585 if (namelist[nlx].n_type == 0 || namelist[nlx].n_value == 0) { 1586 sym = namelist[nlx].n_name; 1587 if (*sym == '_') 1588 ++sym; 1589 xo_errx(1, "symbol %s not defined", sym); 1590 } 1591 if ((size_t)kvm_read(kd, namelist[nlx].n_value + offset, addr, 1592 size) != size) { 1593 sym = namelist[nlx].n_name; 1594 if (*sym == '_') 1595 ++sym; 1596 xo_errx(1, "%s: %s", sym, kvm_geterr(kd)); 1597 } 1598 } 1599 1600 static void 1601 kread(int nlx, void *addr, size_t size) 1602 { 1603 1604 kreado(nlx, addr, size, 0); 1605 } 1606 1607 static void 1608 kreadptr(uintptr_t addr, void *buf, size_t size) 1609 { 1610 1611 if ((size_t)kvm_read(kd, addr, buf, size) != size) 1612 xo_errx(1, "%s", kvm_geterr(kd)); 1613 } 1614 1615 static void __dead2 1616 usage(void) 1617 { 1618 xo_error("%s%s", 1619 "usage: vmstat [-afHhimoPsz] [-M core [-N system]] [-c count] [-n devs]\n", 1620 " [-p type,if,pass] [-w wait] [disks] [wait [count]]\n"); 1621 xo_finish(); 1622 exit(1); 1623 } 1624