Make the -O option (show *only* kernel threads) imply the -T option (show
[dragonfly.git] / usr.bin / top / machine.c
CommitLineData
984263bc
MD
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>
95578ad0 21 * Hiten Pandya <hmp@backplane.com>
984263bc
MD
22 *
23 * $FreeBSD: src/usr.bin/top/machine.c,v 1.29.2.2 2001/07/31 20:27:05 tmm Exp $
e225a94c 24 * $DragonFly: src/usr.bin/top/machine.c,v 1.25 2008/03/01 18:49:00 nant Exp $
984263bc
MD
25 */
26
27
28#include <sys/time.h>
29#include <sys/types.h>
30#include <sys/signal.h>
31#include <sys/param.h>
32
33#include "os.h"
f5d21610
JS
34#include <err.h>
35#include <kvm.h>
984263bc 36#include <stdio.h>
984263bc 37#include <math.h>
984263bc
MD
38#include <pwd.h>
39#include <sys/errno.h>
40#include <sys/sysctl.h>
984263bc
MD
41#include <sys/file.h>
42#include <sys/time.h>
984263bc
MD
43#include <sys/user.h>
44#include <sys/vmmeter.h>
45#include <sys/resource.h>
46#include <sys/rtprio.h>
47
48/* Swap */
49#include <stdlib.h>
50#include <sys/conf.h>
51
52#include <osreldate.h> /* for changes in kernel structures */
53
f5d21610 54#include <sys/kinfo.h>
9169bd75 55#include <kinfo.h>
984263bc
MD
56#include "top.h"
57#include "machine.h"
58
1d1731fa
HP
59static int check_nlist(struct nlist *);
60static int getkval(unsigned long, int *, int, char *);
61extern char* printable(char *);
62int swapmode(int *retavail, int *retfree);
984263bc
MD
63static int smpmode;
64static int namelength;
65static int cmdlength;
66
95578ad0
HP
67/*
68 * needs to be a global symbol, so wrapper can be
69 * modified accordingly.
70 */
71static int show_threads = 0;
984263bc
MD
72
73/* get_process_info passes back a handle. This is what it looks like: */
74
75struct handle
76{
77 struct kinfo_proc **next_proc; /* points to next valid proc pointer */
78 int remaining; /* number of pointers remaining */
79};
80
81/* declarations for load_avg */
82#include "loadavg.h"
83
5dfd06ac
SS
84#define PP(pp, field) ((pp)->kp_ ## field)
85#define LP(pp, field) ((pp)->kp_lwp.kl_ ## field)
86#define VP(pp, field) ((pp)->kp_vm_ ## field)
984263bc
MD
87
88/* define what weighted cpu is. */
08f2f1bb
SS
89#define weighted_cpu(pct, pp) (PP((pp), swtime) == 0 ? 0.0 : \
90 ((pct) / (1.0 - exp(PP((pp), swtime) * logcpu))))
984263bc
MD
91
92/* what we consider to be process size: */
5dfd06ac 93#define PROCSIZE(pp) (VP((pp), map_size) / 1024)
984263bc 94
984263bc
MD
95/*
96 * These definitions control the format of the per-process area
97 */
98
99static char smp_header[] =
100 " PID %-*.*s PRI NICE SIZE RES STATE C TIME WCPU CPU COMMAND";
101
102#define smp_Proc_format \
103 "%5d %-*.*s %3d %3d%7s %6s %-6.6s %1x%7s %5.2f%% %5.2f%% %.*s"
104
105static char up_header[] =
106 " PID %-*.*s PRI NICE SIZE RES STATE TIME WCPU CPU COMMAND";
107
108#define up_Proc_format \
109 "%5d %-*.*s %3d %3d%7s %6s %-6.6s%.0d%7s %5.2f%% %5.2f%% %.*s"
110
111
112
113/* process state names for the "STATE" column of the display */
114/* the extra nulls in the string "run" are for adding a slash and
115 the processor number when needed */
116
117char *state_abbrev[] =
118{
164b8401 119 "", "RUN\0\0\0", "STOP", "SLEEP",
984263bc
MD
120};
121
122
123static kvm_t *kd;
124
125/* values that we stash away in _init and use in later routines */
126
127static double logcpu;
128
984263bc 129static long lastpid;
984263bc 130static long cnt;
f5d21610 131static int ccpu;
984263bc
MD
132
133/* these are for calculating cpu state percentages */
134
edb881dd 135static struct kinfo_cputime *cp_time, *cp_old;
984263bc
MD
136
137/* these are for detailing the process states */
138
139int process_states[6];
140char *procstatenames[] = {
141 "", " starting, ", " running, ", " sleeping, ", " stopped, ",
142 " zombie, ",
143 NULL
144};
145
146/* these are for detailing the cpu states */
f5d21610 147#define CPU_STATES 5
edb881dd 148int *cpu_states;
f5d21610 149char *cpustatenames[CPU_STATES + 1] = {
984263bc
MD
150 "user", "nice", "system", "interrupt", "idle", NULL
151};
152
153/* these are for detailing the memory statistics */
154
155int memory_stats[7];
156char *memorynames[] = {
157 "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
158 NULL
159};
160
161int swap_stats[7];
162char *swapnames[] = {
163/* 0 1 2 3 4 5 */
164 "K Total, ", "K Used, ", "K Free, ", "% Inuse, ", "K In, ", "K Out",
165 NULL
166};
167
168
169/* these are for keeping track of the proc array */
170
171static int nproc;
172static int onproc = -1;
173static int pref_len;
174static struct kinfo_proc *pbase;
175static struct kinfo_proc **pref;
176
177/* these are for getting the memory statistics */
178
179static int pageshift; /* log base 2 of the pagesize */
180
181/* define pagetok in terms of pageshift */
182
183#define pagetok(size) ((size) << pageshift)
184
984263bc
MD
185#ifdef ORDER
186/* sorting orders. first is default */
187char *ordernames[] = {
95578ad0 188 "cpu", "size", "res", "time", "pri", "thr", NULL
984263bc
MD
189};
190#endif
191
f5d21610
JS
192static void
193cputime_percentages(int out[CPU_STATES], struct kinfo_cputime *new,
194 struct kinfo_cputime *old)
195{
196 struct kinfo_cputime diffs;
f5d21610
JS
197 uint64_t total_change, half_total;
198
199 /* initialization */
200 total_change = 0;
201
202 diffs.cp_user = new->cp_user - old->cp_user;
203 diffs.cp_nice = new->cp_nice - old->cp_nice;
204 diffs.cp_sys = new->cp_sys - old->cp_sys;
205 diffs.cp_intr = new->cp_intr - old->cp_intr;
206 diffs.cp_idle = new->cp_idle - old->cp_idle;
207 total_change = diffs.cp_user + diffs.cp_nice + diffs.cp_sys +
208 diffs.cp_intr + diffs.cp_idle;
209 old->cp_user = new->cp_user;
210 old->cp_nice = new->cp_nice;
211 old->cp_sys = new->cp_sys;
212 old->cp_intr = new->cp_intr;
213 old->cp_idle = new->cp_idle;
214
215 /* avoid divide by zero potential */
216 if (total_change == 0)
217 total_change = 1;
218
219 /* calculate percentages based on overall change, rounding up */
220 half_total = total_change >> 1;
221
222 out[0] = ((diffs.cp_user * 1000LL + half_total) / total_change);
223 out[1] = ((diffs.cp_nice * 1000LL + half_total) / total_change);
224 out[2] = ((diffs.cp_sys * 1000LL + half_total) / total_change);
225 out[3] = ((diffs.cp_intr * 1000LL + half_total) / total_change);
226 out[4] = ((diffs.cp_idle * 1000LL + half_total) / total_change);
227}
228
984263bc 229int
1d1731fa 230machine_init(struct statics *statics)
984263bc
MD
231{
232 register int i = 0;
233 register int pagesize;
234 size_t modelen;
235 struct passwd *pw;
236
edb881dd
YT
237 if (n_cpus < 1) {
238 if (kinfo_get_cpus(&n_cpus))
239 err(1, "kinfo_get_cpus failed");
240 }
984263bc
MD
241 modelen = sizeof(smpmode);
242 if ((sysctlbyname("machdep.smp_active", &smpmode, &modelen, NULL, 0) < 0 &&
243 sysctlbyname("smp.smp_active", &smpmode, &modelen, NULL, 0) < 0) ||
244 modelen != sizeof(smpmode))
245 smpmode = 0;
246
247 while ((pw = getpwent()) != NULL) {
248 if (strlen(pw->pw_name) > namelength)
249 namelength = strlen(pw->pw_name);
250 }
251 if (namelength < 8)
252 namelength = 8;
253 if (smpmode && namelength > 13)
254 namelength = 13;
255 else if (namelength > 15)
256 namelength = 15;
257
258 if ((kd = kvm_open(NULL, NULL, NULL, O_RDONLY, "kvm_open")) == NULL)
259 return -1;
260
f5d21610
JS
261 if (kinfo_get_sched_ccpu(&ccpu)) {
262 fprintf(stderr, "top: kinfo_get_sched_ccpu failed\n");
984263bc
MD
263 return(-1);
264 }
265
984263bc
MD
266 /* this is used in calculating WCPU -- calculate it ahead of time */
267 logcpu = log(loaddouble(ccpu));
268
269 pbase = NULL;
270 pref = NULL;
271 nproc = 0;
272 onproc = -1;
273 /* get the page size with "getpagesize" and calculate pageshift from it */
274 pagesize = getpagesize();
275 pageshift = 0;
276 while (pagesize > 1)
277 {
278 pageshift++;
279 pagesize >>= 1;
280 }
281
282 /* we only need the amount of log(2)1024 for our conversion */
283 pageshift -= LOG1024;
284
285 /* fill in the statics information */
286 statics->procstate_names = procstatenames;
287 statics->cpustate_names = cpustatenames;
288 statics->memory_names = memorynames;
289 statics->swap_names = swapnames;
290#ifdef ORDER
291 statics->order_names = ordernames;
292#endif
293
294 /* all done! */
295 return(0);
296}
297
1d1731fa 298char *format_header(register char *uname_field)
984263bc
MD
299{
300 register char *ptr;
301 static char Header[128];
302
303 snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
304 namelength, namelength, uname_field);
305
95578ad0
HP
306 if (screen_width <= 79)
307 cmdlength = 80;
308 else
309 cmdlength = 89;
310
311 cmdlength = cmdlength - strlen(Header) + 6;
984263bc
MD
312
313 return Header;
314}
315
316static int swappgsin = -1;
317static int swappgsout = -1;
318extern struct timeval timeout;
319
320void
1d1731fa 321get_system_info(struct system_info *si)
984263bc
MD
322{
323 long total;
984263bc
MD
324 int mib[2];
325 struct timeval boottime;
326 size_t bt_size;
edb881dd
YT
327 size_t len;
328 int cpu;
329
330 if (cpu_states == NULL) {
331 cpu_states = malloc(sizeof(*cpu_states) * CPU_STATES * n_cpus);
332 if (cpu_states == NULL)
333 err(1, "malloc");
334 bzero(cpu_states, sizeof(*cpu_states) * CPU_STATES * n_cpus);
335 }
336 if (cp_time == NULL) {
337 cp_time = malloc(2 * n_cpus * sizeof(cp_time[0]));
338 if (cp_time == NULL)
339 err(1, "cp_time");
340 cp_old = cp_time + n_cpus;
341
342 len = n_cpus * sizeof(cp_old[0]);
343 bzero(cp_time, len);
344 if (sysctlbyname("kern.cputime", cp_old, &len, NULL, 0))
345 err(1, "kern.cputime");
346 }
984263bc 347
edb881dd
YT
348 len = n_cpus * sizeof(cp_time[0]);
349 bzero(cp_time, len);
350 if (sysctlbyname("kern.cputime", cp_time, &len, NULL, 0))
351 err(1, "kern.cputime");
984263bc 352
f5d21610 353 getloadavg(si->load_avg, 3);
984263bc 354
f5d21610 355 lastpid = 0;
984263bc
MD
356
357 /* convert cp_time counts to percentages */
edb881dd
YT
358 for (cpu = 0; cpu < n_cpus; ++cpu) {
359 cputime_percentages(cpu_states + cpu * CPU_STATES,
360 &cp_time[cpu], &cp_old[cpu]);
361 }
984263bc
MD
362
363 /* sum memory & swap statistics */
364 {
393dfc63
MD
365 struct vmmeter vmm;
366 struct vmstats vms;
367 int vms_size = sizeof(vms);
368 int vmm_size = sizeof(vmm);
984263bc
MD
369 static unsigned int swap_delay = 0;
370 static int swapavail = 0;
371 static int swapfree = 0;
372 static int bufspace = 0;
373
47e61ecd
LF
374 if (sysctlbyname("vm.vmstats", &vms, &vms_size, NULL, 0))
375 err(1, "sysctlbyname: vm.vmstats");
376
377 if (sysctlbyname("vm.vmmeter", &vmm, &vmm_size, NULL, 0))
378 err(1, "sysctlbyname: vm.vmmeter");
379
380 if (kinfo_get_vfs_bufspace(&bufspace))
381 err(1, "kinfo_get_vfs_bufspace");
984263bc
MD
382
383 /* convert memory stats to Kbytes */
393dfc63
MD
384 memory_stats[0] = pagetok(vms.v_active_count);
385 memory_stats[1] = pagetok(vms.v_inactive_count);
386 memory_stats[2] = pagetok(vms.v_wire_count);
387 memory_stats[3] = pagetok(vms.v_cache_count);
984263bc 388 memory_stats[4] = bufspace / 1024;
393dfc63 389 memory_stats[5] = pagetok(vms.v_free_count);
984263bc
MD
390 memory_stats[6] = -1;
391
392 /* first interval */
393 if (swappgsin < 0) {
394 swap_stats[4] = 0;
395 swap_stats[5] = 0;
396 }
397
398 /* compute differences between old and new swap statistic */
399 else {
393dfc63
MD
400 swap_stats[4] = pagetok(((vmm.v_swappgsin - swappgsin)));
401 swap_stats[5] = pagetok(((vmm.v_swappgsout - swappgsout)));
984263bc
MD
402 }
403
393dfc63
MD
404 swappgsin = vmm.v_swappgsin;
405 swappgsout = vmm.v_swappgsout;
984263bc
MD
406
407 /* call CPU heavy swapmode() only for changes */
408 if (swap_stats[4] > 0 || swap_stats[5] > 0 || swap_delay == 0) {
409 swap_stats[3] = swapmode(&swapavail, &swapfree);
410 swap_stats[0] = swapavail;
411 swap_stats[1] = swapavail - swapfree;
412 swap_stats[2] = swapfree;
413 }
414 swap_delay = 1;
415 swap_stats[6] = -1;
416 }
417
418 /* set arrays and strings */
419 si->cpustates = cpu_states;
420 si->memory = memory_stats;
421 si->swap = swap_stats;
422
423
424 if(lastpid > 0) {
425 si->last_pid = lastpid;
426 } else {
427 si->last_pid = -1;
428 }
429
430 /*
431 * Print how long system has been up.
432 * (Found by looking getting "boottime" from the kernel)
433 */
434 mib[0] = CTL_KERN;
435 mib[1] = KERN_BOOTTIME;
436 bt_size = sizeof(boottime);
437 if (sysctl(mib, 2, &boottime, &bt_size, NULL, 0) != -1 &&
438 boottime.tv_sec != 0) {
439 si->boottime = boottime;
440 } else {
441 si->boottime.tv_sec = -1;
442 }
443}
444
445static struct handle handle;
446
1d1731fa
HP
447caddr_t get_process_info(struct system_info *si, struct process_select *sel,
448 int (*compare)())
984263bc
MD
449{
450 register int i;
451 register int total_procs;
452 register int active_procs;
453 register struct kinfo_proc **prefp;
454 register struct kinfo_proc *pp;
455
456 /* these are copied out of sel for speed */
457 int show_idle;
458 int show_self;
459 int show_system;
a45ee431 460 int show_only_threads;
984263bc
MD
461 int show_uid;
462 int show_command;
463
464
465 pbase = kvm_getprocs(kd, KERN_PROC_ALL, 0, &nproc);
466 if (nproc > onproc)
467 pref = (struct kinfo_proc **) realloc(pref, sizeof(struct kinfo_proc *)
468 * (onproc = nproc));
469 if (pref == NULL || pbase == NULL) {
470 (void) fprintf(stderr, "top: Out of memory.\n");
471 quit(23);
472 }
473 /* get a pointer to the states summary array */
474 si->procstates = process_states;
475
476 /* set up flags which define what we are going to select */
477 show_idle = sel->idle;
478 show_self = sel->self;
479 show_system = sel->system;
e225a94c 480 show_threads = sel->threads || sel->only_threads;
a45ee431 481 show_only_threads = sel->only_threads;
984263bc
MD
482 show_uid = sel->uid != -1;
483 show_command = sel->command != NULL;
484
485 /* count up process states and get pointers to interesting procs */
486 total_procs = 0;
487 active_procs = 0;
488 memset((char *)process_states, 0, sizeof(process_states));
489 prefp = pref;
490 for (pp = pbase, i = 0; i < nproc; pp++, i++)
491 {
492 /*
493 * Place pointers to each valid proc structure in pref[].
494 * Process slots that are actually in use have a non-zero
495 * status field. Processes with P_SYSTEM set are system
496 * processes---these get ignored unless show_sysprocs is set.
497 */
18170ab7 498 if ((show_threads && (LP(pp, pid) == -1)) ||
5dfd06ac
SS
499 (!show_only_threads && (PP(pp, stat) != 0 &&
500 (show_self != PP(pp, pid)) &&
501 (show_system || ((PP(pp, flags) & P_SYSTEM) == 0)))))
984263bc
MD
502 {
503 total_procs++;
5dfd06ac 504 process_states[(unsigned char) PP(pp, stat)]++;
18170ab7 505 if ((show_threads && (LP(pp, pid) == -1)) ||
416d05d7 506 (!show_only_threads && PP(pp, stat) != SZOMB &&
5dfd06ac 507 (show_idle || (LP(pp, pctcpu) != 0) ||
164b8401 508 (LP(pp, stat) == LSRUN)) &&
5dfd06ac 509 (!show_uid || PP(pp, ruid) == (uid_t)sel->uid)))
984263bc
MD
510 {
511 *prefp++ = pp;
512 active_procs++;
513 }
514 }
515 }
516
517 /* if requested, sort the "interesting" processes */
518 if (compare != NULL)
519 {
520 qsort((char *)pref, active_procs, sizeof(struct kinfo_proc *), compare);
521 }
522
523 /* remember active and total counts */
524 si->p_total = total_procs;
525 si->p_active = pref_len = active_procs;
526
527 /* pass back a handle */
528 handle.next_proc = pref;
529 handle.remaining = active_procs;
530 return((caddr_t)&handle);
531}
532
533char fmt[128]; /* static area where result is built */
534
1d1731fa 535char *format_next_process(caddr_t handle, char *(*get_userid)())
984263bc 536{
6ac7b760
MD
537 struct kinfo_proc *pp;
538 long cputime;
539 double pct;
984263bc
MD
540 struct handle *hp;
541 char status[16];
95578ad0 542 char const *wrapper;
984263bc 543 int state;
17c88c3a 544 int nice;
984263bc
MD
545
546 /* find and remember the next proc structure */
547 hp = (struct handle *)handle;
548 pp = *(hp->next_proc++);
549 hp->remaining--;
550
95578ad0 551 /* set the wrapper for the process/thread name */
5dfd06ac 552 if ((PP(pp, flags) & P_SWAPPEDOUT))
95578ad0 553 wrapper = "[]"; /* swapped process [pname] */
18170ab7 554 else if (((PP(pp, flags) & P_SYSTEM) != 0) && (LP(pp, pid) > 0))
95578ad0 555 wrapper = "()"; /* system process (pname) */
18170ab7 556 else if (show_threads && (LP(pp, pid) == -1))
95578ad0
HP
557 wrapper = "<>"; /* pure kernel threads <thread> */
558 else
559 wrapper = NULL;
560
984263bc 561 /* get the process's command name */
95578ad0 562 if (wrapper != NULL) {
5dfd06ac
SS
563 char *comm = PP(pp, comm);
564#define COMSIZ sizeof(PP(pp, comm))
984263bc
MD
565 char buf[COMSIZ];
566 (void) strncpy(buf, comm, COMSIZ);
95578ad0 567 comm[0] = wrapper[0];
984263bc
MD
568 (void) strncpy(&comm[1], buf, COMSIZ - 2);
569 comm[COMSIZ - 2] = '\0';
95578ad0 570 (void) strncat(comm, &wrapper[1], COMSIZ - 1);
984263bc
MD
571 comm[COMSIZ - 1] = '\0';
572 }
573
574 /*
575 * Convert the process's runtime from microseconds to seconds. This
576 * time includes the interrupt time although that is not wanted here.
577 * ps(1) is similarly sloppy.
578 */
5dfd06ac 579 cputime = (LP(pp, uticks) + LP(pp, sticks)) / 1000000;
984263bc
MD
580
581 /* calculate the base for cpu percentages */
5dfd06ac 582 pct = pctdouble(LP(pp, pctcpu));
984263bc
MD
583
584 /* generate "STATE" field */
164b8401
SS
585 switch (state = LP(pp, stat)) {
586 case LSRUN:
5dfd06ac
SS
587 if (smpmode && LP(pp, tdflags) & TDF_RUNNING)
588 sprintf(status, "CPU%d", LP(pp, cpuid));
984263bc
MD
589 else
590 strcpy(status, "RUN");
591 break;
164b8401 592 case LSSLEEP:
5dfd06ac
SS
593 if (LP(pp, wmesg) != NULL) {
594 sprintf(status, "%.6s", LP(pp, wmesg));
984263bc
MD
595 break;
596 }
597 /* fall through */
598 default:
599
600 if (state >= 0 &&
601 state < sizeof(state_abbrev) / sizeof(*state_abbrev))
602 sprintf(status, "%.6s", state_abbrev[(unsigned char) state]);
603 else
604 sprintf(status, "?%5d", state);
605 break;
606 }
607
416d05d7 608 if (PP(pp, stat) == SZOMB)
164b8401
SS
609 strcpy(status, "ZOMB");
610
17c88c3a
MD
611 /*
612 * idle time 0 - 31 -> nice value +21 - +52
613 * normal time -> nice value -20 - +20
614 * real time 0 - 31 -> nice value -52 - -21
615 * thread 0 - 31 -> nice value -53 -
616 */
5dfd06ac 617 switch(LP(pp, rtprio.type)) {
17c88c3a 618 case RTP_PRIO_REALTIME:
5dfd06ac 619 nice = PRIO_MIN - 1 - RTP_PRIO_MAX + LP(pp, rtprio.prio);
17c88c3a
MD
620 break;
621 case RTP_PRIO_IDLE:
5dfd06ac 622 nice = PRIO_MAX + 1 + LP(pp, rtprio.prio);
17c88c3a
MD
623 break;
624 case RTP_PRIO_THREAD:
5dfd06ac 625 nice = PRIO_MIN - 1 - RTP_PRIO_MAX - LP(pp, rtprio.prio);
17c88c3a
MD
626 break;
627 default:
5dfd06ac 628 nice = PP(pp, nice);
17c88c3a
MD
629 break;
630 }
631
632
984263bc 633 /* format this entry */
95578ad0 634 snprintf(fmt, sizeof(fmt),
984263bc 635 smpmode ? smp_Proc_format : up_Proc_format,
5dfd06ac 636 PP(pp, pid),
984263bc 637 namelength, namelength,
5dfd06ac 638 (*get_userid)(PP(pp, ruid)),
18170ab7 639 (show_threads && (LP(pp, pid) == -1)) ? LP(pp, tdprio) :
5dfd06ac 640 LP(pp, prio),
17c88c3a 641 nice,
984263bc 642 format_k2(PROCSIZE(pp)),
5dfd06ac 643 format_k2(pagetok(VP(pp, rssize))),
984263bc 644 status,
5dfd06ac 645 smpmode ? LP(pp, cpuid) : 0,
984263bc
MD
646 format_time(cputime),
647 100.0 * weighted_cpu(pct, pp),
648 100.0 * pct,
649 cmdlength,
5dfd06ac 650 printable(PP(pp, comm)));
984263bc
MD
651
652 /* return the result */
653 return(fmt);
654}
655
656
657/*
658 * check_nlist(nlst) - checks the nlist to see if any symbols were not
659 * found. For every symbol that was not found, a one-line
660 * message is printed to stderr. The routine returns the
661 * number of symbols NOT found.
662 */
663
1d1731fa 664static int check_nlist(register struct nlist *nlst)
984263bc
MD
665{
666 register int i;
667
668 /* check to see if we got ALL the symbols we requested */
669 /* this will write one line to stderr for every symbol not found */
670
671 i = 0;
672 while (nlst->n_name != NULL)
673 {
674 if (nlst->n_type == 0)
675 {
676 /* this one wasn't found */
677 (void) fprintf(stderr, "kernel: no symbol named `%s'\n",
678 nlst->n_name);
679 i = 1;
680 }
681 nlst++;
682 }
683
684 return(i);
685}
686
984263bc
MD
687/* comparison routines for qsort */
688
689/*
690 * proc_compare - comparison function for "qsort"
691 * Compares the resource consumption of two processes using five
692 * distinct keys. The keys (in descending order of importance) are:
693 * percent cpu, cpu ticks, state, resident set size, total virtual
694 * memory usage. The process states are ordered as follows (from least
695 * to most important): WAIT, zombie, sleep, stop, start, run. The
696 * array declaration below maps a process state index into a number
697 * that reflects this ordering.
698 */
699
700static unsigned char sorted_state[] =
701{
702 0, /* not used */
703 3, /* sleep */
704 1, /* ABANDONED (WAIT) */
705 6, /* run */
706 5, /* start */
707 2, /* zombie */
708 4 /* stop */
709};
710
711
712#define ORDERKEY_PCTCPU \
5dfd06ac 713 if (lresult = (long) LP(p2, pctcpu) - (long) LP(p1, pctcpu), \
984263bc
MD
714 (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
715
5dfd06ac 716#define CPTICKS(p) (LP(p, uticks) + LP(p, sticks))
6ac7b760 717
984263bc 718#define ORDERKEY_CPTICKS \
6ac7b760
MD
719 if ((result = CPTICKS(p2) > CPTICKS(p1) ? 1 : \
720 CPTICKS(p2) < CPTICKS(p1) ? -1 : 0) == 0)
984263bc
MD
721
722#define ORDERKEY_STATE \
5dfd06ac
SS
723 if ((result = sorted_state[(unsigned char) PP(p2, stat)] - \
724 sorted_state[(unsigned char) PP(p1, stat)]) == 0)
984263bc
MD
725
726#define ORDERKEY_PRIO \
5dfd06ac 727 if ((result = LP(p2, prio) - LP(p1, prio)) == 0)
984263bc 728
95578ad0 729#define ORDERKEY_KTHREADS \
5dfd06ac 730 if ((result = (LP(p1, pid) == 0) - (LP(p2, pid) == 0)) == 0)
95578ad0
HP
731
732#define ORDERKEY_KTHREADS_PRIO \
5dfd06ac 733 if ((result = LP(p2, tdprio) - LP(p1, tdprio)) == 0)
95578ad0 734
984263bc 735#define ORDERKEY_RSSIZE \
5dfd06ac 736 if ((result = VP(p2, rssize) - VP(p1, rssize)) == 0)
984263bc
MD
737
738#define ORDERKEY_MEM \
739 if ( (result = PROCSIZE(p2) - PROCSIZE(p1)) == 0 )
740
741/* compare_cpu - the comparison function for sorting by cpu percentage */
742
743int
744#ifdef ORDER
1d1731fa 745compare_cpu(struct proc **pp1, struct proc **pp2)
984263bc 746#else
1d1731fa 747proc_compare(struct proc **pp1, struct proc **pp2)
984263bc 748#endif
984263bc
MD
749{
750 register struct kinfo_proc *p1;
751 register struct kinfo_proc *p2;
752 register int result;
753 register pctcpu lresult;
754
755 /* remove one level of indirection */
756 p1 = *(struct kinfo_proc **) pp1;
757 p2 = *(struct kinfo_proc **) pp2;
758
759 ORDERKEY_PCTCPU
760 ORDERKEY_CPTICKS
761 ORDERKEY_STATE
762 ORDERKEY_PRIO
763 ORDERKEY_RSSIZE
764 ORDERKEY_MEM
765 ;
766
767 return(result);
768}
769
770#ifdef ORDER
771/* compare routines */
95578ad0 772int compare_size(), compare_res(), compare_time(), compare_prio(), compare_thr();
984263bc
MD
773
774int (*proc_compares[])() = {
775 compare_cpu,
776 compare_size,
777 compare_res,
778 compare_time,
779 compare_prio,
95578ad0 780 compare_thr,
984263bc
MD
781 NULL
782};
783
784/* compare_size - the comparison function for sorting by total memory usage */
785
786int
1d1731fa 787compare_size(struct proc **pp1, struct proc **pp2)
984263bc
MD
788{
789 register struct kinfo_proc *p1;
790 register struct kinfo_proc *p2;
791 register int result;
792 register pctcpu lresult;
793
794 /* remove one level of indirection */
795 p1 = *(struct kinfo_proc **) pp1;
796 p2 = *(struct kinfo_proc **) pp2;
797
798 ORDERKEY_MEM
799 ORDERKEY_RSSIZE
800 ORDERKEY_PCTCPU
801 ORDERKEY_CPTICKS
802 ORDERKEY_STATE
803 ORDERKEY_PRIO
804 ;
805
806 return(result);
807}
808
809/* compare_res - the comparison function for sorting by resident set size */
810
811int
1d1731fa 812compare_res(struct proc **pp1, struct proc **pp2)
984263bc
MD
813{
814 register struct kinfo_proc *p1;
815 register struct kinfo_proc *p2;
816 register int result;
817 register pctcpu lresult;
818
819 /* remove one level of indirection */
820 p1 = *(struct kinfo_proc **) pp1;
821 p2 = *(struct kinfo_proc **) pp2;
822
823 ORDERKEY_RSSIZE
824 ORDERKEY_MEM
825 ORDERKEY_PCTCPU
826 ORDERKEY_CPTICKS
827 ORDERKEY_STATE
828 ORDERKEY_PRIO
829 ;
830
831 return(result);
832}
833
834/* compare_time - the comparison function for sorting by total cpu time */
835
836int
1d1731fa 837compare_time(struct proc **pp1, struct proc **pp2)
984263bc
MD
838{
839 register struct kinfo_proc *p1;
840 register struct kinfo_proc *p2;
841 register int result;
842 register pctcpu lresult;
843
844 /* remove one level of indirection */
845 p1 = *(struct kinfo_proc **) pp1;
846 p2 = *(struct kinfo_proc **) pp2;
847
848 ORDERKEY_CPTICKS
849 ORDERKEY_PCTCPU
95578ad0
HP
850 ORDERKEY_KTHREADS
851 ORDERKEY_KTHREADS_PRIO
984263bc
MD
852 ORDERKEY_STATE
853 ORDERKEY_PRIO
854 ORDERKEY_RSSIZE
855 ORDERKEY_MEM
856 ;
857
858 return(result);
859 }
860
861/* compare_prio - the comparison function for sorting by cpu percentage */
862
863int
1d1731fa 864compare_prio(struct proc **pp1, struct proc **pp2)
984263bc
MD
865{
866 register struct kinfo_proc *p1;
867 register struct kinfo_proc *p2;
868 register int result;
869 register pctcpu lresult;
870
871 /* remove one level of indirection */
872 p1 = *(struct kinfo_proc **) pp1;
873 p2 = *(struct kinfo_proc **) pp2;
874
95578ad0
HP
875 ORDERKEY_KTHREADS
876 ORDERKEY_KTHREADS_PRIO
984263bc
MD
877 ORDERKEY_PRIO
878 ORDERKEY_CPTICKS
879 ORDERKEY_PCTCPU
880 ORDERKEY_STATE
881 ORDERKEY_RSSIZE
882 ORDERKEY_MEM
883 ;
884
885 return(result);
886}
95578ad0
HP
887
888int
889compare_thr(struct proc **pp1, struct proc **pp2)
890{
891 register struct kinfo_proc *p1;
892 register struct kinfo_proc *p2;
893 register int result;
894 register pctcpu lresult;
895
896 /* remove one level of indirection */
897 p1 = *(struct kinfo_proc **) pp1;
898 p2 = *(struct kinfo_proc **) pp2;
899
900 ORDERKEY_KTHREADS
901 ORDERKEY_KTHREADS_PRIO
902 ORDERKEY_CPTICKS
903 ORDERKEY_PCTCPU
904 ORDERKEY_STATE
905 ORDERKEY_RSSIZE
906 ORDERKEY_MEM
907 ;
908
909 return(result);
910}
911
912
984263bc
MD
913#endif
914
915/*
916 * proc_owner(pid) - returns the uid that owns process "pid", or -1 if
917 * the process does not exist.
918 * It is EXTREMLY IMPORTANT that this function work correctly.
919 * If top runs setuid root (as in SVR4), then this function
920 * is the only thing that stands in the way of a serious
921 * security problem. It validates requests for the "kill"
922 * and "renice" commands.
923 */
924
1d1731fa 925int proc_owner(int pid)
984263bc
MD
926{
927 register int cnt;
928 register struct kinfo_proc **prefp;
929 register struct kinfo_proc *pp;
930
931 prefp = pref;
932 cnt = pref_len;
933 while (--cnt >= 0)
934 {
935 pp = *prefp++;
5dfd06ac 936 if (PP(pp, pid) == (pid_t)pid)
984263bc 937 {
5dfd06ac 938 return((int)PP(pp, ruid));
984263bc
MD
939 }
940 }
941 return(-1);
942}
943
944
945/*
946 * swapmode is based on a program called swapinfo written
947 * by Kevin Lahey <kml@rokkaku.atl.ga.us>.
948 */
984263bc 949int
1d1731fa 950swapmode(int *retavail, int *retfree)
984263bc
MD
951{
952 int n;
953 int pagesize = getpagesize();
954 struct kvm_swap swapary[1];
955
956 *retavail = 0;
957 *retfree = 0;
958
959#define CONVERT(v) ((quad_t)(v) * pagesize / 1024)
960
961 n = kvm_getswapinfo(kd, swapary, 1, 0);
962 if (n < 0 || swapary[0].ksw_total == 0)
963 return(0);
964
965 *retavail = CONVERT(swapary[0].ksw_total);
966 *retfree = CONVERT(swapary[0].ksw_total - swapary[0].ksw_used);
967
968 n = (int)((double)swapary[0].ksw_used * 100.0 /
969 (double)swapary[0].ksw_total);
970 return(n);
971}