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