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