machine.c revision 132015
1238438Sdteske/* 2238438Sdteske * top - a top users display for Unix 3249746Sdteske * 4238438Sdteske * SYNOPSIS: For FreeBSD-2.x and later 5238438Sdteske * 6238438Sdteske * DESCRIPTION: 7238438Sdteske * Originally written for BSD4.4 system by Christos Zoulas. 8238438Sdteske * Ported to FreeBSD 2.x by Steven Wallace && Wolfram Schneider 9238438Sdteske * Order support hacked in from top-3.5beta6/machine/m_aix41.c 10238438Sdteske * by Monte Mitzelfelt (for latest top see http://www.groupsys.com/topinfo/) 11238438Sdteske * 12238438Sdteske * This is the machine-dependent module for FreeBSD 2.2 13238438Sdteske * Works for: 14238438Sdteske * FreeBSD 2.2.x, 3.x, 4.x, and probably FreeBSD 2.1.x 15238438Sdteske * 16238438Sdteske * LIBS: -lkvm 17238438Sdteske * 18238438Sdteske * AUTHOR: Christos Zoulas <christos@ee.cornell.edu> 19238438Sdteske * Steven Wallace <swallace@freebsd.org> 20238438Sdteske * Wolfram Schneider <wosch@FreeBSD.org> 21238438Sdteske * Thomas Moestl <tmoestl@gmx.net> 22238438Sdteske * 23238438Sdteske * $FreeBSD: head/usr.bin/top/machine.c 132015 2004-07-12 04:55:07Z alfred $ 24238438Sdteske */ 25238438Sdteske 26238438Sdteske#include <sys/param.h> 27238438Sdteske#include <sys/errno.h> 28238438Sdteske#include <sys/file.h> 29238438Sdteske#include <sys/proc.h> 30238438Sdteske#include <sys/resource.h> 31240684Sdteske#include <sys/rtprio.h> 32240684Sdteske#include <sys/signal.h> 33244675Sdteske#include <sys/sysctl.h> 34240684Sdteske#include <sys/time.h> 35240684Sdteske#include <sys/user.h> 36240684Sdteske#include <sys/vmmeter.h> 37240684Sdteske 38238438Sdteske#include <kvm.h> 39240684Sdteske#include <math.h> 40238438Sdteske#include <nlist.h> 41238438Sdteske#include <paths.h> 42243112Sdteske#include <pwd.h> 43238438Sdteske#include <stdio.h> 44238438Sdteske#include <stdlib.h> 45238438Sdteske#include <unistd.h> 46238438Sdteske 47238438Sdteske#include "top.h" 48238438Sdteske#include "machine.h" 49238438Sdteske#include "screen.h" 50238438Sdteske#include "utils.h" 51238438Sdteske 52238438Sdteskestatic void getsysctl(char *, void *, size_t); 53238438Sdteske 54238438Sdteske#define GETSYSCTL(name, var) getsysctl(name, &(var), sizeof(var)) 55238438Sdteske 56238438Sdteskeextern char* printable(char *); 57240798Sdteskeint swapmode(int *retavail, int *retfree); 58238438Sdteskestatic int smpmode; 59238438Sdteskeenum displaymodes displaymode; 60238438Sdteskestatic int namelength; 61238438Sdteskestatic int cmdlengthdelta; 62238438Sdteske 63238438Sdteske/* Prototypes for top internals */ 64238438Sdteskevoid quit(int); 65238438Sdteskeint compare_pid(const void *a, const void *b); 66238438Sdteske 67238438Sdteske/* get_process_info passes back a handle. This is what it looks like: */ 68238438Sdteske 69238438Sdteskestruct handle 70238438Sdteske{ 71238438Sdteske struct kinfo_proc **next_proc; /* points to next valid proc pointer */ 72238438Sdteske int remaining; /* number of pointers remaining */ 73238438Sdteske}; 74238438Sdteske 75249751Sdteske/* declarations for load_avg */ 76238438Sdteske#include "loadavg.h" 77249751Sdteske 78249751Sdteske/* define what weighted cpu is. */ 79249751Sdteske#define weighted_cpu(pct, pp) ((pp)->ki_swtime == 0 ? 0.0 : \ 80238438Sdteske ((pct) / (1.0 - exp((pp)->ki_swtime * logcpu)))) 81249751Sdteske 82238438Sdteske/* what we consider to be process size: */ 83238438Sdteske#define PROCSIZE(pp) ((pp)->ki_size / 1024) 84238438Sdteske 85238438Sdteske#define RU(pp) (&(pp)->ki_rusage) 86238438Sdteske#define RUTOT(pp) \ 87249751Sdteske (RU(pp)->ru_inblock + RU(pp)->ru_oublock + RU(pp)->ru_majflt) 88240783Sdteske 89240783Sdteske 90238438Sdteske/* definitions for indices in the nlist array */ 91238438Sdteske 92238438Sdteske/* 93238438Sdteske * These definitions control the format of the per-process area 94238438Sdteske */ 95238438Sdteske 96238438Sdteskestatic char io_header[] = 97238438Sdteske " PID %-*.*s READ WRITE FAULT TOTAL PERCENT COMMAND"; 98238438Sdteske 99238438Sdteske#define io_Proc_format \ 100238438Sdteske "%5d %-*.*s %6ld %6ld %6ld %6ld %6.2f%% %.*s" 101238438Sdteske 102238438Sdteskestatic char smp_header[] = 103238438Sdteske " PID %-*.*s PRI NICE SIZE RES STATE C TIME WCPU CPU COMMAND"; 104238438Sdteske 105238438Sdteske#define smp_Proc_format \ 106238438Sdteske "%5d %-*.*s %3d %4d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s" 107238438Sdteske 108238438Sdteskestatic char up_header[] = 109238438Sdteske " PID %-*.*s PRI NICE SIZE RES STATE TIME WCPU CPU COMMAND"; 110238438Sdteske 111238438Sdteske#define up_Proc_format \ 112238438Sdteske "%5d %-*.*s %3d %4d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s" 113238438Sdteske 114238438Sdteske 115238438Sdteske 116238438Sdteske/* process state names for the "STATE" column of the display */ 117238438Sdteske/* the extra nulls in the string "run" are for adding a slash and 118238438Sdteske the processor number when needed */ 119238438Sdteske 120238438Sdteskechar *state_abbrev[] = 121238438Sdteske{ 122238438Sdteske "", "START", "RUN\0\0\0", "SLEEP", "STOP", "ZOMB", "WAIT", "LOCK" 123238438Sdteske}; 124238438Sdteske 125238438Sdteske 126238438Sdteskestatic kvm_t *kd; 127238438Sdteske 128238438Sdteske/* values that we stash away in _init and use in later routines */ 129238438Sdteske 130238438Sdteskestatic double logcpu; 131238438Sdteske 132238438Sdteske/* these are retrieved from the kernel in _init */ 133238438Sdteske 134238438Sdteskestatic load_avg ccpu; 135238438Sdteske 136238438Sdteske/* these are used in the get_ functions */ 137238438Sdteske 138238438Sdteskestatic int lastpid; 139238438Sdteske 140249751Sdteske/* these are for calculating cpu state percentages */ 141249751Sdteske 142238438Sdteskestatic long cp_time[CPUSTATES]; 143249751Sdteskestatic long cp_old[CPUSTATES]; 144249751Sdteskestatic long cp_diff[CPUSTATES]; 145249751Sdteske 146249751Sdteske/* these are for detailing the process states */ 147249751Sdteske 148249751Sdteskeint process_states[8]; 149249751Sdteskechar *procstatenames[] = { 150249751Sdteske "", " starting, ", " running, ", " sleeping, ", " stopped, ", 151238438Sdteske " zombie, ", " waiting, ", " lock, ", 152249751Sdteske NULL 153249751Sdteske}; 154249751Sdteske 155249751Sdteske/* these are for detailing the cpu states */ 156249751Sdteske 157249751Sdteskeint cpu_states[CPUSTATES]; 158249751Sdteskechar *cpustatenames[] = { 159249751Sdteske "user", "nice", "system", "interrupt", "idle", NULL 160249751Sdteske}; 161249751Sdteske 162249751Sdteske/* these are for detailing the memory statistics */ 163249751Sdteske 164249751Sdteskeint memory_stats[7]; 165249751Sdteskechar *memorynames[] = { 166249751Sdteske /* 0 1 2 3 4 5 */ 167249751Sdteske "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free", 168249751Sdteske NULL 169249751Sdteske}; 170249751Sdteske 171249751Sdteskeint swap_stats[7]; 172249751Sdteskechar *swapnames[] = { 173249751Sdteske /* 0 1 2 3 4 5 */ 174249751Sdteske "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out", 175249751Sdteske NULL 176249751Sdteske}; 177249751Sdteske 178249751Sdteske 179249751Sdteske/* these are for keeping track of the proc array */ 180249751Sdteske 181249751Sdteskestatic int nproc; 182249751Sdteskestatic int onproc = -1; 183249751Sdteskestatic int pref_len; 184249751Sdteskestatic struct kinfo_proc *pbase; 185249751Sdteskestatic struct kinfo_proc **pref; 186249751Sdteskestatic struct kinfo_proc *previous_procs; 187249751Sdteskestatic struct kinfo_proc **previous_pref; 188249751Sdteskestatic int previous_proc_count = 0; 189249751Sdteskestatic int previous_proc_count_max = 0; 190249751Sdteske 191249751Sdteske/* total number of io operations */ 192249751Sdteskestatic long total_inblock; 193249751Sdteskestatic long total_oublock; 194249751Sdteskestatic long total_majflt; 195249751Sdteske 196249751Sdteske/* these are for getting the memory statistics */ 197249751Sdteske 198249751Sdteskestatic int pageshift; /* log base 2 of the pagesize */ 199251190Sdteske 200251190Sdteske/* define pagetok in terms of pageshift */ 201251190Sdteske 202251190Sdteske#define pagetok(size) ((size) << pageshift) 203251190Sdteske 204251190Sdteske/* useful externals */ 205251190Sdteskelong percentages(); 206251190Sdteske 207238438Sdteske#ifdef ORDER 208251236Sdteske/* 209251236Sdteske * Sorting orders. One vector per display mode. 210249751Sdteske * The first element is the default for each mode. 211249751Sdteske */ 212249751Sdteskechar *proc_ordernames[] = { 213249751Sdteske "cpu", "size", "res", "time", "pri", NULL 214249751Sdteske}; 215249751Sdteskechar *io_ordernames[] = { 216249751Sdteske "total", "read", "write", "fault", NULL 217249751Sdteske}; 218249751Sdteske#endif 219249751Sdteske 220251190Sdteskeint 221251190Sdteskemachine_init(struct statics *statics) 222249751Sdteske{ 223240768Sdteske int pagesize; 224240768Sdteske size_t modelen; 225240768Sdteske struct passwd *pw; 226251236Sdteske 227251236Sdteske modelen = sizeof(smpmode); 228249751Sdteske if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 && 229249751Sdteske sysctlbyname("kern.smp.active", &smpmode, &modelen, NULL, 0) < 0) || 230251236Sdteske modelen != sizeof(smpmode)) 231249751Sdteske smpmode = 0; 232240768Sdteske 233238438Sdteske while ((pw = getpwent()) != NULL) { 234238438Sdteske if (strlen(pw->pw_name) > namelength) 235249751Sdteske namelength = strlen(pw->pw_name); 236238438Sdteske } 237249751Sdteske if (namelength < 8) 238249751Sdteske namelength = 8; 239249751Sdteske if (smpmode && namelength > 13) 240238438Sdteske namelength = 13; 241249751Sdteske else if (namelength > 15) 242238438Sdteske namelength = 15; 243238438Sdteske 244238438Sdteske kd = kvm_open(NULL, _PATH_DEVNULL, NULL, O_RDONLY, "kvm_open"); 245238438Sdteske if (kd == NULL) 246238438Sdteske return (-1); 247238438Sdteske 248238438Sdteske GETSYSCTL("kern.ccpu", ccpu); 249238438Sdteske 250245402Sdteske /* this is used in calculating WCPU -- calculate it ahead of time */ 251238438Sdteske logcpu = log(loaddouble(ccpu)); 252238438Sdteske 253238438Sdteske pbase = NULL; 254238438Sdteske pref = NULL; 255238438Sdteske nproc = 0; 256238438Sdteske onproc = -1; 257238438Sdteske /* get the page size with "getpagesize" and calculate pageshift from it */ 258238438Sdteske pagesize = getpagesize(); 259238438Sdteske pageshift = 0; 260238438Sdteske while (pagesize > 1) { 261238438Sdteske pageshift++; 262238438Sdteske pagesize >>= 1; 263238438Sdteske } 264238438Sdteske 265238438Sdteske /* we only need the amount of log(2)1024 for our conversion */ 266238438Sdteske pageshift -= LOG1024; 267238438Sdteske 268238438Sdteske /* fill in the statics information */ 269238438Sdteske statics->procstate_names = procstatenames; 270238438Sdteske statics->cpustate_names = cpustatenames; 271238438Sdteske statics->memory_names = memorynames; 272238438Sdteske statics->swap_names = swapnames; 273238438Sdteske#ifdef ORDER 274251190Sdteske switch (displaymode) { 275251190Sdteske case DISP_IO: 276251190Sdteske statics->order_names = io_ordernames; 277251190Sdteske break; 278251190Sdteske case DISP_CPU: 279251190Sdteske default: 280251190Sdteske statics->order_names = proc_ordernames; 281238438Sdteske break; 282238438Sdteske } 283238438Sdteske#endif 284238438Sdteske 285249751Sdteske /* all done! */ 286249751Sdteske return (0); 287238438Sdteske} 288238438Sdteske 289238438Sdteskechar * 290238438Sdteskeformat_header(char *uname_field) 291238438Sdteske{ 292251190Sdteske static char Header[128]; 293251190Sdteske const char *prehead; 294238438Sdteske 295249751Sdteske switch (displaymode) { 296249954Sdteske case DISP_CPU: 297249954Sdteske prehead = smpmode ? smp_header : up_header; 298238438Sdteske break; 299238438Sdteske case DISP_IO: 300238438Sdteske prehead = io_header; 301238438Sdteske break; 302238438Sdteske } 303238438Sdteske 304238438Sdteske snprintf(Header, sizeof(Header), prehead, 305238438Sdteske namelength, namelength, uname_field); 306238438Sdteske 307238438Sdteske cmdlengthdelta = strlen(Header) - 7; 308250633Sdteske 309238438Sdteske return (Header); 310238438Sdteske} 311238438Sdteske 312238438Sdteskestatic int swappgsin = -1; 313238438Sdteskestatic int swappgsout = -1; 314238438Sdteskeextern struct timeval timeout; 315238438Sdteske 316238438Sdteskevoid 317238438Sdteskeget_system_info(struct system_info *si) 318238438Sdteske{ 319238438Sdteske long total; 320238438Sdteske struct loadavg sysload; 321238438Sdteske int mib[2]; 322249751Sdteske struct timeval boottime; 323249751Sdteske size_t bt_size; 324249751Sdteske int i; 325249751Sdteske 326249751Sdteske /* get the cp_time array */ 327249751Sdteske GETSYSCTL("kern.cp_time", cp_time); 328249751Sdteske GETSYSCTL("vm.loadavg", sysload); 329249751Sdteske GETSYSCTL("kern.lastpid", lastpid); 330249751Sdteske 331249751Sdteske /* convert load averages to doubles */ 332238438Sdteske for (i = 0; i < 3; i++) 333238438Sdteske si->load_avg[i] = (double)sysload.ldavg[i] / sysload.fscale; 334238438Sdteske 335251236Sdteske /* convert cp_time counts to percentages */ 336238438Sdteske total = percentages(CPUSTATES, cpu_states, cp_time, cp_old, cp_diff); 337238438Sdteske 338249751Sdteske /* sum memory & swap statistics */ 339249751Sdteske { 340238438Sdteske static unsigned int swap_delay = 0; 341238438Sdteske static int swapavail = 0; 342238438Sdteske static int swapfree = 0; 343238438Sdteske static int bufspace = 0; 344249751Sdteske static int nspgsin, nspgsout; 345238438Sdteske 346238438Sdteske GETSYSCTL("vfs.bufspace", bufspace); 347238438Sdteske GETSYSCTL("vm.stats.vm.v_active_count", memory_stats[0]); 348238438Sdteske GETSYSCTL("vm.stats.vm.v_inactive_count", memory_stats[1]); 349238438Sdteske GETSYSCTL("vm.stats.vm.v_wire_count", memory_stats[2]); 350238438Sdteske GETSYSCTL("vm.stats.vm.v_cache_count", memory_stats[3]); 351238438Sdteske GETSYSCTL("vm.stats.vm.v_free_count", memory_stats[5]); 352238438Sdteske GETSYSCTL("vm.stats.vm.v_swappgsin", nspgsin); 353238438Sdteske GETSYSCTL("vm.stats.vm.v_swappgsout", nspgsout); 354238438Sdteske /* convert memory stats to Kbytes */ 355238438Sdteske memory_stats[0] = pagetok(memory_stats[0]); 356238438Sdteske memory_stats[1] = pagetok(memory_stats[1]); 357238438Sdteske memory_stats[2] = pagetok(memory_stats[2]); 358238438Sdteske memory_stats[3] = pagetok(memory_stats[3]); 359249751Sdteske memory_stats[4] = bufspace / 1024; 360238438Sdteske memory_stats[5] = pagetok(memory_stats[5]); 361238438Sdteske memory_stats[6] = -1; 362238438Sdteske 363238438Sdteske /* first interval */ 364238438Sdteske if (swappgsin < 0) { 365238438Sdteske swap_stats[4] = 0; 366245437Sdteske swap_stats[5] = 0; 367238438Sdteske } 368238438Sdteske 369238438Sdteske /* compute differences between old and new swap statistic */ 370238438Sdteske else { 371249751Sdteske swap_stats[4] = pagetok(((nspgsin - swappgsin))); 372238438Sdteske swap_stats[5] = pagetok(((nspgsout - swappgsout))); 373238438Sdteske } 374238438Sdteske 375238438Sdteske swappgsin = nspgsin; 376238438Sdteske swappgsout = nspgsout; 377238438Sdteske 378238438Sdteske /* call CPU heavy swapmode() only for changes */ 379238438Sdteske if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) { 380238438Sdteske swap_stats[3] = swapmode(&swapavail, &swapfree); 381238438Sdteske swap_stats[0] = swapavail; 382238438Sdteske swap_stats[1] = swapavail - swapfree; 383238438Sdteske swap_stats[2] = swapfree; 384238438Sdteske } 385238438Sdteske swap_delay = 1; 386238438Sdteske swap_stats[6] = -1; 387238438Sdteske } 388238438Sdteske 389238438Sdteske /* set arrays and strings */ 390238438Sdteske si->cpustates = cpu_states; 391238438Sdteske si->memory = memory_stats; 392238438Sdteske si->swap = swap_stats; 393238438Sdteske 394238438Sdteske 395250317Sdteske if (lastpid > 0) { 396238438Sdteske si->last_pid = lastpid; 397238438Sdteske } else { 398238438Sdteske si->last_pid = -1; 399238438Sdteske } 400238438Sdteske 401238438Sdteske /* 402238438Sdteske * Print how long system has been up. 403238438Sdteske * (Found by looking getting "boottime" from the kernel) 404238438Sdteske */ 405238438Sdteske mib[0] = CTL_KERN; 406238438Sdteske mib[1] = KERN_BOOTTIME; 407238438Sdteske bt_size = sizeof(boottime); 408238438Sdteske if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 && 409238438Sdteske boottime.tv_sec != 0) { 410 si->boottime = boottime; 411 } else { 412 si->boottime.tv_sec = -1; 413 } 414} 415 416#define NOPROC ((void *)-1) 417 418const struct kinfo_proc * 419get_old_proc(struct kinfo_proc *pp) 420{ 421 struct kinfo_proc **oldpp, *oldp; 422 423 if (previous_proc_count == 0) 424 return (NULL); 425 if (pp->ki_udata == NOPROC) 426 return (NULL); 427 if (pp->ki_udata != NULL) 428 return (pp->ki_udata); 429 oldpp = bsearch(&pp, previous_pref, previous_proc_count, 430 sizeof(*previous_pref), compare_pid); 431 if (oldpp == NULL) { 432 pp->ki_udata = NOPROC; 433 return (NULL); 434 } 435 oldp = *oldpp; 436 if (bcmp(&oldp->ki_start, &pp->ki_start, sizeof(pp->ki_start)) != 0) { 437 pp->ki_udata = NOPROC; 438 return (NULL); 439 } 440 pp->ki_udata = oldp; 441 return (oldp); 442} 443 444long 445get_io_stats(struct kinfo_proc *pp, long *inp, long *oup, long *flp) 446{ 447 const struct kinfo_proc *oldp; 448 static struct kinfo_proc dummy; 449 long ret; 450 451 oldp = get_old_proc(pp); 452 if (oldp == NULL) { 453 bzero(&dummy, sizeof(dummy)); 454 oldp = &dummy; 455 } 456 457 *inp = RU(pp)->ru_inblock - RU(oldp)->ru_inblock; 458 *oup = RU(pp)->ru_oublock - RU(oldp)->ru_oublock; 459 *flp = RU(pp)->ru_majflt - RU(oldp)->ru_majflt; 460 ret = 461 (RU(pp)->ru_inblock - RU(oldp)->ru_inblock) + 462 (RU(pp)->ru_oublock - RU(oldp)->ru_oublock) + 463 (RU(pp)->ru_majflt - RU(oldp)->ru_majflt); 464 return (ret); 465} 466 467long 468get_io_total(struct kinfo_proc *pp) 469{ 470 long dummy; 471 472 return (get_io_stats(pp, &dummy, &dummy, &dummy)); 473} 474 475static struct handle handle; 476 477caddr_t 478get_process_info(struct system_info *si, struct process_select *sel, 479 int (*compare)(const void *, const void *)) 480{ 481 int i; 482 int total_procs; 483 long p_io; 484 long p_inblock, p_oublock, p_majflt; 485 int active_procs; 486 struct kinfo_proc **prefp; 487 struct kinfo_proc *pp; 488 struct kinfo_proc *prev_pp = NULL; 489 490 /* these are copied out of sel for speed */ 491 int show_idle; 492 int show_self; 493 int show_system; 494 int show_uid; 495 int show_command; 496 497 /* 498 * Save the previous process info. 499 */ 500 if (previous_proc_count_max < nproc) { 501 free(previous_procs); 502 previous_procs = malloc(nproc * sizeof(*previous_procs)); 503 free(previous_pref); 504 previous_pref = malloc(nproc * sizeof(*previous_pref)); 505 if (previous_procs == NULL || previous_pref == NULL) { 506 (void) fprintf(stderr, "top: Out of memory.\n"); 507 quit(23); 508 } 509 previous_proc_count_max = nproc; 510 } 511 if (nproc) { 512 for (i = 0; i < nproc; i++) 513 previous_pref[i] = &previous_procs[i]; 514 bcopy(pbase, previous_procs, nproc * sizeof(*previous_procs)); 515 qsort(previous_pref, nproc, sizeof(*previous_pref), compare_pid); 516 } 517 previous_proc_count = nproc; 518 519 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc); 520 if (nproc > onproc) 521 pref = realloc(pref, sizeof(*pref) * (onproc = nproc)); 522 if (pref == NULL || pbase == NULL) { 523 (void) fprintf(stderr, "top: Out of memory.\n"); 524 quit(23); 525 } 526 /* get a pointer to the states summary array */ 527 si->procstates = process_states; 528 529 /* set up flags which define what we are going to select */ 530 show_idle = sel->idle; 531 show_self = sel->self; 532 show_system = sel->system; 533 show_uid = sel->uid != -1; 534 show_command = sel->command != NULL; 535 536 /* count up process states and get pointers to interesting procs */ 537 total_procs = 0; 538 active_procs = 0; 539 total_inblock = 0; 540 total_oublock = 0; 541 total_majflt = 0; 542 memset((char *)process_states, 0, sizeof(process_states)); 543 prefp = pref; 544 for (pp = pbase, i = 0; i < nproc; pp++, i++) { 545 546 if (pp->ki_stat == 0) 547 /* not in use */ 548 continue; 549 550 if (!show_self && pp->ki_pid == sel->self) 551 /* skip self */ 552 continue; 553 554 if (!show_system && (pp->ki_flag & P_SYSTEM)) 555 /* skip system process */ 556 continue; 557 558 p_io = get_io_stats(pp, &p_inblock, &p_oublock, &p_majflt); 559 total_inblock += p_inblock; 560 total_oublock += p_oublock; 561 total_majflt += p_majflt; 562 total_procs++; 563 process_states[pp->ki_stat]++; 564 565 if (pp->ki_stat == SZOMB) 566 /* skip zombies */ 567 continue; 568 569 if (displaymode == DISP_CPU && !show_idle && 570 (pp->ki_pctcpu == 0 || pp->ki_stat != SRUN)) 571 /* skip idle or non-running processes */ 572 continue; 573 574 if (displaymode == DISP_IO && !show_idle && p_io == 0) 575 /* skip processes that aren't doing I/O */ 576 continue; 577 578 if (show_uid && pp->ki_ruid != (uid_t)sel->uid) 579 /* skip processes which don't belong to the selected UID */ 580 continue; 581 582 /* 583 * When not showing threads, take the first thread 584 * for output and add the fields that we can from 585 * the rest of the process's threads rather than 586 * using the system's mostly-broken KERN_PROC_PROC. 587 */ 588 if (sel->thread || prev_pp == NULL || 589 prev_pp->ki_pid != pp->ki_pid) { 590 *prefp++ = pp; 591 active_procs++; 592 prev_pp = pp; 593 } else { 594 prev_pp->ki_pctcpu += pp->ki_pctcpu; 595 } 596 } 597 598 /* if requested, sort the "interesting" processes */ 599 if (compare != NULL) 600 qsort(pref, active_procs, sizeof(*pref), compare); 601 602 /* remember active and total counts */ 603 si->p_total = total_procs; 604 si->p_active = pref_len = active_procs; 605 606 /* pass back a handle */ 607 handle.next_proc = pref; 608 handle.remaining = active_procs; 609 return ((caddr_t)&handle); 610} 611 612static char fmt[128]; /* static area where result is built */ 613 614char * 615format_next_process(caddr_t handle, char *(*get_userid)(int)) 616{ 617 struct kinfo_proc *pp; 618 const struct kinfo_proc *oldp; 619 long cputime; 620 double pct; 621 struct handle *hp; 622 char status[16]; 623 int state; 624 struct rusage ru, *rup; 625 long p_tot, s_tot; 626 627 /* find and remember the next proc structure */ 628 hp = (struct handle *)handle; 629 pp = *(hp->next_proc++); 630 hp->remaining--; 631 632 /* get the process's command name */ 633 if ((pp->ki_sflag & PS_INMEM) == 0) { 634 /* 635 * Print swapped processes as <pname> 636 */ 637 size_t len = strlen(pp->ki_comm); 638 if (len > sizeof(pp->ki_comm) - 3) 639 len = sizeof(pp->ki_comm) - 3; 640 memmove(pp->ki_comm + 1, pp->ki_comm, len); 641 pp->ki_comm[0] = '<'; 642 pp->ki_comm[len + 1] = '>'; 643 pp->ki_comm[len + 2] = '\0'; 644 } 645 646 /* 647 * Convert the process's runtime from microseconds to seconds. This 648 * time includes the interrupt time although that is not wanted here. 649 * ps(1) is similarly sloppy. 650 */ 651 cputime = (pp->ki_runtime + 500000) / 1000000; 652 653 /* calculate the base for cpu percentages */ 654 pct = pctdouble(pp->ki_pctcpu); 655 656 /* generate "STATE" field */ 657 switch (state = pp->ki_stat) { 658 case SRUN: 659 if (smpmode && pp->ki_oncpu != 0xff) 660 sprintf(status, "CPU%d", pp->ki_oncpu); 661 else 662 strcpy(status, "RUN"); 663 break; 664 case SLOCK: 665 if (pp->ki_kiflag & KI_LOCKBLOCK) { 666 sprintf(status, "*%.6s", pp->ki_lockname); 667 break; 668 } 669 /* fall through */ 670 case SSLEEP: 671 if (pp->ki_wmesg != NULL) { 672 sprintf(status, "%.6s", pp->ki_wmesg); 673 break; 674 } 675 /* FALLTHROUGH */ 676 default: 677 678 if (state >= 0 && 679 state < sizeof(state_abbrev) / sizeof(*state_abbrev)) 680 sprintf(status, "%.6s", state_abbrev[state]); 681 else 682 sprintf(status, "?%5d", state); 683 break; 684 } 685 686 if (displaymode == DISP_IO) { 687 oldp = get_old_proc(pp); 688 if (oldp != NULL) { 689 ru.ru_inblock = RU(pp)->ru_inblock - RU(oldp)->ru_inblock; 690 ru.ru_oublock = RU(pp)->ru_oublock - RU(oldp)->ru_oublock; 691 ru.ru_majflt = RU(pp)->ru_majflt - RU(oldp)->ru_majflt; 692 rup = &ru; 693 } else { 694 rup = RU(pp); 695 } 696 p_tot = rup->ru_inblock + rup->ru_oublock + rup->ru_majflt; 697 s_tot = total_inblock + total_oublock + total_majflt; 698 699 sprintf(fmt, io_Proc_format, 700 pp->ki_pid, 701 namelength, namelength, 702 (*get_userid)(pp->ki_ruid), 703 rup->ru_inblock, 704 rup->ru_oublock, 705 rup->ru_majflt, 706 p_tot, 707 s_tot == 0 ? 0.0 : (p_tot * 100.0 / s_tot), 708 screen_width > cmdlengthdelta ? 709 screen_width - cmdlengthdelta : 0, 710 printable(pp->ki_comm)); 711 return (fmt); 712 } 713 /* format this entry */ 714 sprintf(fmt, 715 smpmode ? smp_Proc_format : up_Proc_format, 716 pp->ki_pid, 717 namelength, namelength, 718 (*get_userid)(pp->ki_ruid), 719 pp->ki_pri.pri_level - PZERO, 720 721 /* 722 * normal time -> nice value -20 - +20 723 * real time 0 - 31 -> nice value -52 - -21 724 * idle time 0 - 31 -> nice value +21 - +52 725 */ 726 (pp->ki_pri.pri_class == PRI_TIMESHARE ? 727 pp->ki_nice - NZERO : 728 (PRI_IS_REALTIME(pp->ki_pri.pri_class) ? 729 (PRIO_MIN - 1 - (PRI_MAX_REALTIME - pp->ki_pri.pri_level)) : 730 (PRIO_MAX + 1 + pp->ki_pri.pri_level - PRI_MIN_IDLE))), 731 format_k2(PROCSIZE(pp)), 732 format_k2(pagetok(pp->ki_rssize)), 733 status, 734 smpmode ? pp->ki_lastcpu : 0, 735 format_time(cputime), 736 100.0 * weighted_cpu(pct, pp), 737 100.0 * pct, 738 screen_width > cmdlengthdelta ? 739 screen_width - cmdlengthdelta : 740 0, 741 printable(pp->ki_comm)); 742 743 /* return the result */ 744 return (fmt); 745} 746 747static void 748getsysctl(char *name, void *ptr, size_t len) 749{ 750 size_t nlen = len; 751 752 if (sysctlbyname(name, ptr, &nlen, NULL, 0) == -1) { 753 fprintf(stderr, "top: sysctl(%s...) failed: %s\n", name, 754 strerror(errno)); 755 quit(23); 756 } 757 if (nlen != len) { 758 fprintf(stderr, "top: sysctl(%s...) expected %lu, got %lu\n", name, 759 (unsigned long)len, (unsigned long)nlen); 760 quit(23); 761 } 762} 763 764/* comparison routines for qsort */ 765 766int 767compare_pid(const void *p1, const void *p2) 768{ 769 const struct kinfo_proc * const *pp1 = p1; 770 const struct kinfo_proc * const *pp2 = p2; 771 772 if ((*pp2)->ki_pid < 0 || (*pp1)->ki_pid < 0) 773 abort(); 774 775 return ((*pp1)->ki_pid - (*pp2)->ki_pid); 776} 777 778/* 779 * proc_compare - comparison function for "qsort" 780 * Compares the resource consumption of two processes using five 781 * distinct keys. The keys (in descending order of importance) are: 782 * percent cpu, cpu ticks, state, resident set size, total virtual 783 * memory usage. The process states are ordered as follows (from least 784 * to most important): WAIT, zombie, sleep, stop, start, run. The 785 * array declaration below maps a process state index into a number 786 * that reflects this ordering. 787 */ 788 789static int sorted_state[] = 790{ 791 0, /* not used */ 792 3, /* sleep */ 793 1, /* ABANDONED (WAIT) */ 794 6, /* run */ 795 5, /* start */ 796 2, /* zombie */ 797 4 /* stop */ 798}; 799 800 801#define ORDERKEY_PCTCPU(a, b) do { \ 802 long diff = (long)(b)->ki_pctcpu - (long)(a)->ki_pctcpu; \ 803 if (diff != 0) \ 804 return (diff > 0 ? 1 : -1); \ 805} while (0) 806 807#define ORDERKEY_CPTICKS(a, b) do { \ 808 int64_t diff = (int64_t)(b)->ki_runtime - (int64_t)(a)->ki_runtime; \ 809 if (diff != 0) \ 810 return (diff > 0 ? 1 : -1); \ 811} while (0) 812 813#define ORDERKEY_STATE(a, b) do { \ 814 int diff = sorted_state[(b)->ki_stat] - sorted_state[(a)->ki_stat]; \ 815 if (diff != 0) \ 816 return (diff > 0 ? 1 : -1); \ 817} while (0) 818 819#define ORDERKEY_PRIO(a, b) do { \ 820 int diff = (int)(b)->ki_pri.pri_level - (int)(a)->ki_pri.pri_level; \ 821 if (diff != 0) \ 822 return (diff > 0 ? 1 : -1); \ 823} while (0) 824 825#define ORDERKEY_RSSIZE(a, b) do { \ 826 long diff = (long)(b)->ki_rssize - (long)(a)->ki_rssize; \ 827 if (diff != 0) \ 828 return (diff > 0 ? 1 : -1); \ 829} while (0) 830 831#define ORDERKEY_MEM(a, b) do { \ 832 long diff = (long)PROCSIZE((b)) - (long)PROCSIZE((a)); \ 833 if (diff != 0) \ 834 return (diff > 0 ? 1 : -1); \ 835} while (0) 836 837/* compare_cpu - the comparison function for sorting by cpu percentage */ 838 839int 840#ifdef ORDER 841compare_cpu(void *arg1, void *arg2) 842#else 843proc_compare(void *arg1, void *arg2) 844#endif 845{ 846 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 847 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 848 849 ORDERKEY_PCTCPU(p1, p2); 850 ORDERKEY_CPTICKS(p1, p2); 851 ORDERKEY_STATE(p1, p2); 852 ORDERKEY_PRIO(p1, p2); 853 ORDERKEY_RSSIZE(p1, p2); 854 ORDERKEY_MEM(p1, p2); 855 856 return (0); 857} 858 859#ifdef ORDER 860/* compare routines */ 861int compare_size(), compare_res(), compare_time(), compare_prio(); 862 863int (*proc_compares[])() = { 864 compare_cpu, 865 compare_size, 866 compare_res, 867 compare_time, 868 compare_prio, 869 NULL 870}; 871 872/* compare_size - the comparison function for sorting by total memory usage */ 873 874int 875compare_size(void *arg1, void *arg2) 876{ 877 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 878 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 879 880 ORDERKEY_MEM(p1, p2); 881 ORDERKEY_RSSIZE(p1, p2); 882 ORDERKEY_PCTCPU(p1, p2); 883 ORDERKEY_CPTICKS(p1, p2); 884 ORDERKEY_STATE(p1, p2); 885 ORDERKEY_PRIO(p1, p2); 886 887 return (0); 888} 889 890/* compare_res - the comparison function for sorting by resident set size */ 891 892int 893compare_res(void *arg1, void *arg2) 894{ 895 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 896 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 897 898 ORDERKEY_RSSIZE(p1, p2); 899 ORDERKEY_MEM(p1, p2); 900 ORDERKEY_PCTCPU(p1, p2); 901 ORDERKEY_CPTICKS(p1, p2); 902 ORDERKEY_STATE(p1, p2); 903 ORDERKEY_PRIO(p1, p2); 904 905 return (0); 906} 907 908/* compare_time - the comparison function for sorting by total cpu time */ 909 910int 911compare_time(void *arg1, void *arg2) 912{ 913 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 914 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 915 916 ORDERKEY_CPTICKS(p1, p2); 917 ORDERKEY_PCTCPU(p1, p2); 918 ORDERKEY_STATE(p1, p2); 919 ORDERKEY_PRIO(p1, p2); 920 ORDERKEY_RSSIZE(p1, p2); 921 ORDERKEY_MEM(p1, p2); 922 923 return (0); 924} 925 926/* compare_prio - the comparison function for sorting by priority */ 927 928int 929compare_prio(void *arg1, void *arg2) 930{ 931 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 932 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 933 934 ORDERKEY_PRIO(p1, p2); 935 ORDERKEY_CPTICKS(p1, p2); 936 ORDERKEY_PCTCPU(p1, p2); 937 ORDERKEY_STATE(p1, p2); 938 ORDERKEY_RSSIZE(p1, p2); 939 ORDERKEY_MEM(p1, p2); 940 941 return (0); 942} 943#endif 944 945/* compare_io - the comparison function for sorting by total io */ 946 947int 948#ifdef ORDER 949compare_iototal(void *arg1, void *arg2) 950#else 951io_compare(void *arg1, void *arg2) 952#endif 953{ 954 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 955 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 956 957 return (get_io_total(p2) - get_io_total(p1)); 958} 959 960#ifdef ORDER 961/* io compare routines */ 962int compare_ioread(), compare_iowrite(), compare_iofault(); 963 964int (*io_compares[])() = { 965 compare_iototal, 966 compare_ioread, 967 compare_iowrite, 968 compare_iofault, 969 NULL 970}; 971 972int 973compare_ioread(void *arg1, void *arg2) 974{ 975 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 976 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 977 long dummy, inp1, inp2; 978 979 (void) get_io_stats(p1, &inp1, &dummy, &dummy); 980 (void) get_io_stats(p2, &inp2, &dummy, &dummy); 981 982 return (inp2 - inp1); 983} 984 985int 986compare_iowrite(void *arg1, void *arg2) 987{ 988 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 989 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 990 long dummy, oup1, oup2; 991 992 (void) get_io_stats(p1, &dummy, &oup1, &dummy); 993 (void) get_io_stats(p2, &dummy, &oup2, &dummy); 994 995 return (oup2 - oup1); 996} 997 998int 999compare_iofault(void *arg1, void *arg2) 1000{ 1001 struct kinfo_proc *p1 = *(struct kinfo_proc **)arg1; 1002 struct kinfo_proc *p2 = *(struct kinfo_proc **)arg2; 1003 long dummy, flp1, flp2; 1004 1005 (void) get_io_stats(p1, &dummy, &dummy, &flp1); 1006 (void) get_io_stats(p2, &dummy, &dummy, &flp2); 1007 1008 return (flp2 - flp1); 1009} 1010 1011#endif /* ORDER */ 1012 1013/* 1014 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if 1015 * the process does not exist. 1016 * It is EXTREMLY IMPORTANT that this function work correctly. 1017 * If top runs setuid root (as in SVR4), then this function 1018 * is the only thing that stands in the way of a serious 1019 * security problem. It validates requests for the "kill" 1020 * and "renice" commands. 1021 */ 1022 1023int 1024proc_owner(int pid) 1025{ 1026 int cnt; 1027 struct kinfo_proc **prefp; 1028 struct kinfo_proc *pp; 1029 1030 prefp = pref; 1031 cnt = pref_len; 1032 while (--cnt >= 0) { 1033 pp = *prefp++; 1034 if (pp->ki_pid == (pid_t)pid) 1035 return ((int)pp->ki_ruid); 1036 } 1037 return (-1); 1038} 1039 1040int 1041swapmode(int *retavail, int *retfree) 1042{ 1043 int n; 1044 int pagesize = getpagesize(); 1045 struct kvm_swap swapary[1]; 1046 1047 *retavail = 0; 1048 *retfree = 0; 1049 1050#define CONVERT(v) ((quad_t)(v) * pagesize / 1024) 1051 1052 n = kvm_getswapinfo(kd, swapary, 1, 0); 1053 if (n < 0 || swapary[0].ksw_total == 0) 1054 return (0); 1055 1056 *retavail = CONVERT(swapary[0].ksw_total); 1057 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used); 1058 1059 n = (int)(swapary[0].ksw_used * 100.0 / swapary[0].ksw_total); 1060 return (n); 1061} 1062