1 /* 2 * top - a top users display for Unix 3 * 4 * SYNOPSIS: For FreeBSD-2.x and later 5 * 6 * DESCRIPTION: 7 * Originally written for BSD4.4 system by Christos Zoulas. 8 * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider 9 * Order support hacked in from top-3.5beta6/machine/m_aix41.c 10 * by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/) 11 * 12 * This is the machine-dependent module for FreeBSD 2.2 13 * Works for: 14 * FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x 15 * 16 * LIBS: -lkvm 17 * 18 * AUTHOR: Christos Zoulas <christos@ee.cornell.edu> 19 * Steven Wallace <swallace@freebsd.org> 20 * Wolfram Schneider <wosch@FreeBSD.org> 21 * Thomas Moestl <tmoestl@gmx.net> 22 * 23 * $FreeBSD$ 24 */ 25 26 #include <sys/param.h> 27 #include <sys/errno.h> 28 #include <sys/file.h> 29 #include <sys/proc.h> 30 #include <sys/resource.h> 31 #include <sys/rtprio.h> 32 #include <sys/signal.h> 33 #include <sys/sysctl.h> 34 #include <sys/time.h> 35 #include <sys/user.h> 36 #include <sys/vmmeter.h> 37 38 #include <err.h> 39 #include <kvm.h> 40 #include <math.h> 41 #include <nlist.h> 42 #include <paths.h> 43 #include <pwd.h> 44 #include <stdio.h> 45 #include <stdlib.h> 46 #include <string.h> 47 #include <strings.h> 48 #include <unistd.h> 49 #include <vis.h> 50 51 #include "top.h" 52 #include "machine.h" 53 #include "screen.h" 54 #include "utils.h" 55 #include "layout.h" 56 57 #define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var)) 58 #define SMPUNAMELEN 13 59 #define UPUNAMELEN 15 60 61 extern struct process_select ps; 62 extern char* printable(char *); 63 static int smpmode; 64 enum displaymodes displaymode; 65 #ifdef TOP_USERNAME_LEN 66 static int namelength = TOP_USERNAME_LEN; 67 #else 68 static int namelength = 8; 69 #endif 70 /* TOP_JID_LEN based on max of 999999 */ 71 #define TOP_JID_LEN 7 72 static int jidlength; 73 static int cmdlengthdelta; 74 75 /* Prototypes for top internals */ 76 void quit(int); 77 78 /* get_process_info passes back a handle. This is what it looks like: */ 79 80 struct handle { 81 struct kinfo_proc **next_proc; /* points to next valid proc pointer */ 82 int remaining; /* number of pointers remaining */ 83 }; 84 85 /* declarations for load_avg */ 86 #include "loadavg.h" 87 88 /* define what weighted cpu is. */ 89 #define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \ 90 ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu)))) 91 92 /* what we consider to be process size: */ 93 #define PROCSIZE(pp) ((pp)->ki_size / 1024) 94 95 #define RU(pp) (&(pp)->ki_rusage) 96 #define RUTOT(pp) \ 97 (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt) 98 99 #define PCTCPU(pp) (pcpu[pp - pbase]) 100 101 /* definitions for indices in the nlist array */ 102 103 /* 104 * These definitions control the format of the per-process area 105 */ 106 107 static char io_header[] = 108 " PID%*s %-*.*s VCSW IVCSW READ WRITE FAULT TOTAL PERCENT COMMAND"; 109 110 #define io_Proc_format \ 111 "%5d%*s %-*.*s %6ld %6ld %6ld %6ld %6ld %6ld %6.2f%% %.*s" 112 113 static char smp_header_thr[] = 114 " PID%*s %-*.*s THR PRI NICE SIZE RES STATE C TIME %7s COMMAND"; 115 static char smp_header[] = 116 " PID%*s %-*.*s " "PRI NICE SIZE RES STATE C TIME %7s COMMAND"; 117 118 #define smp_Proc_format \ 119 "%5d%*s %-*.*s %s%3d %4s%7s %6s %-6.6s %2d%7s %6.2f%% %.*s" 120 121 static char up_header_thr[] = 122 " PID%*s %-*.*s THR PRI NICE SIZE RES STATE TIME %7s COMMAND"; 123 static char up_header[] = 124 " PID%*s %-*.*s " "PRI NICE SIZE RES STATE TIME %7s COMMAND"; 125 126 #define up_Proc_format \ 127 "%5d%*s %-*.*s %s%3d %4s%7s %6s %-6.6s%.0d%7s %6.2f%% %.*s" 128 129 130 /* process state names for the "STATE" column of the display */ 131 /* the extra nulls in the string "run" are for adding a slash and 132 the processor number when needed */ 133 134 char *state_abbrev[] = { 135 "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK" 136 }; 137 138 139 static kvm_t *kd; 140 141 /* values that we stash away in _init and use in later routines */ 142 143 static double logcpu; 144 145 /* these are retrieved from the kernel in _init */ 146 147 static load_avg ccpu; 148 149 /* these are used in the get_ functions */ 150 151 static int lastpid; 152 153 /* these are for calculating cpu state percentages */ 154 155 static long cp_time[CPUSTATES]; 156 static long cp_old[CPUSTATES]; 157 static long cp_diff[CPUSTATES]; 158 159 /* these are for detailing the process states */ 160 161 int process_states[8]; 162 char *procstatenames[] = { 163 "", " starting, ", " running, ", " sleeping, ", " stopped, ", 164 " zombie, ", " waiting, ", " lock, ", 165 NULL 166 }; 167 168 /* these are for detailing the cpu states */ 169 170 int cpu_states[CPUSTATES]; 171 char *cpustatenames[] = { 172 "user", "nice", "system", "interrupt", "idle", NULL 173 }; 174 175 /* these are for detailing the memory statistics */ 176 177 int memory_stats[7]; 178 char *memorynames[] = { 179 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", 180 "K Free", NULL 181 }; 182 183 int arc_stats[7]; 184 char *arcnames[] = { 185 "K Total, ", "K MFU, ", "K MRU, ", "K Anon, ", "K Header, ", "K Other", 186 NULL 187 }; 188 189 int swap_stats[7]; 190 char *swapnames[] = { 191 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out", 192 NULL 193 }; 194 195 196 /* these are for keeping track of the proc array */ 197 198 static int nproc; 199 static int onproc = -1; 200 static int pref_len; 201 static struct kinfo_proc *pbase; 202 static struct kinfo_proc **pref; 203 static struct kinfo_proc *previous_procs; 204 static struct kinfo_proc **previous_pref; 205 static int previous_proc_count = 0; 206 static int previous_proc_count_max = 0; 207 static int previous_thread; 208 209 /* data used for recalculating pctcpu */ 210 static double *pcpu; 211 static struct timespec proc_uptime; 212 static struct timeval proc_wall_time; 213 static struct timeval previous_wall_time; 214 static uint64_t previous_interval = 0; 215 216 /* total number of io operations */ 217 static long total_inblock; 218 static long total_oublock; 219 static long total_majflt; 220 221 /* these are for getting the memory statistics */ 222 223 static int arc_enabled; 224 static int pageshift; /* log base 2 of the pagesize */ 225 226 /* define pagetok in terms of pageshift */ 227 228 #define pagetok(size) ((size) << pageshift) 229 230 /* useful externals */ 231 long percentages(); 232 233 #ifdef ORDER 234 /* 235 * Sorting orders. The first element is the default. 236 */ 237 char *ordernames[] = { 238 "cpu", "size", "res", "time", "pri", "threads", 239 "total", "read", "write", "fault", "vcsw", "ivcsw", 240 "jid", "pid", NULL 241 }; 242 #endif 243 244 /* Per-cpu time states */ 245 static int maxcpu; 246 static int maxid; 247 static int ncpus; 248 static u_long cpumask; 249 static long *times; 250 static long *pcpu_cp_time; 251 static long *pcpu_cp_old; 252 static long *pcpu_cp_diff; 253 static int *pcpu_cpu_states; 254 255 static int compare_jid(const void *a, const void *b); 256 static int compare_pid(const void *a, const void *b); 257 static int compare_tid(const void *a, const void *b); 258 static const char *format_nice(const struct kinfo_proc *pp); 259 static void getsysctl(const char *name, void *ptr, size_t len); 260 static int swapmode(int *retavail, int *retfree); 261 static void update_layout(void); 262 263 void 264 toggle_pcpustats(void) 265 { 266 267 if (ncpus == 1) 268 return; 269 update_layout(); 270 } 271 272 /* Adjust display based on ncpus and the ARC state. */ 273 static void 274 update_layout(void) 275 { 276 277 y_mem = 3; 278 y_arc = 4; 279 y_swap = 4 + arc_enabled; 280 y_idlecursor = 5 + arc_enabled; 281 y_message = 5 + arc_enabled; 282 y_header = 6 + arc_enabled; 283 y_procs = 7 + arc_enabled; 284 Header_lines = 7 + arc_enabled; 285 286 if (pcpu_stats) { 287 y_mem += ncpus - 1; 288 y_arc += ncpus - 1; 289 y_swap += ncpus - 1; 290 y_idlecursor += ncpus - 1; 291 y_message += ncpus - 1; 292 y_header += ncpus - 1; 293 y_procs += ncpus - 1; 294 Header_lines += ncpus - 1; 295 } 296 } 297 298 int 299 machine_init(struct statics *statics, char do_unames) 300 { 301 int i, j, empty, pagesize; 302 uint64_t arc_size; 303 size_t size; 304 struct passwd *pw; 305 306 size = sizeof(smpmode); 307 if ((sysctlbyname("machdep.smp_active", &smpmode, &size, 308 NULL, 0) != 0 && 309 sysctlbyname("kern.smp.active", &smpmode, &size, 310 NULL, 0) != 0) || 311 size != sizeof(smpmode)) 312 smpmode = 0; 313 314 size = sizeof(arc_size); 315 if (sysctlbyname("kstat.zfs.misc.arcstats.size", &arc_size, &size, 316 NULL, 0) == 0 && arc_size != 0) 317 arc_enabled = 1; 318 319 if (do_unames) { 320 while ((pw = getpwent()) != NULL) { 321 if (strlen(pw->pw_name) > namelength) 322 namelength = strlen(pw->pw_name); 323 } 324 } 325 if (smpmode && namelength > SMPUNAMELEN) 326 namelength = SMPUNAMELEN; 327 else if (namelength > UPUNAMELEN) 328 namelength = UPUNAMELEN; 329 330 kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open"); 331 if (kd == NULL) 332 return (-1); 333 334 GETSYSCTL("kern.ccpu", ccpu); 335 336 /* this is used in calculating WCPU -- calculate it ahead of time */ 337 logcpu = log(loaddouble(ccpu)); 338 339 pbase = NULL; 340 pref = NULL; 341 pcpu = NULL; 342 nproc = 0; 343 onproc = -1; 344 345 /* get the page size and calculate pageshift from it */ 346 pagesize = getpagesize(); 347 pageshift = 0; 348 while (pagesize > 1) { 349 pageshift++; 350 pagesize >>= 1; 351 } 352 353 /* we only need the amount of log(2)1024 for our conversion */ 354 pageshift -= LOG1024; 355 356 /* fill in the statics information */ 357 statics->procstate_names = procstatenames; 358 statics->cpustate_names = cpustatenames; 359 statics->memory_names = memorynames; 360 if (arc_enabled) 361 statics->arc_names = arcnames; 362 else 363 statics->arc_names = NULL; 364 statics->swap_names = swapnames; 365 #ifdef ORDER 366 statics->order_names = ordernames; 367 #endif 368 369 /* Allocate state for per-CPU stats. */ 370 cpumask = 0; 371 ncpus = 0; 372 GETSYSCTL("kern.smp.maxcpus", maxcpu); 373 size = sizeof(long) * maxcpu * CPUSTATES; 374 times = malloc(size); 375 if (times == NULL) 376 err(1, "malloc %zd bytes", size); 377 if (sysctlbyname("kern.cp_times", times, &size, NULL, 0) == -1) 378 err(1, "sysctlbyname kern.cp_times"); 379 pcpu_cp_time = calloc(1, size); 380 maxid = (size / CPUSTATES / sizeof(long)) - 1; 381 for (i = 0; i <= maxid; i++) { 382 empty = 1; 383 for (j = 0; empty && j < CPUSTATES; j++) { 384 if (times[i * CPUSTATES + j] != 0) 385 empty = 0; 386 } 387 if (!empty) { 388 cpumask |= (1ul << i); 389 ncpus++; 390 } 391 } 392 size = sizeof(long) * ncpus * CPUSTATES; 393 pcpu_cp_old = calloc(1, size); 394 pcpu_cp_diff = calloc(1, size); 395 pcpu_cpu_states = calloc(1, size); 396 statics->ncpus = ncpus; 397 398 update_layout(); 399 400 /* all done! */ 401 return (0); 402 } 403 404 char * 405 format_header(char *uname_field) 406 { 407 static char Header[128]; 408 const char *prehead; 409 410 if (ps.jail) 411 jidlength = TOP_JID_LEN + 1; /* +1 for extra left space. */ 412 else 413 jidlength = 0; 414 415 switch (displaymode) { 416 case DISP_CPU: 417 /* 418 * The logic of picking the right header format seems reverse 419 * here because we only want to display a THR column when 420 * "thread mode" is off (and threads are not listed as 421 * separate lines). 422 */ 423 prehead = smpmode ? 424 (ps.thread ? smp_header : smp_header_thr) : 425 (ps.thread ? up_header : up_header_thr); 426 snprintf(Header, sizeof(Header), prehead, 427 jidlength, ps.jail ? " JID" : "", 428 namelength, namelength, uname_field, 429 ps.wcpu ? "WCPU" : "CPU"); 430 break; 431 case DISP_IO: 432 prehead = io_header; 433 snprintf(Header, sizeof(Header), prehead, 434 jidlength, ps.jail ? " JID" : "", 435 namelength, namelength, uname_field); 436 break; 437 } 438 cmdlengthdelta = strlen(Header) - 7; 439 return (Header); 440 } 441 442 static int swappgsin = -1; 443 static int swappgsout = -1; 444 extern struct timeval timeout; 445 446 447 void 448 get_system_info(struct system_info *si) 449 { 450 long total; 451 struct loadavg sysload; 452 int mib[2]; 453 struct timeval boottime; 454 uint64_t arc_stat, arc_stat2; 455 int i, j; 456 size_t size; 457 458 /* get the CPU stats */ 459 size = (maxid + 1) * CPUSTATES * sizeof(long); 460 if (sysctlbyname("kern.cp_times", pcpu_cp_time, &size, NULL, 0) == -1) 461 err(1, "sysctlbyname kern.cp_times"); 462 GETSYSCTL("kern.cp_time", cp_time); 463 GETSYSCTL("vm.loadavg", sysload); 464 GETSYSCTL("kern.lastpid", lastpid); 465 466 /* convert load averages to doubles */ 467 for (i = 0; i < 3; i++) 468 si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale; 469 470 /* convert cp_time counts to percentages */ 471 for (i = j = 0; i <= maxid; i++) { 472 if ((cpumask & (1ul << i)) == 0) 473 continue; 474 percentages(CPUSTATES, &pcpu_cpu_states[j * CPUSTATES], 475 &pcpu_cp_time[j * CPUSTATES], 476 &pcpu_cp_old[j * CPUSTATES], 477 &pcpu_cp_diff[j * CPUSTATES]); 478 j++; 479 } 480 percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff); 481 482 /* sum memory & swap statistics */ 483 { 484 static unsigned int swap_delay = 0; 485 static int swapavail = 0; 486 static int swapfree = 0; 487 static long bufspace = 0; 488 static int nspgsin, nspgsout; 489 490 GETSYSCTL("vfs.bufspace", bufspace); 491 GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]); 492 GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]); 493 GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]); 494 GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]); 495 GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]); 496 GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin); 497 GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout); 498 /* convert memory stats to Kbytes */ 499 memory_stats[0] = pagetok(memory_stats[0]); 500 memory_stats[1] = pagetok(memory_stats[1]); 501 memory_stats[2] = pagetok(memory_stats[2]); 502 memory_stats[3] = pagetok(memory_stats[3]); 503 memory_stats[4] = bufspace / 1024; 504 memory_stats[5] = pagetok(memory_stats[5]); 505 memory_stats[6] = -1; 506 507 /* first interval */ 508 if (swappgsin < 0) { 509 swap_stats[4] = 0; 510 swap_stats[5] = 0; 511 } 512 513 /* compute differences between old and new swap statistic */ 514 else { 515 swap_stats[4] = pagetok(((nspgsin - swappgsin))); 516 swap_stats[5] = pagetok(((nspgsout - swappgsout))); 517 } 518 519 swappgsin = nspgsin; 520 swappgsout = nspgsout; 521 522 /* call CPU heavy swapmode() only for changes */ 523 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) { 524 swap_stats[3] = swapmode(&swapavail, &swapfree); 525 swap_stats[0] = swapavail; 526 swap_stats[1] = swapavail - swapfree; 527 swap_stats[2] = swapfree; 528 } 529 swap_delay = 1; 530 swap_stats[6] = -1; 531 } 532 533 if (arc_enabled) { 534 GETSYSCTL("kstat.zfs.misc.arcstats.size", arc_stat); 535 arc_stats[0] = arc_stat >> 10; 536 GETSYSCTL("vfs.zfs.mfu_size", arc_stat); 537 arc_stats[1] = arc_stat >> 10; 538 GETSYSCTL("vfs.zfs.mru_size", arc_stat); 539 arc_stats[2] = arc_stat >> 10; 540 GETSYSCTL("vfs.zfs.anon_size", arc_stat); 541 arc_stats[3] = arc_stat >> 10; 542 GETSYSCTL("kstat.zfs.misc.arcstats.hdr_size", arc_stat); 543 GETSYSCTL("kstat.zfs.misc.arcstats.l2_hdr_size", arc_stat2); 544 arc_stats[4] = arc_stat + arc_stat2 >> 10; 545 GETSYSCTL("kstat.zfs.misc.arcstats.other_size", arc_stat); 546 arc_stats[5] = arc_stat >> 10; 547 si->arc = arc_stats; 548 } 549 550 /* set arrays and strings */ 551 if (pcpu_stats) { 552 si->cpustates = pcpu_cpu_states; 553 si->ncpus = ncpus; 554 } else { 555 si->cpustates = cpu_states; 556 si->ncpus = 1; 557 } 558 si->memory = memory_stats; 559 si->swap = swap_stats; 560 561 562 if (lastpid > 0) { 563 si->last_pid = lastpid; 564 } else { 565 si->last_pid = -1; 566 } 567 568 /* 569 * Print how long system has been up. 570 * (Found by looking getting "boottime" from the kernel) 571 */ 572 mib[0] = CTL_KERN; 573 mib[1] = KERN_BOOTTIME; 574 size = sizeof(boottime); 575 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && 576 boottime.tv_sec != 0) { 577 si->boottime = boottime; 578 } else { 579 si->boottime.tv_sec = -1; 580 } 581 } 582 583 #define NOPROC ((void *)-1) 584 585 /* 586 * We need to compare data from the old process entry with the new 587 * process entry. 588 * To facilitate doing this quickly we stash a pointer in the kinfo_proc 589 * structure to cache the mapping. We also use a negative cache pointer 590 * of NOPROC to avoid duplicate lookups. 591 * XXX: this could be done when the actual processes are fetched, we do 592 * it here out of laziness. 593 */ 594 const struct kinfo_proc * 595 get_old_proc(struct kinfo_proc *pp) 596 { 597 struct kinfo_proc **oldpp, *oldp; 598 599 /* 600 * If this is the first fetch of the kinfo_procs then we don't have 601 * any previous entries. 602 */ 603 if (previous_proc_count == 0) 604 return (NULL); 605 /* negative cache? */ 606 if (pp->ki_udata == NOPROC) 607 return (NULL); 608 /* cached? */ 609 if (pp->ki_udata != NULL) 610 return (pp->ki_udata); 611 /* 612 * Not cached, 613 * 1) look up based on pid. 614 * 2) compare process start. 615 * If we fail here, then setup a negative cache entry, otherwise 616 * cache it. 617 */ 618 oldpp = bsearch(&pp, previous_pref, previous_proc_count, 619 sizeof(*previous_pref), ps.thread ? compare_tid : compare_pid); 620 if (oldpp == NULL) { 621 pp->ki_udata = NOPROC; 622 return (NULL); 623 } 624 oldp = *oldpp; 625 if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) { 626 pp->ki_udata = NOPROC; 627 return (NULL); 628 } 629 pp->ki_udata = oldp; 630 return (oldp); 631 } 632 633 /* 634 * Return the total amount of IO done in blocks in/out and faults. 635 * store the values individually in the pointers passed in. 636 */ 637 long 638 get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp, 639 long *vcsw, long *ivcsw) 640 { 641 const struct kinfo_proc *oldp; 642 static struct kinfo_proc dummy; 643 long ret; 644 645 oldp = get_old_proc(pp); 646 if (oldp == NULL) { 647 bzero(&dummy, sizeof(dummy)); 648 oldp = &dummy; 649 } 650 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock; 651 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock; 652 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt; 653 *vcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw; 654 *ivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw; 655 ret = 656 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) + 657 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) + 658 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt); 659 return (ret); 660 } 661 662 /* 663 * If there was a previous update, use the delta in ki_runtime over 664 * the previous interval to calculate pctcpu. Otherwise, fall back 665 * to using the kernel's ki_pctcpu. 666 */ 667 static double 668 proc_calc_pctcpu(struct kinfo_proc *pp) 669 { 670 const struct kinfo_proc *oldp; 671 672 if (previous_interval != 0) { 673 oldp = get_old_proc(pp); 674 if (oldp != NULL) 675 return ((double)(pp->ki_runtime - oldp->ki_runtime) 676 / previous_interval); 677 678 /* 679 * If this process/thread was created during the previous 680 * interval, charge it's total runtime to the previous 681 * interval. 682 */ 683 else if (pp->ki_start.tv_sec > previous_wall_time.tv_sec || 684 (pp->ki_start.tv_sec == previous_wall_time.tv_sec && 685 pp->ki_start.tv_usec >= previous_wall_time.tv_usec)) 686 return ((double)pp->ki_runtime / previous_interval); 687 } 688 return (pctdouble(pp->ki_pctcpu)); 689 } 690 691 /* 692 * Return true if this process has used any CPU time since the 693 * previous update. 694 */ 695 static int 696 proc_used_cpu(struct kinfo_proc *pp) 697 { 698 const struct kinfo_proc *oldp; 699 700 oldp = get_old_proc(pp); 701 if (oldp == NULL) 702 return (PCTCPU(pp) != 0); 703 return (pp->ki_runtime != oldp->ki_runtime || 704 RU(pp)->ru_nvcsw != RU(oldp)->ru_nvcsw || 705 RU(pp)->ru_nivcsw != RU(oldp)->ru_nivcsw); 706 } 707 708 /* 709 * Return the total number of block in/out and faults by a process. 710 */ 711 long 712 get_io_total(struct kinfo_proc *pp) 713 { 714 long dummy; 715 716 return (get_io_stats(pp, &dummy, &dummy, &dummy, &dummy, &dummy)); 717 } 718 719 static struct handle handle; 720 721 caddr_t 722 get_process_info(struct system_info *si, struct process_select *sel, 723 int (*compare)(const void *, const void *)) 724 { 725 int i; 726 int total_procs; 727 long p_io; 728 long p_inblock, p_oublock, p_majflt, p_vcsw, p_ivcsw; 729 long nsec; 730 int active_procs; 731 struct kinfo_proc **prefp; 732 struct kinfo_proc *pp; 733 struct timespec previous_proc_uptime; 734 735 /* these are copied out of sel for speed */ 736 int show_idle; 737 int show_jid; 738 int show_self; 739 int show_system; 740 int show_uid; 741 int show_command; 742 int show_kidle; 743 744 /* 745 * If thread state was toggled, don't cache the previous processes. 746 */ 747 if (previous_thread != sel->thread) 748 nproc = 0; 749 previous_thread = sel->thread; 750 751 /* 752 * Save the previous process info. 753 */ 754 if (previous_proc_count_max < nproc) { 755 free(previous_procs); 756 previous_procs = malloc(nproc * sizeof(*previous_procs)); 757 free(previous_pref); 758 previous_pref = malloc(nproc * sizeof(*previous_pref)); 759 if (previous_procs == NULL || previous_pref == NULL) { 760 (void) fprintf(stderr, "top: Out of memory.\n"); 761 quit(23); 762 } 763 previous_proc_count_max = nproc; 764 } 765 if (nproc) { 766 for (i = 0; i < nproc; i++) 767 previous_pref[i] = &previous_procs[i]; 768 bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs)); 769 qsort(previous_pref, nproc, sizeof(*previous_pref), 770 ps.thread ? compare_tid : compare_pid); 771 } 772 previous_proc_count = nproc; 773 previous_proc_uptime = proc_uptime; 774 previous_wall_time = proc_wall_time; 775 previous_interval = 0; 776 777 pbase = kvm_getprocs(kd, sel->thread ? KERN_PROC_ALL : KERN_PROC_PROC, 778 0, &nproc); 779 (void)gettimeofday(&proc_wall_time, NULL); 780 if (clock_gettime(CLOCK_UPTIME, &proc_uptime) != 0) 781 memset(&proc_uptime, 0, sizeof(proc_uptime)); 782 else if (previous_proc_uptime.tv_sec != 0 && 783 previous_proc_uptime.tv_nsec != 0) { 784 previous_interval = (proc_uptime.tv_sec - 785 previous_proc_uptime.tv_sec) * 1000000; 786 nsec = proc_uptime.tv_nsec - previous_proc_uptime.tv_nsec; 787 if (nsec < 0) { 788 previous_interval -= 1000000; 789 nsec += 1000000000; 790 } 791 previous_interval += nsec / 1000; 792 } 793 if (nproc > onproc) { 794 pref = realloc(pref, sizeof(*pref) * nproc); 795 pcpu = realloc(pcpu, sizeof(*pcpu) * nproc); 796 onproc = nproc; 797 } 798 if (pref == NULL || pbase == NULL || pcpu == NULL) { 799 (void) fprintf(stderr, "top: Out of memory.\n"); 800 quit(23); 801 } 802 /* get a pointer to the states summary array */ 803 si->procstates = process_states; 804 805 /* set up flags which define what we are going to select */ 806 show_idle = sel->idle; 807 show_jid = sel->jid != -1; 808 show_self = sel->self == -1; 809 show_system = sel->system; 810 show_uid = sel->uid != -1; 811 show_command = sel->command != NULL; 812 show_kidle = sel->kidle; 813 814 /* count up process states and get pointers to interesting procs */ 815 total_procs = 0; 816 active_procs = 0; 817 total_inblock = 0; 818 total_oublock = 0; 819 total_majflt = 0; 820 memset((char *)process_states, 0, sizeof(process_states)); 821 prefp = pref; 822 for (pp = pbase, i = 0; i < nproc; pp++, i++) { 823 824 if (pp->ki_stat == 0) 825 /* not in use */ 826 continue; 827 828 if (!show_self && pp->ki_pid == sel->self) 829 /* skip self */ 830 continue; 831 832 if (!show_system && (pp->ki_flag & P_SYSTEM)) 833 /* skip system process */ 834 continue; 835 836 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt, 837 &p_vcsw, &p_ivcsw); 838 total_inblock += p_inblock; 839 total_oublock += p_oublock; 840 total_majflt += p_majflt; 841 total_procs++; 842 process_states[pp->ki_stat]++; 843 844 if (pp->ki_stat == SZOMB) 845 /* skip zombies */ 846 continue; 847 848 if (!show_kidle && pp->ki_tdflags & TDF_IDLETD) 849 /* skip kernel idle process */ 850 continue; 851 852 PCTCPU(pp) = proc_calc_pctcpu(pp); 853 if (displaymode == DISP_CPU && !show_idle && 854 (!proc_used_cpu(pp) || 855 pp->ki_stat == SSTOP || pp->ki_stat == SIDL)) 856 /* skip idle or non-running processes */ 857 continue; 858 859 if (displaymode == DISP_IO && !show_idle && p_io == 0) 860 /* skip processes that aren't doing I/O */ 861 continue; 862 863 if (show_jid && pp->ki_jid != sel->jid) 864 /* skip proc. that don't belong to the selected JID */ 865 continue; 866 867 if (show_uid && pp->ki_ruid != (uid_t)sel->uid) 868 /* skip proc. that don't belong to the selected UID */ 869 continue; 870 871 *prefp++ = pp; 872 active_procs++; 873 } 874 875 /* if requested, sort the "interesting" processes */ 876 if (compare != NULL) 877 qsort(pref, active_procs, sizeof(*pref), compare); 878 879 /* remember active and total counts */ 880 si->p_total = total_procs; 881 si->p_active = pref_len = active_procs; 882 883 /* pass back a handle */ 884 handle.next_proc = pref; 885 handle.remaining = active_procs; 886 return ((caddr_t)&handle); 887 } 888 889 static char fmt[512]; /* static area where result is built */ 890 891 char * 892 format_next_process(caddr_t handle, char *(*get_userid)(int), int flags) 893 { 894 struct kinfo_proc *pp; 895 const struct kinfo_proc *oldp; 896 long cputime; 897 double pct; 898 struct handle *hp; 899 char status[16]; 900 int cpu, state; 901 struct rusage ru, *rup; 902 long p_tot, s_tot; 903 char *proc_fmt, thr_buf[6], jid_buf[TOP_JID_LEN + 1]; 904 char *cmdbuf = NULL; 905 char **args; 906 const int cmdlen = 128; 907 908 /* find and remember the next proc structure */ 909 hp = (struct handle *)handle; 910 pp = *(hp->next_proc++); 911 hp->remaining--; 912 913 /* get the process's command name */ 914 if ((pp->ki_flag & P_INMEM) == 0) { 915 /* 916 * Print swapped processes as <pname> 917 */ 918 size_t len; 919 920 len = strlen(pp->ki_comm); 921 if (len > sizeof(pp->ki_comm) - 3) 922 len = sizeof(pp->ki_comm) - 3; 923 memmove(pp->ki_comm + 1, pp->ki_comm, len); 924 pp->ki_comm[0] = '<'; 925 pp->ki_comm[len + 1] = '>'; 926 pp->ki_comm[len + 2] = '\0'; 927 } 928 929 /* 930 * Convert the process's runtime from microseconds to seconds. This 931 * time includes the interrupt time although that is not wanted here. 932 * ps(1) is similarly sloppy. 933 */ 934 cputime = (pp->ki_runtime + 500000) / 1000000; 935 936 /* calculate the base for cpu percentages */ 937 pct = PCTCPU(pp); 938 939 /* generate "STATE" field */ 940 switch (state = pp->ki_stat) { 941 case SRUN: 942 if (smpmode && pp->ki_oncpu != 0xff) 943 sprintf(status, "CPU%d", pp->ki_oncpu); 944 else 945 strcpy(status, "RUN"); 946 break; 947 case SLOCK: 948 if (pp->ki_kiflag & KI_LOCKBLOCK) { 949 sprintf(status, "*%.6s", pp->ki_lockname); 950 break; 951 } 952 /* fall through */ 953 case SSLEEP: 954 if (pp->ki_wmesg != NULL) { 955 sprintf(status, "%.6s", pp->ki_wmesg); 956 break; 957 } 958 /* FALLTHROUGH */ 959 default: 960 961 if (state >= 0 && 962 state < sizeof(state_abbrev) / sizeof(*state_abbrev)) 963 sprintf(status, "%.6s", state_abbrev[state]); 964 else 965 sprintf(status, "?%5d", state); 966 break; 967 } 968 969 cmdbuf = (char *)malloc(cmdlen + 1); 970 if (cmdbuf == NULL) { 971 warn("malloc(%d)", cmdlen + 1); 972 return NULL; 973 } 974 975 if (!(flags & FMT_SHOWARGS)) { 976 if (ps.thread && pp->ki_flag & P_HADTHREADS && 977 pp->ki_tdname[0]) { 978 snprintf(cmdbuf, cmdlen, "%s{%s}", pp->ki_comm, 979 pp->ki_tdname); 980 } else { 981 snprintf(cmdbuf, cmdlen, "%s", pp->ki_comm); 982 } 983 } else { 984 if (pp->ki_flag & P_SYSTEM || 985 pp->ki_args == NULL || 986 (args = kvm_getargv(kd, pp, cmdlen)) == NULL || 987 !(*args)) { 988 if (ps.thread && pp->ki_flag & P_HADTHREADS && 989 pp->ki_tdname[0]) { 990 snprintf(cmdbuf, cmdlen, 991 "[%s{%s}]", pp->ki_comm, pp->ki_tdname); 992 } else { 993 snprintf(cmdbuf, cmdlen, 994 "[%s]", pp->ki_comm); 995 } 996 } else { 997 char *src, *dst, *argbuf; 998 char *cmd; 999 size_t argbuflen; 1000 size_t len; 1001 1002 argbuflen = cmdlen * 4; 1003 argbuf = (char *)malloc(argbuflen + 1); 1004 if (argbuf == NULL) { 1005 warn("malloc(%zd)", argbuflen + 1); 1006 free(cmdbuf); 1007 return NULL; 1008 } 1009 1010 dst = argbuf; 1011 1012 /* Extract cmd name from argv */ 1013 cmd = strrchr(*args, '/'); 1014 if (cmd == NULL) 1015 cmd = *args; 1016 else 1017 cmd++; 1018 1019 for (; (src = *args++) != NULL; ) { 1020 if (*src == '\0') 1021 continue; 1022 len = (argbuflen - (dst - argbuf) - 1) / 4; 1023 strvisx(dst, src, 1024 strlen(src) < len ? strlen(src) : len, 1025 VIS_NL | VIS_CSTYLE); 1026 while (*dst != '\0') 1027 dst++; 1028 if ((argbuflen - (dst - argbuf) - 1) / 4 > 0) 1029 *dst++ = ' '; /* add delimiting space */ 1030 } 1031 if (dst != argbuf && dst[-1] == ' ') 1032 dst--; 1033 *dst = '\0'; 1034 1035 if (strcmp(cmd, pp->ki_comm) != 0) { 1036 if (ps.thread && pp->ki_flag & P_HADTHREADS && 1037 pp->ki_tdname[0]) 1038 snprintf(cmdbuf, cmdlen, 1039 "%s (%s){%s}", argbuf, pp->ki_comm, 1040 pp->ki_tdname); 1041 else 1042 snprintf(cmdbuf, cmdlen, 1043 "%s (%s)", argbuf, pp->ki_comm); 1044 } else { 1045 if (ps.thread && pp->ki_flag & P_HADTHREADS && 1046 pp->ki_tdname[0]) 1047 snprintf(cmdbuf, cmdlen, 1048 "%s{%s}", argbuf, pp->ki_tdname); 1049 else 1050 strlcpy(cmdbuf, argbuf, cmdlen); 1051 } 1052 free(argbuf); 1053 } 1054 } 1055 1056 if (ps.jail == 0) 1057 jid_buf[0] = '\0'; 1058 else 1059 snprintf(jid_buf, sizeof(jid_buf), "%*d", 1060 jidlength - 1, pp->ki_jid); 1061 1062 if (displaymode == DISP_IO) { 1063 oldp = get_old_proc(pp); 1064 if (oldp != NULL) { 1065 ru.ru_inblock = RU(pp)->ru_inblock - 1066 RU(oldp)->ru_inblock; 1067 ru.ru_oublock = RU(pp)->ru_oublock - 1068 RU(oldp)->ru_oublock; 1069 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt; 1070 ru.ru_nvcsw = RU(pp)->ru_nvcsw - RU(oldp)->ru_nvcsw; 1071 ru.ru_nivcsw = RU(pp)->ru_nivcsw - RU(oldp)->ru_nivcsw; 1072 rup = &ru; 1073 } else { 1074 rup = RU(pp); 1075 } 1076 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt; 1077 s_tot = total_inblock + total_oublock + total_majflt; 1078 1079 snprintf(fmt, sizeof(fmt), io_Proc_format, 1080 pp->ki_pid, 1081 jidlength, jid_buf, 1082 namelength, namelength, (*get_userid)(pp->ki_ruid), 1083 rup->ru_nvcsw, 1084 rup->ru_nivcsw, 1085 rup->ru_inblock, 1086 rup->ru_oublock, 1087 rup->ru_majflt, 1088 p_tot, 1089 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot), 1090 screen_width > cmdlengthdelta ? 1091 screen_width - cmdlengthdelta : 0, 1092 printable(cmdbuf)); 1093 1094 free(cmdbuf); 1095 1096 return (fmt); 1097 } 1098 1099 /* format this entry */ 1100 if (smpmode) { 1101 if (state == SRUN && pp->ki_oncpu != 0xff) 1102 cpu = pp->ki_oncpu; 1103 else 1104 cpu = pp->ki_lastcpu; 1105 } else 1106 cpu = 0; 1107 proc_fmt = smpmode ? smp_Proc_format : up_Proc_format; 1108 if (ps.thread != 0) 1109 thr_buf[0] = '\0'; 1110 else 1111 snprintf(thr_buf, sizeof(thr_buf), "%*d ", 1112 (int)(sizeof(thr_buf) - 2), pp->ki_numthreads); 1113 1114 snprintf(fmt, sizeof(fmt), proc_fmt, 1115 pp->ki_pid, 1116 jidlength, jid_buf, 1117 namelength, namelength, (*get_userid)(pp->ki_ruid), 1118 thr_buf, 1119 pp->ki_pri.pri_level - PZERO, 1120 format_nice(pp), 1121 format_k2(PROCSIZE(pp)), 1122 format_k2(pagetok(pp->ki_rssize)), 1123 status, 1124 cpu, 1125 format_time(cputime), 1126 ps.wcpu ? 100.0 * weighted_cpu(pct, pp) : 100.0 * pct, 1127 screen_width > cmdlengthdelta ? screen_width - cmdlengthdelta : 0, 1128 printable(cmdbuf)); 1129 1130 free(cmdbuf); 1131 1132 /* return the result */ 1133 return (fmt); 1134 } 1135 1136 static void 1137 getsysctl(const char *name, void *ptr, size_t len) 1138 { 1139 size_t nlen = len; 1140 1141 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) { 1142 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name, 1143 strerror(errno)); 1144 quit(23); 1145 } 1146 if (nlen != len) { 1147 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", 1148 name, (unsigned long)len, (unsigned long)nlen); 1149 quit(23); 1150 } 1151 } 1152 1153 static const char * 1154 format_nice(const struct kinfo_proc *pp) 1155 { 1156 const char *fifo, *kthread; 1157 int rtpri; 1158 static char nicebuf[4 + 1]; 1159 1160 fifo = PRI_NEED_RR(pp->ki_pri.pri_class) ? "" : "F"; 1161 kthread = (pp->ki_flag & P_KTHREAD) ? "k" : ""; 1162 switch (PRI_BASE(pp->ki_pri.pri_class)) { 1163 case PRI_ITHD: 1164 return ("-"); 1165 case PRI_REALTIME: 1166 /* 1167 * XXX: the kernel doesn't tell us the original rtprio and 1168 * doesn't really know what it was, so to recover it we 1169 * must be more chummy with the implementation than the 1170 * implementation is with itself. pri_user gives a 1171 * constant "base" priority, but is only initialized 1172 * properly for user threads. pri_native gives what the 1173 * kernel calls the "base" priority, but it isn't constant 1174 * since it is changed by priority propagation. pri_native 1175 * also isn't properly initialized for all threads, but it 1176 * is properly initialized for kernel realtime and idletime 1177 * threads. Thus we use pri_user for the base priority of 1178 * user threads (it is always correct) and pri_native for 1179 * the base priority of kernel realtime and idletime threads 1180 * (there is nothing better, and it is usually correct). 1181 * 1182 * The field width and thus the buffer are too small for 1183 * values like "kr31F", but such values shouldn't occur, 1184 * and if they do then the tailing "F" is not displayed. 1185 */ 1186 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native : 1187 pp->ki_pri.pri_user) - PRI_MIN_REALTIME; 1188 snprintf(nicebuf, sizeof(nicebuf), "%sr%d%s", 1189 kthread, rtpri, fifo); 1190 break; 1191 case PRI_TIMESHARE: 1192 if (pp->ki_flag & P_KTHREAD) 1193 return ("-"); 1194 snprintf(nicebuf, sizeof(nicebuf), "%d", pp->ki_nice - NZERO); 1195 break; 1196 case PRI_IDLE: 1197 /* XXX: as above. */ 1198 rtpri = ((pp->ki_flag & P_KTHREAD) ? pp->ki_pri.pri_native : 1199 pp->ki_pri.pri_user) - PRI_MIN_IDLE; 1200 snprintf(nicebuf, sizeof(nicebuf), "%si%d%s", 1201 kthread, rtpri, fifo); 1202 break; 1203 default: 1204 return ("?"); 1205 } 1206 return (nicebuf); 1207 } 1208 1209 /* comparison routines for qsort */ 1210 1211 static int 1212 compare_pid(const void *p1, const void *p2) 1213 { 1214 const struct kinfo_proc * const *pp1 = p1; 1215 const struct kinfo_proc * const *pp2 = p2; 1216 1217 if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0) 1218 abort(); 1219 1220 return ((*pp1)->ki_pid - (*pp2)->ki_pid); 1221 } 1222 1223 static int 1224 compare_tid(const void *p1, const void *p2) 1225 { 1226 const struct kinfo_proc * const *pp1 = p1; 1227 const struct kinfo_proc * const *pp2 = p2; 1228 1229 if ((*pp2)->ki_tid < 0 || (*pp1)->ki_tid < 0) 1230 abort(); 1231 1232 return ((*pp1)->ki_tid - (*pp2)->ki_tid); 1233 } 1234 1235 /* 1236 * proc_compare - comparison function for "qsort" 1237 * Compares the resource consumption of two processes using five 1238 * distinct keys. The keys (in descending order of importance) are: 1239 * percent cpu, cpu ticks, state, resident set size, total virtual 1240 * memory usage. The process states are ordered as follows (from least 1241 * to most important): WAIT, zombie, sleep, stop, start, run. The 1242 * array declaration below maps a process state index into a number 1243 * that reflects this ordering. 1244 */ 1245 1246 static int sorted_state[] = { 1247 0, /* not used */ 1248 3, /* sleep */ 1249 1, /* ABANDONED (WAIT) */ 1250 6, /* run */ 1251 5, /* start */ 1252 2, /* zombie */ 1253 4 /* stop */ 1254 }; 1255 1256 1257 #define ORDERKEY_PCTCPU(a, b) do { \ 1258 double diff; \ 1259 if (ps.wcpu) \ 1260 diff = weighted_cpu(PCTCPU((b)), (b)) - \ 1261 weighted_cpu(PCTCPU((a)), (a)); \ 1262 else \ 1263 diff = PCTCPU((b)) - PCTCPU((a)); \ 1264 if (diff != 0) \ 1265 return (diff > 0 ? 1 : -1); \ 1266 } while (0) 1267 1268 #define ORDERKEY_CPTICKS(a, b) do { \ 1269 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \ 1270 if (diff != 0) \ 1271 return (diff > 0 ? 1 : -1); \ 1272 } while (0) 1273 1274 #define ORDERKEY_STATE(a, b) do { \ 1275 int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \ 1276 if (diff != 0) \ 1277 return (diff > 0 ? 1 : -1); \ 1278 } while (0) 1279 1280 #define ORDERKEY_PRIO(a, b) do { \ 1281 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \ 1282 if (diff != 0) \ 1283 return (diff > 0 ? 1 : -1); \ 1284 } while (0) 1285 1286 #define ORDERKEY_THREADS(a, b) do { \ 1287 int diff = (int)(b)->ki_numthreads - (int)(a)->ki_numthreads; \ 1288 if (diff != 0) \ 1289 return (diff > 0 ? 1 : -1); \ 1290 } while (0) 1291 1292 #define ORDERKEY_RSSIZE(a, b) do { \ 1293 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \ 1294 if (diff != 0) \ 1295 return (diff > 0 ? 1 : -1); \ 1296 } while (0) 1297 1298 #define ORDERKEY_MEM(a, b) do { \ 1299 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \ 1300 if (diff != 0) \ 1301 return (diff > 0 ? 1 : -1); \ 1302 } while (0) 1303 1304 #define ORDERKEY_JID(a, b) do { \ 1305 int diff = (int)(b)->ki_jid - (int)(a)->ki_jid; \ 1306 if (diff != 0) \ 1307 return (diff > 0 ? 1 : -1); \ 1308 } while (0) 1309 1310 /* compare_cpu - the comparison function for sorting by cpu percentage */ 1311 1312 int 1313 #ifdef ORDER 1314 compare_cpu(void *arg1, void *arg2) 1315 #else 1316 proc_compare(void *arg1, void *arg2) 1317 #endif 1318 { 1319 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1320 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1321 1322 ORDERKEY_PCTCPU(p1, p2); 1323 ORDERKEY_CPTICKS(p1, p2); 1324 ORDERKEY_STATE(p1, p2); 1325 ORDERKEY_PRIO(p1, p2); 1326 ORDERKEY_RSSIZE(p1, p2); 1327 ORDERKEY_MEM(p1, p2); 1328 1329 return (0); 1330 } 1331 1332 #ifdef ORDER 1333 /* "cpu" compare routines */ 1334 int compare_size(), compare_res(), compare_time(), compare_prio(), 1335 compare_threads(); 1336 1337 /* 1338 * "io" compare routines. Context switches aren't i/o, but are displayed 1339 * on the "io" display. 1340 */ 1341 int compare_iototal(), compare_ioread(), compare_iowrite(), compare_iofault(), 1342 compare_vcsw(), compare_ivcsw(); 1343 1344 int (*compares[])() = { 1345 compare_cpu, 1346 compare_size, 1347 compare_res, 1348 compare_time, 1349 compare_prio, 1350 compare_threads, 1351 compare_iototal, 1352 compare_ioread, 1353 compare_iowrite, 1354 compare_iofault, 1355 compare_vcsw, 1356 compare_ivcsw, 1357 compare_jid, 1358 NULL 1359 }; 1360 1361 /* compare_size - the comparison function for sorting by total memory usage */ 1362 1363 int 1364 compare_size(void *arg1, void *arg2) 1365 { 1366 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1367 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1368 1369 ORDERKEY_MEM(p1, p2); 1370 ORDERKEY_RSSIZE(p1, p2); 1371 ORDERKEY_PCTCPU(p1, p2); 1372 ORDERKEY_CPTICKS(p1, p2); 1373 ORDERKEY_STATE(p1, p2); 1374 ORDERKEY_PRIO(p1, p2); 1375 1376 return (0); 1377 } 1378 1379 /* compare_res - the comparison function for sorting by resident set size */ 1380 1381 int 1382 compare_res(void *arg1, void *arg2) 1383 { 1384 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1385 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1386 1387 ORDERKEY_RSSIZE(p1, p2); 1388 ORDERKEY_MEM(p1, p2); 1389 ORDERKEY_PCTCPU(p1, p2); 1390 ORDERKEY_CPTICKS(p1, p2); 1391 ORDERKEY_STATE(p1, p2); 1392 ORDERKEY_PRIO(p1, p2); 1393 1394 return (0); 1395 } 1396 1397 /* compare_time - the comparison function for sorting by total cpu time */ 1398 1399 int 1400 compare_time(void *arg1, void *arg2) 1401 { 1402 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1403 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1404 1405 ORDERKEY_CPTICKS(p1, p2); 1406 ORDERKEY_PCTCPU(p1, p2); 1407 ORDERKEY_STATE(p1, p2); 1408 ORDERKEY_PRIO(p1, p2); 1409 ORDERKEY_RSSIZE(p1, p2); 1410 ORDERKEY_MEM(p1, p2); 1411 1412 return (0); 1413 } 1414 1415 /* compare_prio - the comparison function for sorting by priority */ 1416 1417 int 1418 compare_prio(void *arg1, void *arg2) 1419 { 1420 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1421 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1422 1423 ORDERKEY_PRIO(p1, p2); 1424 ORDERKEY_CPTICKS(p1, p2); 1425 ORDERKEY_PCTCPU(p1, p2); 1426 ORDERKEY_STATE(p1, p2); 1427 ORDERKEY_RSSIZE(p1, p2); 1428 ORDERKEY_MEM(p1, p2); 1429 1430 return (0); 1431 } 1432 1433 /* compare_threads - the comparison function for sorting by threads */ 1434 int 1435 compare_threads(void *arg1, void *arg2) 1436 { 1437 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1438 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1439 1440 ORDERKEY_THREADS(p1, p2); 1441 ORDERKEY_PCTCPU(p1, p2); 1442 ORDERKEY_CPTICKS(p1, p2); 1443 ORDERKEY_STATE(p1, p2); 1444 ORDERKEY_PRIO(p1, p2); 1445 ORDERKEY_RSSIZE(p1, p2); 1446 ORDERKEY_MEM(p1, p2); 1447 1448 return (0); 1449 } 1450 1451 /* compare_jid - the comparison function for sorting by jid */ 1452 static int 1453 compare_jid(const void *arg1, const void *arg2) 1454 { 1455 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1456 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1457 1458 ORDERKEY_JID(p1, p2); 1459 ORDERKEY_PCTCPU(p1, p2); 1460 ORDERKEY_CPTICKS(p1, p2); 1461 ORDERKEY_STATE(p1, p2); 1462 ORDERKEY_PRIO(p1, p2); 1463 ORDERKEY_RSSIZE(p1, p2); 1464 ORDERKEY_MEM(p1, p2); 1465 1466 return (0); 1467 } 1468 #endif /* ORDER */ 1469 1470 /* assorted comparison functions for sorting by i/o */ 1471 1472 int 1473 #ifdef ORDER 1474 compare_iototal(void *arg1, void *arg2) 1475 #else 1476 io_compare(void *arg1, void *arg2) 1477 #endif 1478 { 1479 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1480 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1481 1482 return (get_io_total(p2) - get_io_total(p1)); 1483 } 1484 1485 #ifdef ORDER 1486 int 1487 compare_ioread(void *arg1, void *arg2) 1488 { 1489 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1490 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1491 long dummy, inp1, inp2; 1492 1493 (void) get_io_stats(p1, &inp1, &dummy, &dummy, &dummy, &dummy); 1494 (void) get_io_stats(p2, &inp2, &dummy, &dummy, &dummy, &dummy); 1495 1496 return (inp2 - inp1); 1497 } 1498 1499 int 1500 compare_iowrite(void *arg1, void *arg2) 1501 { 1502 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1503 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1504 long dummy, oup1, oup2; 1505 1506 (void) get_io_stats(p1, &dummy, &oup1, &dummy, &dummy, &dummy); 1507 (void) get_io_stats(p2, &dummy, &oup2, &dummy, &dummy, &dummy); 1508 1509 return (oup2 - oup1); 1510 } 1511 1512 int 1513 compare_iofault(void *arg1, void *arg2) 1514 { 1515 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1516 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1517 long dummy, flp1, flp2; 1518 1519 (void) get_io_stats(p1, &dummy, &dummy, &flp1, &dummy, &dummy); 1520 (void) get_io_stats(p2, &dummy, &dummy, &flp2, &dummy, &dummy); 1521 1522 return (flp2 - flp1); 1523 } 1524 1525 int 1526 compare_vcsw(void *arg1, void *arg2) 1527 { 1528 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1529 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1530 long dummy, flp1, flp2; 1531 1532 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &flp1, &dummy); 1533 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &flp2, &dummy); 1534 1535 return (flp2 - flp1); 1536 } 1537 1538 int 1539 compare_ivcsw(void *arg1, void *arg2) 1540 { 1541 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1542 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1543 long dummy, flp1, flp2; 1544 1545 (void) get_io_stats(p1, &dummy, &dummy, &dummy, &dummy, &flp1); 1546 (void) get_io_stats(p2, &dummy, &dummy, &dummy, &dummy, &flp2); 1547 1548 return (flp2 - flp1); 1549 } 1550 #endif /* ORDER */ 1551 1552 /* 1553 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if 1554 * the process does not exist. 1555 * It is EXTREMELY IMPORTANT that this function work correctly. 1556 * If top runs setuid root (as in SVR4), then this function 1557 * is the only thing that stands in the way of a serious 1558 * security problem. It validates requests for the "kill" 1559 * and "renice" commands. 1560 */ 1561 1562 int 1563 proc_owner(int pid) 1564 { 1565 int cnt; 1566 struct kinfo_proc **prefp; 1567 struct kinfo_proc *pp; 1568 1569 prefp = pref; 1570 cnt = pref_len; 1571 while (--cnt >= 0) { 1572 pp = *prefp++; 1573 if (pp->ki_pid == (pid_t)pid) 1574 return ((int)pp->ki_ruid); 1575 } 1576 return (-1); 1577 } 1578 1579 static int 1580 swapmode(int *retavail, int *retfree) 1581 { 1582 int n; 1583 int pagesize = getpagesize(); 1584 struct kvm_swap swapary[1]; 1585 1586 *retavail = 0; 1587 *retfree = 0; 1588 1589 #define CONVERT(v) ((quad_t)(v) * pagesize / 1024) 1590 1591 n = kvm_getswapinfo(kd, swapary, 1, 0); 1592 if (n < 0 || swapary[0].ksw_total == 0) 1593 return (0); 1594 1595 *retavail = CONVERT(swapary[0].ksw_total); 1596 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used); 1597 1598 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total); 1599 return (n); 1600 } 1601