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