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