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