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