amd64: Fix several "sizeof(size_t) != sizeof(int)" bugs.
[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 <math.h>
38 #include <pwd.h>
39 #include <sys/errno.h>
40 #include <sys/sysctl.h>
41 #include <sys/file.h>
42 #include <sys/time.h>
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
54 #include <sys/kinfo.h>
55 #include <kinfo.h>
56 #include "top.h"
57 #include "machine.h"
58
59 static int check_nlist(struct nlist *);
60 static int getkval(unsigned long, int *, int, char *);
61 extern char* printable(char *);
62 int swapmode(int *retavail, int *retfree);
63 static int smpmode;
64 static int namelength;
65 static int cmdlength;
66
67 /* 
68  * needs to be a global symbol, so wrapper can be
69  * modified accordingly.
70  */
71 static int show_threads = 0;
72
73 /* get_process_info passes back a handle.  This is what it looks like: */
74
75 struct 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
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)
87
88 /* define what weighted cpu is.  */
89 #define weighted_cpu(pct, pp) (PP((pp), swtime) == 0 ? 0.0 : \
90                          ((pct) / (1.0 - exp(PP((pp), swtime) * logcpu))))
91
92 /* what we consider to be process size: */
93 #define PROCSIZE(pp) (VP((pp), map_size) / 1024)
94
95 /*
96  *  These definitions control the format of the per-process area
97  */
98
99 static 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
105 static 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
117 char *state_abbrev[] =
118 {
119     "", "RUN\0\0\0", "STOP", "SLEEP",
120 };
121
122
123 static kvm_t *kd;
124
125 /* values that we stash away in _init and use in later routines */
126
127 static double logcpu;
128
129 static long lastpid;
130 static long cnt;
131 static int ccpu;
132
133 /* these are for calculating cpu state percentages */
134
135 static struct kinfo_cputime *cp_time, *cp_old;
136
137 /* these are for detailing the process states */
138
139 int process_states[6];
140 char *procstatenames[] = {
141     "", " starting, ", " running, ", " sleeping, ", " stopped, ",
142     " 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 int memory_stats[7];
156 char *memorynames[] = {
157     "K Active, ", "K Inact, ", "K Wired, ", "K Cache, ", "K Buf, ", "K Free",
158     NULL
159 };
160
161 int 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 #ifdef ORDER
186 /* sorting orders. first is default */
187 char *ordernames[] = {
188     "cpu", "size", "res", "time", "pri", "thr", NULL
189 };
190 #endif
191
192 static void
193 cputime_percentages(int out[CPU_STATES], struct kinfo_cputime *new,
194                     struct kinfo_cputime *old)
195 {
196         struct kinfo_cputime diffs;
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
229 int
230 machine_init(struct statics *statics)
231 {
232     int i = 0;
233     int pagesize;
234     size_t modelen;
235     struct passwd *pw;
236
237     if (n_cpus < 1) {
238         if (kinfo_get_cpus(&n_cpus))
239             err(1, "kinfo_get_cpus failed");
240     }
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
261     if (kinfo_get_sched_ccpu(&ccpu)) {
262         fprintf(stderr, "top: kinfo_get_sched_ccpu failed\n");
263         return(-1);
264     }
265
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
298 char *format_header(char *uname_field)
299 {
300     char *ptr;
301     static char Header[128];
302
303     snprintf(Header, sizeof(Header), smpmode ? smp_header : up_header,
304              namelength, namelength, uname_field);
305
306     if (screen_width <= 79)
307         cmdlength = 80;
308     else
309         cmdlength = 89;
310
311     cmdlength = cmdlength - strlen(Header) + 6;
312
313     return Header;
314 }
315
316 static int swappgsin = -1;
317 static int swappgsout = -1;
318 extern struct timeval timeout;
319
320 void
321 get_system_info(struct system_info *si)
322 {
323     long total;
324     int mib[2];
325     struct timeval boottime;
326     size_t bt_size;
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     }
347
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");
352
353     getloadavg(si->load_avg, 3);
354
355     lastpid = 0;
356
357     /* convert cp_time counts to percentages */
358     for (cpu = 0; cpu < n_cpus; ++cpu) {
359         cputime_percentages(cpu_states + cpu * CPU_STATES,
360                             &cp_time[cpu], &cp_old[cpu]);
361     }
362
363     /* sum memory & swap statistics */
364     {
365         struct vmmeter vmm;
366         struct vmstats vms;
367         size_t vms_size = sizeof(vms);
368         size_t vmm_size = sizeof(vmm);
369         static unsigned int swap_delay = 0;
370         static int swapavail = 0;
371         static int swapfree = 0;
372         static int bufspace = 0;
373
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");
382
383         /* convert memory stats to Kbytes */
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);
388         memory_stats[4] = bufspace / 1024;
389         memory_stats[5] = pagetok(vms.v_free_count);
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 {
400             swap_stats[4] = pagetok(((vmm.v_swappgsin - swappgsin)));
401             swap_stats[5] = pagetok(((vmm.v_swappgsout - swappgsout)));
402         }
403
404         swappgsin = vmm.v_swappgsin;
405         swappgsout = vmm.v_swappgsout;
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
445 static struct handle handle;
446
447 caddr_t get_process_info(struct system_info *si, struct process_select *sel,
448                          int (*compare)())
449 {
450     int i;
451     int total_procs;
452     int active_procs;
453     struct kinfo_proc **prefp;
454     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;
460     int show_only_threads;
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;
480     show_threads = sel->threads || sel->only_threads;
481     show_only_threads = sel->only_threads;
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          */
498         if ((show_threads && (LP(pp, pid) == -1)) ||
499             (!show_only_threads && (PP(pp, stat) != 0 &&
500             (show_self != PP(pp, pid)) &&
501             (show_system || ((PP(pp, flags) & P_SYSTEM) == 0)))))
502         {
503             total_procs++;
504             process_states[(unsigned char) PP(pp, stat)]++;
505             if ((show_threads && (LP(pp, pid) == -1)) ||
506                 (!show_only_threads && PP(pp, stat) != SZOMB &&
507                 (show_idle || (LP(pp, pctcpu) != 0) ||
508                  (LP(pp, stat) == LSRUN)) &&
509                 (!show_uid || PP(pp, ruid) == (uid_t)sel->uid)))
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
533 char fmt[128];          /* static area where result is built */
534
535 char *format_next_process(caddr_t handle, char *(*get_userid)())
536 {
537     struct kinfo_proc *pp;
538     long cputime;
539     double pct;
540     struct handle *hp;
541     char status[16];
542     char const *wrapper;
543     int state;
544     int nice;
545
546     /* find and remember the next proc structure */
547     hp = (struct handle *)handle;
548     pp = *(hp->next_proc++);
549     hp->remaining--;
550     
551     /* set the wrapper for the process/thread name */
552     if ((PP(pp, flags) & P_SWAPPEDOUT))
553          wrapper = "[]"; /* swapped process [pname] */
554     else if (((PP(pp, flags) & P_SYSTEM) != 0) && (LP(pp, pid) > 0))
555          wrapper = "()"; /* system process (pname) */
556     else if (show_threads && (LP(pp, pid) == -1))
557          wrapper = "<>"; /* pure kernel threads <thread> */
558     else
559          wrapper = NULL;
560   
561     /* get the process's command name */
562     if (wrapper != NULL) {
563         char *comm = PP(pp, comm);
564 #define COMSIZ sizeof(PP(pp, comm))
565         char buf[COMSIZ];
566         (void) strncpy(buf, comm, COMSIZ);
567         comm[0] = wrapper[0];
568         (void) strncpy(&comm[1], buf, COMSIZ - 2);
569         comm[COMSIZ - 2] = '\0';
570         (void) strncat(comm, &wrapper[1], COMSIZ - 1);
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      */
579     cputime = (LP(pp, uticks) + LP(pp, sticks)) / 1000000;
580
581     /* calculate the base for cpu percentages */
582     pct = pctdouble(LP(pp, pctcpu));
583
584     /* generate "STATE" field */
585     switch (state = LP(pp, stat)) {
586         case LSRUN:
587             if (smpmode && LP(pp, tdflags) & TDF_RUNNING)
588                 sprintf(status, "CPU%d", LP(pp, cpuid));
589             else
590                 strcpy(status, "RUN");
591             break;
592         case LSSLEEP:
593             if (LP(pp, wmesg) != NULL) {
594                 sprintf(status, "%.6s", LP(pp, wmesg));
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
608     if (PP(pp, stat) == SZOMB)
609             strcpy(status, "ZOMB");
610
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      */
617     switch(LP(pp, rtprio.type)) {
618     case RTP_PRIO_REALTIME:
619         nice = PRIO_MIN - 1 - RTP_PRIO_MAX + LP(pp, rtprio.prio);
620         break;
621     case RTP_PRIO_IDLE:
622         nice = PRIO_MAX + 1 + LP(pp, rtprio.prio);
623         break;
624     case RTP_PRIO_THREAD:
625         nice = PRIO_MIN - 1 - RTP_PRIO_MAX - LP(pp, rtprio.prio);
626         break;
627     default:
628         nice = PP(pp, nice);
629         break;
630     }
631
632
633     /* format this entry */
634     snprintf(fmt, sizeof(fmt),
635             smpmode ? smp_Proc_format : up_Proc_format,
636             PP(pp, pid),
637             namelength, namelength,
638             (*get_userid)(PP(pp, ruid)),
639             (show_threads && (LP(pp, pid) == -1)) ? LP(pp, tdprio) :
640                 LP(pp, prio),
641             nice,
642             format_k2(PROCSIZE(pp)),
643             format_k2(pagetok(VP(pp, rssize))),
644             status,
645             smpmode ? LP(pp, cpuid) : 0,
646             format_time(cputime),
647             100.0 * weighted_cpu(pct, pp),
648             100.0 * pct,
649             cmdlength,
650             printable(PP(pp, comm)));
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
664 static int check_nlist(struct nlist *nlst)
665 {
666     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
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
700 static 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 \
713   if (lresult = (long) LP(p2, pctcpu) - (long) LP(p1, pctcpu), \
714      (result = lresult > 0 ? 1 : lresult < 0 ? -1 : 0) == 0)
715
716 #define CPTICKS(p)      (LP(p, uticks) + LP(p, sticks))
717
718 #define ORDERKEY_CPTICKS \
719   if ((result = CPTICKS(p2) > CPTICKS(p1) ? 1 : \
720                 CPTICKS(p2) < CPTICKS(p1) ? -1 : 0) == 0)
721
722 #define ORDERKEY_STATE \
723   if ((result = sorted_state[(unsigned char) PP(p2, stat)] - \
724                 sorted_state[(unsigned char) PP(p1, stat)]) == 0)
725
726 #define ORDERKEY_PRIO \
727   if ((result = LP(p2, prio) - LP(p1, prio)) == 0)
728
729 #define ORDERKEY_KTHREADS \
730   if ((result = (LP(p1, pid) == 0) - (LP(p2, pid) == 0)) == 0)
731
732 #define ORDERKEY_KTHREADS_PRIO \
733   if ((result = LP(p2, tdprio) - LP(p1, tdprio)) == 0)
734
735 #define ORDERKEY_RSSIZE \
736   if ((result = VP(p2, rssize) - VP(p1, rssize)) == 0) 
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
743 int
744 #ifdef ORDER
745 compare_cpu(struct proc **pp1, struct proc **pp2)
746 #else
747 proc_compare(struct proc **pp1, struct proc **pp2)
748 #endif
749 {
750     struct kinfo_proc *p1;
751     struct kinfo_proc *p2;
752     int result;
753     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 */
772 int compare_size(), compare_res(), compare_time(), compare_prio(), compare_thr();
773
774 int (*proc_compares[])() = {
775     compare_cpu,
776     compare_size,
777     compare_res,
778     compare_time,
779     compare_prio,
780     compare_thr,
781     NULL
782 };
783
784 /* compare_size - the comparison function for sorting by total memory usage */
785
786 int
787 compare_size(struct proc **pp1, struct proc **pp2)
788 {
789     struct kinfo_proc *p1;
790     struct kinfo_proc *p2;
791     int result;
792     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
811 int
812 compare_res(struct proc **pp1, struct proc **pp2)
813 {
814     struct kinfo_proc *p1;
815     struct kinfo_proc *p2;
816     int result;
817     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
836 int
837 compare_time(struct proc **pp1, struct proc **pp2)
838 {
839     struct kinfo_proc *p1;
840     struct kinfo_proc *p2;
841     int result;
842     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
850     ORDERKEY_KTHREADS
851     ORDERKEY_KTHREADS_PRIO
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
863 int
864 compare_prio(struct proc **pp1, struct proc **pp2)
865 {
866     struct kinfo_proc *p1;
867     struct kinfo_proc *p2;
868     int result;
869     pctcpu lresult;
870
871     /* remove one level of indirection */
872     p1 = *(struct kinfo_proc **) pp1;
873     p2 = *(struct kinfo_proc **) pp2;
874
875     ORDERKEY_KTHREADS
876     ORDERKEY_KTHREADS_PRIO
877     ORDERKEY_PRIO
878     ORDERKEY_CPTICKS
879     ORDERKEY_PCTCPU
880     ORDERKEY_STATE
881     ORDERKEY_RSSIZE
882     ORDERKEY_MEM
883     ;
884
885     return(result);
886 }
887
888 int
889 compare_thr(struct proc **pp1, struct proc **pp2)
890 {
891     struct kinfo_proc *p1;
892     struct kinfo_proc *p2;
893     int result;
894     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
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
925 int proc_owner(int pid)
926 {
927     int cnt;
928     struct kinfo_proc **prefp;
929     struct kinfo_proc *pp;
930
931     prefp = pref;
932     cnt = pref_len;
933     while (--cnt >= 0)
934     {
935         pp = *prefp++;  
936         if (PP(pp, pid) == (pid_t)pid)
937         {
938             return((int)PP(pp, ruid));
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  */
949 int
950 swapmode(int *retavail, int *retfree)
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 }