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