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