1 /* $NetBSD: m_netbsd.c,v 1.17 2013/01/03 10:12:36 para Exp $ */ 2 3 /* 4 * top - a top users display for Unix 5 * 6 * SYNOPSIS: For a NetBSD-1.5 (or later) system 7 * 8 * DESCRIPTION: 9 * Originally written for BSD4.4 system by Christos Zoulas. 10 * Based on the FreeBSD 2.0 version by Steven Wallace and Wolfram Schneider. 11 * NetBSD-1.0 port by Arne Helme. Process ordering by Luke Mewburn. 12 * NetBSD-1.3 port by Luke Mewburn, based on code by Matthew Green. 13 * NetBSD-1.4/UVM port by matthew green. 14 * NetBSD-1.5 port by Simon Burge. 15 * NetBSD-1.6/UBC port by Tomas Svensson. 16 * - 17 * This is the machine-dependent module for NetBSD-1.5 and later 18 * works for: 19 * NetBSD-1.6ZC 20 * and should work for: 21 * NetBSD-2.0 (when released) 22 * - 23 * top does not need to be installed setuid or setgid with this module. 24 * 25 * LIBS: -lkvm 26 * 27 * CFLAGS: -DHAVE_GETOPT -DORDER -DHAVE_STRERROR 28 * 29 * AUTHORS: Christos Zoulas <christos@ee.cornell.edu> 30 * Steven Wallace <swallace@freebsd.org> 31 * Wolfram Schneider <wosch@cs.tu-berlin.de> 32 * Arne Helme <arne@acm.org> 33 * Luke Mewburn <lukem@NetBSD.org> 34 * matthew green <mrg@eterna.com.au> 35 * Simon Burge <simonb@NetBSD.org> 36 * Tomas Svensson <ts@unix1.net> 37 * Andrew Doran <ad@NetBSD.org> 38 * 39 * 40 * $Id: m_netbsd.c,v 1.17 2013/01/03 10:12:36 para Exp $ 41 */ 42 #include <sys/cdefs.h> 43 44 #ifndef lint 45 __RCSID("$NetBSD: m_netbsd.c,v 1.17 2013/01/03 10:12:36 para Exp $"); 46 #endif 47 48 #include <sys/param.h> 49 #include <sys/resource.h> 50 #include <sys/sysctl.h> 51 #include <sys/sched.h> 52 #include <sys/swap.h> 53 54 #include <uvm/uvm_extern.h> 55 56 #include <err.h> 57 #include <errno.h> 58 #include <kvm.h> 59 #include <math.h> 60 #include <nlist.h> 61 #include <stdio.h> 62 #include <stdlib.h> 63 #include <string.h> 64 #include <unistd.h> 65 66 #include "os.h" 67 #include "top.h" 68 #include "machine.h" 69 #include "utils.h" 70 #include "display.h" 71 #include "loadavg.h" 72 #include "username.h" 73 74 static void percentages64(int, int *, u_int64_t *, u_int64_t *, 75 u_int64_t *); 76 77 /* get_process_info passes back a handle. This is what it looks like: */ 78 79 struct handle { 80 struct process_select *sel; 81 struct kinfo_proc2 **next_proc; /* points to next valid proc pointer */ 82 int remaining; /* number of pointers remaining */ 83 }; 84 85 /* define what weighted CPU is. */ 86 #define weighted_cpu(pfx, pct, pp) ((pp)->pfx ## swtime == 0 ? 0.0 : \ 87 ((pct) / (1.0 - exp((pp)->pfx ## swtime * logcpu)))) 88 89 /* what we consider to be process size: */ 90 /* NetBSD introduced p_vm_msize with RLIMIT_AS */ 91 #ifdef RLIMIT_AS 92 #define PROCSIZE(pp) \ 93 ((pp)->p_vm_msize) 94 #else 95 #define PROCSIZE(pp) \ 96 ((pp)->p_vm_tsize + (pp)->p_vm_dsize + (pp)->p_vm_ssize) 97 #endif 98 99 100 /* 101 * These definitions control the format of the per-process area 102 */ 103 104 static char Proc_header[] = 105 " PID X PRI NICE SIZE RES STATE TIME WCPU CPU COMMAND"; 106 /* 0123456 -- field to fill in starts at header+6 */ 107 #define PROC_UNAME_START 6 108 #define Proc_format \ 109 "%5d %-8.8s %3d %4d%7s %5s %-8.8s%7s %5.*f%% %5.*f%% %s" 110 111 static char Thread_header[] = 112 " PID LID X PRI STATE TIME WCPU CPU NAME COMMAND"; 113 /* 0123456 -- field to fill in starts at header+6 */ 114 #define THREAD_UNAME_START 12 115 #define Thread_format \ 116 "%5d %5d %-8.8s %3d %-8.8s%7s %5.2f%% %5.2f%% %-9.9s %s" 117 118 /* 119 * Process state names for the "STATE" column of the display. 120 */ 121 122 const char *state_abbrev[] = { 123 "", "IDLE", "RUN", "SLEEP", "STOP", "ZOMB", "DEAD", "CPU" 124 }; 125 126 static kvm_t *kd; 127 128 static char *(*userprint)(int); 129 130 /* these are retrieved from the kernel in _init */ 131 132 static double logcpu; 133 static int hz; 134 static int ccpu; 135 136 /* these are for calculating CPU state percentages */ 137 138 static int ncpu = 0; 139 static u_int64_t *cp_time; 140 static u_int64_t *cp_old; 141 static u_int64_t *cp_diff; 142 143 /* these are for detailing the process states */ 144 145 int process_states[8]; 146 const char *procstatenames[] = { 147 "", " idle, ", " runnable, ", " sleeping, ", " stopped, ", 148 " zombie, ", " dead, ", " on CPU, ", 149 NULL 150 }; 151 152 /* these are for detailing the CPU states */ 153 154 int *cpu_states; 155 const char *cpustatenames[] = { 156 "user", "nice", "system", "interrupt", "idle", NULL 157 }; 158 159 /* these are for detailing the memory statistics */ 160 161 long memory_stats[7]; 162 const char *memorynames[] = { 163 "K Act, ", "K Inact, ", "K Wired, ", "K Exec, ", "K File, ", 164 "K Free, ", 165 NULL 166 }; 167 168 long swap_stats[4]; 169 const char *swapnames[] = { 170 "K Total, ", "K Used, ", "K Free, ", 171 NULL 172 }; 173 174 175 /* these are names given to allowed sorting orders -- first is default */ 176 const char *ordernames[] = { 177 "cpu", 178 "pri", 179 "res", 180 "size", 181 "state", 182 "time", 183 "pid", 184 "command", 185 "username", 186 NULL 187 }; 188 189 /* forward definitions for comparison functions */ 190 static int compare_cpu(struct proc **, struct proc **); 191 static int compare_prio(struct proc **, struct proc **); 192 static int compare_res(struct proc **, struct proc **); 193 static int compare_size(struct proc **, struct proc **); 194 static int compare_state(struct proc **, struct proc **); 195 static int compare_time(struct proc **, struct proc **); 196 static int compare_pid(struct proc **, struct proc **); 197 static int compare_command(struct proc **, struct proc **); 198 static int compare_username(struct proc **, struct proc **); 199 200 int (*proc_compares[])(struct proc **, struct proc **) = { 201 compare_cpu, 202 compare_prio, 203 compare_res, 204 compare_size, 205 compare_state, 206 compare_time, 207 compare_pid, 208 compare_command, 209 compare_username, 210 NULL 211 }; 212 213 static char *format_next_lwp(caddr_t, char *(*)(int)); 214 static char *format_next_proc(caddr_t, char *(*)(int)); 215 216 static caddr_t get_proc_info(struct system_info *, struct process_select *, 217 int (*)(struct proc **, struct proc **)); 218 static caddr_t get_lwp_info(struct system_info *, struct process_select *, 219 int (*)(struct proc **, struct proc **)); 220 221 /* these are for keeping track of the proc array */ 222 223 static int nproc; 224 static int onproc = -1; 225 static int nlwp; 226 static int onlwp = -1; 227 static int pref_len; 228 static int lref_len; 229 static struct kinfo_proc2 *pbase; 230 static struct kinfo_lwp *lbase; 231 static struct kinfo_proc2 **pref; 232 static struct kinfo_lwp **lref; 233 static int maxswap; 234 static void *swapp; 235 static int procgen; 236 static int thread_nproc; 237 static int thread_onproc = -1; 238 static struct kinfo_proc2 *thread_pbase; 239 240 /* these are for getting the memory statistics */ 241 242 static int pageshift; /* log base 2 of the pagesize */ 243 244 int threadmode; 245 246 /* define pagetok in terms of pageshift */ 247 248 #define pagetok(size) ((size) << pageshift) 249 250 /* 251 * Print swapped processes as <pname> and 252 * system processes as [pname] 253 */ 254 static const char * 255 get_pretty(const struct kinfo_proc2 *pp) 256 { 257 if ((pp->p_flag & P_SYSTEM) != 0) 258 return "[]"; 259 if ((pp->p_flag & P_INMEM) == 0) 260 return "<>"; 261 return ""; 262 } 263 264 static const char * 265 get_command(const struct process_select *sel, struct kinfo_proc2 *pp) 266 { 267 static char cmdbuf[128]; 268 const char *pretty; 269 char **argv; 270 if (pp == NULL) 271 return "<gone>"; 272 pretty = get_pretty(pp); 273 274 if (sel->fullcmd == 0 || kd == NULL || (argv = kvm_getargv2(kd, pp, 275 sizeof(cmdbuf))) == NULL) { 276 if (pretty[0] != '\0' && pp->p_comm[0] != pretty[0]) 277 snprintf(cmdbuf, sizeof(cmdbuf), "%c%s%c", pretty[0], 278 printable(pp->p_comm), pretty[1]); 279 else 280 strlcpy(cmdbuf, printable(pp->p_comm), sizeof(cmdbuf)); 281 } else { 282 char *d = cmdbuf; 283 if (pretty[0] != '\0' && argv[0][0] != pretty[0]) 284 *d++ = pretty[0]; 285 while (*argv) { 286 const char *s = printable(*argv++); 287 while (d < cmdbuf + sizeof(cmdbuf) - 2 && 288 (*d++ = *s++) != '\0') 289 continue; 290 if (d > cmdbuf && d < cmdbuf + sizeof(cmdbuf) - 2 && 291 d[-1] == '\0') 292 d[-1] = ' '; 293 } 294 if (pretty[0] != '\0' && pretty[0] == cmdbuf[0]) 295 *d++ = pretty[1]; 296 *d++ = '\0'; 297 } 298 return cmdbuf; 299 } 300 301 int 302 machine_init(statics) 303 struct statics *statics; 304 { 305 int pagesize; 306 int mib[2]; 307 size_t size; 308 struct clockinfo clockinfo; 309 struct timeval boottime; 310 311 if ((kd = kvm_open(NULL, NULL, NULL, KVM_NO_FILES, "kvm_open")) == NULL) 312 return -1; 313 314 mib[0] = CTL_HW; 315 mib[1] = HW_NCPU; 316 size = sizeof(ncpu); 317 if (sysctl(mib, 2, &ncpu, &size, NULL, 0) == -1) { 318 fprintf(stderr, "top: sysctl hw.ncpu failed: %s\n", 319 strerror(errno)); 320 return(-1); 321 } 322 statics->ncpu = ncpu; 323 cp_time = malloc(sizeof(cp_time[0]) * CPUSTATES * ncpu); 324 mib[0] = CTL_KERN; 325 mib[1] = KERN_CP_TIME; 326 size = sizeof(cp_time[0]) * CPUSTATES * ncpu; 327 if (sysctl(mib, 2, cp_time, &size, NULL, 0) < 0) { 328 fprintf(stderr, "top: sysctl kern.cp_time failed: %s\n", 329 strerror(errno)); 330 return(-1); 331 } 332 333 /* Handle old call that returned only aggregate */ 334 if (size == sizeof(cp_time[0]) * CPUSTATES) 335 ncpu = 1; 336 337 cpu_states = malloc(sizeof(cpu_states[0]) * CPUSTATES * ncpu); 338 cp_old = malloc(sizeof(cp_old[0]) * CPUSTATES * ncpu); 339 cp_diff = malloc(sizeof(cp_diff[0]) * CPUSTATES * ncpu); 340 if (cpu_states == NULL || cp_time == NULL || cp_old == NULL || 341 cp_diff == NULL) { 342 fprintf(stderr, "top: machine_init: %s\n", 343 strerror(errno)); 344 return(-1); 345 } 346 347 mib[0] = CTL_KERN; 348 mib[1] = KERN_CCPU; 349 size = sizeof(ccpu); 350 if (sysctl(mib, 2, &ccpu, &size, NULL, 0) == -1) { 351 fprintf(stderr, "top: sysctl kern.ccpu failed: %s\n", 352 strerror(errno)); 353 return(-1); 354 } 355 356 mib[0] = CTL_KERN; 357 mib[1] = KERN_CLOCKRATE; 358 size = sizeof(clockinfo); 359 if (sysctl(mib, 2, &clockinfo, &size, NULL, 0) == -1) { 360 fprintf(stderr, "top: sysctl kern.clockrate failed: %s\n", 361 strerror(errno)); 362 return(-1); 363 } 364 hz = clockinfo.stathz; 365 366 /* this is used in calculating WCPU -- calculate it ahead of time */ 367 logcpu = log(loaddouble(ccpu)); 368 369 pbase = NULL; 370 lbase = NULL; 371 pref = NULL; 372 nproc = 0; 373 onproc = -1; 374 nlwp = 0; 375 onlwp = -1; 376 /* get the page size with "getpagesize" and calculate pageshift from it */ 377 pagesize = getpagesize(); 378 pageshift = 0; 379 while (pagesize > 1) { 380 pageshift++; 381 pagesize >>= 1; 382 } 383 384 /* we only need the amount of log(2)1024 for our conversion */ 385 pageshift -= LOG1024; 386 387 /* fill in the statics information */ 388 #ifdef notyet 389 statics->ncpu = ncpu; 390 #endif 391 statics->procstate_names = procstatenames; 392 statics->cpustate_names = cpustatenames; 393 statics->memory_names = memorynames; 394 statics->swap_names = swapnames; 395 statics->order_names = ordernames; 396 statics->flags.threads = 1; 397 statics->flags.fullcmds = 1; 398 399 mib[0] = CTL_KERN; 400 mib[1] = KERN_BOOTTIME; 401 size = sizeof(boottime); 402 if (sysctl(mib, 2, &boottime, &size, NULL, 0) != -1 && 403 boottime.tv_sec != 0) 404 statics->boottime = boottime.tv_sec; 405 else 406 statics->boottime = 0; 407 /* all done! */ 408 return(0); 409 } 410 411 char * 412 format_process_header(struct process_select *sel, caddr_t handle, int count) 413 414 { 415 char *header; 416 char *ptr; 417 const char *uname_field = sel->usernames ? "USERNAME" : " UID "; 418 419 if (sel->threads) { 420 header = Thread_header; 421 ptr = header + THREAD_UNAME_START; 422 } else { 423 header = Proc_header; 424 ptr = header + PROC_UNAME_START; 425 } 426 427 while (*uname_field != '\0') { 428 *ptr++ = *uname_field++; 429 } 430 431 return(header); 432 } 433 434 char * 435 format_header(char *uname_field) 436 { 437 char *header = Proc_header; 438 char *ptr = header + PROC_UNAME_START; 439 440 while (*uname_field != '\0') { 441 *ptr++ = *uname_field++; 442 } 443 444 return(header); 445 } 446 447 void 448 get_system_info(struct system_info *si) 449 { 450 size_t ssize; 451 int mib[2]; 452 struct uvmexp_sysctl uvmexp; 453 struct swapent *sep; 454 u_int64_t totalsize, totalinuse; 455 int size, inuse, ncounted, i; 456 int rnswap, nswap; 457 458 mib[0] = CTL_KERN; 459 mib[1] = KERN_CP_TIME; 460 ssize = sizeof(cp_time[0]) * CPUSTATES * ncpu; 461 if (sysctl(mib, 2, cp_time, &ssize, NULL, 0) < 0) { 462 fprintf(stderr, "top: sysctl kern.cp_time failed: %s\n", 463 strerror(errno)); 464 quit(23); 465 } 466 467 if (getloadavg(si->load_avg, NUM_AVERAGES) < 0) { 468 int j; 469 470 warn("can't getloadavg"); 471 for (j = 0; j < NUM_AVERAGES; j++) 472 si->load_avg[j] = 0.0; 473 } 474 475 /* convert cp_time counts to percentages */ 476 for (i = 0; i < ncpu; i++) { 477 int j = i * CPUSTATES; 478 percentages64(CPUSTATES, cpu_states + j, cp_time + j, cp_old + j, 479 cp_diff + j); 480 } 481 482 mib[0] = CTL_VM; 483 mib[1] = VM_UVMEXP2; 484 ssize = sizeof(uvmexp); 485 if (sysctl(mib, 2, &uvmexp, &ssize, NULL, 0) < 0) { 486 fprintf(stderr, "top: sysctl vm.uvmexp2 failed: %s\n", 487 strerror(errno)); 488 quit(23); 489 } 490 491 /* convert memory stats to Kbytes */ 492 memory_stats[0] = pagetok(uvmexp.active); 493 memory_stats[1] = pagetok(uvmexp.inactive); 494 memory_stats[2] = pagetok(uvmexp.wired); 495 memory_stats[3] = pagetok(uvmexp.execpages); 496 memory_stats[4] = pagetok(uvmexp.filepages); 497 memory_stats[5] = pagetok(uvmexp.free); 498 499 swap_stats[0] = swap_stats[1] = swap_stats[2] = 0; 500 501 do { 502 nswap = swapctl(SWAP_NSWAP, 0, 0); 503 if (nswap < 1) 504 break; 505 if (nswap > maxswap) { 506 if (swapp) 507 free(swapp); 508 swapp = sep = malloc(nswap * sizeof(*sep)); 509 if (sep == NULL) 510 break; 511 maxswap = nswap; 512 } else 513 sep = swapp; 514 rnswap = swapctl(SWAP_STATS, (void *)sep, nswap); 515 if (nswap != rnswap) 516 break; 517 518 totalsize = totalinuse = ncounted = 0; 519 for (; rnswap-- > 0; sep++) { 520 ncounted++; 521 size = sep->se_nblks; 522 inuse = sep->se_inuse; 523 totalsize += size; 524 totalinuse += inuse; 525 } 526 swap_stats[0] = dbtob(totalsize) / 1024; 527 swap_stats[1] = dbtob(totalinuse) / 1024; 528 swap_stats[2] = dbtob(totalsize) / 1024 - swap_stats[1]; 529 } while (0); 530 531 memory_stats[6] = -1; 532 swap_stats[3] = -1; 533 534 /* set arrays and strings */ 535 si->cpustates = cpu_states; 536 si->memory = memory_stats; 537 si->swap = swap_stats; 538 si->last_pid = -1; 539 540 } 541 542 static struct kinfo_proc2 * 543 proc_from_thread(struct kinfo_lwp *pl) 544 { 545 struct kinfo_proc2 *pp = thread_pbase; 546 int i; 547 548 for (i = 0; i < thread_nproc; i++, pp++) 549 if ((pid_t)pp->p_pid == (pid_t)pl->l_pid) 550 return pp; 551 return NULL; 552 } 553 554 static int 555 uid_from_thread(struct kinfo_lwp *pl) 556 { 557 struct kinfo_proc2 *pp; 558 559 if ((pp = proc_from_thread(pl)) == NULL) 560 return -1; 561 return pp->p_ruid; 562 } 563 564 caddr_t 565 get_process_info(struct system_info *si, struct process_select *sel, int c) 566 { 567 userprint = sel->usernames ? username : itoa7; 568 569 if ((threadmode = sel->threads) != 0) 570 return get_lwp_info(si, sel, proc_compares[c]); 571 else 572 return get_proc_info(si, sel, proc_compares[c]); 573 } 574 575 static caddr_t 576 get_proc_info(struct system_info *si, struct process_select *sel, 577 int (*compare)(struct proc **, struct proc **)) 578 { 579 int i; 580 int total_procs; 581 int active_procs; 582 struct kinfo_proc2 **prefp, **n; 583 struct kinfo_proc2 *pp; 584 int op, arg; 585 586 /* these are copied out of sel for speed */ 587 int show_idle; 588 int show_system; 589 int show_uid; 590 int show_command; 591 592 static struct handle handle; 593 594 procgen++; 595 596 if (sel->pid == (pid_t)-1) { 597 op = KERN_PROC_ALL; 598 arg = 0; 599 } else { 600 op = KERN_PROC_PID; 601 arg = sel->pid; 602 } 603 604 pbase = kvm_getproc2(kd, op, arg, sizeof(struct kinfo_proc2), &nproc); 605 if (pbase == NULL) { 606 if (sel->pid != (pid_t)-1) { 607 nproc = 0; 608 } else { 609 (void) fprintf(stderr, "top: Out of memory.\n"); 610 quit(23); 611 } 612 } 613 if (nproc > onproc) { 614 n = (struct kinfo_proc2 **) realloc(pref, 615 sizeof(struct kinfo_proc2 *) * nproc); 616 if (n == NULL) { 617 (void) fprintf(stderr, "top: Out of memory.\n"); 618 quit(23); 619 } 620 pref = n; 621 onproc = nproc; 622 } 623 /* get a pointer to the states summary array */ 624 si->procstates = process_states; 625 626 /* set up flags which define what we are going to select */ 627 show_idle = sel->idle; 628 show_system = sel->system; 629 show_uid = sel->uid != -1; 630 show_command = sel->command != NULL; 631 632 /* count up process states and get pointers to interesting procs */ 633 total_procs = 0; 634 active_procs = 0; 635 memset((char *)process_states, 0, sizeof(process_states)); 636 prefp = pref; 637 for (pp = pbase, i = 0; i < nproc; pp++, i++) { 638 639 /* 640 * Place pointers to each valid proc structure in pref[]. 641 * Process slots that are actually in use have a non-zero 642 * status field. Processes with P_SYSTEM set are system 643 * processes---these get ignored unless show_sysprocs is set. 644 */ 645 if (pp->p_stat != 0 && (show_system || ((pp->p_flag & P_SYSTEM) == 0))) { 646 total_procs++; 647 process_states[(unsigned char) pp->p_stat]++; 648 if (pp->p_stat != LSZOMB && 649 (show_idle || (pp->p_pctcpu != 0) || 650 (pp->p_stat == LSRUN || pp->p_stat == LSONPROC)) && 651 (!show_uid || pp->p_ruid == (uid_t)sel->uid)) { 652 *prefp++ = pp; 653 active_procs++; 654 } 655 } 656 } 657 658 /* if requested, sort the "interesting" processes */ 659 if (compare != NULL) { 660 qsort((char *)pref, active_procs, sizeof(struct kinfo_proc2 *), 661 (int (*)(const void *, const void *))compare); 662 } 663 664 /* remember active and total counts */ 665 si->p_total = total_procs; 666 si->p_active = pref_len = active_procs; 667 668 /* pass back a handle */ 669 handle.next_proc = pref; 670 handle.remaining = active_procs; 671 handle.sel = sel; 672 return((caddr_t)&handle); 673 } 674 675 static caddr_t 676 get_lwp_info(struct system_info *si, struct process_select *sel, 677 int (*compare)(struct proc **, struct proc **)) 678 { 679 int i; 680 int total_lwps; 681 int active_lwps; 682 struct kinfo_lwp **lrefp, **n; 683 struct kinfo_lwp *lp; 684 struct kinfo_proc2 *pp; 685 686 /* these are copied out of sel for speed */ 687 int show_idle; 688 int show_system; 689 int show_uid; 690 int show_command; 691 692 static struct handle handle; 693 694 pp = kvm_getproc2(kd, KERN_PROC_ALL, 0, sizeof(struct kinfo_proc2), 695 &thread_nproc); 696 if (pp == NULL) { 697 (void) fprintf(stderr, "top: Out of memory.\n"); 698 quit(23); 699 } 700 if (thread_pbase == NULL || thread_nproc != thread_onproc) { 701 free(thread_pbase); 702 thread_onproc = thread_nproc; 703 thread_pbase = calloc(sizeof(struct kinfo_proc2), thread_nproc); 704 if (thread_pbase == NULL) { 705 (void) fprintf(stderr, "top: Out of memory.\n"); 706 quit(23); 707 } 708 } 709 memcpy(thread_pbase, pp, sizeof(struct kinfo_proc2) * thread_nproc); 710 711 lbase = kvm_getlwps(kd, -1, 0, sizeof(struct kinfo_lwp), &nlwp); 712 if (lbase == NULL) { 713 #ifdef notyet 714 if (sel->pid != (pid_t)-1) { 715 nproc = 0; 716 nlwp = 0; 717 } 718 else 719 #endif 720 { 721 (void) fprintf(stderr, "top: Out of memory.\n"); 722 quit(23); 723 } 724 } 725 if (nlwp > onlwp) { 726 n = (struct kinfo_lwp **) realloc(lref, 727 sizeof(struct kinfo_lwp *) * nlwp); 728 if (n == NULL) { 729 (void) fprintf(stderr, "top: Out of memory.\n"); 730 quit(23); 731 } 732 lref = n; 733 onlwp = nlwp; 734 } 735 /* get a pointer to the states summary array */ 736 si->procstates = process_states; 737 738 /* set up flags which define what we are going to select */ 739 show_idle = sel->idle; 740 show_system = sel->system; 741 show_uid = sel->uid != -1; 742 show_command = sel->command != NULL; 743 744 /* count up thread states and get pointers to interesting threads */ 745 total_lwps = 0; 746 active_lwps = 0; 747 memset((char *)process_states, 0, sizeof(process_states)); 748 lrefp = lref; 749 for (lp = lbase, i = 0; i < nlwp; lp++, i++) { 750 if (sel->pid != (pid_t)-1 && sel->pid != (pid_t)lp->l_pid) 751 continue; 752 753 /* 754 * Place pointers to each valid lwp structure in lref[]. 755 * thread slots that are actually in use have a non-zero 756 * status field. threads with L_SYSTEM set are system 757 * threads---these get ignored unless show_sysprocs is set. 758 */ 759 if (lp->l_stat != 0 && (show_system || ((lp->l_flag & LW_SYSTEM) == 0))) { 760 total_lwps++; 761 process_states[(unsigned char) lp->l_stat]++; 762 if (lp->l_stat != LSZOMB && 763 (show_idle || (lp->l_pctcpu != 0) || 764 (lp->l_stat == LSRUN || lp->l_stat == LSONPROC)) && 765 (!show_uid || uid_from_thread(lp) == sel->uid)) { 766 *lrefp++ = lp; 767 active_lwps++; 768 } 769 } 770 } 771 772 /* if requested, sort the "interesting" threads */ 773 if (compare != NULL) { 774 qsort((char *)lref, active_lwps, sizeof(struct kinfo_lwp *), 775 (int (*)(const void *, const void *))compare); 776 } 777 778 /* remember active and total counts */ 779 si->p_total = total_lwps; 780 si->p_active = lref_len = active_lwps; 781 782 /* pass back a handle */ 783 handle.next_proc = (struct kinfo_proc2 **)lref; 784 handle.remaining = active_lwps; 785 handle.sel = sel; 786 787 return((caddr_t)&handle); 788 } 789 790 char * 791 format_next_process(caddr_t handle, char *(*get_userid)(int)) 792 { 793 794 if (threadmode) 795 return format_next_lwp(handle, get_userid); 796 else 797 return format_next_proc(handle, get_userid); 798 } 799 800 801 char * 802 format_next_proc(caddr_t handle, char *(*get_userid)(int)) 803 { 804 struct kinfo_proc2 *pp; 805 long cputime; 806 double pct, wcpu, cpu; 807 struct handle *hp; 808 const char *statep; 809 #ifdef KI_NOCPU 810 char state[10]; 811 #endif 812 char wmesg[KI_WMESGLEN + 1]; 813 static char fmt[MAX_COLS]; /* static area where result is built */ 814 815 /* find and remember the next proc structure */ 816 hp = (struct handle *)handle; 817 pp = *(hp->next_proc++); 818 hp->remaining--; 819 820 /* get the process's user struct and set cputime */ 821 822 #if 0 823 /* This does not produce the correct results */ 824 cputime = pp->p_uticks + pp->p_sticks + pp->p_iticks; 825 #else 826 cputime = pp->p_rtime_sec; /* This does not count interrupts */ 827 #endif 828 829 /* calculate the base for CPU percentages */ 830 pct = pctdouble(pp->p_pctcpu); 831 832 if (pp->p_stat == LSSLEEP) { 833 strlcpy(wmesg, pp->p_wmesg, sizeof(wmesg)); 834 statep = wmesg; 835 } else 836 statep = state_abbrev[(unsigned)pp->p_stat]; 837 838 #ifdef KI_NOCPU 839 /* Post-1.5 change: add CPU number if appropriate */ 840 if (pp->p_cpuid != KI_NOCPU && ncpu > 1) { 841 switch (pp->p_stat) { 842 case LSONPROC: 843 case LSRUN: 844 case LSSLEEP: 845 case LSIDL: 846 (void)snprintf(state, sizeof(state), "%.6s/%u", 847 statep, (unsigned int)pp->p_cpuid); 848 statep = state; 849 break; 850 } 851 } 852 #endif 853 wcpu = 100.0 * weighted_cpu(p_, pct, pp); 854 cpu = 100.0 * pct; 855 856 /* format this entry */ 857 sprintf(fmt, 858 Proc_format, 859 pp->p_pid, 860 (*userprint)(pp->p_ruid), 861 pp->p_priority, 862 pp->p_nice - NZERO, 863 format_k(pagetok(PROCSIZE(pp))), 864 format_k(pagetok(pp->p_vm_rssize)), 865 statep, 866 format_time(cputime), 867 (wcpu >= 100.0) ? 0 : 2, wcpu, 868 (cpu >= 100.0) ? 0 : 2, cpu, 869 get_command(hp->sel, pp)); 870 871 /* return the result */ 872 return(fmt); 873 } 874 875 static char * 876 format_next_lwp(caddr_t handle, char *(*get_userid)(int)) 877 { 878 struct kinfo_proc2 *pp; 879 struct kinfo_lwp *pl; 880 long cputime; 881 double pct; 882 struct handle *hp; 883 const char *statep; 884 #ifdef KI_NOCPU 885 char state[10]; 886 #endif 887 char wmesg[KI_WMESGLEN + 1]; 888 static char fmt[MAX_COLS]; /* static area where result is built */ 889 int uid; 890 891 /* find and remember the next proc structure */ 892 hp = (struct handle *)handle; 893 pl = (struct kinfo_lwp *)*(hp->next_proc++); 894 hp->remaining--; 895 pp = proc_from_thread(pl); 896 897 /* get the process's user struct and set cputime */ 898 uid = pp ? pp->p_ruid : 0; 899 900 cputime = pl->l_rtime_sec; 901 902 /* calculate the base for CPU percentages */ 903 pct = pctdouble(pl->l_pctcpu); 904 905 if (pl->l_stat == LSSLEEP) { 906 strlcpy(wmesg, pl->l_wmesg, sizeof(wmesg)); 907 statep = wmesg; 908 } else 909 statep = state_abbrev[(unsigned)pl->l_stat]; 910 911 #ifdef KI_NOCPU 912 /* Post-1.5 change: add CPU number if appropriate */ 913 if (pl->l_cpuid != KI_NOCPU && ncpu > 1) { 914 switch (pl->l_stat) { 915 case LSONPROC: 916 case LSRUN: 917 case LSSLEEP: 918 case LSIDL: 919 (void)snprintf(state, sizeof(state), "%.6s/%u", 920 statep, (unsigned int)pl->l_cpuid); 921 statep = state; 922 break; 923 } 924 } 925 #endif 926 927 if (pl->l_name[0] == '\0') { 928 pl->l_name[0] = '-'; 929 pl->l_name[1] = '\0'; 930 } 931 932 /* format this entry */ 933 sprintf(fmt, 934 Thread_format, 935 pl->l_pid, 936 pl->l_lid, 937 (*userprint)(uid), 938 pl->l_priority, 939 statep, 940 format_time(cputime), 941 100.0 * weighted_cpu(l_, pct, pl), 942 100.0 * pct, 943 printable(pl->l_name), 944 get_command(hp->sel, pp)); 945 946 /* return the result */ 947 return(fmt); 948 } 949 950 /* comparison routines for qsort */ 951 952 /* 953 * There are currently four possible comparison routines. main selects 954 * one of these by indexing in to the array proc_compares. 955 * 956 * Possible keys are defined as macros below. Currently these keys are 957 * defined: percent CPU, CPU ticks, process state, resident set size, 958 * total virtual memory usage. The process states are ordered as follows 959 * (from least to most important): WAIT, zombie, sleep, stop, start, run. 960 * The array declaration below maps a process state index into a number 961 * that reflects this ordering. 962 */ 963 964 /* 965 * First, the possible comparison keys. These are defined in such a way 966 * that they can be merely listed in the source code to define the actual 967 * desired ordering. 968 */ 969 970 #define ORDERKEY_PCTCPU(pfx) \ 971 if (lresult = (pctcpu)(p2)->pfx ## pctcpu - (pctcpu)(p1)->pfx ## pctcpu,\ 972 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0) 973 974 #define ORDERKEY_CPTICKS(pfx) \ 975 if (lresult = (pctcpu)(p2)->pfx ## rtime_sec \ 976 - (pctcpu)(p1)->pfx ## rtime_sec,\ 977 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0) 978 979 #define ORDERKEY_STATE(pfx) \ 980 if ((result = sorted_state[(int)(p2)->pfx ## stat] - \ 981 sorted_state[(int)(p1)->pfx ## stat] ) == 0) 982 983 #define ORDERKEY_PRIO(pfx) \ 984 if ((result = (p2)->pfx ## priority - (p1)->pfx ## priority) == 0) 985 986 #define ORDERKEY_RSSIZE \ 987 if ((result = p2->p_vm_rssize - p1->p_vm_rssize) == 0) 988 989 #define ORDERKEY_MEM \ 990 if ((result = (PROCSIZE(p2) - PROCSIZE(p1))) == 0) 991 #define ORDERKEY_SIZE(v1, v2) \ 992 if ((result = (v2 - v1)) == 0) 993 994 /* 995 * Now the array that maps process state to a weight. 996 * The order of the elements should match those in state_abbrev[] 997 */ 998 999 static int sorted_state[] = { 1000 0, /* (not used) ? */ 1001 1, /* "start" SIDL */ 1002 4, /* "run" SRUN */ 1003 3, /* "sleep" SSLEEP */ 1004 3, /* "stop" SSTOP */ 1005 2, /* "dead" SDEAD */ 1006 1, /* "zomb" SZOMB */ 1007 5, /* "onproc" SONPROC */ 1008 }; 1009 1010 /* compare_cpu - the comparison function for sorting by CPU percentage */ 1011 1012 static int 1013 compare_cpu(pp1, pp2) 1014 struct proc **pp1, **pp2; 1015 { 1016 int result; 1017 pctcpu lresult; 1018 1019 if (threadmode) { 1020 struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1; 1021 struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2; 1022 1023 ORDERKEY_PCTCPU(l_) 1024 ORDERKEY_CPTICKS(l_) 1025 ORDERKEY_STATE(l_) 1026 ORDERKEY_PRIO(l_) 1027 return result; 1028 } else { 1029 struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1; 1030 struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2; 1031 1032 ORDERKEY_PCTCPU(p_) 1033 ORDERKEY_CPTICKS(p_) 1034 ORDERKEY_STATE(p_) 1035 ORDERKEY_PRIO(p_) 1036 ORDERKEY_RSSIZE 1037 ORDERKEY_MEM 1038 return result; 1039 } 1040 1041 return (result); 1042 } 1043 1044 /* compare_prio - the comparison function for sorting by process priority */ 1045 1046 static int 1047 compare_prio(pp1, pp2) 1048 struct proc **pp1, **pp2; 1049 { 1050 int result; 1051 pctcpu lresult; 1052 1053 if (threadmode) { 1054 struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1; 1055 struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2; 1056 1057 ORDERKEY_PRIO(l_) 1058 ORDERKEY_PCTCPU(l_) 1059 ORDERKEY_CPTICKS(l_) 1060 ORDERKEY_STATE(l_) 1061 return result; 1062 } else { 1063 struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1; 1064 struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2; 1065 1066 ORDERKEY_PRIO(p_) 1067 ORDERKEY_PCTCPU(p_) 1068 ORDERKEY_CPTICKS(p_) 1069 ORDERKEY_STATE(p_) 1070 ORDERKEY_RSSIZE 1071 ORDERKEY_MEM 1072 return result; 1073 } 1074 1075 return (result); 1076 } 1077 1078 /* compare_res - the comparison function for sorting by resident set size */ 1079 1080 static int 1081 compare_res(pp1, pp2) 1082 struct proc **pp1, **pp2; 1083 { 1084 int result; 1085 pctcpu lresult; 1086 1087 if (threadmode) { 1088 struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1; 1089 struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2; 1090 1091 ORDERKEY_PCTCPU(l_) 1092 ORDERKEY_CPTICKS(l_) 1093 ORDERKEY_STATE(l_) 1094 ORDERKEY_PRIO(l_) 1095 return result; 1096 } else { 1097 struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1; 1098 struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2; 1099 1100 ORDERKEY_RSSIZE 1101 ORDERKEY_MEM 1102 ORDERKEY_PCTCPU(p_) 1103 ORDERKEY_CPTICKS(p_) 1104 ORDERKEY_STATE(p_) 1105 ORDERKEY_PRIO(p_) 1106 return result; 1107 } 1108 1109 return (result); 1110 } 1111 1112 static int 1113 compare_pid(pp1, pp2) 1114 struct proc **pp1, **pp2; 1115 { 1116 if (threadmode) { 1117 struct kinfo_lwp *l1 = *(struct kinfo_lwp **) pp1; 1118 struct kinfo_lwp *l2 = *(struct kinfo_lwp **) pp2; 1119 struct kinfo_proc2 *p1 = proc_from_thread(l1); 1120 struct kinfo_proc2 *p2 = proc_from_thread(l2); 1121 return p2->p_pid - p1->p_pid; 1122 } else { 1123 struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1; 1124 struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2; 1125 return p2->p_pid - p1->p_pid; 1126 } 1127 } 1128 1129 static int 1130 compare_command(pp1, pp2) 1131 struct proc **pp1, **pp2; 1132 { 1133 if (threadmode) { 1134 struct kinfo_lwp *l1 = *(struct kinfo_lwp **) pp1; 1135 struct kinfo_lwp *l2 = *(struct kinfo_lwp **) pp2; 1136 struct kinfo_proc2 *p1 = proc_from_thread(l1); 1137 struct kinfo_proc2 *p2 = proc_from_thread(l2); 1138 return strcmp(p2->p_comm, p1->p_comm); 1139 } else { 1140 struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1; 1141 struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2; 1142 return strcmp(p2->p_comm, p1->p_comm); 1143 } 1144 } 1145 1146 static int 1147 compare_username(pp1, pp2) 1148 struct proc **pp1, **pp2; 1149 { 1150 if (threadmode) { 1151 struct kinfo_lwp *l1 = *(struct kinfo_lwp **) pp1; 1152 struct kinfo_lwp *l2 = *(struct kinfo_lwp **) pp2; 1153 struct kinfo_proc2 *p1 = proc_from_thread(l1); 1154 struct kinfo_proc2 *p2 = proc_from_thread(l2); 1155 return strcmp(p2->p_login, p1->p_login); 1156 } else { 1157 struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1; 1158 struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2; 1159 return strcmp(p2->p_login, p1->p_login); 1160 } 1161 } 1162 /* compare_size - the comparison function for sorting by total memory usage */ 1163 1164 static int 1165 compare_size(pp1, pp2) 1166 struct proc **pp1, **pp2; 1167 { 1168 int result; 1169 pctcpu lresult; 1170 1171 if (threadmode) { 1172 struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1; 1173 struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2; 1174 1175 ORDERKEY_PCTCPU(l_) 1176 ORDERKEY_CPTICKS(l_) 1177 ORDERKEY_STATE(l_) 1178 ORDERKEY_PRIO(l_) 1179 return result; 1180 } else { 1181 struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1; 1182 struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2; 1183 1184 ORDERKEY_MEM 1185 ORDERKEY_RSSIZE 1186 ORDERKEY_PCTCPU(p_) 1187 ORDERKEY_CPTICKS(p_) 1188 ORDERKEY_STATE(p_) 1189 ORDERKEY_PRIO(p_) 1190 return result; 1191 } 1192 1193 return (result); 1194 } 1195 1196 /* compare_state - the comparison function for sorting by process state */ 1197 1198 static int 1199 compare_state(pp1, pp2) 1200 struct proc **pp1, **pp2; 1201 { 1202 int result; 1203 pctcpu lresult; 1204 1205 if (threadmode) { 1206 struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1; 1207 struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2; 1208 1209 ORDERKEY_STATE(l_) 1210 ORDERKEY_PCTCPU(l_) 1211 ORDERKEY_CPTICKS(l_) 1212 ORDERKEY_PRIO(l_) 1213 return result; 1214 } else { 1215 struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1; 1216 struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2; 1217 1218 ORDERKEY_STATE(p_) 1219 ORDERKEY_PCTCPU(p_) 1220 ORDERKEY_CPTICKS(p_) 1221 ORDERKEY_PRIO(p_) 1222 ORDERKEY_RSSIZE 1223 ORDERKEY_MEM 1224 return result; 1225 } 1226 1227 return (result); 1228 } 1229 1230 /* compare_time - the comparison function for sorting by total CPU time */ 1231 1232 static int 1233 compare_time(pp1, pp2) 1234 struct proc **pp1, **pp2; 1235 { 1236 int result; 1237 pctcpu lresult; 1238 1239 if (threadmode) { 1240 struct kinfo_lwp *p1 = *(struct kinfo_lwp **) pp1; 1241 struct kinfo_lwp *p2 = *(struct kinfo_lwp **) pp2; 1242 1243 ORDERKEY_CPTICKS(l_) 1244 ORDERKEY_PCTCPU(l_) 1245 ORDERKEY_STATE(l_) 1246 ORDERKEY_PRIO(l_) 1247 return result; 1248 } else { 1249 struct kinfo_proc2 *p1 = *(struct kinfo_proc2 **) pp1; 1250 struct kinfo_proc2 *p2 = *(struct kinfo_proc2 **) pp2; 1251 1252 ORDERKEY_CPTICKS(p_) 1253 ORDERKEY_PCTCPU(p_) 1254 ORDERKEY_STATE(p_) 1255 ORDERKEY_PRIO(p_) 1256 ORDERKEY_MEM 1257 ORDERKEY_RSSIZE 1258 return result; 1259 } 1260 1261 return (result); 1262 } 1263 1264 1265 /* 1266 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if 1267 * the process does not exist. 1268 * It is EXTREMLY IMPORTANT that this function work correctly. 1269 * If top runs setuid root (as in SVR4), then this function 1270 * is the only thing that stands in the way of a serious 1271 * security problem. It validates requests for the "kill" 1272 * and "renice" commands. 1273 */ 1274 1275 int 1276 proc_owner(pid) 1277 int pid; 1278 { 1279 int cnt; 1280 struct kinfo_proc2 **prefp; 1281 struct kinfo_proc2 *pp; 1282 1283 if (threadmode) 1284 return(-1); 1285 1286 prefp = pref; 1287 cnt = pref_len; 1288 while (--cnt >= 0) { 1289 pp = *prefp++; 1290 if (pp->p_pid == (pid_t)pid) 1291 return(pp->p_ruid); 1292 } 1293 return(-1); 1294 } 1295 1296 /* 1297 * percentages(cnt, out, new, old, diffs) - calculate percentage change 1298 * between array "old" and "new", putting the percentages i "out". 1299 * "cnt" is size of each array and "diffs" is used for scratch space. 1300 * The array "old" is updated on each call. 1301 * The routine assumes modulo arithmetic. This function is especially 1302 * useful on BSD mchines for calculating CPU state percentages. 1303 */ 1304 1305 static void 1306 percentages64(cnt, out, new, old, diffs) 1307 int cnt; 1308 int *out; 1309 u_int64_t *new; 1310 u_int64_t *old; 1311 u_int64_t *diffs; 1312 { 1313 int i; 1314 u_int64_t change; 1315 u_int64_t total_change; 1316 u_int64_t *dp; 1317 u_int64_t half_total; 1318 1319 /* initialization */ 1320 total_change = 0; 1321 dp = diffs; 1322 1323 /* calculate changes for each state and the overall change */ 1324 for (i = 0; i < cnt; i++) { 1325 /* 1326 * Don't worry about wrapping - even at hz=1GHz, a 1327 * u_int64_t will last at least 544 years. 1328 */ 1329 change = *new - *old; 1330 total_change += (*dp++ = change); 1331 *old++ = *new++; 1332 } 1333 1334 /* avoid divide by zero potential */ 1335 if (total_change == 0) 1336 total_change = 1; 1337 1338 /* calculate percentages based on overall change, rounding up */ 1339 half_total = total_change / 2; 1340 for (i = 0; i < cnt; i++) 1341 *out++ = (int)((*diffs++ * 1000 + half_total) / total_change); 1342 } 1343