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