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