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